From dd80630f74b5c64847167030e8f295f003e480e5 Mon Sep 17 00:00:00 2001 From: bkellam Date: Mon, 2 Sep 2024 19:19:22 -0700 Subject: [PATCH] Add hotkey to focus search bar --- package.json | 1 + src/app/page.tsx | 4 +++- src/app/searchBar.tsx | 13 +++++++++++++ yarn.lock | 5 +++++ 4 files changed, 22 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index b1ba8900..a9bcc52c 100644 --- a/package.json +++ b/package.json @@ -33,6 +33,7 @@ "react": "^18", "react-dom": "^18", "react-hook-form": "^7.53.0", + "react-hotkeys-hook": "^4.5.1", "react-resizable-panels": "^2.1.1", "sharp": "^0.33.5", "tailwind-merge": "^2.5.2", diff --git a/src/app/page.tsx b/src/app/page.tsx index db96f926..bcb04afe 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -43,7 +43,9 @@ export default function Home() { />
- +
diff --git a/src/app/searchBar.tsx b/src/app/searchBar.tsx index 327e8972..29a84750 100644 --- a/src/app/searchBar.tsx +++ b/src/app/searchBar.tsx @@ -14,11 +14,14 @@ import { cva } from "class-variance-authority"; import { useRouter } from "next/navigation"; import { useForm } from "react-hook-form"; import { z } from "zod"; +import { useHotkeys } from 'react-hotkeys-hook' +import { useRef } from "react"; interface SearchBarProps { className?: string; size?: "default" | "sm"; defaultQuery?: string; + autoFocus?: boolean; } const formSchema = z.object({ @@ -44,7 +47,15 @@ export const SearchBar = ({ className, size, defaultQuery, + autoFocus, }: SearchBarProps) => { + + const inputRef = useRef(null); + useHotkeys('/', (event) => { + event.preventDefault(); + inputRef.current?.focus(); + }); + const router = useRouter(); const form = useForm>({ resolver: zodResolver(formSchema), @@ -73,6 +84,8 @@ export const SearchBar = ({ placeholder="Search..." className={cn(searchBarVariants({ size, className }))} {...field} + ref={inputRef} + autoFocus={autoFocus ?? false} /> diff --git a/yarn.lock b/yarn.lock index 9eb490f7..84269e48 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2889,6 +2889,11 @@ react-hook-form@^7.53.0: resolved "https://registry.yarnpkg.com/react-hook-form/-/react-hook-form-7.53.0.tgz#3cf70951bf41fa95207b34486203ebefbd3a05ab" integrity sha512-M1n3HhqCww6S2hxLxciEXy2oISPnAzxY7gvwVPrtlczTM/1dDadXgUxDpHMrMTblDOcm/AXtXxHwZ3jpg1mqKQ== +react-hotkeys-hook@^4.5.1: + version "4.5.1" + resolved "https://registry.yarnpkg.com/react-hotkeys-hook/-/react-hotkeys-hook-4.5.1.tgz#990260ecc7e5a431414148a93b02a2f1a9707897" + integrity sha512-scAEJOh3Irm0g95NIn6+tQVf/OICCjsQsC9NBHfQws/Vxw4sfq1tDQut5fhTEvPraXhu/sHxRd9lOtxzyYuNAg== + react-is@^16.13.1: version "16.13.1" resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4"