forked from nan-academy/tron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkey-handler.js
69 lines (62 loc) · 1.17 KB
/
key-handler.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
import { isFn } from './is.js'
const regular = {
8: 'backspace',
9: 'tab',
13: 'enter',
32: 'space',
37: 'left',
38: 'up',
39: 'right',
40: 'down',
186: ';',
187: '=',
188: ',',
189: '-',
190: '.',
191: '/',
192: '`',
219: '[',
220: '\\',
221: ']',
222: "'",
}
const shifted = Object.assign({}, regular, {
48: ')',
49: '!',
50: '@',
51: '#',
52: '$',
53: '%',
54: '^',
55: '&',
56: '*',
57: '(',
186: ':',
187: '+',
188: '<',
189: '_',
190: '>',
191: '?',
192: '~',
219: '{',
220: '|',
221: '}',
222: '"',
})
const getAlias = (ev, which) => (ev.shiftKey ? shifted : regular)[which]
|| String.fromCharCode(which)
const applyMod = (ev, prev, fn) => fn
? applyMod(ev, fn, (ev.ctrlKey && fn.ctrl)
|| (ev.shiftKey && fn.shift)
|| (ev.metaKey && fn.meta)
|| (ev.altKey && fn.alt)
|| fn.none)
: prev
const noOp = () => {}
export default (handlers, fallback = noOp) => ev => {
let fn = handlers[ev.key.toLowerCase()] || handlers[getAlias(ev, ev.which)]
if (!fn) return fallback(ev)
fn = applyMod(ev, fn, fn)
if (!isFn(fn)) return fallback(ev)
if (fn(ev) !== false) ev.preventDefault()
}