diff options
author | 2023-08-10 19:46:45 -0700 | |
---|---|---|
committer | 2023-08-10 20:29:34 -0700 | |
commit | 168a870c025bfef6efdeb46e166e79a16093c157 (patch) | |
tree | 4d8ab69c7e3ef03a7ade06e7b5e5053429a64c3b /internal/ui/static/js/keyboard_handler.js | |
parent | c2349032552891745cbbc3d2a9e772845a0239f4 (diff) | |
download | v2-168a870c025bfef6efdeb46e166e79a16093c157.tar.gz v2-168a870c025bfef6efdeb46e166e79a16093c157.tar.zst v2-168a870c025bfef6efdeb46e166e79a16093c157.zip |
Move internal packages to an internal folder
For reference: https://go.dev/doc/go1.4#internalpackages
Diffstat (limited to 'internal/ui/static/js/keyboard_handler.js')
-rw-r--r-- | internal/ui/static/js/keyboard_handler.js | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/internal/ui/static/js/keyboard_handler.js b/internal/ui/static/js/keyboard_handler.js new file mode 100644 index 00000000..037f9949 --- /dev/null +++ b/internal/ui/static/js/keyboard_handler.js @@ -0,0 +1,72 @@ +class KeyboardHandler { + constructor() { + this.queue = []; + this.shortcuts = {}; + this.triggers = []; + } + + on(combination, callback) { + this.shortcuts[combination] = callback; + this.triggers.push(combination.split(" ")[0]); + } + + listen() { + document.onkeydown = (event) => { + let key = this.getKey(event); + if (this.isEventIgnored(event, key) || this.isModifierKeyDown(event)) { + return; + } + + event.preventDefault(); + this.queue.push(key); + + for (let combination in this.shortcuts) { + let keys = combination.split(" "); + + if (keys.every((value, index) => value === this.queue[index])) { + this.queue = []; + this.shortcuts[combination](event); + return; + } + + if (keys.length === 1 && key === keys[0]) { + this.queue = []; + this.shortcuts[combination](event); + return; + } + } + + if (this.queue.length >= 2) { + this.queue = []; + } + }; + } + + isEventIgnored(event, key) { + return event.target.tagName === "INPUT" || + event.target.tagName === "TEXTAREA" || + (this.queue.length < 1 && !this.triggers.includes(key)); + } + + isModifierKeyDown(event) { + return event.getModifierState("Control") || event.getModifierState("Alt") || event.getModifierState("Meta"); + } + + getKey(event) { + const mapping = { + 'Esc': 'Escape', + 'Up': 'ArrowUp', + 'Down': 'ArrowDown', + 'Left': 'ArrowLeft', + 'Right': 'ArrowRight' + }; + + for (let key in mapping) { + if (mapping.hasOwnProperty(key) && key === event.key) { + return mapping[key]; + } + } + + return event.key; + } +} |