-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeyboard.js
71 lines (61 loc) · 1.64 KB
/
keyboard.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
const createCommand = require('./command')
const keycode = require('keycode')
const events = require('dom-events')
/**
* Creates a function that is suite to be an
* Axis3D command and current exposes keyboard
* state.
*
* @param {!Object} ctx
* @return {Function}
* @throws TypeError
*/
module.exports = createKeyboardCommand
function createKeyboardCommand(ctx) {
const keycodes = {}
const keys = {}
const state = {
prev: null,
current: {keycodes: keycodes, keys: keys}
}
if (!ctx || 'object' != typeof ctx || Array.isArray(ctx)) {
throw new TypeError("createKeyboardCommand(): Expecting context object.")
}
events.on(document, 'keydown', onkeydown, false)
events.on(document, 'keyup', onkeyup, false)
events.on(window, 'blur', reset)
ctx.once('destroy', cleanup)
ctx.on('blur', reset)
return createCommand(state)
function onkeydown(e) {
const code = e.which || e.keyCode || e.charCode
if (false == ctx.hasFocus) { return false }
if ('number' == typeof code) {
keycodes[code] = true
keys[keycode(code)] = true
}
}
function onkeyup(e) {
const code = e.which || e.keyCode || e.charCode
if (false == ctx.hasFocus) { return false }
if ('number' == typeof code) {
keycodes[code] = false
keys[keycode(code)] = false
}
}
function reset() {
for (const code in keycodes) {
keycodes[code] = false
}
for (const key in keys) {
keys[key] = false
}
}
function cleanup() {
reset()
ctx.off('blur', reset)
events.off(document, 'keydown', onkeydown)
events.off(document, 'keyup', onkeyup)
events.off(window, 'blur', reset)
}
}