-
Notifications
You must be signed in to change notification settings - Fork 3
/
kanye.js
147 lines (125 loc) · 2.63 KB
/
kanye.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
'use strict';
var sektor = require('sektor');
var crossvent = require('crossvent');
var rspaces = /\s+/g;
var keymap = {
13: 'enter',
27: 'esc',
32: 'space'
};
var handlers = {};
crossvent.add(window, 'keydown', keydown);
function clear (context) {
if (context) {
if (context in handlers) {
handlers[context] = {};
}
} else {
handlers = {};
}
}
function switchboard (then, combo, options, fn) {
if (fn === void 0) {
fn = options;
options = {};
}
var context = options.context || 'defaults';
if (!fn) {
return;
}
if (handlers[context] === void 0) {
handlers[context] = {};
}
combo.toLowerCase().split(rspaces).forEach(item);
function item (keys) {
var c = keys.trim();
if (c.length === 0) {
return;
}
then(handlers[context], c, options, fn);
}
}
function on (combo, options, fn) {
switchboard(add, combo, options, fn);
function add (area, key, options, fn) {
var handler = {
handle: fn,
filter: options.filter
};
if (area[key]) {
area[key].push(handler);
} else {
area[key] = [handler];
}
}
}
function off (combo, options, fn) {
switchboard(rm, combo, options, fn);
function rm (area, key, options, fn) {
if (area[key]) {
area[key] = area[key].filter(matching);
}
function matching (handler) {
return handler.handle === fn && handler.filter === options.filter;
}
}
}
function getKeyCode (e) {
return e.which || e.keyCode || e.charCode;
}
function keydown (e) {
var code = getKeyCode(e);
var key = keymap[code] || String.fromCharCode(code);
if (key) {
handle(key, e);
}
}
function parseKeyCombo (key, e) {
var combo = [key];
if (e.shiftKey) {
combo.unshift('shift');
}
if (e.altKey) {
combo.unshift('alt');
}
if (e.ctrlKey ^ e.metaKey) {
combo.unshift('cmd');
}
return combo.join('+').toLowerCase();
}
function handle (key, e) {
var combo = parseKeyCombo(key, e);
var context;
for (context in handlers) {
if (handlers[context][combo]) {
handlers[context][combo].forEach(exec);
}
}
function filtered (handler) {
var filter = handler.filter;
if (!filter) {
return;
}
var el = e.target;
var selector = typeof filter === 'string';
if (selector) {
return sektor.matchesSelector(el, filter) === false;
}
while (el.parentElement && el !== filter) {
el = el.parentElement;
}
return el !== filter;
}
function exec (handler) {
if (filtered(handler)) {
return;
}
handler.handle(e);
}
}
module.exports = {
on: on,
off: off,
clear: clear,
handlers: handlers
};