import * as React from "react" import { Command as CommandPrimitive } from "cmdk" import { CheckIcon, SearchIcon, XIcon } from "lucide-react" import { cn } from "../lib/utils" import { CommandGroup, CommandItem, CommandList } from "../ui/command" import { InputGroup, InputGroupAddon } from "../ui/input-group" import { Popover, PopoverAnchor, PopoverContent } from "../ui/popover" import { Spinner } from "../ui/spinner" const norm = (v: string) => v.toLowerCase().replace(/ё/g, "е") /** * Поиск с подсказками: печатают прямо в поле, варианты — списком под ним (как MUI Autocomplete). * Значение — сам объект. Без `onSearchChange` фильтрует `options` по `getLabel`; * с ним — ищет сервер: текст уходит в `onSearchChange` через `searchDelay` мс, `options` и `loading` — от запроса. */ export function Autocomplete({ options, value, onChange, getKey, getLabel, renderOption, onSearchChange, searchDelay = 300, minSearchLength = 0, loading = false, emptyText = "Ничего не найдено", hint, placeholder, autoFocus, disabled, invalid, id, className, "aria-label": ariaLabel, }: { options: readonly T[] value: T | null onChange: (value: T | null) => void getKey: (option: T) => string | number /** Текст в поле после выбора; по нему же фильтруются варианты без `onSearchChange`. */ getLabel: (option: T) => string /** Строка списка; по умолчанию — `getLabel`. */ renderOption?: (option: T) => React.ReactNode /** Задан — варианты ищет сервер, сами не фильтруем. */ onSearchChange?: (search: string) => void searchDelay?: number /** Пока текст короче — список не ищется, показывается `hint` (только с `onSearchChange`). */ minSearchLength?: number loading?: boolean emptyText?: React.ReactNode hint?: React.ReactNode placeholder?: string autoFocus?: boolean disabled?: boolean invalid?: boolean id?: string className?: string "aria-label"?: string }) { const anchorRef = React.useRef(null) const inputRef = React.useRef(null) const [open, setOpen] = React.useState(false) const [text, setText] = React.useState(value ? getLabel(value) : "") // null — пользователь не печатает (после выбора или ухода из поля): показываем все варианты const [query, setQuery] = React.useState(null) const [active, setActive] = React.useState("") // значение сменили снаружи (сброс формы) — показываем его подпись const valueKey = value == null ? null : getKey(value) const [shownKey, setShownKey] = React.useState(valueKey) if (shownKey !== valueKey) { setShownKey(valueKey) setText(value ? getLabel(value) : "") setQuery(null) } const onSearchRef = React.useRef(onSearchChange) React.useLayoutEffect(() => { onSearchRef.current = onSearchChange }) const server = !!onSearchChange React.useEffect(() => { if (query === null || !onSearchRef.current) return const timer = setTimeout(() => onSearchRef.current?.(query.trim()), searchDelay) return () => clearTimeout(timer) }, [query, searchDelay]) const search = (query ?? "").trim() const items = server || !search ? options : options.filter((o) => norm(getLabel(o)).includes(norm(search))) const tooShort = server && search.length < minSearchLength const keys = items.map((o) => String(getKey(o))) // подсвеченный вариант — всегда из текущего списка: Enter берёт первый const activeKey = keys.includes(active) ? active : (keys[0] ?? "") // вариант выбран и пользователь ещё не печатает — подсказка «от N символов» не нужна const hasContent = tooShort ? !!hint && !(query === null && value) : true const pick = (option: T) => { onChange(option) setText(getLabel(option)) setQuery(null) setOpen(false) } const restore = () => { setOpen(false) setQuery(null) setText(value ? getLabel(value) : "") } const isInside = (target: EventTarget | null) => !!target && !!anchorRef.current?.contains(target as Node) return ( !next && setOpen(false)}> { setText(next) setQuery(next) setOpen(true) if (!next && value) onChange(null) }} onFocus={() => setOpen(true)} onClick={() => setOpen(true)} onBlur={restore} onKeyDown={(e) => { if (!open && (e.key === "ArrowDown" || e.key === "ArrowUp")) setOpen(true) }} autoFocus={autoFocus} disabled={disabled} placeholder={placeholder} aria-label={ariaLabel ?? placeholder} aria-invalid={invalid} autoComplete="off" className="h-full min-w-0 flex-1 bg-transparent pr-2 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50" /> {(loading || (text && !disabled)) && ( {loading && } {text && !disabled && ( )} )} e.preventDefault()} onCloseAutoFocus={(e) => e.preventDefault()} onInteractOutside={(e) => isInside(e.target) && e.preventDefault()} onFocusOutside={(e) => isInside(e.target) && e.preventDefault()} // клик по варианту не должен уводить фокус из поля (иначе blur закроет список до выбора) onMouseDown={(e) => e.preventDefault()} > {tooShort ? (
{hint}
) : !items.length ? (
{loading ? "Поиск…" : emptyText}
) : ( {items.map((o, i) => { const selected = valueKey !== null && getKey(o) === valueKey return ( pick(o)}>
{renderOption ? renderOption(o) : getLabel(o)}
) })}
)}
) }