-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathget_key_down_handler.ts
More file actions
86 lines (72 loc) · 2.33 KB
/
get_key_down_handler.ts
File metadata and controls
86 lines (72 loc) · 2.33 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
81
82
83
84
85
86
import type {
KeyboardEvent as ReactKeyboardEvent,
MutableRefObject,
} from 'react';
import { useRef } from 'react';
import type { KbsInternalShortcut } from '../types.ts';
import { eventToKeyOrCode } from './make_key.ts';
import { shouldIgnoreElement } from './should_ignore_element.ts';
export interface LastTriggerData {
keyOrCode: string;
timestamp: number;
}
export function useLastTriggerRef() {
return useRef<LastTriggerData>({ keyOrCode: '', timestamp: 0 });
}
function parseEvent(
event: KeyboardEvent | ReactKeyboardEvent<HTMLDivElement>,
combinedShortcuts: Record<string, KbsInternalShortcut>,
) {
const { key, code } = eventToKeyOrCode(event);
let keyOrCode;
let shortcut;
if (combinedShortcuts[key]) {
shortcut = combinedShortcuts[key];
keyOrCode = key;
} else {
shortcut = combinedShortcuts[code];
keyOrCode = code;
}
return { key, code, keyOrCode, shortcut };
}
export function getKeyDownHandler(
lastTrigger: MutableRefObject<LastTriggerData>,
combinedShortcuts: Record<string, KbsInternalShortcut>,
) {
return function handleKeyDown(
event: KeyboardEvent | ReactKeyboardEvent<HTMLDivElement>,
) {
if (shouldIgnoreElement(event.target as HTMLElement)) {
return;
}
const { key, keyOrCode, shortcut } = parseEvent(event, combinedShortcuts);
if (!shortcut) return;
const initialKeys = new Set(key.split(']_'));
event.stopPropagation();
event.preventDefault();
if (shortcut.maxFrequency > 0) {
const now = performance.now();
if (
event.repeat &&
lastTrigger.current.keyOrCode === keyOrCode &&
now - lastTrigger.current.timestamp < 1000 / shortcut.maxFrequency
) {
return;
}
lastTrigger.current = { keyOrCode, timestamp: now };
}
const cleanup = shortcut.handler(event);
if (!cleanup) return;
const handleKeyUp = (
event: KeyboardEvent | ReactKeyboardEvent<HTMLDivElement>,
) => {
if (shouldIgnoreElement(event.target as HTMLElement)) return;
const { key } = parseEvent(event, combinedShortcuts);
const releasedKeys = key.split(']_');
if (!releasedKeys.some((key) => initialKeys.has(key))) return;
document.body.removeEventListener('keyup', handleKeyUp);
cleanup(event);
};
document.body.addEventListener('keyup', handleKeyUp);
};
}