forked from github/hotkey
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
57 lines (47 loc) · 1.67 KB
/
Copy pathindex.js
File metadata and controls
57 lines (47 loc) · 1.67 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
/* @flow strict */
import {Leaf, RadixTrie} from './radix-trie'
import {fireDeterminedAction, expandHotkeyToEdges, isFormField} from './utils'
import hotkey from './hotkey'
const hotkeyRadixTrie = new RadixTrie()
const elementsLeaves = new WeakMap()
let currentTriePosition = hotkeyRadixTrie
let resetTriePositionTimer = null
function resetTriePosition() {
resetTriePositionTimer = null
currentTriePosition = hotkeyRadixTrie
}
document.addEventListener('keydown', (event: KeyboardEvent) => {
if (event.target instanceof Node && isFormField(event.target)) return
if (resetTriePositionTimer != null) {
clearTimeout(resetTriePositionTimer)
}
resetTriePositionTimer = setTimeout(resetTriePosition, 1500)
// If the user presses a hotkey that doesn't exist in the Trie,
// they've pressed a wrong key-combo and we should reset the flow
const newTriePosition = currentTriePosition.get(hotkey(event))
if (!newTriePosition) {
resetTriePosition()
return
}
currentTriePosition = newTriePosition
if (newTriePosition instanceof Leaf) {
fireDeterminedAction(newTriePosition.children[newTriePosition.children.length - 1])
event.preventDefault()
resetTriePosition()
return
}
})
export {RadixTrie, Leaf}
export function install(element: HTMLElement) {
const hotkeys = expandHotkeyToEdges(element.getAttribute('data-hotkey') || '')
const leaves = hotkeys.map(hotkey => hotkeyRadixTrie.insert(hotkey).add(element))
elementsLeaves.set(element, leaves)
}
export function uninstall(element: HTMLElement) {
const leaves = elementsLeaves.get(element)
if (leaves && leaves.length) {
for (const leaf of leaves) {
leaf && leaf.delete(element)
}
}
}