forked from PinSpace-Org/GistPin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseKeyboardShortcuts.ts
More file actions
37 lines (31 loc) 路 1.08 KB
/
Copy pathuseKeyboardShortcuts.ts
File metadata and controls
37 lines (31 loc) 路 1.08 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
'use client';
import { useEffect, useCallback } from 'react';
export interface KeyboardShortcutHandlers {
onSearch?: () => void;
onRefresh?: () => void;
onToggleDark?: () => void;
onHelp?: () => void;
}
export function useKeyboardShortcuts({
onSearch,
onRefresh,
onToggleDark,
onHelp,
}: KeyboardShortcutHandlers) {
const handleKeyDown = useCallback(
(e: KeyboardEvent) => {
const tag = (e.target as HTMLElement).tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA' || (e.target as HTMLElement).isContentEditable) return;
if ((e.metaKey || e.ctrlKey) && e.key === 'k') { e.preventDefault(); onSearch?.(); return; }
if (e.metaKey || e.ctrlKey || e.altKey) return;
if (e.key === 'r' || e.key === 'R') onRefresh?.();
else if (e.key === 'd' || e.key === 'D') onToggleDark?.();
else if (e.key === '?') onHelp?.();
},
[onSearch, onRefresh, onToggleDark, onHelp],
);
useEffect(() => {
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [handleKeyDown]);
}