import * as React from "react" import { CheckIcon, ChevronDownIcon, PlusIcon, XIcon } from "lucide-react" import { cn } from "../lib/utils" import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "../ui/command" import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover" /** * Одиночный выбор из справочника с поиском и очисткой (как tui-combo-box). * `creatable` — можно оставить своё значение, если в справочнике его нет. */ export function Combobox({ options, value, onChange, placeholder = "Выберите", searchPlaceholder = "Поиск…", creatable = false, disabled, id, className, "aria-label": ariaLabel, "aria-invalid": invalid, }: { options: readonly string[] value: string onChange: (value: string) => void placeholder?: string searchPlaceholder?: string creatable?: boolean disabled?: boolean id?: string className?: string "aria-label"?: string "aria-invalid"?: boolean }) { const [open, setOpen] = React.useState(false) const [search, setSearch] = React.useState("") const custom = search.trim() const norm = (v: string) => v.toLowerCase().replace(/ё/g, "е") // Фильтруем сами: так «Указать …» всегда последним, а Enter берёт первое совпадение из справочника. const filtered = custom ? options.filter((o) => norm(o).includes(norm(custom))) : options const canCreate = creatable && custom && !options.some((o) => norm(o) === norm(custom)) const pick = (next: string) => { onChange(next) setOpen(false) setSearch("") } return ( !disabled && setOpen(v)}>
{ if (e.key === "Enter" || e.key === " " || e.key === "ArrowDown") { e.preventDefault() setOpen(true) } }} className={cn( "flex h-9 w-full cursor-pointer items-center gap-1.5 rounded-md border border-input bg-transparent px-3 text-sm shadow-xs transition-[color,box-shadow] outline-none dark:bg-input/30", "focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive", "aria-disabled:cursor-not-allowed aria-disabled:opacity-50", open && "border-ring ring-[3px] ring-ring/50", className, )} > {value || placeholder} {value && !disabled && ( )}
{!canCreate && !filtered.length && Ничего не найдено} {filtered.map((o) => ( pick(o)}> {o} ))} {canCreate && ( pick(custom)}> Указать «{custom}» )}
) }