1 "use client"
2
3 import { useCallback, useEffect } from "react"
4
5 export type useKeyboardShortcutOptions = {
6 metakey?: boolean
7 shortcutKeys: string[]
8 action: (e: KeyboardEvent) => void
9 checkEditing?: boolean
10 preventDefault?: boolean
11 isLoading?: boolean
12 }
13
14 export const useKeyboardShortcut = ({
15 metakey = true,
16 shortcutKeys,
17 action,
18 checkEditing = true,
19 preventDefault = true,
20 isLoading = false,
21 }: useKeyboardShortcutOptions) => {
22 function isEditingContent(event: KeyboardEvent) {
23 const element = event.target as HTMLElement
24 const tagName = element.tagName
25 return (
26 element.isContentEditable ||
27 tagName === "INPUT" ||
28 tagName === "SELECT" ||
29 tagName === "TEXTAREA"
30 )
31 }
32
33 const checkKeysPressed = useCallback(
34 (pressedKey: string) => {
35 const lowerPressedKey = pressedKey.toLowerCase()
36 return shortcutKeys.some(
37 (value) => lowerPressedKey === value.toLowerCase()
38 )
39 },
40 [shortcutKeys]
41 )
42
43 const onKeyDown = useCallback(
44 (e: KeyboardEvent) => {
45 // the event is triggered when an input
46 // autocompletes, and in that case
47 // e.key will be empty
48 if (isLoading || !e.key) {
49 return
50 }
51 if (
52 (!metakey || e.metaKey || e.ctrlKey) &&
53 checkKeysPressed(e.key) &&
54 (!checkEditing || !isEditingContent(e))
55 ) {
56 if (preventDefault) {
57 e.preventDefault()
58 }
59 action(e)
60 }
61 },
62 [isLoading, metakey, checkKeysPressed, checkEditing, action, preventDefault]
63 )
64
65 useEffect(() => {
66 window.addEventListener("keydown", onKeyDown)
67
68 return () => {
69 window.removeEventListener("keydown", onKeyDown)
70 }
71 }, [onKeyDown])
72 }