From 6b16bd2dd42dc5a86d665dd485585c117ef4c6d6 Mon Sep 17 00:00:00 2001 From: Ichsan Kurniawan Date: Mon, 20 Apr 2026 17:13:20 +0700 Subject: [PATCH] add new UI Component --- components/modal/ConfirmDeleteWithInput.tsx | 108 ++++++++++ components/ui/combobox-custom-ui.tsx | 220 ++++++++++++++++++++ components/ui/multi-select-custom-ui.tsx | 172 +++++++++++++++ components/ui/multi-select.tsx | 157 ++++++++++++++ 4 files changed, 657 insertions(+) create mode 100644 components/modal/ConfirmDeleteWithInput.tsx create mode 100644 components/ui/combobox-custom-ui.tsx create mode 100644 components/ui/multi-select-custom-ui.tsx create mode 100644 components/ui/multi-select.tsx diff --git a/components/modal/ConfirmDeleteWithInput.tsx b/components/modal/ConfirmDeleteWithInput.tsx new file mode 100644 index 0000000..35dfe75 --- /dev/null +++ b/components/modal/ConfirmDeleteWithInput.tsx @@ -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({ + 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 ( + + + + Are you absolutely sure? + + {description || "This action cannot be undone. This will permanently delete this data and remove our servers."} + + + +
+ +
+ ( + + Please type {title} to confirm * + + + + + + )} + /> +
+ + + + + +
+ + +
+
+ ) +} diff --git a/components/ui/combobox-custom-ui.tsx b/components/ui/combobox-custom-ui.tsx new file mode 100644 index 0000000..7207552 --- /dev/null +++ b/components/ui/combobox-custom-ui.tsx @@ -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 ( + + + + + + + + + {emptyText} + + {options.map((option) => { + const isSelected = String(option.value) === String(value); + return ( + { + // Toggle selection: if already selected, clear it (undefined), else set new value + onChange(isSelected ? undefined : option.value); + setOpen(false); + }} + > + {renderOption ? ( + renderOption(option, isSelected) + ) : ( + <> + + {option.label} + + )} + + ); + })} + + + + + + ); +} + + +/** Standalone (No Form) +export function SalesFilter() { + const [selectedId, setSelectedId] = useState(); + + return ( +
+ +
+ ); +} + */ + + +/** 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 ( + + {(field) => ( + + Sales Program + field.handleChange(val as number)} // Cast back to your strict type + placeholder="Pilih Sales Program" + searchPlaceholder="Cari Sales Program..." + /> + {field.state.meta.errors && {field.state.meta.errors}} + + )} + + ); +} + */ + + +/** 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 ( + console.log(val)} + // 1. Custom Selected Value + renderTrigger={(selected) => ( +
+ {selected?.label || "Pilih User"} +
+ )} + // 2. Custom Dropdown Items + renderOption={(option, isSelected) => { + // Safely cast originalData back to your expected type + const user = option.originalData as typeof users[0]; + + return ( +
+
+ {option.label} + {user.role} +
+ {isSelected && Active} +
+ ); + }} + /> + ); +} + */ \ No newline at end of file diff --git a/components/ui/multi-select-custom-ui.tsx b/components/ui/multi-select-custom-ui.tsx new file mode 100644 index 0000000..8117bd3 --- /dev/null +++ b/components/ui/multi-select-custom-ui.tsx @@ -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 ( + + + + + + + + + {emptyText} + + {/* --- RENDER OPTIONS --- */} + {options.map((option) => { + const isSelected = value.some((v) => String(v) === String(option.value)); + return ( + handleSelect(option.value)} + > + {renderOption ? ( + renderOption(option, isSelected) + ) : ( + // Default Option UI + <> +
+ +
+ {option.label} + + )} +
+ ); + })} +
+
+
+
+
+ ); +} \ No newline at end of file diff --git a/components/ui/multi-select.tsx b/components/ui/multi-select.tsx new file mode 100644 index 0000000..04e358c --- /dev/null +++ b/components/ui/multi-select.tsx @@ -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 ( + + + + + + + + + {emptyText} + + {options.map((option) => { + const isSelected = value.some((v) => String(v) === String(option.value)); + return ( + handleSelect(option.value)} + // Notice we DO NOT call setOpen(false) here, allowing multiple clicks + > +
+ +
+ {option.label} +
+ ); + })} +
+
+
+
+
+ ); +} \ No newline at end of file