import React, {useEffect, useId, useRef, useState} from 'react'; import {Icon} from './Icon'; import {IconButton} from './Button'; import {Loader} from './Feedback'; /* * The search box, with optional grouped suggestions. * * Replaces Semantic's ``, and deliberately keeps its `results` * shape — `{groupKey: {name, results: [{title, description}]}}` — because four * call sites already build that structure from the API. * * Suggestions are a combobox: the input keeps focus and owns the keyboard, while * `aria-activedescendant` points at the highlighted option. Arrow keys move, * Enter takes the highlighted suggestion or submits what was typed, Escape * closes the list without clearing the text. */ export interface SearchResult { /** The value put into the input when chosen. Also the visible first line. */ title: string; /** Second line, for context: a channel name, a domain. */ description?: string; [key: string]: any; } export interface SearchResultGroup { /** Group heading. */ name: string; results: SearchResult[]; } export type SearchResults = Record; export interface SearchBoxProps { value?: string; onChange?: (value: string) => void; /** Enter, or the search button. Receives the current text. */ onSubmit?: (value: string) => void; /** Called with the chosen suggestion. */ onResultSelect?: (result: SearchResult) => void; onBlur?: React.FocusEventHandler; results?: SearchResults; /** Suggestions are being fetched; shows a spinner rather than "no results". */ loading?: boolean; placeholder?: string; /** Show a button that empties the input. */ clearable?: boolean; /** Force the clear button's disabled state; defaults to "nothing typed". */ clearDisabled?: boolean | null; onClear?: () => void; disabled?: boolean; required?: boolean; inputRef?: React.Ref; /** Accessible name. Falls back to the placeholder. */ label?: string; className?: string; autoFocus?: boolean; name?: string; } /** Flatten the groups into the order they are displayed, for keyboard movement. */ const flatten = (results?: SearchResults): SearchResult[] => Object.values(results ?? {}).flatMap(group => group?.results ?? []); export function SearchBox({ value, onChange, onSubmit, onResultSelect, onBlur, results, loading, placeholder = 'Search...', clearable, clearDisabled = null, onClear, disabled, required, inputRef, label, className, autoFocus, name, }: SearchBoxProps) { const [open, setOpen] = useState(false); const [highlighted, setHighlighted] = useState(-1); const containerRef = useRef(null); const listId = useId(); const text = value ?? ''; const flat = flatten(results); const hasSuggestions = onResultSelect !== undefined || !!results; // Close when focus or a click leaves the box entirely. A blur handler alone would // fire before a click on a suggestion registers. useEffect(() => { if (!open) return; const onDocumentClick = (event: MouseEvent) => { if (!containerRef.current?.contains(event.target as Node)) setOpen(false); }; document.addEventListener('mousedown', onDocumentClick); return () => document.removeEventListener('mousedown', onDocumentClick); }, [open]); const choose = (result: SearchResult) => { setOpen(false); setHighlighted(-1); onResultSelect?.(result); } const handleChange = (event: React.ChangeEvent) => { setHighlighted(-1); if (hasSuggestions) setOpen(true); onChange?.(event.currentTarget.value); } const handleKeyDown = (event: React.KeyboardEvent) => { if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { if (!flat.length) return; event.preventDefault(); setOpen(true); const step = event.key === 'ArrowDown' ? 1 : -1; setHighlighted(current => { // Wrap, so holding a key cannot strand the user at either end. const next = current + step; if (next < 0) return flat.length - 1; if (next >= flat.length) return 0; return next; }); } else if (event.key === 'Enter') { event.preventDefault(); if (open && highlighted >= 0 && flat[highlighted]) { choose(flat[highlighted]); } else { setOpen(false); onSubmit?.(text); } } else if (event.key === 'Escape') { // Closes the list; the typed text is left alone. setOpen(false); setHighlighted(-1); } } const handleClear = () => { onChange?.(''); onSubmit?.(''); onClear?.(); setOpen(false); } let index = -1; return
hasSuggestions && (flat.length > 0 || loading) && setOpen(true)} onBlur={onBlur} role={hasSuggestions ? 'combobox' : undefined} aria-expanded={hasSuggestions ? open : undefined} aria-controls={hasSuggestions ? listId : undefined} aria-autocomplete={hasSuggestions ? 'list' : undefined} aria-activedescendant={open && highlighted >= 0 ? `${listId}-${highlighted}` : undefined} /> {loading && } {clearable && }
{open && hasSuggestions &&
{loading && !flat.length &&
Searching…
} {!loading && !flat.length &&
No results
} {Object.entries(results ?? {}).map(([key, group]) => { if (!group?.results?.length) return null; return
{group.name}
{group.results.map((result, resultIndex) => { index += 1; const optionIndex = index; return
{ event.preventDefault(); choose(result); }} onMouseEnter={() => setHighlighted(optionIndex)} >
{result.title}
{result.description &&
{result.description}
}
})}
})}
}
}