forked from nicholasrq/keymaster
-
Notifications
You must be signed in to change notification settings - Fork 0
/
keymaster.js
335 lines (275 loc) · 8.95 KB
/
keymaster.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
// keymaster.js
// (c) 2011-2013 Thomas Fuchs
// keymaster.js may be freely distributed under the MIT license.
(function(global){
const _handlers = {};
const _mods = { 16: false, 18: false, 17: false, 91: false, 93: false };
let _scope = 'all';
// modifier keys
const _MODIFIERS = {
'⇧': [16], shift: [16],
'⌥': [18], alt: [18], option: [18],
'⌃': [17], ctrl: [17], control: [17],
'⌘': [91, 93], command: [91, 93],
};
// special keys
const _MAP = {
backspace: 8, tab: 9, clear: 12,
enter: 13, 'return': 13,
esc: 27, escape: 27, space: 32,
left: 37, up: 38,
right: 39, down: 40,
del: 46, 'delete': 46,
home: 36, end: 35,
pageup: 33, pagedown: 34,
plus: 187, minus: 189,
',': 188, '.': 190, '/': 191,
'`': 192, '-': 189, '=': 187,
';': 186, '\'': 222,
'[': 219, ']': 221, '\\': 220,
};
const code = function(x){
return _MAP[x] || x.toUpperCase().charCodeAt(0);
};
let k, _downKeys = [];
for(k=1;k<20;k++) _MAP['f'+k] = 111+k;
// IE doesn't support Array#indexOf, so have a simple replacement
function index(array, item){
let i = array.length;
while(i--) if(array[i]===item) return i;
return -1;
}
// check every key in mods
function hasMod(mods, item) {
for(const mod of mods) {
if (mod.includes(item)) return true;
}
return false;
}
// for comparing mods before unassignment
function compareArray(a1, a2) {
if (a1.length !== a2.length) return false;
for (let i = 0; i < a1.length; i++) {
if (!compareArray(a1[i], a2[i])) return false;
}
return true;
}
const modifierMap = {
16:'shiftKey',
18:'altKey',
17:'ctrlKey',
91:'metaKey',
93:'metaKey',
};
function updateModifierKey(event) {
for(k in _mods) _mods[k] = event[modifierMap[k]];
}
// handle keydown event
function dispatch(event) {
let key, handler, k, i, modifiersMatch;
key = event.keyCode;
if (index(_downKeys, key) === -1) {
_downKeys.push(key);
}
// if a modifier key, set the key.<modifierkeyname> property to true and return
if(key === 93 || key === 224) key = 91; // right command on webkit, command on Gecko
if(key in _mods) {
_mods[key] = true;
// 'assignKey' from inside this closure is exported to window.key
for(k in _MODIFIERS) if(_MODIFIERS[k].includes(key)) assignKey[k] = true;
return;
}
updateModifierKey(event);
// see if we need to ignore the keypress (filter() can can be overridden)
// by default ignore key presses if a select, textarea, or input is focused
if(!assignKey.filter.call(this, event)) return;
// abort if no potentially matching shortcuts found
if (!(key in _handlers)) return;
const scope = getScope();
// for each potential shortcut
for (i = 0; i < _handlers[key].length; i++) {
handler = _handlers[key][i];
// see if it's in the current scope
if(handler.scope === scope || handler.scope === 'all'){
// check if modifiers match if any
modifiersMatch = handler.mods.length > 0;
for(k in _mods)
if((!_mods[k] && hasMod(handler.mods, +k) === true) ||
(_mods[k] && hasMod(handler.mods, +k) === false)) {
modifiersMatch = false;
}
// call the handler and stop the event if neccessary
if (_downKeys.length === (handler.mods.length + 1) && checkKeys(handler.key)) {
if(handler.method(event, handler)===false){
if(event.preventDefault) event.preventDefault();
else event.returnValue = false;
if(event.stopPropagation) event.stopPropagation();
if(event.cancelBubble) event.cancelBubble = true;
}
}
}
}
}
function checkKeys(key) {
const keys = key.split('+');
for (let i = 0, l = keys.length; i < l; i++) {
const key = keys[i];
const mods = [...(_MODIFIERS[key] || []), code(key)];
const hasKeys = _downKeys.some(k => mods.includes(k));
if (!hasKeys) return false;
}
return true;
}
// unset modifier keys on keyup
function clearModifier(event){
let key = event.keyCode, k;
const i = index(_downKeys, key);
// remove key from _downKeys
if (i >= 0) {
_downKeys.splice(i, 1);
}
if(key === 93 || key === 224) key = 91;
if(key in _mods) {
_mods[key] = false;
for(k in _MODIFIERS) if(_MODIFIERS[k].includes(key)) assignKey[k] = false;
}
}
function resetModifiers() {
for(k in _mods) _mods[k] = false;
for(k in _MODIFIERS) assignKey[k] = false;
_downKeys = [];
}
// parse and assign shortcut
function assignKey(key, scope, method){
let mods;
const keys = getKeys(key);
if (method === undefined) {
method = scope;
scope = 'all';
}
// for each shortcut
for (let i = 0; i < keys.length; i++) {
// set modifier keys if any
mods = [];
key = keys[i].split('+');
if (key.length > 1){
mods = getMods(key);
key = [key[key.length-1]];
}
// convert to keycode and...
key = key[0];
key = code(key);
// ...store handler
if (!(key in _handlers)) _handlers[key] = [];
_handlers[key].push({ shortcut: keys[i], scope, method, key: keys[i], mods });
}
}
// unbind all handlers for given key in current scope
function unbindKey(key, scope) {
let keys,
mods = [],
i, j, obj;
const multipleKeys = getKeys(key);
for (j = 0; j < multipleKeys.length; j++) {
keys = multipleKeys[j].split('+');
if (keys.length > 1) {
mods = getMods(keys);
}
key = keys[keys.length - 1];
key = code(key);
if (scope === undefined) {
scope = getScope();
}
if (!_handlers[key]) {
return;
}
for (i = 0; i < _handlers[key].length; i++) {
obj = _handlers[key][i];
// only clear handlers if correct scope and mods match
if (obj.scope === scope && compareArray(obj.mods, mods)) {
_handlers[key][i] = {};
}
}
}
}
// Returns true if the key with code 'keyCode' is currently down
// Converts strings into key codes.
function isPressed(keyCode) {
if (typeof (keyCode)==='string') {
keyCode = code(keyCode);
}
return index(_downKeys, keyCode) !== -1;
}
function getPressedKeyCodes() {
return _downKeys.slice(0);
}
function filter(event){
const tagName = (event.target || event.srcElement).tagName;
// ignore keypressed in any elements that support keyboard data input
return !(tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA');
}
// initialize key.<modifier> to false
for(k in _MODIFIERS) assignKey[k] = false;
// set current scope (default 'all')
function setScope(scope){ _scope = scope || 'all'; }
function getScope(){ return _scope || 'all'; }
// delete all handlers for a given scope
function deleteScope(scope){
let key, handlers, i;
for (key in _handlers) {
handlers = _handlers[key];
for (i = 0; i < handlers.length; ) {
if (handlers[i].scope === scope) handlers.splice(i, 1);
else i++;
}
}
}
// abstract key logic for assign and unassign
function getKeys(key) {
key = key.replace(/\s/g, '');
const keys = key.split(',');
if ((keys[keys.length - 1]) === '') {
keys[keys.length - 2] += ',';
}
return keys;
}
// abstract mods logic for assign and unassign
function getMods(key) {
const mods = key.slice(0, key.length - 1);
for (let mi = 0; mi < mods.length; mi++) {
mods[mi] = _MODIFIERS[mods[mi]];
}
return mods;
}
// cross-browser events
function addEvent(object, event, method) {
if (object.addEventListener)
object.addEventListener(event, method, false);
else if(object.attachEvent)
object.attachEvent('on'+event, function(){ method(window.event); });
}
// set the handlers globally on document
addEvent(document, 'keydown', function(event) { dispatch(event); }); // Passing _scope to a callback to ensure it remains the same by execution. Fixes #48
addEvent(document, 'keyup', clearModifier);
// reset modifiers to false whenever the window is (re)focused.
addEvent(window, 'focus', resetModifiers);
// store previously defined key
const previousKey = global.key;
// restore previously defined key and return reference to our key object
function noConflict() {
const k = global.key;
global.key = previousKey;
return k;
}
// set window.key and window.key.set/get/deleteScope, and the default filter
global.key = assignKey;
global.key.setScope = setScope;
global.key.getScope = getScope;
global.key.deleteScope = deleteScope;
global.key.filter = filter;
global.key.isPressed = isPressed;
global.key.getPressedKeyCodes = getPressedKeyCodes;
global.key.noConflict = noConflict;
global.key.unbind = unbindKey;
if(typeof module !== 'undefined') module.exports = assignKey;
})(this);