This repository was archived by the owner on Jan 28, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemoteControlManager.ts
82 lines (66 loc) · 2.18 KB
/
RemoteControlManager.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { SupportedKeys } from './SupportedKeys';
import { RemoteControlManagerInterface } from './RemoteControlManager.interface';
import CustomEventEmitter from './CustomEventEmitter';
const LONG_PRESS_DURATION = 500;
class RemoteControlManager implements RemoteControlManagerInterface {
constructor() {
window.addEventListener('keydown', this.handleKeyDown);
window.addEventListener('keyup', this.handleKeyUp);
}
private eventEmitter = new CustomEventEmitter<{ keyDown: SupportedKeys }>();
private isEnterKeyDown = false;
private longEnterTimeout: NodeJS.Timeout | null = null;
private handleLongEnter = () => {
this.longEnterTimeout = setTimeout(() => {
this.eventEmitter.emit('keyDown', SupportedKeys.LongEnter);
this.longEnterTimeout = null;
}, LONG_PRESS_DURATION);
};
private handleKeyDown = (event: KeyboardEvent) => {
const mappedKey = {
ArrowRight: SupportedKeys.Right,
ArrowLeft: SupportedKeys.Left,
ArrowUp: SupportedKeys.Up,
ArrowDown: SupportedKeys.Down,
Enter: SupportedKeys.Enter,
Backspace: SupportedKeys.Back,
}[event.code];
if (!mappedKey) {
return;
}
if (mappedKey === SupportedKeys.Enter) {
if (!this.isEnterKeyDown) {
this.isEnterKeyDown = true;
this.handleLongEnter();
}
return;
}
this.eventEmitter.emit('keyDown', mappedKey);
};
private handleKeyUp = (event: KeyboardEvent) => {
const mappedKey = {
Enter: SupportedKeys.Enter,
}[event.code];
if (!mappedKey) {
return;
}
if (mappedKey === SupportedKeys.Enter) {
this.isEnterKeyDown = false;
if (this.longEnterTimeout) {
clearTimeout(this.longEnterTimeout);
this.eventEmitter.emit('keyDown', mappedKey);
}
}
};
addKeydownListener = (listener: (event: SupportedKeys) => boolean) => {
this.eventEmitter.on('keyDown', listener);
return listener;
};
removeKeydownListener = (listener: (event: SupportedKeys) => boolean) => {
this.eventEmitter.off('keyDown', listener);
};
emitKeyDown = (key: SupportedKeys) => {
this.eventEmitter.emit('keyDown', key);
};
}
export default new RemoteControlManager();