import { useCallback, useEffect, useRef } from 'react'; import { TYPEAHEAD_QUERY_RESET_TIMEOUT_MS } from '../constants'; import { searchableString } from '../SelectInput.utils'; const resetsTypeaheadQuery = (key: string) => key === 'ArrowDown' || key === 'ArrowUp' || key === 'Home' || key === 'End' || key === 'PageDown' || key === 'PageUp'; export const isTypingKey = (event: React.KeyboardEvent, query = '') => !event.metaKey && !event.ctrlKey && !event.nativeEvent.isComposing && /^.$/u.test(event.key) && (event.key !== ' ' || query !== ''); interface UseTypeaheadParams { disabled?: boolean; onMatch?: () => void; } export function useTypeahead({ disabled = false, onMatch }: UseTypeaheadParams = {}) { const queryRef = useRef(''); const timeoutRef = useRef | null>(null); const resetQuery = useCallback(() => { queryRef.current = ''; if (timeoutRef.current != null) { clearTimeout(timeoutRef.current); timeoutRef.current = null; } }, []); useEffect(() => resetQuery, [resetQuery]); return useCallback( (event: React.KeyboardEvent) => { if (disabled || !isTypingKey(event, queryRef.current)) { if (resetsTypeaheadQuery(event.key)) { resetQuery(); } return; } event.preventDefault(); event.stopPropagation(); queryRef.current += event.key; const needle = searchableString(queryRef.current); if (timeoutRef.current != null) { clearTimeout(timeoutRef.current); } timeoutRef.current = setTimeout(resetQuery, TYPEAHEAD_QUERY_RESET_TIMEOUT_MS); const options = Array.from( event.currentTarget.querySelectorAll( '[role="option"]:not([aria-disabled="true"])', ), ); const optionLabels = options.map((option) => searchableString(option.textContent ?? '')); const matchingIndex = optionLabels.findIndex((label) => label.startsWith(needle)); const closestIndex = matchingIndex === -1 ? optionLabels.findIndex((label) => label.includes(needle)) : matchingIndex; if (closestIndex === -1) { return; } options[closestIndex].focus({ preventScroll: true }); event.currentTarget.focus({ preventScroll: true }); onMatch?.(); }, [disabled, onMatch, resetQuery], ); }