-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (55 loc) · 1.2 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
/**
* Keyboard map.
*/
var map = {
37: 'left'
, 38: 'up'
, 39: 'right'
, 40: 'down'
}
/**
* Keyboard system.
*/
module.exports = function (el) {
var kbd = {}
kbd.keys = []
kbd.init = function () {
// add listeners
el.addEventListener('keydown', function (ev) {
ev.preventDefault()
ev.stopPropagation()
if (!kbd.isKeyPressed(ev.which)) {
kbd.keys.push(ev.which)
kbd.emit('keys', kbd.keys)
}
return false
})
el.addEventListener('keyup', function (ev) {
ev.preventDefault()
ev.stopPropagation()
if (kbd.isKeyPressed(ev.which)) {
kbd.keys.splice(kbd.keys.indexOf(ev.which), 1)
kbd.emit('keys', kbd.keys)
}
return false
})
}
kbd.isKeyPressed = function (key) {
return !!~kbd.keys.indexOf(key)
}
kbd.getMappedKeys = function () {
return kbd.keys.map(function (el) { return map[el] })
}
kbd.satisfies = function (keymap, str) {
var m = str.split(' ')
var cnt = m.length
if (keymap.length !== cnt) return false
var p
while (p = m.shift()) {
if (~keymap.indexOf(p)) cnt--
}
if (cnt === 0) return true
else return false
}
return kbd
}