-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
62 lines (45 loc) · 1.48 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
'use strict';
// Dependencies
const Events = require('events');
function FlowKeypress (args) {
let self = new Events();
args = args || {};
let events = args.events || {};
self.handlers = {};
self.context = args.defaultContext || '_no_context_';
// assing an event name for each of the key codes configured
Object.keys(events).forEach(eventName => {
events[eventName].forEach(handler => {
if (!handler.keyCode) return;
let context = handler.context || '_no_context_';
self.handlers[context] = self.handlers[context] || {};
self.handlers[context][handler.keyCode] = {
eventName: eventName,
ctrl: handler.ctrl || false,
shift: handler.shift || false
};
});
});
// listen for key presses
window.addEventListener('keydown', e => {
if (!self.handlers[self.context]) { // context must exist
return;
}
let handler = self.handlers[self.context][e.keyCode];
if (handler) { // handler must exist
// check for modifiers
if (handler.ctrl !== e.ctrlKey || handler.shift !== e.shiftKey) {
return;
}
self.emit('keyEvent', {
name: handler.eventName,
data: e
});
}
});
self.setContext = (context) => {
self.context = context;
}
return self;
}
module.exports = FlowKeypress;