import {useRef, useEffect} from 'react'; import {Form, type FormProps} from 'react-router'; type SearchFormProps = Omit & { children: (args: { inputRef: React.RefObject; }) => React.ReactNode; }; /** * Search form component that sends search requests to the `/search` route. * @example * ```tsx * * {({inputRef}) => ( * <> * * * * )} * */ export function SearchForm({children, ...props}: SearchFormProps) { const inputRef = useRef(null); useFocusOnCmdK(inputRef); if (typeof children !== 'function') { return null; } return (
{children({inputRef})}
); } /** * Focuses the input when cmd+k is pressed */ function useFocusOnCmdK(inputRef: React.RefObject) { // focus the input when cmd+k is pressed useEffect(() => { function handleKeyDown(event: KeyboardEvent) { if (event.key === 'k' && event.metaKey) { event.preventDefault(); inputRef.current?.focus(); } if (event.key === 'Escape') { inputRef.current?.blur(); } } document.addEventListener('keydown', handleKeyDown); return () => { document.removeEventListener('keydown', handleKeyDown); }; }, [inputRef]); }