File: keyboard_handler.js

package info (click to toggle)
miniflux 2.2.16-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,188 kB
  • sloc: xml: 4,853; javascript: 1,158; sh: 257; makefile: 161
file content (68 lines) | stat: -rw-r--r-- 1,980 bytes parent folder | download | duplicates (2)
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
68
class KeyboardHandler {
    constructor() {
        this.queue = [];
        this.shortcuts = {};
        this.triggers = new Set();
    }

    on(combination, callback) {
        this.shortcuts[combination] = callback;
        this.triggers.add(combination.split(" ")[0]);
    }

    listen() {
        document.onkeydown = (event) => {
            const key = KeyboardHandler.getKey(event);
            if (this.isEventIgnored(event, key) || KeyboardHandler.isModifierKeyDown(event)) {
                return;
            }

            if (key !== "Enter") {
                event.preventDefault();
            }

            this.queue.push(key);

            for (const combination in this.shortcuts) {
                const 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.has(key));
    }

    static isModifierKeyDown(event) {
        return event.getModifierState("Control") || event.getModifierState("Alt") || event.getModifierState("Meta");
    }

    static getKey(event) {
        switch (event.key) {
        case 'Esc': return 'Escape';
        case 'Up': return 'ArrowUp';
        case 'Down': return 'ArrowDown';
        case 'Left': return 'ArrowLeft';
        case 'Right': return 'ArrowRight';
        default: return event.key;
        }
    }
}