aboutsummaryrefslogtreecommitdiffhomepage
path: root/ui/static/js/keyboard_handler.js
blob: ecf1f44cb414adbd95ffd762e999b44f78fece7e (plain)
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
class KeyboardHandler {
    constructor() {
        this.queue = [];
        this.shortcuts = {};
    }

    on(combination, callback) {
        this.shortcuts[combination] = callback;
    }

    listen() {
        document.onkeydown = (event) => {
            if (this.isEventIgnored(event) || this.isModifierKeyDown(event)) {
                return;
            }

            let key = this.getKey(event);
            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) {
        return event.target.tagName === "INPUT" || event.target.tagName === "TEXTAREA";
    }

    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;
    }
}