Repository navigation
Expand file tree
/
Copy pathcontrols.js
More file actions
68 lines (55 loc) · 1.76 KB
/
Copy pathcontrols.js
File metadata and controls
68 lines (55 loc) · 1.76 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
class Keys {
constructor() {
this.keys_down = {}
}
/**
* Register a keyboard listener and create a Keys object that
* will be updated by it.
*
* @returns Keys
*/
static start_listening() {
let keys = new Keys();
addEventListener('keydown', function (ev) {
// Prevent default behavior for arrow keys and space
if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Space'].includes(ev.code)) {
ev.preventDefault();
}
if (typeof ev.code === 'string') {
keys.keys_down[ev.code] = true;
}
});
addEventListener('keyup', function (ev) {
if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Space'].includes(ev.code)) {
ev.preventDefault();
}
if (typeof ev.code === 'string') {
keys.keys_down[ev.code] = false;
}
});
return keys;
}
is_key_down(code) {
return !!this.keys_down[code];
}
is_key_up(code) {
return !this.keys_down[code];
}
keys_down_list() {
return Object.entries(this.keys_down)
.filter(kv => kv[1] /* the value */)
.map(kv => kv[0] /* the key */);
// the code above is equivalent to this:
/*
let ret = [];
for( const [key, value] of Object.entries(this.keys_down) ) {
if( value ) {
ret.push( key );
}
}
return ret;
*/
// notice how much more terse the functional is. It's easier to read, too,
// if you're comfortable with functional programming.
}
}