import { useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode, } from "react"; import clsx from "clsx"; import { Icon, type IconName } from "./icons"; import { Popup } from "./Popup"; import { List, listNavigate } from "./List"; import { tx, useGivenTx } from "@/platform/i18n"; import { SearchField } from "./Input"; import styles from "./Select.module.css"; export interface SelectOption { value: V; label: string; /** User values are displayed as written. */ verbatim?: boolean; icon?: IconName | (string & {}); detail?: string; /** Extra text (not shown) that the search should also match. */ keywords?: string; disabled?: boolean; /** A non-selectable group heading, independent of disabled options. */ section?: boolean; /** Tree row: indented by `depth`; `expanded` (when set) draws a disclosure chevron. */ tree?: { depth: number; expanded?: boolean }; } export interface SelectProps { id?: string; value: V | null; options: readonly SelectOption[]; onChange: (value: V) => void; placeholder?: string; disabled?: boolean; /** `ghost` renders as plain text + chevron (title bar widgets); `chip` as a chip that opens. */ variant?: "framed" | "ghost" | "chip"; className?: string; title?: string; "aria-label"?: string; "aria-description"?: string; /** Custom trigger content. */ renderValue?: (option: SelectOption | undefined) => ReactNode; /** Show a search box in the popup (useful for long option lists); typing on the closed trigger opens it with that text. */ searchable?: boolean; /** The option under the pointer or keyboard while the list is open; `null` once it closes. */ onPreview?: (value: V | null) => void; /** Choosing an option this returns `true` for keeps the popup open (e.g. expanding a tree row). */ keepOpen?: (value: V) => boolean; } const TYPE_AHEAD_MS = 800; /** Substring or subsequence (fuzzy) match. */ function containsOrFuzzy(haystack: string, needle: string): boolean { if (haystack.includes(needle)) return true; let i = 0; for (const ch of haystack) { if (ch === needle[i]) i++; if (i >= needle.length) return true; } return false; } export interface SelectListboxProps { value: V | null; options: readonly SelectOption[]; /** Called with the chosen option; closing, if any, is the caller's. */ onChoose: (value: V) => void; searchable?: boolean; /** Search text the list opens with. */ initialQuery?: string; onPreview?: (value: V | null) => void; /** Optional trailing action control rendered at the end of a non-section row. */ renderAction?: (option: SelectOption) => ReactNode; /** Extra class for the scrolling list, e.g. to set its height. */ listClassName?: string; "aria-label"?: string; } /** The searchable listbox of a {@link Select}, for a popup that shows it without a trigger button. */ export function SelectListbox({ value, options, onChoose, searchable = false, initialQuery = "", onPreview, renderAction, listClassName, ...aria }: SelectListboxProps) { const given = useGivenTx(); const labelOf = (o: SelectOption) => (o.verbatim ? o.label : given(o.label)); const [active, setActive] = useState(() => Math.max( 0, options.findIndex((o) => !o.section && !o.disabled && o.value === value), ), ); const [query, setQuery] = useState(initialQuery); const caretPlaced = useRef(false); const typeAhead = useRef({ text: "", at: -Infinity }); const isSection = (o: SelectOption) => !!o.section; const unavailable = (o: SelectOption) => !!(o.section || o.disabled); const filtered = searchable && query.trim() ? (() => { const q = query.trim().toLowerCase(); const tokens = q.split(/\s+/).filter(Boolean); const matches = (o: SelectOption) => { const haystack = `${labelOf(o)} ${o.detail != null ? given(o.detail) : ""} ${o.keywords ?? ""}`.toLowerCase(); return tokens.every((tok) => containsOrFuzzy(haystack, tok)); }; // Keep section headers visible as long as at least one of their // items matches, so the provider grouping survives filtering. const out: SelectOption[] = []; let section: SelectOption | null = null; let bucket: SelectOption[] = []; let sectionMatched = false; const flush = () => { if (section && sectionMatched) { out.push(section, ...bucket); } else if (!section && bucket.length) { out.push(...bucket); } section = null; bucket = []; sectionMatched = false; }; for (const o of options) { if (o.section) { flush(); section = o; } else if (matches(o)) { bucket.push(o); sectionMatched = true; } } flush(); return out; })() : options; const activeIndex = filtered[active] && !unavailable(filtered[active]!) ? active : filtered.findIndex((o) => !unavailable(o)); const previewed = filtered[activeIndex]?.value ?? null; const lastPreview = useRef(null); const previewRef = useRef(onPreview); useLayoutEffect(() => { previewRef.current = onPreview; }); useEffect(() => { if (previewed === lastPreview.current) return; lastPreview.current = previewed; onPreview?.(previewed); }, [previewed, onPreview]); // The list is only mounted while open: closing it ends the preview. useEffect( () => () => { if (lastPreview.current !== null) previewRef.current?.(null); lastPreview.current = null; }, [], ); const choose = (o: SelectOption | undefined) => { if (!o || unavailable(o)) return; onChoose(o.value); }; const onPopupKey = (e: KeyboardEvent) => { const searching = searchable && e.target instanceof HTMLInputElement; if (e.key === "Enter" || (e.key === " " && !searching)) { e.preventDefault(); choose(filtered[activeIndex]); return; } if (searching && !["ArrowDown", "ArrowUp"].includes(e.key)) return; const next = listNavigate(e.key, { items: filtered, active: activeIndex, isSection: unavailable, wrap: true, }); if (next !== null) { e.preventDefault(); setActive(next); return; } if (e.key.length === 1 && !e.metaKey && !e.ctrlKey) { // Keys typed in quick succession extend the prefix ("me" → Menlo); a lone key cycles. const ahead = typeAhead.current; ahead.text = e.timeStamp - ahead.at < TYPE_AHEAD_MS ? ahead.text + e.key.toLowerCase() : e.key.toLowerCase(); ahead.at = e.timeStamp; const repeat = ahead.text.length > 1 && [...ahead.text].every((c) => c === ahead.text[0]); const prefix = repeat ? ahead.text[0]! : ahead.text; const n = filtered.length; for (let s = prefix.length > 1 ? 0 : 1; s <= n; s++) { const i = (activeIndex + s) % n; if (!unavailable(filtered[i]!) && labelOf(filtered[i]!).toLowerCase().startsWith(prefix)) { setActive(i); break; } } } }; return (
{searchable && (
{ // Keep typing after the text that opened the list instead of before it. if (caretPlaced.current) return; caretPlaced.current = true; const end = e.currentTarget.value.length; e.currentTarget.setSelectionRange(end, end); }} placeholder={tx("Search…")} onChange={(v) => { setQuery(v); setActive(-1); }} size="normal" variant="framed" className={styles.search} />
)} {/* Virtualised rows are absolutely positioned; this sizes the popup to the widest label. */}
{options.map((o) => (
{o.tree && } {o.icon && } {labelOf(o)} {o.detail && {given(o.detail)}}
))}
`${o.section ? "section" : "option"}:${o.value}`} isSection={isSection} renderSection={(o) => {labelOf(o)}} activeIndex={activeIndex} onActiveChange={(i) => { if (!unavailable(filtered[i]!)) setActive(i); }} onActivate={(o) => choose(o)} focusable={false} hoverSelects aria-label={given(aria["aria-label"])} className={clsx(styles.list, listClassName)} renderItem={(o) => { const action = !o.section && !o.disabled ? renderAction?.(o) : null; return ( {o.value === value && } {o.tree && } {o.icon && } {labelOf(o)} {o.detail && ( {given(o.detail)} )} {action && ( e.stopPropagation()} onClick={(e) => e.stopPropagation()} onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") e.stopPropagation(); }} > {action} )} ); }} />
); } function TreeIndent({ depth, expanded }: { depth: number; expanded?: boolean }) { return ( {expanded !== undefined && } ); } /** Dropdown select with a listbox popup (↑↓ Enter Esc, type-ahead). */ export function Select({ value, options, onChange, placeholder = "Select…", disabled, variant = "framed", className, title, renderValue, searchable = false, onPreview, keepOpen, ...aria }: SelectProps) { const given = useGivenTx(); const [open, setOpen] = useState(false); const [initialQuery, setInitialQuery] = useState(""); const triggerRef = useRef(null); const current = options.find((o) => !o.section && o.value === value); const openPopup = (query = "") => { setInitialQuery(query); setOpen(true); }; // Selection can update the callback as the list unmounts; use the committed trigger props. const previewRef = useRef(onPreview); useLayoutEffect(() => { previewRef.current = onPreview; }); const preview = useCallback((next: V | null) => previewRef.current?.(next), []); return ( <> setOpen(false)} anchor={triggerRef} matchWidth role="presentation" className={styles.popup} > { onChange(v); if (!keepOpen?.(v)) setOpen(false); }} /> ); }