-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathindex.ts
58 lines (48 loc) · 2.16 KB
/
index.ts
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
import getKeyEventModifiers from '@libs/KeyboardShortcut/getKeyEventModifiers';
import isEnterWhileComposition from '@libs/KeyboardShortcut/isEnterWhileComposition';
import type BindHandlerToKeydownEvent from './types';
/**
* Checks if an event for that key is configured and if so, runs it.
*/
const bindHandlerToKeydownEvent: BindHandlerToKeydownEvent = (getDisplayName, eventHandlers, keyCommandEvent, event) => {
if (!(event instanceof KeyboardEvent) || isEnterWhileComposition(event)) {
return;
}
const eventModifiers = getKeyEventModifiers(keyCommandEvent);
const displayName = getDisplayName(keyCommandEvent.input, eventModifiers);
// If we didn't register any event handlers for a key we ignore it
if (!eventHandlers[displayName]) {
return;
}
// Loop over all the callbacks
Object.values(eventHandlers[displayName]).every((callback) => {
const textArea = event.target as HTMLTextAreaElement;
const contentEditable = textArea?.contentEditable;
const nodeName = textArea?.nodeName;
// Early return for excludedNodes
if (callback.excludedNodes.includes(nodeName)) {
return true;
}
// If configured to do so, prevent input text control to trigger this event
if (!callback.captureOnInputs && (nodeName === 'INPUT' || nodeName === 'TEXTAREA' || contentEditable === 'true')) {
return true;
}
// Determine if the event should bubble before executing the callback (which may have side-effects)
let shouldBubble: boolean | (() => void) | void = callback.shouldBubble || false;
if (typeof callback.shouldBubble === 'function') {
shouldBubble = callback.shouldBubble();
}
if (typeof callback.callback === 'function') {
callback.callback(event);
}
if (callback.shouldPreventDefault) {
event.preventDefault();
}
if (callback.shouldStopPropagation) {
event.stopPropagation();
}
// If the event should not bubble, short-circuit the loop
return shouldBubble;
});
};
export default bindHandlerToKeydownEvent;