summaryrefslogtreecommitdiff
path: root/wwwroot/js/keyboard.js
blob: 392a7d1a3d37ba8fa3440e91e97c130d22498621 (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
async function keyDownHandler(e) {
    function isDialogChild(e) {
        while(e = e.parentElement)
            if(e.tagName == 'DIV' && e.classList.contains('dialog'))
                return true;
        return false;
    }

    var tag = document.activeElement.tagName;
    if((tag == 'INPUT' || (tag == 'TEXTAREA' && e.ctrlKey)) && e.key == 'Enter') {
        var element = document.activeElement;
        while(element = element.parentElement) {
            if(element.tagName == 'FORM') {
                element.submit();
                e.preventDefault();
                return;
            }
        }
    }

    if((tag == 'INPUT' || tag == 'TEXTAREA') && e.key != 'Escape')
        return;

    var element = Array.from(document.querySelectorAll('div.dialog'))
        .filter(e => e.style.visibility == 'visible')
        .map(e => ({ element: e, zIndex: parseInt(e.style.zIndex) }))
        .sort((a, b) => b.zIndex - a.zIndex)
        .map(e => e.element)[0];

    if(element) {
        await window.dialogObjects
            .find(d => d.element == element)
            .dialogObject
            .invokeMethodAsync('KeyHandler', e.key);
        e.preventDefault();
        return;
    }

    var button = Array.from(document.getElementsByTagName('button'))
        .filter(b => typeof(b.dataset.keyboardShortcut) == 'string')
        .filter(b => !isDialogChild(b))
        .find(b => b.dataset.keyboardShortcut == e.key);

    if(button) {
        button.click();
        e.preventDefault();
        return;
    }
}

window.onload = () => document.onkeydown = keyDownHandler;