-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseKeyboardShortcuts.ts
More file actions
80 lines (71 loc) 路 2.29 KB
/
Copy pathuseKeyboardShortcuts.ts
File metadata and controls
80 lines (71 loc) 路 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { useEffect } from "react";
interface ShortcutConfig {
/**
* The key to trigger the shortcut (e.g., 'b', 'k', 'Enter').
* Case-insensitive.
*/
key: string;
/**
* Whether the Ctrl key (Windows/Linux) or Command key (Mac) must be pressed.
*/
ctrlOrMeta?: boolean;
/**
* Whether the Alt key must be pressed.
*/
alt?: boolean;
/**
* Whether the Shift key must be pressed.
*/
shift?: boolean;
/**
* Callback when the shortcut is triggered.
*/
handler: (event: KeyboardEvent) => void;
/**
* Optional description for documentation or UI hints.
*/
description?: string;
/**
* Whether to allow triggering even when focused on an input.
* Default is false.
*/
allowInInputs?: boolean;
}
/**
* A hook to register global keyboard shortcuts.
*/
export function useKeyboardShortcuts(shortcuts: ShortcutConfig[]) {
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
// 1. Check if we should ignore this event (e.g., focused in an input)
const target = event.target as HTMLElement;
const isInput =
target?.tagName === "INPUT" || target?.tagName === "TEXTAREA" || target?.isContentEditable;
for (const shortcut of shortcuts) {
if (isInput && !shortcut.allowInInputs) {
continue;
}
// 2. Match modifiers
const matchesCtrlMeta = shortcut.ctrlOrMeta
? event.ctrlKey || event.metaKey
: !(event.ctrlKey || event.metaKey);
const matchesAlt = !!shortcut.alt === event.altKey;
const matchesShift = !!shortcut.shift === event.shiftKey;
// 3. Match key
// We check both key and code to be more robust (e.g., 'KeyB' or 'b')
const pressedKey = event.key.toLowerCase();
const targetKey = shortcut.key.toLowerCase();
const matchesKey =
pressedKey === targetKey || event.code.toLowerCase() === `key${targetKey}`;
if (matchesCtrlMeta && matchesAlt && matchesShift && matchesKey) {
// Found a match!
event.preventDefault();
shortcut.handler(event);
return; // Stop after first match
}
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [shortcuts]);
}