-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
107 lines (86 loc) · 2.3 KB
/
index.js
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
function createKeyBus(target) {
const simulDownListeners = {};
let isMultiKey = false;
let keyhash = null;
if (!(target instanceof HTMLElement)) {
throw Error('KeyBus: target must be a DOM element.');
}
function enableMultiKey() {
isMultiKey = true;
keyhash = {};
}
function disableMultiKey() {
isMultiKey = false;
keyhash = null;
}
function getKeyhash() {
return isMultiKey ? keyhash : null;
}
function down(keyCode, cb) {
if (isMultiKey) {
throw Error('multikey handlers should not use the "down" method of KeyBus');
return;
}
function keydownHandler(e) {
if (e.keyCode === keyCode) {
e.preventDefault();
cb(e);
}
}
target.addEventListener('keydown', keydownHandler);
return {
remove() {
target.removeEventListener('keydown', keydownHandler);
}
};
}
function up(keyCode, cb) {
if (isMultiKey) {
throw Error('multikey handlers should not use the "on" method of KeyBus');
return;
}
function keyupHandler(e) {
if (e.keyCode === keyCode) {
e.preventDefault();
cb(e);
}
}
target.addEventListener('keyup', keyupHandler);
return {
remove() {
target.removeEventListener('keyup', keyupHandler);
}
};
}
function simulDown(keyCode, cb) {
simulDownListeners[keyCode] ? simulDownListeners[keyCode] = [cb]
: simulDownListeners[keyCode].push(cb);
function updateKeyhash(e, val) {
if (e.keyCode === keyCode) {
e.preventDefault();
keyhash[keyCode] = val;
}
}
const keydownUpdate = (e) => updateKeyhash(e, true);
const keyupUpdate = (e) => updateKeyhash(e, false);
target.addEventListener('keydown', keydownUpdate);
target.addEventListener('keyup', keyupUpdate);
return {
remove() {
simulDownListeners[keyCode].splice(simulDownListeners[keyCode].indexOf(cb), 1);
target.removeEventListener('keydown', keydownUpdate);
target.removeEventListener('keyup', keyupUpdate);
}
};
}
function executeMultiKeyHandlers() {
for (let key in simulDownListeners) {
if (keyhash[key]) {
simulDownListeners[key].forEach(cb => {
cb();
});
}
}
}
}
module.exports = createKeyBus;