forked from MergeFi/frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseKeyboardShortcut.ts
More file actions
20 lines (20 loc) · 839 Bytes
/
Copy pathuseKeyboardShortcut.ts
File metadata and controls
20 lines (20 loc) · 839 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { useEffect } from "react"
type Modifier = "ctrl" | "meta" | "alt" | "shift"
interface Options { modifier?: Modifier; enabled?: boolean }
export function useKeyboardShortcut(key: string, callback: () => void, { modifier, enabled = true }: Options = {}) {
useEffect(() => {
if (!enabled) return
const handler = (e: KeyboardEvent) => {
const modOk = !modifier ||
(modifier === "ctrl" && e.ctrlKey) ||
(modifier === "meta" && e.metaKey) ||
(modifier === "alt" && e.altKey) ||
(modifier === "shift" && e.shiftKey)
if (modOk && e.key.toLowerCase() === key.toLowerCase()) {
e.preventDefault(); callback()
}
}
window.addEventListener("keydown", handler)
return () => window.removeEventListener("keydown", handler)
}, [key, callback, modifier, enabled])
}