Repository Public
1"use client";2import { useId, useMemo, useRef, useState } from "react";3import { useI18n } from "@/i18n";4import { cx } from "./cx";5import { Icon } from "./Icon";6import { Field } from "./form";78export interface ComboOption {9 value: string;10 label: string;11 hint?: string;12 keywords?: string;13}1415interface Base {16 label: string;17 hint?: string;18 error?: string | undefined;19 required?: boolean;20 options: readonly ComboOption[];21 placeholder?: string;22 hideLabel?: boolean;23 disabled?: boolean;24}25type Props =26 | (Base & { multiple?: false; value: string | null; onChange: (v: string | null) => void })27 | (Base & { multiple: true; value: readonly string[]; onChange: (v: string[]) => void });2829/** Editable combobox with list autocomplete (WAI-ARIA 1.2 pattern). `multiple` adds removable chips. */30export function Combobox(props: Props) {31 const { t } = useI18n();32 const { label, hint, error, required, options, placeholder, hideLabel, disabled } = props;33 const listId = useId();34 const [open, setOpen] = useState(false);35 const [text, setText] = useState("");36 const [active, setActive] = useState(0);37 const input = useRef<HTMLInputElement>(null);38 const selectedSet = useMemo(() => new Set(props.multiple ? props.value : props.value ? [props.value] : []), [props.multiple, props.value]);39 const current = !props.multiple && props.value ? options.find((o) => o.value === props.value) : undefined;40 const filtered = useMemo(() => {41 const q = text.trim().toLowerCase();42 const list = q ? options.filter((o) => `${o.label} ${o.value} ${o.keywords ?? ""}`.toLowerCase().includes(q)) : options;43 return list.slice(0, 200);44 }, [options, text]);4546 const pick = (o: ComboOption) => {47 if (props.multiple) {48 const next = new Set(props.value);49 if (next.has(o.value)) next.delete(o.value);50 else next.add(o.value);51 props.onChange([...next]);52 setText("");53 } else {54 props.onChange(o.value);55 setText("");56 setOpen(false);57 }58 };59 const activeId = open && filtered[active] ? `${listId}-o-${active}` : undefined;6061 return (62 <Field label={label} hint={hint} error={error} required={required ?? false} hideLabel={hideLabel ?? false}>63 {(a) => (64 <div className="stack-sm">65 {props.multiple && props.value.length > 0 ? (66 <ul className="mcc-chips" aria-label={t("ui.combobox.selected", { label })}>67 {props.value.map((v) => {68 const o = options.find((x) => x.value === v);69 return (70 <li key={v} className="mcc-chip">71 {o?.label ?? v}72 <button type="button" aria-label={t("ui.combobox.remove", { item: o?.label ?? v })} onClick={() => props.onChange(props.value.filter((x) => x !== v))} disabled={disabled}><Icon name="close" size={12} /></button>73 </li>74 );75 })}76 </ul>77 ) : null}78 <div className="mcc-pop-anchor" onBlur={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) { setOpen(false); setText(""); } }}>79 <input80 {...a}81 ref={input}82 className="mcc-input"83 role="combobox"84 aria-expanded={open}85 aria-controls={listId}86 aria-autocomplete="list"87 aria-activedescendant={activeId}88 autoComplete="off"89 disabled={disabled}90 placeholder={current ? current.label : (placeholder ?? t("ui.combobox.placeholder"))}91 value={open || props.multiple ? text : (current?.label ?? text)}92 onFocus={() => setOpen(true)}93 onClick={() => setOpen(true)}94 onChange={(e) => { setText(e.target.value); setOpen(true); setActive(0); if (!props.multiple && e.target.value === "" && props.value) props.onChange(null); }}95 onKeyDown={(e) => {96 if (e.key === "ArrowDown") { e.preventDefault(); setOpen(true); setActive((i) => Math.min(filtered.length - 1, i + 1)); }97 else if (e.key === "ArrowUp") { e.preventDefault(); setActive((i) => Math.max(0, i - 1)); }98 else if (e.key === "Enter" && open && filtered[active]) { e.preventDefault(); pick(filtered[active]); }99 else if (e.key === "Escape" && open) { e.preventDefault(); e.stopPropagation(); setOpen(false); setText(""); }100 else if (e.key === "Backspace" && props.multiple && text === "" && props.value.length > 0) props.onChange(props.value.slice(0, -1));101 }}102 />103 <ul id={listId} role="listbox" aria-label={label} aria-multiselectable={props.multiple || undefined} className="mcc-pop block" hidden={!open}>104 {filtered.length === 0 ? <li className="mcc-menu-label muted" role="presentation">{t("ui.combobox.none")}</li> : null}105 {filtered.map((o, i) => (106 <li key={o.value} id={`${listId}-o-${i}`} role="option" aria-selected={selectedSet.has(o.value)} data-active={i === active} className="mcc-option"107 onMouseDown={(e) => e.preventDefault()} onMouseEnter={() => setActive(i)} onClick={() => { pick(o); input.current?.focus(); }}>108 {props.multiple ? <Icon name={selectedSet.has(o.value) ? "check" : "plus"} size={13} /> : null}109 <span className={cx("truncate")}>{o.label}</span>110 {o.hint ? <span className="hint">{o.hint}</span> : null}111 </li>112 ))}113 </ul>114 </div>115 </div>116 )}117 </Field>118 );119}120