import { useMemo, useCallback, useRef, useState, useEffect } from 'react'; import matchSorter from 'match-sorter'; import cn from 'classnames'; import { useRouter } from 'next/router'; import Link from 'next/link'; const Item = ({ title, active, href, onMouseOver, search }) => { const highlight = title.toLowerCase().indexOf(search.toLowerCase()); return (
  • {title.substring(0, highlight)} {title.substring(highlight, highlight + search.length)} {title.substring(highlight + search.length)}
  • ); }; const Search = ({ directories }) => { const router = useRouter(); const [show, setShow] = useState(false); const [search, setSearch] = useState(''); const [active, setActive] = useState(0); const input = useRef(null); const results = useMemo(() => { if (!search) return []; // Will need to scrape all the headers from each page and search through them here // (similar to what we already do to render the hash links in sidebar) // We could also try to search the entire string text from each page return matchSorter(directories, search, { keys: ['title'] }); }, [search]); const handleKeyDown = useCallback( (e) => { switch (e.key) { case 'ArrowDown': { e.preventDefault(); if (active + 1 < results.length) { setActive(active + 1); } break; } case 'ArrowUp': { e.preventDefault(); if (active - 1 >= 0) { setActive(active - 1); } break; } case 'Enter': { router.push(results[active].route); break; } } }, [active, results, router] ); useEffect(() => { setActive(0); }, [search]); useEffect(() => { const inputs = ['input', 'select', 'button', 'textarea']; const down = (e) => { if ( document.activeElement && inputs.indexOf(document.activeElement.tagName.toLowerCase() !== -1) ) { if (e.key === '/') { e.preventDefault(); input.current.focus(); } else if (e.key === 'Escape') { setShow(false); } } }; window.addEventListener('keydown', down); return () => window.removeEventListener('keydown', down); }, []); const renderList = show && results.length > 0; return (
    {renderList && (
    setShow(false)} /> )}
    { setSearch(e.target.value); setShow(true); }} className="appearance-none pl-8 border rounded-md py-2 pr-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline w-full" type="search" placeholder='Search ("/" to focus)' onKeyDown={handleKeyDown} onFocus={() => setShow(true)} ref={input} aria-label="Search documentation" /> {renderList && ( )}
    ); }; export default Search;