import * as React from "react"; import { Check, ChevronsUpDown } from "lucide-react"; import { cn } from "@/lib/utils"; import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, } from "@/Components/ui/command"; import { Popover, PopoverContent, PopoverTrigger, } from "@/Components/ui/popover"; interface Option { label: string; value: string; sublabel?: string; disabled?: boolean; } interface SearchableSelectProps { value: string; onValueChange: (value: string) => void; options: Option[]; placeholder?: string; searchPlaceholder?: string; emptyText?: string; disabled?: boolean; className?: string; /** 當選項數量超過此閾值時顯示搜尋框,預設為 10。若設為 0 則總是顯示。 */ searchThreshold?: number; /** 強制控制是否顯示搜尋框。若設定此值,則忽略 searchThreshold */ showSearch?: boolean; } export function SearchableSelect({ value, onValueChange, options, placeholder = "請選擇...", searchPlaceholder = "搜尋...", emptyText = "找不到符合的項目", disabled = false, className, searchThreshold = 10, showSearch, }: SearchableSelectProps) { const [open, setOpen] = React.useState(false); // 決定是否顯示搜尋框 const shouldShowSearch = showSearch !== undefined ? showSearch : options.length > searchThreshold; const selectedOption = options.find((option) => option.value === value); return ( {shouldShowSearch && ( )} {emptyText} {options.map((option) => ( { onValueChange(option.value); setOpen(false); }} disabled={option.disabled} className="cursor-pointer" >
{option.label} {option.sublabel && ( {option.sublabel} )}
))}
); }