-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhotkey.class.js
More file actions
88 lines (76 loc) · 1.63 KB
/
hotkey.class.js
File metadata and controls
88 lines (76 loc) · 1.63 KB
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
export default class Hotkey {
constructor(name, func, {
keys = [],
clicks = [],
} = {}) {
try {
this.name = name;
this.fn = func;
this.keys = [];
this.clicks = [];
if (Array.isArray(keys)) {
keys.forEach((k) => this.bindKey(k));
} else if (typeof keys === 'string') {
this.bindKey(keys);
}
if (Array.isArray(clicks)) {
clicks.forEach((c) => this.bindClick(c));
} else if (clicks) {
this.bindClick(clicks);
}
} catch (_) {
// Ignore
}
}
has(x, a = []) {
return a.some((v) => v === x);
}
del(x, a) {
a.some((v, i) => {
if (x === v) {
a.splice(i, 1);
return true;
}
return false;
});
}
bindKey(x) {
if (!this.keybound(x)) {
this.keys.push(x);
}
return this;
}
unbindKey(x) {
this.del(x, this.keys);
return this;
}
keybound(x) {
return this.has(x, this.keys);
}
bindClick(x) {
if (!this.clickbound(x)) {
this.clicks.push(x);
}
return this;
}
unbindClick(x) {
this.del(x, this.clicks);
return this;
}
clickbound(x) {
return this.has(x, this.clicks);
}
run(x, ...rest) {
if (typeof x === 'function') { // Set the function
this.fn = x;
return this; // Allow inline constructing
}
if (typeof this.fn === 'function') { // All clear (x is the event)
return this.fn(x, ...rest);
}
return undefined;
}
toString() {
return `${this.name || 'Hotkey'}: Bind{Keys:${JSON.stringify(this.keys)}, Clicks:${JSON.stringify(this.clicks)}}, FN:${this.fn !== null}`;
}
}