({ open, onClose }: SearchDialogProps)
| 43 | }; |
| 44 | |
| 45 | export const SearchDialog = ({ open, onClose }: SearchDialogProps) => { |
| 46 | const inputId = useId(); |
| 47 | const resultsId = useId(); |
| 48 | const statusId = useId(); |
| 49 | const [query, setQuery] = useState(''); |
| 50 | const [results, setResults] = useState<SearchResult[]>([]); |
| 51 | const [loading, setLoading] = useState(false); |
| 52 | const trimmedQuery = query.trim(); |
| 53 | const statusMessage = |
| 54 | trimmedQuery.length < 2 |
| 55 | ? 'Search by page title, heading, or text.' |
| 56 | : loading |
| 57 | ? 'Searching...' |
| 58 | : results.length === 0 |
| 59 | ? 'No results found.' |
| 60 | : undefined; |
| 61 | |
| 62 | useEffect(() => { |
| 63 | if (!open) return; |
| 64 | if (trimmedQuery.length < 2) { |
| 65 | setResults([]); |
| 66 | setLoading(false); |
| 67 | return; |
| 68 | } |
| 69 | |
| 70 | const controller = new AbortController(); |
| 71 | setLoading(true); |
| 72 | const timeout = window.setTimeout(() => { |
| 73 | void fetch(`/docs/search?query=${encodeURIComponent(trimmedQuery)}`, { |
| 74 | signal: controller.signal, |
| 75 | }) |
| 76 | .then((response) => { |
| 77 | if (!response.ok) throw new Error('Search request failed'); |
| 78 | return response.json() as Promise<SearchResult[]>; |
| 79 | }) |
| 80 | .then((data) => { |
| 81 | setResults(data); |
| 82 | }) |
| 83 | .catch((error: unknown) => { |
| 84 | if (!(error instanceof DOMException && error.name === 'AbortError')) { |
| 85 | setResults([]); |
| 86 | } |
| 87 | }) |
| 88 | .finally(() => { |
| 89 | if (!controller.signal.aborted) { |
| 90 | setLoading(false); |
| 91 | } |
| 92 | }); |
| 93 | }, 180); |
| 94 | |
| 95 | return () => { |
| 96 | controller.abort(); |
| 97 | window.clearTimeout(timeout); |
| 98 | }; |
| 99 | }, [open, trimmedQuery]); |
| 100 | |
| 101 | return ( |
| 102 | <Modal |
nothing calls this directly
no test coverage detected