Add rich autocomplete values

This commit is contained in:
Ilya Mukhortov 2026-10-30 16:39:47 +10:00
parent 2386174d9a
commit 14e2806142
1 changed files with 88 additions and 52 deletions

View File

@ -22,6 +22,7 @@ export function Autocomplete<T>({
getKey, getKey,
getLabel, getLabel,
renderOption, renderOption,
renderValue,
onSearchChange, onSearchChange,
searchDelay = 300, searchDelay = 300,
minSearchLength = 0, minSearchLength = 0,
@ -44,6 +45,8 @@ export function Autocomplete<T>({
getLabel: (option: T) => string getLabel: (option: T) => string
/** Строка списка; по умолчанию — `getLabel`. */ /** Строка списка; по умолчанию — `getLabel`. */
renderOption?: (option: T) => React.ReactNode renderOption?: (option: T) => React.ReactNode
/** Расширенное представление выбранного значения внутри поля. */
renderValue?: (option: T) => React.ReactNode
/** Задан — варианты ищет сервер, сами не фильтруем. */ /** Задан — варианты ищет сервер, сами не фильтруем. */
onSearchChange?: (search: string) => void onSearchChange?: (search: string) => void
searchDelay?: number searchDelay?: number
@ -96,6 +99,7 @@ export function Autocomplete<T>({
const activeKey = keys.includes(active) ? active : (keys[0] ?? "") const activeKey = keys.includes(active) ? active : (keys[0] ?? "")
// вариант выбран и пользователь ещё не печатает — подсказка «от N символов» не нужна // вариант выбран и пользователь ещё не печатает — подсказка «от N символов» не нужна
const hasContent = tooShort ? !!hint && !(query === null && value) : true const hasContent = tooShort ? !!hint && !(query === null && value) : true
const richValue = value && query === null && renderValue ? renderValue(value) : null
const pick = (option: T) => { const pick = (option: T) => {
onChange(option) onChange(option)
@ -104,6 +108,16 @@ export function Autocomplete<T>({
setOpen(false) setOpen(false)
} }
const beginEdit = () => {
if (disabled) return
setQuery(text)
setOpen(true)
requestAnimationFrame(() => {
inputRef.current?.focus()
inputRef.current?.select()
})
}
const restore = () => { const restore = () => {
setOpen(false) setOpen(false)
setQuery(null) setQuery(null)
@ -122,59 +136,81 @@ export function Autocomplete<T>({
> >
<Popover open={open && hasContent && !disabled} onOpenChange={(next) => !next && setOpen(false)}> <Popover open={open && hasContent && !disabled} onOpenChange={(next) => !next && setOpen(false)}>
<PopoverAnchor asChild> <PopoverAnchor asChild>
<InputGroup ref={anchorRef} data-disabled={disabled || undefined}> <div ref={anchorRef} className="w-full">
<InputGroupAddon> <InputGroup
<SearchIcon /> data-disabled={disabled || undefined}
</InputGroupAddon> className={cn(richValue && "h-auto min-h-12 bg-primary/10 dark:bg-primary/10")}
<CommandPrimitive.Input >
ref={inputRef} {!richValue && <InputGroupAddon>
id={id} <SearchIcon />
data-slot="input-group-control" </InputGroupAddon>}
value={text} {richValue && (
onValueChange={(next) => { <button
setText(next) type="button"
setQuery(next) disabled={disabled}
setOpen(true) aria-label={`Изменить: ${getLabel(value!)}`}
if (!next && value) onChange(null) onClick={beginEdit}
}} className="min-w-0 flex-1 px-2.5 py-1.5 text-left disabled:cursor-not-allowed"
onFocus={() => setOpen(true)} >
onClick={() => setOpen(true)} {richValue}
onBlur={restore} </button>
onKeyDown={(e) => { )}
if (!open && (e.key === "ArrowDown" || e.key === "ArrowUp")) setOpen(true) <CommandPrimitive.Input
}} ref={inputRef}
autoFocus={autoFocus} id={id}
disabled={disabled} data-slot="input-group-control"
placeholder={placeholder} value={text}
aria-label={ariaLabel ?? placeholder} onValueChange={(next) => {
aria-invalid={invalid} setText(next)
autoComplete="off" setQuery(next)
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" setOpen(true)
/> if (!next && value) onChange(null)
{(loading || (text && !disabled)) && ( }}
<InputGroupAddon align="inline-end"> onFocus={() => {
{loading && <Spinner />} if (richValue) setQuery(text)
{text && !disabled && ( setOpen(true)
<button }}
type="button" onClick={() => setOpen(true)}
aria-label="Очистить" onBlur={restore}
tabIndex={-1} onKeyDown={(e) => {
onMouseDown={(e) => e.preventDefault()} if (!open && (e.key === "ArrowDown" || e.key === "ArrowUp")) setOpen(true)
onClick={() => { }}
if (value) onChange(null) autoFocus={autoFocus}
setText("") disabled={disabled}
setQuery("") placeholder={placeholder}
setOpen(true) aria-label={ariaLabel ?? placeholder}
inputRef.current?.focus() aria-invalid={invalid}
}} autoComplete="off"
className="grid size-5 place-items-center rounded text-muted-foreground hover:bg-muted hover:text-foreground" 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",
<XIcon className="size-3.5" /> richValue && "sr-only",
</button>
)} )}
</InputGroupAddon> />
)} {(loading || (text && !disabled)) && (
</InputGroup> <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> </PopoverAnchor>
<PopoverContent <PopoverContent
align="start" align="start"