"use client"; import { Button } from "@suphark/ui/components/shared/button/button"; import { SwitcherChevron } from "@suphark/ui/components/shared/switcher-chevron"; import { useUiText } from "@suphark/ui/components/shared/ui-text"; import { Badge } from "@suphark/ui/components/ui/badge"; import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, } from "@suphark/ui/components/ui/command"; import { Popover, PopoverContent, PopoverTrigger } from "@suphark/ui/components/ui/popover"; import { commandContainsFilter } from "@suphark/ui/lib/command-filter"; import { cn } from "@suphark/ui/lib/utils"; import { Check, Plus, X } from "lucide-react"; import * as React from "react"; export interface MultiSelectOption { label: string; value: string; description?: string; searchableValue?: string; disabled?: boolean; } export interface MultiSelectComboboxProps { /** All available options */ options: MultiSelectOption[]; /** Selected values */ value?: string[]; /** Change callback */ onChange: (value: string[]) => void; /** Trigger placeholder */ placeholder?: string; /** Search input placeholder */ searchPlaceholder?: string; /** Empty search result message */ emptyText?: string; /** แสดงเมื่อค้นไม่พบ — ชื่อเดียวกับ `emptyText` (ให้ตรงกับ SimpleTable/DataList/NotificationCenter) */ empty?: React.ReactNode; /** Additional CSS class for the trigger button */ className?: string; /** Disabled state */ disabled?: boolean; /** Maximum number of badges to display before showing +N more */ maxDisplay?: number; /** Allow creating custom options on the fly */ creatable?: boolean; /** Show select all / clear all actions in the dropdown */ showSelectAll?: boolean; /** Select all button label */ selectAllText?: string; /** Clear all button label */ clearAllText?: string; /** Show group headers separating selected vs unselected items (default: true) */ showGroupHeaders?: boolean; /** Selected group header label */ selectedGroupHeading?: string; /** Unselected group header label */ unselectedGroupHeading?: string; /** Popover modal mode (useful inside Dialogs) */ modal?: boolean; /** Custom render element for PopoverTrigger (e.g. ) */ triggerRender?: React.ReactElement; /** Accessibility label */ /** id / aria-describedby / aria-invalid ของปุ่ม — FormControl ส่งมาให้ label/ข้อความ error ผูกกับช่อง */ id?: string; "aria-describedby"?: string; "aria-invalid"?: boolean | "true" | "false"; ariaLabel?: string; /** ให้ชื่อรายการที่เลือกขึ้นบรรทัดใหม่ได้ แทนการตัดที่ 200px เป็น "..." */ wrapText?: boolean; } export function MultiSelectCombobox({ options = [], value = [], onChange, placeholder: placeholderProp, searchPlaceholder: searchPlaceholderProp, emptyText, empty, className, disabled = false, maxDisplay, creatable = false, showSelectAll = false, selectAllText = "เลือกทั้งหมด", clearAllText = "ล้างการเลือก", showGroupHeaders = true, selectedGroupHeading = "รายการที่เลือก", unselectedGroupHeading = "ตัวเลือกทั้งหมด", modal, triggerRender, ariaLabel, wrapText = false, id, "aria-describedby": ariaDescribedBy, "aria-invalid": ariaInvalid, }: MultiSelectComboboxProps) { const text = useUiText(); const placeholder = placeholderProp ?? text.combobox?.placeholder ?? "เลือก..."; const searchPlaceholder = searchPlaceholderProp ?? text.combobox?.searchPlaceholder ?? "ค้นหา..."; const [open, setOpen] = React.useState(false); const [inputValue, setInputValue] = React.useState(""); // ค่าที่เลือกไว้ตอนเปิดรายการ — จัดกลุ่ม "ที่เลือก" จากค่านี้ระหว่างเปิด ติ๊ก/เอาออกแล้วตัวเลือกไม่กระโดดย้ายกลุ่มใต้เมาส์ const [pinnedValues, setPinnedValues] = React.useState(value); const handleOpenChange = (next: boolean) => { if (next) setPinnedValues(value); setOpen(next); }; const valueSet = new Set(value); const handleToggle = (optionValue: string) => { if (value.includes(optionValue)) { onChange(value.filter((v) => v !== optionValue)); } else { onChange([...value, optionValue]); } }; const handleRemove = (valueToRemove: string, e?: React.MouseEvent | React.KeyboardEvent) => { e?.stopPropagation(); onChange(value.filter((v) => v !== valueToRemove)); }; const handleClearAll = (e: React.MouseEvent) => { e.stopPropagation(); onChange([]); }; const handleSelectAll = () => { const allSelectableValues = options.filter((o) => !o.disabled).map((o) => o.value); const combined = Array.from(new Set([...value, ...allSelectableValues])); onChange(combined); }; const handleCreate = () => { const trimmed = inputValue.trim(); if (!trimmed) return; if (!value.includes(trimmed)) { onChange([...value, trimmed]); } setInputValue(""); }; const getLabel = (val: string) => { return options.find((o) => o.value === val)?.label || val; }; // Split and order options: Selected items ALWAYS appear first at the top const groupBy = open ? pinnedValues : value; const { selectedOptions, unselectedOptions } = React.useMemo(() => { const knownSelected: MultiSelectOption[] = []; const unselected: MultiSelectOption[] = []; const groupSet = new Set(groupBy); for (const option of options) { if (groupSet.has(option.value)) { knownSelected.push(option); } else { unselected.push(option); } } // Include values that might not be in options (e.g. custom or external IDs) const optionsValueSet = new Set(options.map((o) => o.value)); // รวมค่าที่สร้างใหม่ระหว่างเปิด (creatable) ด้วย ไม่งั้นหายจากรายการจนปิด const unknownSelected: MultiSelectOption[] = Array.from(new Set([...groupBy, ...value])) .filter((val) => !optionsValueSet.has(val)) .map((val) => ({ label: val, value: val })); return { selectedOptions: [...knownSelected, ...unknownSelected], unselectedOptions: unselected, }; }, [options, value, groupBy]); const displayedValues = typeof maxDisplay === "number" && maxDisplay > 0 ? value.slice(0, maxDisplay) : value; const remainingCount = value.length - displayedValues.length; const canCreate = creatable && inputValue.trim().length > 0 && !options.some( (o) => o.label.toLowerCase() === inputValue.trim().toLowerCase() || o.value.toLowerCase() === inputValue.trim().toLowerCase(), ); const defaultTrigger = ( {value.length > 0 && ( )} )} {empty ?? emptyText ?? text.combobox?.empty ?? "ไม่พบผลลัพธ์"} {/* 1. รายการที่ถูกเลือกจะแสดงอยู่บนสุดเสมอ (Selected items always at the top) */} {selectedOptions.length > 0 && ( {selectedOptions.map((option) => ( handleToggle(option.value)} disabled={option.disabled} className="flex cursor-pointer items-center justify-between gap-2 aria-selected:bg-accent" >
{option.label}
{option.description && ( {option.description} )}
))}
)} {selectedOptions.length > 0 && unselectedOptions.length > 0 && ( )} {/* 2. รายการตัวเลือกที่ยังไม่ได้เลือก (Unselected items) */} {unselectedOptions.length > 0 && ( 0 ? unselectedGroupHeading : undefined } > {unselectedOptions.map((option) => ( handleToggle(option.value)} disabled={option.disabled} className="flex cursor-pointer items-center justify-between gap-2" >
{option.label}
{option.description && ( {option.description} )}
))}
)} {/* 3. Creatable Option */} {canCreate && ( <> {(text.combobox?.add ?? "เพิ่ม “{value}”").replace("{value}", inputValue)} )}
); } /** ช่องติ๊กของแถว — ตามค่าที่เลือกจริง (กลุ่มของแถวตรึงไว้ตอนเปิด จึงอยู่กลุ่มไหนก็ติ๊ก/ไม่ติ๊กได้) */ function CheckMark({ checked }: { checked: boolean }) { return checked ? (
) : (
); }