This repository has been archived by the owner on Nov 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shortcut.js
63 lines (54 loc) · 2.03 KB
/
shortcut.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
let _shortcutExitEventTypes = [
"focusin",
"focusout",
"blur",
"visibilitychange"
]
class Shortcut {
constructor(prompt, callback) {
this.prompt = prompt
this.callback = callback
this.pressedKeys = new Set()
this.pressedModifiers = new Set()
this.boundKd = this.kd.bind(this)
this.boundKu = this.ku.bind(this)
this.doneOnce = false
document.addEventListener("keydown", this.boundKd)
document.addEventListener("keyup", this.boundKu)
_shortcutExitEventTypes.forEach(item => document.addEventListener(item, this.reset))
}
kd(event) {
let keys = this.prompt.keys ? this.prompt.keys.map(key => key.toLowerCase()) : []
this.prompt.keys = keys
if (this.prompt.keys.includes(event.key.toLowerCase())) {
this.pressedKeys.add(event.key.toLowerCase())
}
let map = { alt: "Alt", control: "Control", meta: "Meta", shift: "Shift" }
for (let [key, value] of Object.entries(map)) {
if (event.key == value) this.pressedModifiers.add(key)
}
let hasAllKeys = this.prompt.keys.every(key => this.pressedKeys.has(key))
let hasAllModifiers = Object.keys(map).every(key => this.prompt.implicit ? (this.pressedModifiers.has(key) === this.prompt[key] || this.prompt[key] == null) : (!!this.pressedModifiers.has(key) === !!this.prompt[key] || this.prompt[key] === null))
if (hasAllKeys && hasAllModifiers && (this.prompt.repeat ? true : !this.doneOnce)) {
this.callback(event)
this.doneOnce = true
}
}
ku(event) {
if (this.prompt.keys.includes(event.key)) this.pressedKeys.delete(event.key)
let map = { alt: "Alt", control: "Control", meta: "Meta", shift: "Shift" }
for (let [key, value] of Object.entries(map)) {
if (event.key == value) this.pressedModifiers.delete(key)
}
this.doneOnce = false
}
reset() {
this.pressedKeys?.clear()
this.pressedModifiers?.clear()
this.doneOnce = false
}
kill() {
document.removeEventListener("keydown", this.boundKd)
document.removeEventListener("keyup", this.boundKu)
}
}