forked from jaredly/treed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
key-manager.js
81 lines (68 loc) · 1.75 KB
/
key-manager.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
var keys = require('./lib/keys')
module.exports = KeyManager
function KeyManager() {
this._keyDown = this.keyDown.bind(this)
this.keys = null
this.store = null
this.state = {}
this.views = {}
}
KeyManager.prototype = {
attach: function (store) {
this.store = store
store.on([
store.events.activeViewChanged(),
store.events.activeModeChanged()
], this.update.bind(this))
this.update()
},
update: function () {
if (!this.store.views[this.store.activeView]) return
this.state = {
active: this.store.activeView,
mode: this.store.views[this.store.activeView].mode,
}
},
addView: function (vid, keys) {
this.views[vid] = keys
},
add: function (config) {
if (this.keys) return this.keys.add(config)
this.keys = keys(config)
return null
},
remove: function (lid) {
if (!this.keys) return false
return this.keys.remove(lid)
},
disable: function () {this.keys.disable()},
enable: function () {this.keys.enable()},
addKeys: function (config) {
if (this.keys) return this.keys.add(config)
this.keys = keys(config)
},
keyDown: function (e) {
var res
if (this.keys) {
res = this.keys(e)
if (typeof res !== 'string' && res !== true) {
if (this.store) {
this.views[this.state.active][this.state.mode].clear()
}
return res
} else if (res === true) {
res = undefined
}
}
if (this.store) {
this.views[this.state.active][this.state.mode](e, res)
}
},
listen: function (window) {
this._keyDown = this.keyDown.bind(this)
window.addEventListener('keydown', this._keyDown)
},
unlisten: function (window) {
window.removeEventListener('keydown', this._keyDown)
},
}