diff --git a/docs/components/DocSearch/wrapper.tsx b/docs/components/DocSearch/wrapper.tsx index ab0af65011..cb87ef3585 100644 --- a/docs/components/DocSearch/wrapper.tsx +++ b/docs/components/DocSearch/wrapper.tsx @@ -1,4 +1,4 @@ -import { useEffect } from "react" +import { useEffect, useRef, useState } from "react" import algoliasearch from "algoliasearch/lite" import { InstantSearch, Hits, useInstantSearch } from "react-instantsearch" //import { InstantSearchNext } from "react-instantsearch-nextjs" @@ -32,35 +32,58 @@ const searchClient = { }, } -export default function () { - const ctrlKHandler = (e: KeyboardEvent) => { - if (e.repeat || e.target instanceof HTMLInputElement) return - if (e.ctrlKey && e.key === "k") { - e.preventDefault() - document.querySelector('input[type="search"]')?.focus() - } - } +export default function Wrapper() { + const docSearchRef = useRef(null) + const [isSearchHitsVisible, setIsSearchHitsVisible] = useState(false) useEffect(() => { + function ctrlKHandler(e: KeyboardEvent) { + if (e.repeat || e.target instanceof HTMLInputElement) return + if (e.ctrlKey && e.key === "k") { + e.preventDefault() + document + .querySelector('input[type="search"]') + ?.focus() + } + } + + function clickSearchBoxOutsideHandler(event: MouseEvent) { + setIsSearchHitsVisible( + Boolean( + event.target instanceof Node && + docSearchRef.current?.contains(event.target) + ) + ) + } + window.addEventListener("keydown", ctrlKHandler) + window.addEventListener("mousedown", clickSearchBoxOutsideHandler) - return window.addEventListener("keydown", ctrlKHandler) + return () => { + window.removeEventListener("keydown", ctrlKHandler) + window.removeEventListener("mousedown", clickSearchBoxOutsideHandler) + } }, []) return ( -
+
- - - + {isSearchHitsVisible && ( + + + + )}
)