Skip to content

Build your personal knowledge base with Trilium Notes

6.1 KB
Raw Blame
import server from "./server.js";
import appContext from "../components/app_context.js";
import { formatShortcut, joinShortcut } from "./keyboard_shortcut_display.js";
import shortcutService, { ShortcutBinding } from "./shortcuts.js";
import { isPreAuthScreen, isShare } from "./utils.js";
import type Component from "../components/component.js";
import { closeOpenPopups } from "../widgets/react/Popup";
import type { ActionKeyboardShortcut } from "@triliumnext/commons";

const keyboardActionRepo: Record<string, ActionKeyboardShortcut> = {};

// Skip on the login / set-password pre-auth screens, where an unauthenticated
// GET /api/keyboard-actions would 401 (#10589), and on shared pages, which have no API; neither
// binds shortcuts.
const keyboardActionsLoaded: Promise<ActionKeyboardShortcut[]> = isPreAuthScreen() || isShare
    ? Promise.resolve([])
    : server.get<ActionKeyboardShortcut[]>("keyboard-actions").then((actions) => {
        actions = actions.filter((a) => !!a.actionName); // filter out separators

        for (const action of actions) {
            action.effectiveShortcuts = (action.effectiveShortcuts ?? []).filter((shortcut) => !shortcut.startsWith("global:"));

            keyboardActionRepo[action.actionName] = action;
        }

        return actions;
    });

async function getActions() {
    return await keyboardActionsLoaded;
}

async function getActionsForScope(scope: string) {
    const actions = await keyboardActionsLoaded;

    return actions.filter((action) => action.scope === scope);
}

async function setupActionsForElement(scope: string, $el: JQuery<HTMLElement>, component: Component, ntxId: string | null | undefined) {
    if (!$el[0]) return [];

    const actions = await getActionsForScope(scope);
    const bindings: ShortcutBinding[] = [];

    for (const action of actions) {
        for (const shortcut of action.effectiveShortcuts ?? []) {
            const binding = shortcutService.bindElShortcut($el, shortcut, () => {
                component.triggerCommand(action.actionName, { ntxId });
            });
            if (binding) {
                bindings.push(binding);
            }
        }
    }

    return bindings;
}

/**
 * Binds every window-scoped action (jump to note, reload, tab switching, …) as a global shortcut
 * routed through `appContext.triggerCommand`. `AppContext.initComponents()` calls this once
 * `appContext.tabManager` exists; binding at module load instead left a window during startup in
 * which a matching keypress (F5 held across a reload, for instance) threw on the missing tab manager.
 */
async function setupWindowShortcuts() {
    const actions = await getActionsForScope("window");

    for (const action of actions) {
        /* v8 ignore next -- effectiveShortcuts is always normalized to an array by the loader (line 13) before this resolves, so the ?? [] fallback is unreachable */
        for (const shortcut of action.effectiveShortcuts ?? []) {
            shortcutService.bindGlobalShortcut(shortcut, () => runWindowAction(action.actionName));
        }
    }
}

/**
 * Binds the window-scoped actions on `$el` as well, for content that keeps its keys from the
 * document, such as the content of an embed in a text note.
 */
async function setupWindowShortcutsForElement($el: JQuery<HTMLElement>) {
    const bindings: ShortcutBinding[] = [];

    for (const action of await getActionsForScope("window")) {
        for (const shortcut of action.effectiveShortcuts ?? []) {
            const binding = shortcutService.bindElShortcut($el, shortcut, () => {
                runWindowAction(action.actionName);
            });
            if (binding) {
                bindings.push(binding);
            }
        }
    }

    return bindings;
}

function runWindowAction(actionName: ActionKeyboardShortcut["actionName"]) {
    // Otherwise an open menu stays over a dialog that the action opens.
    closeOpenPopups();
    return appContext.triggerCommand(actionName, { ntxId: appContext.tabManager.activeNtxId });
}

async function getAction(actionName: string, silent = false) {
    await keyboardActionsLoaded;

    const action = keyboardActionRepo[actionName];

    if (!action) {
        if (silent) {
            console.debug(`Cannot find action '${actionName}'`);
        } else {
            throw new Error(`Cannot find action '${actionName}'`);
        }
    }

    return action;
}

export function getActionSync(actionName: string) {
    return keyboardActionRepo[actionName];
}

function updateDisplayedShortcuts($container: JQuery<HTMLElement>) {
    //@ts-ignore
    //TODO: each() does not support async callbacks.
    $container.find("kbd[data-command]").each(async (i, el) => {
        const actionName = $(el).attr("data-command");
        if (!actionName) {
            return;
        }

        const action = await getAction(actionName, true);

        if (action) {
            const keyboardActions = formatShortcutList(action.effectiveShortcuts);

            if (keyboardActions || $(el).text() !== "not set") {
                $(el).text(keyboardActions);
            }
        }
    });

    //@ts-ignore
    //TODO: each() does not support async callbacks.
    $container.find("[data-trigger-command]").each(async (i, el) => {
        const actionName = $(el).attr("data-trigger-command");
        if (!actionName) {
            return;
        }
        const action = await getAction(actionName, true);

        if (action) {
            const title = $(el).attr("title");
            const shortcuts = formatShortcutList(action.effectiveShortcuts);

            if (title?.includes(shortcuts)) {
                return;
            }

            const newTitle = !title?.trim() ? shortcuts : `${title} (${shortcuts})`;

            $(el).attr("title", newTitle);
        }
    });
}

export default {
    updateDisplayedShortcuts,
    setupWindowShortcuts,
    setupWindowShortcutsForElement,
    setupActionsForElement,
    getAction,
    getActions,
    getActionsForScope
};

/** Renders a list of stored shortcuts into a localized, comma-separated display string. */
function formatShortcutList(shortcuts: string[] | undefined) {
    return (shortcuts ?? []).map((shortcut) => joinShortcut(formatShortcut(shortcut))).join(", ");
}