forked from Prompt-Hash-Stellar/prompt-hash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseKeyboardShortcuts.ts
More file actions
53 lines (46 loc) · 1.54 KB
/
Copy pathuseKeyboardShortcuts.ts
File metadata and controls
53 lines (46 loc) · 1.54 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
import { useEffect } from "react";
interface UseKeyboardShortcutsOptions {
onShowShortcuts: () => void;
}
export function useKeyboardShortcuts({
onShowShortcuts,
}: UseKeyboardShortcutsOptions): void {
useEffect(() => {
function handleKeyDown(e: KeyboardEvent) {
const target = e.target as HTMLElement;
const isTyping =
target.tagName === "INPUT" ||
target.tagName === "TEXTAREA" ||
target.isContentEditable;
// `/` — focus search bar (skip when already typing)
if (e.key === "/" && !isTyping) {
e.preventDefault();
const searchInput = document.querySelector<HTMLInputElement>(
'input[placeholder*="earch"], input[type="search"]'
);
searchInput?.focus();
return;
}
// `Escape` — close modals / blur active element
if (e.key === "Escape") {
document.dispatchEvent(new CustomEvent("close-modal"));
(document.activeElement as HTMLElement | null)?.blur();
return;
}
// `Ctrl/Cmd + S` — save-prompt
if (e.key === "s" && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
document.dispatchEvent(new CustomEvent("save-prompt"));
return;
}
// `?` — show shortcuts modal (skip when typing)
if (e.key === "?" && !isTyping) {
e.preventDefault();
onShowShortcuts();
return;
}
}
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [onShowShortcuts]);
}