medkit/src/kit/autocomplete.tsx

249 lines
9.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<T>({
options,
value,
onChange,
getKey,
getLabel,
renderOption,
renderValue,
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
/** Расширенное представление выбранного значения внутри поля. */
renderValue?: (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<HTMLDivElement>(null)
const inputRef = React.useRef<HTMLInputElement>(null)
const [open, setOpen] = React.useState(false)
const [text, setText] = React.useState(value ? getLabel(value) : "")
// null — пользователь не печатает (после выбора или ухода из поля): показываем все варианты
const [query, setQuery] = React.useState<string | null>(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 richValue = value && query === null && renderValue ? renderValue(value) : null
const pick = (option: T) => {
onChange(option)
setText(getLabel(option))
setQuery(null)
setOpen(false)
}
const beginEdit = () => {
if (disabled) return
setQuery(text)
setOpen(true)
requestAnimationFrame(() => {
inputRef.current?.focus()
inputRef.current?.select()
})
}
const restore = () => {
setOpen(false)
setQuery(null)
setText(value ? getLabel(value) : "")
}
const isInside = (target: EventTarget | null) => !!target && !!anchorRef.current?.contains(target as Node)
return (
<CommandPrimitive
shouldFilter={false}
loop
value={activeKey}
onValueChange={setActive}
className={cn("w-full", className)}
>
<Popover open={open && hasContent && !disabled} onOpenChange={(next) => !next && setOpen(false)}>
<PopoverAnchor asChild>
<div ref={anchorRef} className="w-full">
<InputGroup
data-disabled={disabled || undefined}
className={cn(richValue && "h-auto min-h-12")}
>
{!richValue && <InputGroupAddon>
<SearchIcon />
</InputGroupAddon>}
{richValue && (
<button
type="button"
disabled={disabled}
aria-label={`Изменить: ${getLabel(value!)}`}
onClick={beginEdit}
className="min-w-0 flex-1 px-2.5 py-1.5 text-left disabled:cursor-not-allowed"
>
{richValue}
</button>
)}
<CommandPrimitive.Input
ref={inputRef}
id={id}
data-slot="input-group-control"
value={text}
onValueChange={(next) => {
setText(next)
setQuery(next)
setOpen(true)
if (!next && value) onChange(null)
}}
onFocus={() => {
if (richValue) setQuery(text)
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={cn(
"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",
richValue && "sr-only",
)}
/>
{(loading || (text && !disabled)) && (
<InputGroupAddon align="inline-end">
{loading && <Spinner />}
{text && !disabled && (
<button
type="button"
aria-label="Очистить"
tabIndex={-1}
onMouseDown={(e) => e.preventDefault()}
onClick={() => {
if (value) onChange(null)
setText("")
setQuery("")
setOpen(true)
inputRef.current?.focus()
}}
className="grid size-5 place-items-center rounded text-muted-foreground hover:bg-muted hover:text-foreground"
>
<XIcon className="size-3.5" />
</button>
)}
</InputGroupAddon>
)}
</InputGroup>
</div>
</PopoverAnchor>
<PopoverContent
align="start"
className="w-(--radix-popover-trigger-width) min-w-56 p-0"
onOpenAutoFocus={(e) => 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()}
>
<CommandList>
{tooShort ? (
<div className="px-3 py-4 text-center text-sm text-muted-foreground">{hint}</div>
) : !items.length ? (
<div className="px-3 py-4 text-center text-sm text-muted-foreground">{loading ? "Поиск…" : emptyText}</div>
) : (
<CommandGroup>
{items.map((o, i) => {
const selected = valueKey !== null && getKey(o) === valueKey
return (
<CommandItem key={keys[i]} value={keys[i]} onSelect={() => pick(o)}>
<CheckIcon className={cn("size-4", selected ? "text-primary" : "invisible")} />
<div className="min-w-0 flex-1">{renderOption ? renderOption(o) : getLabel(o)}</div>
</CommandItem>
)
})}
</CommandGroup>
)}
</CommandList>
</PopoverContent>
</Popover>
</CommandPrimitive>
)
}