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,10 +136,25 @@ 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
data-disabled={disabled || undefined}
className={cn(richValue && "h-auto min-h-12 bg-primary/10 dark:bg-primary/10")}
>
{!richValue && <InputGroupAddon>
<SearchIcon /> <SearchIcon />
</InputGroupAddon> </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 <CommandPrimitive.Input
ref={inputRef} ref={inputRef}
id={id} id={id}
@ -137,7 +166,10 @@ export function Autocomplete<T>({
setOpen(true) setOpen(true)
if (!next && value) onChange(null) if (!next && value) onChange(null)
}} }}
onFocus={() => setOpen(true)} onFocus={() => {
if (richValue) setQuery(text)
setOpen(true)
}}
onClick={() => setOpen(true)} onClick={() => setOpen(true)}
onBlur={restore} onBlur={restore}
onKeyDown={(e) => { onKeyDown={(e) => {
@ -149,7 +181,10 @@ export function Autocomplete<T>({
aria-label={ariaLabel ?? placeholder} aria-label={ariaLabel ?? placeholder}
aria-invalid={invalid} aria-invalid={invalid}
autoComplete="off" 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" 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)) && ( {(loading || (text && !disabled)) && (
<InputGroupAddon align="inline-end"> <InputGroupAddon align="inline-end">
@ -175,6 +210,7 @@ export function Autocomplete<T>({
</InputGroupAddon> </InputGroupAddon>
)} )}
</InputGroup> </InputGroup>
</div>
</PopoverAnchor> </PopoverAnchor>
<PopoverContent <PopoverContent
align="start" align="start"