118 lines
4.5 KiB
TypeScript
118 lines
4.5 KiB
TypeScript
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 (
|
||
<Popover open={open} onOpenChange={(v) => !disabled && setOpen(v)}>
|
||
<PopoverTrigger asChild>
|
||
<div
|
||
id={id}
|
||
role="combobox"
|
||
tabIndex={disabled ? -1 : 0}
|
||
aria-expanded={open}
|
||
aria-disabled={disabled}
|
||
aria-label={ariaLabel ?? placeholder}
|
||
aria-invalid={invalid}
|
||
onKeyDown={(e) => {
|
||
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,
|
||
)}
|
||
>
|
||
<span className={cn("min-w-0 flex-1 truncate", !value && "text-muted-foreground")}>{value || placeholder}</span>
|
||
{value && !disabled && (
|
||
<button
|
||
type="button"
|
||
aria-label="Очистить"
|
||
onClick={(e) => {
|
||
e.stopPropagation()
|
||
onChange("")
|
||
}}
|
||
className="grid size-5 place-items-center rounded text-muted-foreground hover:bg-muted hover:text-foreground"
|
||
>
|
||
<XIcon className="size-3.5" />
|
||
</button>
|
||
)}
|
||
<ChevronDownIcon className={cn("size-4 shrink-0 text-muted-foreground transition", open && "rotate-180")} />
|
||
</div>
|
||
</PopoverTrigger>
|
||
<PopoverContent align="start" className="w-(--radix-popover-trigger-width) min-w-56 p-0">
|
||
<Command shouldFilter={false}>
|
||
<CommandInput placeholder={searchPlaceholder} value={search} onValueChange={setSearch} />
|
||
<CommandList>
|
||
{!canCreate && !filtered.length && <CommandEmpty>Ничего не найдено</CommandEmpty>}
|
||
<CommandGroup>
|
||
{filtered.map((o) => (
|
||
<CommandItem key={o} value={o} onSelect={() => pick(o)}>
|
||
<CheckIcon className={cn("size-4", o === value ? "text-primary" : "invisible")} />
|
||
{o}
|
||
</CommandItem>
|
||
))}
|
||
{canCreate && (
|
||
<CommandItem value={`__create ${custom}`} onSelect={() => pick(custom)}>
|
||
<PlusIcon className="size-4 text-primary" />
|
||
Указать «{custom}»
|
||
</CommandItem>
|
||
)}
|
||
</CommandGroup>
|
||
</CommandList>
|
||
</Command>
|
||
</PopoverContent>
|
||
</Popover>
|
||
)
|
||
}
|