-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
55 lines (41 loc) · 1.19 KB
/
index.js
File metadata and controls
55 lines (41 loc) · 1.19 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
const START = 0;
const DATA = 1;
const TERMINATE = 2;
const keysDown = new Set();
let isListening = false;
const listeners = [];
function keydownHandler(event /* KeyboardEvent */) {
keysDown.add(event.key);
listeners.forEach(listener => listener({ keysDown }));
}
function keyupHandler(event /* KeyboardEvent */) {
keysDown.delete(event.key);
listeners.forEach(listener => listener({ keysDown }));
}
function startListening() {
if (isListening) return;
isListening = true;
document.addEventListener("keydown", keydownHandler);
document.addEventListener("keyup", keyupHandler);
}
function stopListening() {
isListening = false;
document.removeEventListener("keydown", keydownHandler);
document.removeEventListener("keyup", keyupHandler);
}
function keyboard(start, sink) {
if (start !== START) return;
let listener = gamepads => sink(DATA, gamepads);
listeners.push(listener);
const talkback = (type, d) => {
if (type === TERMINATE) {
listeners.splice(listeners.indexOf(listener), 1);
if (listeners.length === 0) {
stopListening();
}
}
};
sink(START, talkback);
startListening();
}
module.exports = (start, sink) => keyboard(start, sink);