]> BookStack Code Mirror - bookstack/blob - resources/js/components/shortcut-input.js
Updated a batch of JS components
[bookstack] / resources / js / components / shortcut-input.js
1 import {Component} from "./component";
2
3 /**
4  * Keys to ignore when recording shortcuts.
5  * @type {string[]}
6  */
7 const ignoreKeys = ['Control', 'Alt', 'Shift', 'Meta', 'Super', ' ', '+', 'Tab', 'Escape'];
8
9 export class ShortcutInput extends Component {
10
11     setup() {
12         this.input = this.$el;
13
14         this.setupListeners();
15     }
16
17     setupListeners() {
18         this.listenerRecordKey = this.listenerRecordKey.bind(this);
19
20         this.input.addEventListener('focus', () => {
21              this.startListeningForInput();
22         });
23
24         this.input.addEventListener('blur', () => {
25             this.stopListeningForInput();
26         })
27     }
28
29     startListeningForInput() {
30         this.input.addEventListener('keydown', this.listenerRecordKey)
31     }
32
33     /**
34      * @param {KeyboardEvent} event
35      */
36     listenerRecordKey(event) {
37         if (ignoreKeys.includes(event.key)) {
38             return;
39         }
40
41         const keys = [
42             event.ctrlKey ? 'Ctrl' : '',
43             event.metaKey ? 'Cmd' : '',
44             event.key,
45         ];
46
47         this.input.value = keys.filter(s => Boolean(s)).join(' + ');
48     }
49
50     stopListeningForInput() {
51         this.input.removeEventListener('keydown', this.listenerRecordKey);
52     }
53
54 }