119 lines
5.9 KiB
TypeScript
119 lines
5.9 KiB
TypeScript
import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
|
|
import { Check, ChevronDown } from "lucide-preact";
|
|
import { cn } from "@/lib/utils";
|
|
|
|
type ModelComboboxProps = {
|
|
options: string[];
|
|
value: string;
|
|
onChange: (value: string) => void;
|
|
disabled?: boolean;
|
|
className?: string;
|
|
id?: string;
|
|
label?: string;
|
|
inlineOptions?: boolean;
|
|
};
|
|
|
|
export function ModelCombobox({ options, value, onChange, disabled = false, className, id, label = "Model", inlineOptions = false }: ModelComboboxProps) {
|
|
const generatedId = useId();
|
|
const fieldId = id || generatedId;
|
|
const [open, setOpen] = useState(false);
|
|
const [draftValue, setDraftValue] = useState(value);
|
|
const [activeIndex, setActiveIndex] = useState(-1);
|
|
const rootRef = useRef<HTMLDivElement>(null);
|
|
const inputRef = useRef<HTMLInputElement>(null);
|
|
const normalizedDraftValue = draftValue.trim();
|
|
const choices = useMemo(() => {
|
|
const needle = normalizedDraftValue.toLowerCase();
|
|
const listed = options.filter(option => !needle || option.toLowerCase().includes(needle)).map(option => ({ value: option, label: option }));
|
|
return normalizedDraftValue && !options.includes(normalizedDraftValue)
|
|
? [{ value: normalizedDraftValue, label: `Use "${normalizedDraftValue}"` }, ...listed] : listed;
|
|
}, [normalizedDraftValue, options]);
|
|
|
|
useLayoutEffect(() => { if (!open) setDraftValue(value); }, [open, value]);
|
|
useLayoutEffect(() => {
|
|
if (open) inputRef.current?.focus();
|
|
}, [open]);
|
|
useEffect(() => {
|
|
if (activeIndex >= 0) document.getElementById(`${fieldId}-option-${activeIndex}`)?.scrollIntoView({ block: "nearest" });
|
|
}, [activeIndex, fieldId]);
|
|
|
|
const commit = (next = normalizedDraftValue) => {
|
|
if (next !== value) onChange(next);
|
|
setDraftValue(next);
|
|
setActiveIndex(-1);
|
|
setOpen(false);
|
|
};
|
|
|
|
useEffect(() => {
|
|
if (!open) return;
|
|
const handlePointerDown = (event: PointerEvent) => {
|
|
if (!rootRef.current?.contains(event.target as Node)) commit();
|
|
};
|
|
window.addEventListener("pointerdown", handlePointerDown);
|
|
return () => window.removeEventListener("pointerdown", handlePointerDown);
|
|
}, [open, normalizedDraftValue, value, onChange]);
|
|
|
|
return <div className="relative min-w-0" ref={rootRef} onFocusOut={(event) => {
|
|
if (open && !rootRef.current?.contains(event.relatedTarget as Node | null)) commit();
|
|
}} onKeyDown={(event) => {
|
|
if (event.key === "Escape" && open) {
|
|
event.preventDefault();
|
|
event.stopPropagation();
|
|
setOpen(false);
|
|
setDraftValue(value);
|
|
inputRef.current?.focus();
|
|
}
|
|
}}>
|
|
<div className={cn("flex h-10 min-w-56 items-center rounded-lg border border-violet-300/22 bg-background/72 pl-3 text-sm shadow-[inset_0_1px_0_hsl(255_100%_92%_/_0.06)] focus-within:border-violet-300/45 focus-within:ring-1 focus-within:ring-ring/70", className)}>
|
|
<input
|
|
ref={inputRef}
|
|
id={fieldId}
|
|
role="combobox"
|
|
aria-label={label}
|
|
aria-autocomplete="list"
|
|
aria-expanded={open}
|
|
aria-controls={`${fieldId}-options`}
|
|
aria-activedescendant={open && activeIndex >= 0 && choices[activeIndex] ? `${fieldId}-option-${activeIndex}` : undefined}
|
|
value={draftValue}
|
|
onFocus={() => { if (!disabled) { setDraftValue(value); setActiveIndex(-1); setOpen(true); } }}
|
|
onInput={(event) => { setDraftValue(event.currentTarget.value); setActiveIndex(-1); setOpen(true); }}
|
|
onKeyDown={(event) => {
|
|
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
|
event.preventDefault();
|
|
setOpen(true);
|
|
setActiveIndex(current => {
|
|
if (!choices.length) return -1;
|
|
if (current < 0) return event.key === "ArrowDown" ? 0 : choices.length - 1;
|
|
return (current + (event.key === "ArrowDown" ? 1 : -1) + choices.length) % choices.length;
|
|
});
|
|
} else if (event.key === "Enter") {
|
|
event.preventDefault();
|
|
commit(open && choices[activeIndex] ? choices[activeIndex].value : normalizedDraftValue);
|
|
}
|
|
}}
|
|
className="h-full min-w-0 flex-1 bg-transparent outline-none placeholder:text-muted-foreground"
|
|
placeholder="Select or type model"
|
|
disabled={disabled}
|
|
/>
|
|
<button type="button" className="flex h-full w-11 shrink-0 items-center justify-center text-muted-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring disabled:opacity-50"
|
|
onClick={() => { if (open) commit(); else { setDraftValue(value); setActiveIndex(-1); setOpen(true); } }} disabled={disabled}
|
|
aria-label={`Toggle ${label.toLowerCase()} options`} aria-expanded={open} aria-controls={`${fieldId}-options`} tabIndex={-1}>
|
|
<ChevronDown aria-hidden="true" className="h-4 w-4" />
|
|
</button>
|
|
</div>
|
|
{open ? <div className={cn("z-50 mt-2 w-full rounded-lg border border-violet-300/20 bg-[hsl(238_48%_7%)] p-1 shadow-2xl shadow-black/45", !inlineOptions && "absolute right-0")}>
|
|
<div id={`${fieldId}-options`} role="listbox" aria-label={`${label} options`} className="max-h-56 overflow-y-auto overscroll-contain">
|
|
{choices.map((option, index) => <button key={option.value} id={`${fieldId}-option-${index}`} type="button" role="option" tabIndex={-1}
|
|
aria-selected={option.value === value}
|
|
className={cn("flex min-h-11 w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-violet-400/12", activeIndex === index && "bg-violet-400/12")}
|
|
onPointerDown={event => event.preventDefault()}
|
|
onClick={() => commit(option.value)}>
|
|
<Check aria-hidden="true" className={cn("h-4 w-4 shrink-0", option.value === value ? "opacity-100" : "opacity-0")} />
|
|
<span className="truncate">{option.label}</span>
|
|
</button>)}
|
|
{!choices.length ? <p className="px-2 py-2 text-sm text-muted-foreground">No models found</p> : null}
|
|
</div>
|
|
</div> : null}
|
|
</div>;
|
|
}
|