-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
65 lines (58 loc) · 1.55 KB
/
index.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
import { Controller } from 'stimulus'
import hotkeys from 'hotkeys-js'
export default class extends Controller {
static get values () {
return {
key: String,
event: String
}
}
initialize () {
if (this.keyValue) {
this.valid = true
} else {
console.warn('Shortcut key must be defined. Unloading controller.')
this.element.dataset.controller = this.element.dataset.controller
.split(' ')
.filter(controller => controller !== 'shortcut')
.join(' ')
return
}
this.actOnHotkey = this.actOnHotkey.bind(this)
const event =
this.eventValue ||
this.defaultEventNames[this.element.tagName.toLowerCase()] ||
'click'
this.eventFactory = this.newEvent.bind(null, this.element, event)
}
connect () {
if (this.valid) {
this.actOnHotkey(hotkeys)
this.connected = true
}
}
disconnect () {
if (this.connected) this.actOnHotkey(hotkeys.unbind)
this.connected = false
}
actOnHotkey (func) {
setTimeout(() => {
func.call(null, this.keyValue, this.eventFactory)
}, 1)
}
newEvent (element, event) {
element.dispatchEvent(
new CustomEvent(event, { bubbles: true, cancelable: true })
)
}
get defaultEventNames () {
return {
a: e => 'click',
button: e => 'click',
form: e => 'submit',
input: e => (e.getAttribute('type') == 'submit' ? 'click' : 'input'),
select: e => 'change',
textarea: e => 'input'
}
}
}