add new UI Component

This commit is contained in:
Ichsan Kurniawan
2026-04-20 17:13:20 +07:00
parent ad4925bd55
commit 6b16bd2dd4
4 changed files with 657 additions and 0 deletions
+108
View File
@@ -0,0 +1,108 @@
import { useMemo, useState } from "react";
import { toast } from "sonner";
import {
AlertDialog, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle
} from "@/components/ui/alert-dialog"
import { Button } from "@/components/ui/button";
import { Loader2 } from "lucide-react";
import { serverApiCall } from "@/lib/server-api";
import * as Yup from 'yup'
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form";
import { useForm } from "react-hook-form";
import { Input } from "../ui/input";
import { yupResolver } from "@hookform/resolvers/yup";
interface Props {
endpoint?: string
onSuccess?: () => void;
onCancel?: () => void;
title: string
titleButton?: string
description?: string,
method?: any
}
interface FormDataType {
name: string;
}
export function ConfirmDeleteWithInput({ endpoint, title, titleButton, description, onSuccess, onCancel, method }: Props) {
const [isLoading, setIsLoading] = useState(false);
const validationSchema = useMemo(() => {
return Yup.object().shape({
name: Yup.string()
.required("Please fill this field to continue")
.oneOf([title], `Input must exactly match "${title}"`), // <-- Exact match validation
});
}, [title]);
const form = useForm<FormDataType>({
resolver: yupResolver(validationSchema),
defaultValues: {
"name": '',
},
});
const onSubmit = async () => {
setIsLoading(true)
const toastId = toast.loading('Deleting data...');
try {
const res = await serverApiCall(method || 'DELETE', endpoint!)
if (res.success) {
toast.success("Data deleted successfully", { id: toastId });
onSuccess!()
} else {
toast.error("Oops sorry, error has occurred", {
description: `(${res.code}) ${res.message || "An unexpected error occurred while saving data. Please try again later."}`,
id: toastId
})
}
} catch (error: any) {
toast.error(error.message, { id: toastId })
} finally {
setIsLoading(false)
}
};
return (
<AlertDialog open={true}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<AlertDialogDescription>
{description || "This action cannot be undone. This will permanently delete this data and remove our servers."}
</AlertDialogDescription>
</AlertDialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<div className="mt-2 mb-6">
<FormField control={form.control} name='name'
render={({ field }) => (
<FormItem>
<FormLabel>Please type <strong>{title}</strong> to confirm <span className='text-red-600 font-bold'>*</span></FormLabel>
<FormControl>
<Input {...field} placeholder="Type the name..." />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<AlertDialogFooter className="grid grid-cols-1 gap-3">
<Button onClick={onCancel} disabled={isLoading} type='button' variant='secondary'>Cancel</Button>
<Button type="submit" disabled={isLoading}>
{isLoading && <Loader2 className='animate-spin' />}
{titleButton || "I understand the consequences, delete this data"}
</Button>
</AlertDialogFooter>
</form>
</Form>
</AlertDialogContent>
</AlertDialog>
)
}
+220
View File
@@ -0,0 +1,220 @@
"use client";
import * as React from "react";
import { Check, ChevronsUpDown } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
export interface ComboboxOption {
value: string | number;
label: string;
// Allows you to pass raw data for custom UI rendering without using 'any'
originalData?: unknown;
}
interface ComboboxProps {
options: ComboboxOption[];
value?: string | number;
onChange: (value: string | number | undefined) => void;
placeholder?: string;
searchPlaceholder?: string;
emptyText?: string;
disabled?: boolean;
className?: string;
// Optional props for Custom UI
renderTrigger?: (selectedOption?: ComboboxOption) => React.ReactNode;
renderOption?: (option: ComboboxOption, isSelected: boolean) => React.ReactNode;
}
export function Combobox({
options,
value,
onChange,
placeholder = "Pilih opsi...",
searchPlaceholder = "Cari...",
emptyText = "Tidak ditemukan.",
disabled = false,
className,
renderTrigger,
renderOption,
}: ComboboxProps) {
const [open, setOpen] = React.useState(false);
// Safely find the selected option by comparing strings to avoid number/string mismatch bugs
const selectedOption = React.useMemo(
() => options.find((opt) => String(opt.value) === String(value)),
[value, options]
);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild disabled={disabled}>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
className={cn("w-full justify-between font-normal", !selectedOption && "text-muted-foreground", className)}
>
{renderTrigger ? (
renderTrigger(selectedOption)
) : (
<span className="truncate">
{selectedOption ? selectedOption.label : placeholder}
</span>
)}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-(--radix-popover-trigger-width) max-h-(--radix-popover-content-available-height) p-0">
<Command>
<CommandInput placeholder={searchPlaceholder} />
<CommandList>
<CommandEmpty>{emptyText}</CommandEmpty>
<CommandGroup>
{options.map((option) => {
const isSelected = String(option.value) === String(value);
return (
<CommandItem
key={option.value}
// cmdk uses the 'value' prop for searching. We pass the label here so users can search by text.
value={option.label}
onSelect={() => {
// Toggle selection: if already selected, clear it (undefined), else set new value
onChange(isSelected ? undefined : option.value);
setOpen(false);
}}
>
{renderOption ? (
renderOption(option, isSelected)
) : (
<>
<Check
className={cn(
"mr-2 h-4 w-4 shrink-0",
isSelected ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate">{option.label}</span>
</>
)}
</CommandItem>
);
})}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}
/** Standalone (No Form)
export function SalesFilter() {
const [selectedId, setSelectedId] = useState<string | number>();
return (
<div className="w-64">
<Combobox
options={mappedSalesPrograms}
value={selectedId}
onChange={setSelectedId}
/>
</div>
);
}
*/
/** TanStack Form (Standard UI)
import { Combobox } from "@/components/ui/combobox";
import { useMemo } from "react";
export function SalesForm() {
// 1. Map your raw data to the standard option format
const mappedSalesPrograms = useMemo(() => {
return dataSalesProgram?.map((item) => ({
label: item.nama,
value: item.id,
})) || [];
}, [dataSalesProgram]);
return (
<form.AppField name="sales_program">
{(field) => (
<FieldGroup>
<FormLabel>Sales Program</FormLabel>
<Combobox
options={mappedSalesPrograms}
value={field.state.value}
onChange={(val) => field.handleChange(val as number)} // Cast back to your strict type
placeholder="Pilih Sales Program"
searchPlaceholder="Cari Sales Program..."
/>
{field.state.meta.errors && <FormMessage>{field.state.meta.errors}</FormMessage>}
</FieldGroup>
)}
</form.AppField>
);
}
*/
/** Custom UI Selection
export function CustomUICombobox() {
// Passing the raw item in `originalData` so we can use it in the custom render
const users = [
{ id: 1, name: "Luthfi Aditama", role: "Team Leader" },
{ id: 2, name: "Ihsan", role: "Developer" },
];
const options = users.map(user => ({
value: user.id,
label: user.name,
originalData: user // <-- Store raw data here
}));
return (
<Combobox
options={options}
value={1}
onChange={(val) => console.log(val)}
// 1. Custom Selected Value
renderTrigger={(selected) => (
<div className="flex items-center gap-2">
<span className="font-bold text-primary">{selected?.label || "Pilih User"}</span>
</div>
)}
// 2. Custom Dropdown Items
renderOption={(option, isSelected) => {
// Safely cast originalData back to your expected type
const user = option.originalData as typeof users[0];
return (
<div className="flex items-center justify-between w-full">
<div className="flex flex-col">
<span className={isSelected ? "font-bold" : ""}>{option.label}</span>
<span className="text-xs text-muted-foreground">{user.role}</span>
</div>
{isSelected && <Badge variant="secondary">Active</Badge>}
</div>
);
}}
/>
);
}
*/
+172
View File
@@ -0,0 +1,172 @@
"use client";
import * as React from "react";
import { Check, ChevronsUpDown, X } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
export interface MultiSelectOption {
value: string | number;
label: string;
originalData?: unknown; // Holds your raw API data
}
interface MultiSelectProps {
options: MultiSelectOption[];
value?: (string | number)[];
onChange: (value: (string | number)[]) => void;
placeholder?: string;
searchPlaceholder?: string;
emptyText?: string;
disabled?: boolean;
className?: string;
maxCount?: number;
// --- NEW CUSTOM UI PROPS ---
renderBadge?: (option: MultiSelectOption, onRemove: () => void) => React.ReactNode;
renderOption?: (option: MultiSelectOption, isSelected: boolean) => React.ReactNode;
}
export function MultiSelectCustomSelection({
options,
value = [],
onChange,
placeholder = "Select option...",
searchPlaceholder = "Search...",
emptyText = "Not found.",
disabled = false,
className,
maxCount = 3,
renderBadge,
renderOption,
}: MultiSelectProps) {
const [open, setOpen] = React.useState(false);
const selectedOptions = React.useMemo(() => {
return value.map((val) =>
options.find((opt) => String(opt.value) === String(val))
).filter(Boolean) as MultiSelectOption[];
}, [value, options]);
const handleSelect = (selectedValue: string | number) => {
const isSelected = value.some((v) => String(v) === String(selectedValue));
if (isSelected) {
onChange(value.filter((v) => String(v) !== String(selectedValue)));
} else {
onChange([...value, selectedValue]);
}
};
// Helper to safely remove items without closing the popover
const handleRemove = (valueToRemove: string | number) => {
onChange(value.filter((v) => String(v) !== String(valueToRemove)));
};
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild disabled={disabled}>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
className={cn("w-full justify-between min-h-10 h-auto font-normal", className)}
>
<div className="flex flex-wrap gap-1 items-center overflow-hidden">
{selectedOptions.length === 0 && (
<span className="text-muted-foreground">{placeholder}</span>
)}
{/* --- RENDER BADGES --- */}
{selectedOptions.slice(0, maxCount).map((option) => {
if (renderBadge) {
return (
<div key={option.value} onClick={(e) => e.stopPropagation()}>
{renderBadge(option, () => handleRemove(option.value))}
</div>
);
}
// Default Badge UI
return (
<Badge key={option.value} variant="secondary" className="mr-1 mb-1 font-normal">
{option.label}
<div
role="button"
className="ml-1 ring-offset-background rounded-full outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 hover:bg-muted-foreground/20 cursor-pointer"
onClick={(e) => {
e.stopPropagation();
handleRemove(option.value);
}}
>
<X className="h-3 w-3 text-muted-foreground hover:text-foreground" />
</div>
</Badge>
);
})}
{selectedOptions.length > maxCount && (
<Badge variant="secondary" className="mr-1 mb-1 font-normal">
+ {selectedOptions.length - maxCount} selected
</Badge>
)}
</div>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-(--radix-popover-trigger-width) p-0" align="start">
<Command>
<CommandInput placeholder={searchPlaceholder} />
<CommandList>
<CommandEmpty>{emptyText}</CommandEmpty>
<CommandGroup>
{/* --- RENDER OPTIONS --- */}
{options.map((option) => {
const isSelected = value.some((v) => String(v) === String(option.value));
return (
<CommandItem
key={option.value}
value={option.label}
onSelect={() => handleSelect(option.value)}
>
{renderOption ? (
renderOption(option, isSelected)
) : (
// Default Option UI
<>
<div
className={cn(
"mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
isSelected
? "bg-primary text-primary-foreground"
: "opacity-50 [&_svg]:invisible"
)}
>
<Check className={cn("h-4 w-4")} />
</div>
<span>{option.label}</span>
</>
)}
</CommandItem>
);
})}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}
+157
View File
@@ -0,0 +1,157 @@
"use client";
import * as React from "react";
import { Check, ChevronsUpDown, X } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
export interface MultiSelectOption {
value: string | number;
label: string;
originalData?: unknown;
}
interface MultiSelectProps {
options: MultiSelectOption[];
value?: (string | number)[];
onChange: (value: (string | number)[]) => void;
placeholder?: string;
searchPlaceholder?: string;
emptyText?: string;
disabled?: boolean;
className?: string;
maxCount?: number; // How many badges to show before saying "+X more"
}
export function MultiSelect({
options,
value = [], // Default to empty array
onChange,
placeholder = "Select option...",
searchPlaceholder = "Search...",
emptyText = "Not found.",
disabled = false,
className,
maxCount = 3,
}: MultiSelectProps) {
const [open, setOpen] = React.useState(false);
// Map the selected string/number values back to their full option objects
const selectedOptions = React.useMemo(() => {
return value.map((val) =>
options.find((opt) => String(opt.value) === String(val))
).filter(Boolean) as MultiSelectOption[];
}, [value, options]);
const handleSelect = (selectedValue: string | number) => {
const isSelected = value.some((v) => String(v) === String(selectedValue));
if (isSelected) {
// Remove the item
onChange(value.filter((v) => String(v) !== String(selectedValue)));
} else {
// Add the item
onChange([...value, selectedValue]);
}
};
const handleRemove = (e: React.MouseEvent, valueToRemove: string | number) => {
e.stopPropagation(); // Prevent opening/closing the popover when clicking the "X"
e.preventDefault();
onChange(value.filter((v) => String(v) !== String(valueToRemove)));
};
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild disabled={disabled}>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
// min-h-10 and h-auto allows the button to grow if badges wrap to a new line
className={cn("w-full justify-between min-h-10 h-auto font-normal", className)}
>
<div className="flex flex-wrap gap-1 items-center overflow-hidden">
{selectedOptions.length === 0 && (
<span className="text-muted-foreground">{placeholder}</span>
)}
{/* Render Badges */}
{selectedOptions.slice(0, maxCount).map((option) => (
<Badge
key={option.value}
variant="secondary"
className="mr-1 mb-1 font-normal"
>
{option.label}
<div
role="button"
className="ml-1 ring-offset-background rounded-full outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 hover:bg-muted-foreground/20 cursor-pointer"
onClick={(e) => handleRemove(e, option.value)}
>
<X className="h-3 w-3 text-muted-foreground hover:text-foreground" />
</div>
</Badge>
))}
{/* Render "+X more" if selections exceed maxCount */}
{selectedOptions.length > maxCount && (
<Badge variant="secondary" className="mr-1 mb-1 font-normal">
+ {selectedOptions.length - maxCount} selected
</Badge>
)}
</div>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-(--radix-popover-trigger-width) p-0" align="start">
<Command>
<CommandInput placeholder={searchPlaceholder} />
<CommandList>
<CommandEmpty>{emptyText}</CommandEmpty>
<CommandGroup>
{options.map((option) => {
const isSelected = value.some((v) => String(v) === String(option.value));
return (
<CommandItem
key={option.value}
value={option.label}
onSelect={() => handleSelect(option.value)}
// Notice we DO NOT call setOpen(false) here, allowing multiple clicks
>
<div
className={cn(
"mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
isSelected
? "bg-primary text-primary-foreground"
: "opacity-50 [&_svg]:invisible"
)}
>
<Check className={cn("h-4 w-4")} />
</div>
<span>{option.label}</span>
</CommandItem>
);
})}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}