From f45d7fb9ba06713d954c09b53f4602ccba180f42 Mon Sep 17 00:00:00 2001 From: Tushar Daiya Date: Mon, 29 Jul 2024 21:26:57 +0530 Subject: [PATCH] Add useKeyPress hook for keyboard event handling --- apps/web/app/(dash)/menu.tsx | 7 ++++++- apps/web/lib/useKeyPress.ts | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 apps/web/lib/useKeyPress.ts diff --git a/apps/web/app/(dash)/menu.tsx b/apps/web/app/(dash)/menu.tsx index 70439c7d..c1173eb6 100644 --- a/apps/web/app/(dash)/menu.tsx +++ b/apps/web/app/(dash)/menu.tsx @@ -30,6 +30,7 @@ import { createMemory, createSpace } from "../actions/doers"; import ComboboxWithCreate from "@repo/ui/shadcn/combobox"; import { StoredSpace } from "@/server/db/schema"; import useMeasure from "react-use-measure"; +import { useKeyPress } from "@/lib/useKeyPress"; function Menu() { const [spaces, setSpaces] = useState([]); @@ -48,7 +49,11 @@ function Menu() { setSpaces(spaces.data); })(); }, []); - + useKeyPress("a", () => { + if (!dialogOpen) { + setDialogOpen(true); + } + }); const menuItems = [ { icon: HomeIconWeb, diff --git a/apps/web/lib/useKeyPress.ts b/apps/web/lib/useKeyPress.ts new file mode 100644 index 00000000..eee23acb --- /dev/null +++ b/apps/web/lib/useKeyPress.ts @@ -0,0 +1,15 @@ +import { useEffect } from "react"; + +export const useKeyPress = (key: string, callback: () => void) => { + useEffect(() => { + const handler = (e: KeyboardEvent) => { + if (e.key === key && e.altKey) { + callback(); + } + }; + window.addEventListener("keydown", handler); + return () => { + window.removeEventListener("keydown", handler); + }; + }, [key, callback]); +};