| 27 | * on first open. |
| 28 | */ |
| 29 | export const SearchDialog = () => { |
| 30 | const dialog = useRef<HTMLDialogElement>(null) |
| 31 | const opener = useRef<Element | null>(null) |
| 32 | // the panel keeps its query between opens, unless one is opened with a new one |
| 33 | const [session, setSession] = useState<{ id: number; query: string }>() |
| 34 | // what is typed while the panel loads, which it starts from |
| 35 | const [draft, setDraft] = useState("") |
| 36 | const [entered, setEntered] = useState(false) |
| 37 | const [moved, setMoved] = useState(0) |
| 38 | |
| 39 | useEffect(() => { |
| 40 | const open = (query = "") => { |
| 41 | const element = dialog.current |
| 42 | if (!element || element.open) return |
| 43 | closePopups() |
| 44 | opener.current = document.activeElement |
| 45 | setSession(previous => |
| 46 | previous && !query ? previous : { id: (previous?.id ?? 0) + 1, query } |
| 47 | ) |
| 48 | setDraft(query) |
| 49 | setEntered(false) |
| 50 | setMoved(0) |
| 51 | element.showModal() |
| 52 | } |
| 53 | const onOpen = (e: Event) => |
| 54 | open((e as CustomEvent<string | null>).detail ?? "") |
| 55 | const onKeyDown = (e: KeyboardEvent) => { |
| 56 | if (e.key.toLowerCase() === "k" && (e.metaKey || e.ctrlKey)) { |
| 57 | e.preventDefault() |
| 58 | if (dialog.current?.open) dialog.current.close() |
| 59 | else open() |
| 60 | } else if (e.key === "/" && !isTyping(e.target)) { |
| 61 | e.preventDefault() |
| 62 | open() |
| 63 | } |
| 64 | } |
| 65 | window.addEventListener(openSearchEvent, onOpen) |
| 66 | window.addEventListener("keydown", onKeyDown) |
| 67 | if (new URLSearchParams(location.search).has("search")) open() |
| 68 | return () => { |
| 69 | window.removeEventListener(openSearchEvent, onOpen) |
| 70 | window.removeEventListener("keydown", onKeyDown) |
| 71 | } |
| 72 | }, []) |
| 73 | |
| 74 | const close = () => dialog.current?.close() |
| 75 | |
| 76 | return ( |
| 77 | <dialog |
| 78 | ref={dialog} |
| 79 | className="search" |
| 80 | aria-label="Search docs" |
| 81 | onClose={() => { |
| 82 | if (opener.current instanceof HTMLElement) |
| 83 | opener.current.focus({ preventScroll: true }) |
| 84 | }} |
| 85 | onClick={e => { |
| 86 | // a click on the backdrop targets the dialog itself |