From 78d5ab5499342901371e26a858c042c2e7043d7c Mon Sep 17 00:00:00 2001 From: Harry Date: Sat, 5 Oct 2024 17:01:33 +0530 Subject: [PATCH] feature: on pressing ctrl+k on windows and cmd+k on mac search bar will be focused --- components/search.tsx | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/components/search.tsx b/components/search.tsx index 1557f8750..03e7a5d33 100644 --- a/components/search.tsx +++ b/components/search.tsx @@ -9,6 +9,25 @@ import { toast } from "@/components/ui/use-toast" interface DocsSearchProps extends React.HTMLAttributes {} export function DocsSearch({ className, ...props }: DocsSearchProps) { + const inputRef = React.useRef(null) + // if user presses ctrl+k, focus the search input on windows and cmd+k on mac + React.useEffect(() => { + const handleKeyDown = (event: KeyboardEvent) => { + if ( + (event.ctrlKey || event.metaKey) && + event.key === "k" && + document.activeElement !== inputRef.current + ) { + event.preventDefault() + inputRef.current?.focus() + } + } + document.addEventListener("keydown", handleKeyDown) + return () => { + document.removeEventListener("keydown", handleKeyDown) + } + }, []) + function onSubmit(event: React.SyntheticEvent) { event.preventDefault() @@ -28,6 +47,7 @@ export function DocsSearch({ className, ...props }: DocsSearchProps) { type="search" placeholder="Search documentation..." className="h-8 w-full sm:w-64 sm:pr-12" + ref={inputRef} /> K