What UI element is 'in focus'?


#1

I would like to start creating a package Adom. This package will communicate to third-party programs which UI element is in focus and what keyboard shortcuts and command palette shortcuts are available within that focus. In addition how do I read the file that contains all available keyboard shortcuts and command palette.

Any suggestions on where to start within the official documentation?


#2

document.activeElement is the element in focus. Note that if you use Shadow DOM, it encapsulates the element. In that case, you want to recurse the shadow tree:

function getDeepActiveElement() {
    let activeElement = document.activeElement;
    if (!activeElement) return null;
    while (activeElement.shadowRoot && activeElement.shadowRoot.activeElement) {
        activeElement = activeElement.shadowRoot.activeElement;
    }
    return activeElement;
}

Or as a jQuery extension:

$.extend($.expr[':'], {
    'deep-focus': function(el, index, selector) {
        let activeElement = document.activeElement;
        if (!activeElement) return false;
        while (activeElement.shadowRoot && activeElement.shadowRoot.activeElement) {
            activeElement = activeElement.shadowRoot.activeElement;
        }
        return el === activeElement;
    }
});

which allows you to do let focused = $(':deep-focus');

Regarding reading a file, check out https://nodejs.org/api/fs.html#fs_fs_readfile_filename_options_callback – Electron embeds Node so you can just do let fs = require('fs'); and then use it as mentioned in the nodejs docs I linked.


#3

As far as keymaps and commands go, check the KeymapManager and CommandRegistry classes.


#4

And regarding keybindings, they don’t traverse shadow DOM so you don’t need to continue inside the shadow root. And if you want to expose an element in a shadow DOM so that it can receive commands you’ll need to use the content element.