Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

80.2 KB
Raw Blame
import type {BlockQueryRequestInput} from "../../types/api";
import {isAbove} from "../../util/zIndex";
import {stripSemanticMarkersFromRangeText} from "../../protyle/util/inlineElementMarker";
import {
    copyPlainText,
    isMac,
    isNotCtrl,
    updateHotkeyTip,
    writeText
} from "../../protyle/util/compatibility";
import {matchAuxiliaryHotKey, matchHotKey} from "../../protyle/util/hotKey";
import {
    hasClosestBlock,
    hasClosestByAttribute,
    hasClosestByClassName,
    hasTopClosestByTag,
} from "../../protyle/util/hasClosest";
import {newFile} from "../../util/newFile";
import {Constants} from "../../constants";
import {openSetting} from "../../config";
import {getInstanceById, saveLayout} from "../../layout/util";
import {getActiveTab, getDockByType, switchTabByIndex} from "../../layout/tabUtil";
import {Tab} from "../../layout/Tab";
import {Editor} from "../../editor";
import {toggleEditMode} from "../../protyle/util/toggleEditMode";
import {rename} from "../../editor/rename";
import {Files} from "../../layout/dock/Files";
import {newDailyNote} from "../../util/mount";
import {hideElements} from "../../protyle/ui/hideElements";
import {fetchPost} from "../../util/fetch";
import {goBack, goForward} from "../../util/backForward";
import {getDisplayName, getNotebookName, isEncryptedBox} from "../../util/pathName";
import {openFileById} from "../../editor/util";
import {getAllDocks, getAllEditor, getAllModels, getAllTabs} from "../../layout/getAll";
import {getDockHotkey, getDockKeymap} from "../../layout/dock/hotkey";
import {getKeymapBindings} from "../../util/keymapBindings";
import {focusBlock, getBlockElementsByRange, selectBlocksByRange} from "../../protyle/util/selection";
import {focusByRange} from "../../protyle/util/selectionOffsets";
import {initFileMenu, initNavigationMenu} from "../../menus/navigation";
import {bindMenuKeydown} from "../../menus/Menu";
import {Dialog} from "../../dialog";
import {getFileTreeIconHTML} from "../../emoji/fileTreeIcon";
import {deleteFiles} from "../../editor/deleteFile";
import {escapeHtml} from "../../util/escape";
import {syncGuide} from "../../sync/syncGuide";
import {duplicateBlock, getStartEndElement} from "../../protyle/wysiwyg/commonHotkey";
import {handleDocumentBoundaryHotkey} from "../../protyle/util/documentBoundaryHotkey";
import {handleDatabaseRowShortcut} from "../../command/databaseRowShortcut";
import {getNextFileLi, getPreviousFileLi} from "../../protyle/wysiwyg/getBlock";
import {Backlink} from "../../layout/dock/Backlink";
/// #if !BROWSER
import {setZoom} from "../../layout/topBar";
/// #endif
import {openHistory} from "../../history/history";
import {openCard, openCardByData} from "../../card/openCard";
import {lockScreen} from "../../dialog/processSystem";
import {isWindow} from "../../util/functions";
import {reloadProtyle} from "../../protyle/util/reload";
import {openRecentDocs} from "../../business/openRecentDocs";
import type {App} from "../../index";
import {toggleDockPanel} from "../../layout/dock/panel";
import {openBacklink, openGraph, openOutline, toggleDockBar} from "../../layout/dock/util";
import {workspaceMenu} from "../../menus/workspace";
import {Search} from "../../search";
import {Custom} from "../../layout/dock/Custom";
import {transaction} from "../../protyle/wysiwyg/transaction";
import {quickMakeCard} from "../../card/makeCard";
import {getContentByInlineHTML} from "../../protyle/wysiwyg/keydown";
import {searchKeydown} from "./searchKeydown";
import {historyKeydown} from "../../history/keydown";
import {zoomOut} from "../../menus/protyle";
import {getPlainText} from "../../protyle/util/paste";
import {commandPanel} from "./command/panel";
import {execByCommand} from "../../command/executor";
import {captureCommandContext} from "../../command/context";
import {captureShortcutContext, dispatchPluginShortcut} from "../../command/shortcutRuntime";
import {filterHotkey} from "./commonHotkey";
import {editorConfigApi} from "../../config/tabs/editorRuntime";
import {copyPNGByLink} from "../../menus/util";
import {globalCommand} from "./command/global";
import {duplicateCompletely} from "../../protyle/render/av/action";
import {copyTextByType} from "../../protyle/toolbar/util";
import {onlyProtyleCommand} from "./command/protyle";
import {cancelDrag} from "./dragover";
import {bindAVPanelKeydown} from "../../protyle/render/av/keydown";
import {getAVCellPanelTarget} from "../../protyle/render/av/panelTarget";
import {formatPainter} from "../../protyle/toolbar/FormatPainter";
import {adjustEditorFontSize, type TEditorFontSizeAction} from "../../util/editorFontSize";
import {areProtylePluginExtensionsEnabled} from "../../protyle/runtimeCapabilities";

const EDITOR_FONT_SIZE_COMMANDS: Array<{
    command: "increaseEditorFontSize" | "decreaseEditorFontSize" | "resetEditorFontSize",
    action: TEditorFontSizeAction,
}> = [
    {command: "increaseEditorFontSize", action: "increase"},
    {command: "decreaseEditorFontSize", action: "decrease"},
    {command: "resetEditorFontSize", action: "reset"},
];

const getReadonlyBlockSelectionProtyle = (range: Range) => {
    const startElement = hasClosestBlock(range.startContainer);
    const endElement = hasClosestBlock(range.endContainer);
    if (!startElement || !endElement || startElement === endElement) {
        return;
    }
    const protyle = getAllEditor().find(item => item.protyle.wysiwyg.element.contains(startElement) &&
        item.protyle.wysiwyg.element.contains(endElement))?.protyle;
    if (!protyle?.disabled) {
        return;
    }
    return protyle;
};

const selectReadonlyBlocksByRange = (range: Range) => {
    const protyle = getReadonlyBlockSelectionProtyle(range);
    if (!protyle) {
        return false;
    }
    hideElements(["toolbar", "hint", "util", "select"], protyle);
    selectBlocksByRange(protyle, range);
    return true;
};

const switchDialogEvent = (app: App, event: MouseEvent) => {
    event.preventDefault();
    let target = event.target as HTMLElement;
    while (target !== switchDialog.element) {
        if (target.classList.contains("b3-list-item")) {
            const currentType = target.getAttribute("data-type");
            if (currentType) {
                if (currentType === "riffCard") {
                    openCard(app);
                } else {
                    getDockByType(currentType).toggleModel(currentType, true);
                }
            } else {
                const currentId = target.getAttribute("data-id");
                getAllTabs().find(item => {
                    if (item.id === currentId) {
                        item.parent.switchTab(item.headElement);
                        item.parent.showHeading();
                        return true;
                    }
                });
            }
            switchDialog.destroy();
            switchDialog = undefined;
            break;
        }
        target = target.parentElement;
    }
};

const dialogArrow = (app: App, element: HTMLElement, event: KeyboardEvent) => {
    let currentLiElement = element.querySelector(".b3-list-item--focus");
    if (currentLiElement) {
        currentLiElement.classList.remove("b3-list-item--focus");
        if (event.key === "ArrowUp") {
            if (currentLiElement.previousElementSibling) {
                currentLiElement.previousElementSibling.classList.add("b3-list-item--focus");
            } else {
                currentLiElement.parentElement.lastElementChild.classList.add("b3-list-item--focus");
            }
        } else if (event.key === "ArrowDown") {
            if (currentLiElement.nextElementSibling) {
                currentLiElement.nextElementSibling.classList.add("b3-list-item--focus");
            } else {
                currentLiElement.parentElement.firstElementChild.classList.add("b3-list-item--focus");
            }
        } else if (event.key === "ArrowLeft" || event.key === "ArrowRight") {
            const sideElement = currentLiElement.parentElement.previousElementSibling || currentLiElement.parentElement.nextElementSibling;
            if (sideElement) {
                const tempLiElement = sideElement.querySelector(`[data-index="${currentLiElement.getAttribute("data-index")}"]`) || sideElement.lastElementChild;
                if (tempLiElement) {
                    tempLiElement.classList.add("b3-list-item--focus");
                } else {
                    currentLiElement.classList.add("b3-list-item--focus");
                }
            } else {
                currentLiElement.classList.add("b3-list-item--focus");
            }
        } else if (event.key === "Enter") {
            const currentType = currentLiElement.getAttribute("data-type");
            if (currentType) {
                if (currentType === "riffCard") {
                    openCard(app);
                } else {
                    getDockByType(currentType).toggleModel(currentType, true);
                }
            } else {
                openFileById({
                    app,
                    id: currentLiElement.getAttribute("data-node-id"),
                    action: [Constants.CB_GET_FOCUS, Constants.CB_GET_SCROLL]
                });
            }
            hideElements(["dialog"]);
            return;
        }
        currentLiElement = element.querySelector(".b3-list-item--focus");
        const rootId = currentLiElement.getAttribute("data-node-id");
        const pathElement = element.querySelector(".switch-doc__path");
        if (rootId) {
            fetchPost("/api/filetree/getFullHPathByID", {
                id: rootId
            }, (response) => {
                pathElement.innerHTML = escapeHtml(response.data);
            });
        } else {
            pathElement.innerHTML = currentLiElement.querySelector(".b3-list-item__text").innerHTML;
        }
        const currentRect = currentLiElement.getBoundingClientRect();
        const currentParentRect = currentLiElement.parentElement.getBoundingClientRect();
        if (currentRect.top < currentParentRect.top) {
            currentLiElement.scrollIntoView(true);
        } else if (currentRect.bottom > currentParentRect.bottom) {
            currentLiElement.scrollIntoView(false);
        }
    }
};

// 文档操作只依赖所属编辑器,可选选区仅用于正文中的引用定位和搜索。
const documentKeydown = (app: App, event: KeyboardEvent, protyle: IProtyle, range: Range, isFileFocus: boolean) => {
    if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.general.replace, event)) {
        execByCommand({
            command: "replace",
            app,
            protyle,
            previousRange: range
        });
        event.preventDefault();
        return true;
    }
    if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.general.search, event)) {
        execByCommand({
            command: "search",
            app,
            protyle,
            previousRange: range
        });
        event.preventDefault();
        return true;
    }
    if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.editor.general.spaceRepetition, event) &&
        !window.siyuan.config.readonly && !isEncryptedBox(protyle.notebookId)) {
        fetchPost("/api/riff/getTreeRiffDueCards", {rootID: protyle.block.rootID}, (response) => {
            openCardByData(app, response.data, "doc", protyle.block.rootID, protyle.title?.editElement.textContent || window.siyuan.languages.untitled, true);
        });
        event.preventDefault();
        return true;
    }
    if (matchHotKey(window.siyuan.config.keymap.editor.general.exitFocus, event)) {
        event.preventDefault();
        zoomOut({protyle, id: protyle.block.rootID, focusId: protyle.block.id});
        return true;
    }
    if (matchHotKey(window.siyuan.config.keymap.editor.general.switchReadonly, event)) {
        event.preventDefault();
        onlyProtyleCommand({
            protyle,
            command: "switchReadonly",
            previousRange: range,
        });
        return true;
    }
    if (matchHotKey(window.siyuan.config.keymap.editor.general.switchAdjust, event)) {
        event.preventDefault();
        onlyProtyleCommand({
            protyle,
            command: "switchAdjust",
            previousRange: range,
        });
        return true;
    }

    if (matchHotKey(window.siyuan.config.keymap.editor.general.backlinks, event)) {
        event.preventDefault();
        if (range) {
            const refElement = hasClosestByAttribute(range.startContainer, "data-type", "block-ref");
            if (refElement) {
                openBacklink({
                    app: protyle.app,
                    blockId: refElement.dataset.id,
                    notebookId: protyle.notebookId,
                });
                return true;
            }
        }
        openBacklink({
            app: protyle.app,
            blockId: protyle.block.id,
            rootId: protyle.block.rootID,
            notebookId: protyle.notebookId,
            useBlockId: protyle.block.showAll,
            title: protyle.title ? (protyle.title.editElement.textContent || window.siyuan.languages.untitled) : null,
        });
        return true;
    }
    if (matchHotKey(window.siyuan.config.keymap.editor.general.graphView, event)) {
        event.preventDefault();
        if (range) {
            const refElement = hasClosestByAttribute(range.startContainer, "data-type", "block-ref");
            if (refElement) {
                openGraph({
                    app: protyle.app,
                    blockId: refElement.dataset.id,
                    notebookId: protyle.notebookId,
                });
                return true;
            }
        }
        openGraph({
            app: protyle.app,
            blockId: protyle.block.id,
            rootId: protyle.block.rootID,
            notebookId: protyle.notebookId,
            useBlockId: protyle.block.showAll,
            title: protyle.title ? (protyle.title.editElement.textContent || window.siyuan.languages.untitled) : null,
        });
        return true;
    }
    if (matchHotKey(window.siyuan.config.keymap.editor.general.outline, event)) {
        event.preventDefault();
        openOutline({
            app,
            rootId: protyle.block.rootID,
            notebookId: protyle.notebookId,
            title: protyle.options.render.title ? (protyle.title.editElement.textContent || window.siyuan.languages.untitled) : "",
            isPreview: !protyle.preview.element.classList.contains("fn__none")
        });
        return true;
    }
    if (matchHotKey(window.siyuan.config.keymap.editor.general.refresh, event)) {
        reloadProtyle(protyle, true);
        event.preventDefault();
        return true;
    }
    if (matchHotKey(window.siyuan.config.keymap.editor.general.fullscreen, event)) {
        const editor = protyle.getInstance();
        editor.setFullscreen(!editor.isFullscreen());
        event.preventDefault();
        return true;
    }
    if (!event.repeat && !protyle.options.backlinkData &&
        matchHotKey(window.siyuan.config.keymap.editor.general.editMode, event)) {
        toggleEditMode(protyle);
        saveLayout();
        event.preventDefault();
        return true;
    }
    return false;
};

const editKeydown = (app: App, event: KeyboardEvent) => {
    const eventTarget = event.target as HTMLElement;
    if (hasClosestByClassName(eventTarget, "sy__backlink--bottom", true) &&
        !hasClosestByClassName(eventTarget, "protyle", true)) {
        return false;
    }
    // 优先使用事件所属编辑器,避免只读正文获得焦点后仍命中其他编辑器的选区。
    let protyle = getAllEditor().find(item => item.protyle.element.contains(eventTarget))?.protyle;
    let range: Range;
    if (getSelection().rangeCount > 0) {
        range = getSelection().getRangeAt(0);
    }
    const activePanelElement = document.querySelector(".layout__tab--active");
    let isFileFocus = false;
    if (!protyle && activePanelElement && activePanelElement.classList.contains("sy__file")) {
        isFileFocus = true;
    }
    if (!protyle && range) {
        window.siyuan.dialogs.find(item => {
            if (item.editors) {
                Object.keys(item.editors).find(key => {
                    if (item.editors[key].protyle.element.contains(range.startContainer)) {
                        protyle = item.editors[key].protyle;
                        // https://github.com/siyuan-note/siyuan/issues/9384
                        isFileFocus = false;
                        return true;
                    }
                });
                if (protyle) {
                    return true;
                }
            }
        });
    }
    const activeTab = getActiveTab();
    if (!protyle && activeTab) {
        if (activeTab.model instanceof Editor) {
            protyle = activeTab.model.getCurrentProtyle(range);
        } else if (activeTab.model instanceof Search) {
            if (activeTab.model.element.querySelector("#searchUnRefPanel").classList.contains("fn__none")) {
                protyle = activeTab.model.editors.edit.protyle;
            } else {
                protyle = activeTab.model.editors.unRefEdit.protyle;
            }
        } else if (activeTab.model instanceof Custom && activeTab.model.editors?.length > 0) {
            if (range) {
                activeTab.model.editors.find(item => {
                    if (item.protyle.element.contains(range.startContainer)) {
                        protyle = item.protyle;
                        return true;
                    }
                });
            }
        }
        if (!protyle) {
            return;
        }
    } else if (!protyle) {
        if (!protyle && range) {
            window.siyuan.blockPanels.find(item => {
                item.editors.find(editorItem => {
                    if (editorItem.protyle.element.contains(range.startContainer)) {
                        protyle = editorItem.protyle;
                        return true;
                    }
                });
                if (protyle) {
                    return true;
                }
            });
        }
        const models = getAllModels();
        if (!protyle) {
            models.backlink.find(item => {
                if (item.element.classList.contains("layout__tab--active")) {
                    if (range) {
                        item.editors.find(editor => {
                            if (editor.protyle.element.contains(range.startContainer)) {
                                protyle = editor.protyle;
                                return true;
                            }
                        });
                    }
                    if (!protyle && item.editors.length > 0) {
                        protyle = item.editors[0].protyle;
                    }
                    return true;
                }
            });
        }
        if (!protyle) {
            models.editor.find(item => {
                if (item.parent.headElement.classList.contains("item--focus")) {
                    protyle = item.editor.protyle;
                    return true;
                }
            });
        }
        if (!protyle) {
            return false;
        }
    }
    if (protyle.disabled && [
        window.siyuan.config.keymap.general.move,
        window.siyuan.config.keymap.general.addToDatabase,
        window.siyuan.config.keymap.editor.general.quickMakeCard,
        window.siyuan.config.keymap.editor.general.duplicate,
        window.siyuan.config.keymap.editor.general.duplicateCompletely,
        window.siyuan.config.keymap.editor.general.undo,
        window.siyuan.config.keymap.editor.general.redo,
    ].some(keymap => matchHotKey(keymap, event))) {
        // 内容修改在编辑快捷键入口拦截,不阻断搜索、导航和其他全局操作。
        event.preventDefault();
        return true;
    }
    // 控件焦点不携带正文残留选区,文档命令仍使用事件所属编辑器。
    const isEditorControl = !!eventTarget.closest('.protyle-action, button, [role="tab"], [role="checkbox"]');
    if (isEditorControl || !range || !protyle.element.contains(range.commonAncestorContainer)) {
        range = undefined;
    }
    if (documentKeydown(app, event, protyle, range, isFileFocus)) {
        return true;
    }
    // 正文命令需要正文上下文,控件未处理的快捷键继续交给全局处理器。
    if (isEditorControl) {
        return false;
    }
    if (!isFileFocus && range && matchHotKey(window.siyuan.config.keymap.editor.general.quickMakeCard, event) && !window.siyuan.config.readonly && !isEncryptedBox(protyle.notebookId)) {
        if (protyle.title?.editElement.contains(range.startContainer)) {
            quickMakeCard(protyle, [protyle.title.element]);
        } else {
            const selectElement: Element[] = [];
            protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select").forEach(item => {
                const block = hasClosestBlock(item, true) || item;
                if (!selectElement.includes(block)) {
                    selectElement.push(block);
                }
            });
            if (selectElement.length === 0) {
                const nodeElement = hasClosestBlock(range.startContainer, true);
                if (nodeElement) {
                    selectElement.push(nodeElement);
                }
            }
            quickMakeCard(protyle, selectElement);
        }
        event.preventDefault();
        return true;
    }
    if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.general.addToDatabase, event)) {
        execByCommand({
            command: "addToDatabase",
            app,
            protyle,
            previousRange: range
        });
        event.preventDefault();
        return true;
    }
    if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.general.move, event)) {
        execByCommand({
            command: "move",
            app,
            protyle,
            previousRange: range
        });
        event.preventDefault();
        return true;
    }

    if (!isFileFocus && range && !event.repeat && !protyle.disabled &&
        matchHotKey(window.siyuan.config.keymap.editor.general.duplicate, event)) {
        event.preventDefault();
        event.stopPropagation();
        let selectsElement: HTMLElement[] = Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));
        if (selectsElement.length === 0) {
            const nodeElement = hasClosestBlock(range.startContainer, true);
            if (nodeElement) {
                const rangeElements = range.collapsed ? [] : getBlockElementsByRange(range);
                selectsElement = rangeElements.length > 0 ? rangeElements : [nodeElement];
            }
        }
        selectsElement = Array.from(new Set(selectsElement.map(element => hasClosestBlock(element, true) || element)));
        duplicateBlock(selectsElement, protyle);
        return true;
    }

    const target = event.target as HTMLElement;
    if (target.tagName !== "TABLE" && ["INPUT", "TEXTAREA"].includes(target.tagName)) {
        return false;
    }
    if (handleDocumentBoundaryHotkey(protyle, event)) {
        return true;
    }
    if (range && matchHotKey(window.siyuan.config.keymap.editor.general.focusBreadcrumb, event)) {
        if (protyle.breadcrumb?.focus(range)) {
            event.preventDefault();
            return true;
        }
    }
    /// #if !MOBILE
    if (matchHotKey(window.siyuan.config.keymap.editor.general.copyRichText, event)) {
        if (!range || !hasClosestBlock(range.startContainer)) {
            return false;
        }
        protyle.wysiwyg.copyRichText();
        event.preventDefault();
        return true;
    }
    /// #endif
    if (matchHotKey(window.siyuan.config.keymap.editor.general.copyPlainText, event)) {
        if (!range) {
            return false;
        }
        const nodeElement = hasClosestBlock(range.startContainer);
        if (!nodeElement) {
            return false;
        }
        if (range.toString() === "") {
            const selectsElement: HTMLElement[] = Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));
            let html = "";
            if (selectsElement.length === 0) {
                selectsElement.push(nodeElement);
            }
            selectsElement.forEach(item => {
                html += getPlainText(item) + "\n";
            });
            copyPlainText(html.trimEnd());
        } else {
            copyPlainText(stripSemanticMarkersFromRangeText(range));
        }
        event.preventDefault();
        return true;
    }
    if (matchHotKey(window.siyuan.config.keymap.editor.general.duplicateCompletely, event)) {
        if (!range) {
            return false;
        }
        const nodeElement = hasClosestBlock(range.startContainer);
        if (!nodeElement || !nodeElement.classList.contains("av")) {
            return false;
        }
        duplicateCompletely(protyle, nodeElement);
        event.preventDefault();
        return true;
    }
    if (range && !isFileFocus && matchHotKey(window.siyuan.config.keymap.editor.general.copyBlockRef, event)) {
        event.preventDefault();
        event.stopPropagation();
        if (hasClosestByClassName(range.startContainer, "protyle-title")) {
            copyTextByType([protyle.block.rootID], "ref");
        } else {
            const nodeElement = hasClosestBlock(range.startContainer, true);
            if (!nodeElement) {
                return false;
            }
            const selectImgElement = nodeElement.querySelector(".img--select");
            if (selectImgElement) {
                copyPNGByLink(selectImgElement.querySelector("img").getAttribute("src"));
                return true;
            }
            const ids = Array.from(new Set(Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"))
                .map(item => (hasClosestBlock(item, true) || item).getAttribute("data-node-id"))));
            if (ids.length > 0) {
                copyTextByType(ids, "ref");
                return true;
            }
            if (range.toString() !== "") {
                getContentByInlineHTML(range, (content) => {
                    writeText(`((${nodeElement.getAttribute("data-node-id")} "${content.trim()}"))`);
                });
            } else {
                copyTextByType([nodeElement.getAttribute("data-node-id")], "ref");
            }
        }
        return true;
    }
    // 只读正文的快捷键使用所属编辑器上下文,插件命令仍遵循自身的可用性判断。
    if (protyle.disabled && !isFileFocus && !event.isComposing &&
        (target === document.body || protyle.wysiwyg.element.contains(target)) &&
        areProtylePluginExtensionsEnabled(protyle) &&
        dispatchPluginShortcut(app, event, "editorShortcut", () => {
            const context = captureCommandContext({app, source: "editorShortcut", protyle, range});
            // 无有效正文选区时,不携带上下文采集回退得到的历史选区。
            if (!range) {
                context.range = undefined;
                context.block = undefined;
                context.tableCell = undefined;
            }
            return context;
        })) {
        return true;
    }
    if (hasClosestByClassName(target, "protyle-title__input")) {
        return false;
    }
    // 没有光标时,无法撤销 https://ld246.com/article/1624021111567
    if (matchHotKey(window.siyuan.config.keymap.editor.general.undo, event)) {
        protyle.undo.undo(protyle);
        event.preventDefault();
        return true;
    }
    if (matchHotKey(window.siyuan.config.keymap.editor.general.redo, event)) {
        protyle.undo.redo(protyle);
        event.preventDefault();
        return true;
    }
    return false;
};

const fileTreeKeydown = (app: App, event: KeyboardEvent) => {
    const dockFile = getDockByType("file");
    if (!dockFile) {
        return false;
    }
    const files = dockFile.data.file as Files;
    if (typeof dockFile.data.file === "boolean") {
        return true;
    }

    if (!files.element.parentElement.classList.contains("layout__tab--active")) {
        return false;
    }

    const liElements = Array.from(files.element.querySelectorAll(".b3-list-item--focus"));
    if (dispatchPluginShortcut(app, event, "fileTreeShortcut", () => captureCommandContext({
        app, source: "fileTreeShortcut", fileLiElements: liElements,
    }))) {
        return true;
    }

    if (liElements.length === 0) {
        if (event.key.startsWith("Arrow") && isNotCtrl(event)) {
            const liElement = files.element.querySelector(".b3-list-item");
            if (liElement) {
                liElement.classList.add("b3-list-item--focus");
                files.lastSelectedElement = liElement;
            }
            event.preventDefault();
        }
        return false;
    }
    const topULElement = hasTopClosestByTag(liElements[0], "UL");
    if (!topULElement) {
        return false;
    }
    const notebookId = topULElement.getAttribute("data-url");
    const pathString = liElements[0].getAttribute("data-path");
    const isFile = liElements[0].getAttribute("data-type") === "navigation-file";
    const ids: string[] = [];
    liElements.forEach(item => {
        if (item.getAttribute("data-type") === "navigation-file") {
            ids.push(item.getAttribute("data-node-id"));
        }
    });

    if (matchHotKey(window.siyuan.config.keymap.editor.general.spaceRepetition, event) && !window.siyuan.config.readonly && !isEncryptedBox(notebookId)) {
        if (isFile) {
            const id = liElements[0].getAttribute("data-node-id");
            fetchPost("/api/riff/getTreeRiffDueCards", {rootID: id}, (response) => {
                openCardByData(app, response.data, "doc", id, getDisplayName(liElements[0].getAttribute("data-name"), false, true), true);
            });
        } else {
            fetchPost("/api/riff/getNotebookRiffDueCards", {notebook: notebookId}, (response) => {
                openCardByData(app, response.data, "notebook", notebookId, getNotebookName(notebookId), true);
            });
        }
        event.preventDefault();
        return true;
    }

    if (matchHotKey(window.siyuan.config.keymap.editor.general.quickMakeCard, event) && !isEncryptedBox(notebookId)) {
        if (ids.length > 0) {
            transaction(undefined, [{
                action: "addFlashcards",
                deckID: Constants.QUICK_DECK_ID,
                blockIDs: ids,
            }]);
        }
        event.preventDefault();
        return true;
    }

    if (matchHotKey(window.siyuan.config.keymap.general.addToDatabase, event)) {
        execByCommand({
            command: "addToDatabase",
            app,
            fileLiElements: liElements
        });
        event.preventDefault();
        return true;
    }

    if (matchHotKey(window.siyuan.config.keymap.editor.general.rename, event)) {
        window.siyuan.menus.menu.remove();
        if (isFile) {
            const docInfoParam: BlockQueryRequestInput = {
                id: liElements[0].getAttribute("data-node-id")
            };
            if (isEncryptedBox(notebookId)) {
                docInfoParam.notebook = notebookId;
            }
            fetchPost("/api/block/getDocInfo", docInfoParam, (response) => {
                rename({
                    notebookId,
                    path: pathString,
                    name: response.data.ial.title,
                    empty: response.data.ial[Constants.CUSTOM_SY_TITLE_EMPTY] === "true",
                    type: "file",
                });
            });
        } else {
            rename({
                notebookId,
                path: pathString,
                name: getNotebookName(notebookId),
                type: "notebook",
            });
        }
        event.preventDefault();
        return true;
    }

    if (matchHotKey(window.siyuan.config.keymap.general.openContextMenu, event)) {
        const liRect = liElements[0].getBoundingClientRect();
        if (isFile) {
            initFileMenu(app, notebookId, pathString, liElements[0]).popup({
                x: liRect.right - 15,
                y: liRect.top + 15
            });
        } else {
            initNavigationMenu(app, liElements[0] as HTMLElement).popup({x: liRect.right - 15, y: liRect.top + 15});
        }
        return true;
    }

    if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.duplicate, event)) {
        event.preventDefault();
        event.stopPropagation();
        ids.forEach(item => {
            fetchPost("/api/filetree/duplicateDoc", {
                id: item,
            });
        });
        return true;
    }

    if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.copyBlockRef, event)) {
        event.preventDefault();
        event.stopPropagation();
        copyTextByType(ids, "ref");
        return true;
    }

    if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.copyBlockEmbed, event)) {
        event.preventDefault();
        event.stopPropagation();
        copyTextByType(ids, "blockEmbed");
        return true;
    }

    if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.copyProtocol, event)) {
        event.preventDefault();
        event.stopPropagation();
        copyTextByType(ids, "protocol");
        return true;
    }

    if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.copyProtocolInMd, event)) {
        event.preventDefault();
        event.stopPropagation();
        copyTextByType(ids, "protocolMd");
        return true;
    }
    if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.copyHPath, event)) {
        event.preventDefault();
        event.stopPropagation();
        copyTextByType(ids, "hPath");
        return true;
    }
    if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.copyID, event)) {
        event.preventDefault();
        event.stopPropagation();
        copyTextByType(ids, "id");
        return true;
    }

    if (isFile && matchHotKey(window.siyuan.config.keymap.general.move, event)) {
        window.siyuan.menus.menu.remove();
        execByCommand({
            command: "move",
            app,
            fileLiElements: liElements
        });
        event.preventDefault();
        return true;
    }

    if (isFile && matchHotKey(window.siyuan.config.keymap.editor.general.insertRight, event)) {
        window.siyuan.menus.menu.remove();
        openFileById({
            app,
            id: liElements[0].getAttribute("data-node-id"),
            action: [Constants.CB_GET_FOCUS],
            position: "right",
        });
        event.preventDefault();
        return true;
    }

    if (matchHotKey(window.siyuan.config.keymap.general.replace, event)) {
        window.siyuan.menus.menu.remove();
        execByCommand({
            command: "replace",
            app,
            fileLiElements: liElements,
        });
        event.preventDefault();
        return true;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.search, event)) {
        window.siyuan.menus.menu.remove();
        execByCommand({
            command: "search",
            app,
            fileLiElements: liElements,
        });
        event.preventDefault();
        return true;
    }
    const target = event.target as HTMLElement;
    if (["INPUT", "TEXTAREA"].includes(target.tagName) ||
        hasClosestByAttribute(target, "contenteditable", null) ||
        hasClosestByClassName(target, "protyle", true)) {
        return false;
    }
    if (event.shiftKey) {
        if (event.key === "ArrowUp") {
            const startEndElement = getStartEndElement(liElements);
            let previousElement: Element;
            if (startEndElement.startElement.getBoundingClientRect().top >= startEndElement.endElement.getBoundingClientRect().top) {
                previousElement = getPreviousFileLi(startEndElement.endElement) as Element;
                if (previousElement) {
                    previousElement.classList.add("b3-list-item--focus");
                    previousElement.setAttribute("select-end", "true");
                    startEndElement.endElement.removeAttribute("select-end");
                }
            } else {
                startEndElement.endElement.classList.remove("b3-list-item--focus");
                startEndElement.endElement.removeAttribute("select-end");
                previousElement = getPreviousFileLi(startEndElement.endElement) as Element;
                if (previousElement) {
                    previousElement.setAttribute("select-end", "true");
                }
            }
            if (previousElement) {
                const previousRect = previousElement.getBoundingClientRect();
                const fileRect = files.element.getBoundingClientRect();
                if (previousRect.top < fileRect.top || previousRect.bottom > fileRect.bottom) {
                    previousElement.scrollIntoView(previousRect.top < fileRect.top);
                }
            }
        } else if (event.key === "ArrowDown") {
            const startEndElement = getStartEndElement(liElements);
            let nextElement: Element;
            if (startEndElement.startElement.getBoundingClientRect().top <= startEndElement.endElement.getBoundingClientRect().top) {
                nextElement = getNextFileLi(startEndElement.endElement) as Element;
                if (nextElement) {
                    nextElement.classList.add("b3-list-item--focus");
                    nextElement.setAttribute("select-end", "true");
                    startEndElement.endElement.removeAttribute("select-end");
                }
            } else {
                startEndElement.endElement.classList.remove("b3-list-item--focus");
                startEndElement.endElement.removeAttribute("select-end");
                nextElement = getNextFileLi(startEndElement.endElement) as Element;
                if (nextElement) {
                    nextElement.setAttribute("select-end", "true");
                }
            }
            if (nextElement) {
                const nextRect = nextElement.getBoundingClientRect();
                const fileRect = files.element.getBoundingClientRect();
                if (nextRect.top < fileRect.top || nextRect.bottom > fileRect.bottom) {
                    nextElement.scrollIntoView(nextRect.top < fileRect.top);
                }
            }
        }
        return;
    } else if (isNotCtrl(event)) {
        files.element.querySelector('[select-end="true"]')?.removeAttribute("select-end");
        files.element.querySelector('[select-start="true"]')?.removeAttribute("select-start");
        if ((event.key === "ArrowRight" && !liElements[0].querySelector(".b3-list-item__arrow--open") && !liElements[0].querySelector(".b3-list-item__toggle").classList.contains("fn__hidden")) ||
            (event.key === "ArrowLeft" && liElements[0].querySelector(".b3-list-item__arrow--open"))) {
            files.getLeaf(liElements[0], notebookId);
            liElements.forEach((item, index) => {
                if (index !== 0) {
                    item.classList.remove("b3-list-item--focus");
                }
            });
            event.preventDefault();
            return true;
        }
        if (event.key === "ArrowLeft") {
            let parentElement = liElements[0].parentElement.previousElementSibling;
            if (parentElement) {
                if (parentElement.tagName !== "LI") {
                    parentElement = files.element.querySelector(".b3-list-item");
                }
                liElements.forEach((item) => {
                    item.classList.remove("b3-list-item--focus");
                });
                parentElement.classList.add("b3-list-item--focus");
                files.lastSelectedElement = parentElement;
                const parentRect = parentElement.getBoundingClientRect();
                const fileRect = files.element.getBoundingClientRect();
                if (parentRect.top < fileRect.top || parentRect.bottom > fileRect.bottom) {
                    parentElement.scrollIntoView(parentRect.top < fileRect.top);
                }
            }
            event.preventDefault();
            return true;
        }
        if (event.key === "ArrowDown" || event.key === "ArrowRight") {
            let nextElement = liElements[0];
            while (nextElement) {
                if (nextElement.nextElementSibling) {
                    if (nextElement.nextElementSibling.tagName === "UL") {
                        nextElement = nextElement.nextElementSibling.firstElementChild;
                    } else {
                        nextElement = nextElement.nextElementSibling;
                    }
                    break;
                } else {
                    if (nextElement.parentElement.classList.contains("fn__flex-1")) {
                        break;
                    } else {
                        nextElement = nextElement.parentElement;
                    }
                }
            }
            if (nextElement.classList.contains("b3-list-item")) {
                liElements.forEach((item) => {
                    item.classList.remove("b3-list-item--focus");
                });
                nextElement.classList.add("b3-list-item--focus");
                files.lastSelectedElement = nextElement;
                const nextRect = nextElement.getBoundingClientRect();
                const fileRect = files.element.getBoundingClientRect();
                if (nextRect.top < fileRect.top || nextRect.bottom > fileRect.bottom) {
                    nextElement.scrollIntoView(nextRect.top < fileRect.top);
                }
            }
            event.preventDefault();
            return true;
        }
        if (event.key === "ArrowUp") {
            let previousElement = liElements[0];
            while (previousElement) {
                if (previousElement.previousElementSibling) {
                    if (previousElement.previousElementSibling.tagName === "LI") {
                        previousElement = previousElement.previousElementSibling;
                    } else {
                        const liElements = previousElement.previousElementSibling.querySelectorAll(".b3-list-item");
                        previousElement = liElements[liElements.length - 1];
                    }
                    break;
                } else {
                    if (previousElement.parentElement.classList.contains("fn__flex-1")) {
                        break;
                    } else {
                        previousElement = previousElement.parentElement;
                    }
                }
            }
            if (previousElement.classList.contains("b3-list-item")) {
                liElements.forEach((item) => {
                    item.classList.remove("b3-list-item--focus");
                });
                previousElement.classList.add("b3-list-item--focus");
                files.lastSelectedElement = previousElement;
                const previousRect = previousElement.getBoundingClientRect();
                const fileRect = files.element.getBoundingClientRect();
                if (previousRect.top < fileRect.top || previousRect.bottom > fileRect.bottom) {
                    previousElement.scrollIntoView(previousRect.top < fileRect.top);
                }
            }
            event.preventDefault();
            return true;
        }
    }
    if (event.key === "Delete" || (event.key === "Backspace" && isMac())) {
        window.siyuan.menus.menu.remove();
        if (document.querySelector(`.b3-dialog--open[data-key="${Constants.DIALOG_CONFIRM}"]`)) {
            return;
        }
        deleteFiles(liElements);
        return true;
    }
    if (event.key === "Enter") {
        window.siyuan.menus.menu.remove();
        liElements.forEach(item => {
            if (item.getAttribute("data-type") === "navigation-file") {
                openFileById({app, id: item.getAttribute("data-node-id"), action: [Constants.CB_GET_FOCUS]});
            } else {
                const itemTopULElement = hasTopClosestByTag(item, "UL");
                if (itemTopULElement) {
                    files.getLeaf(item, itemTopULElement.getAttribute("data-url"));
                }
            }
        });
        return true;
    }
};

const panelTreeKeydown = (app: App, event: KeyboardEvent) => {
    // 面板折叠展开操作
    const target = event.target as HTMLElement;
    if (["INPUT", "TEXTAREA"].includes(target.tagName) ||
        hasClosestByAttribute(target, "contenteditable", null) ||
        hasClosestByClassName(target, "protyle", true)) {
        return false;
    }

    const bottomBacklinkElement = hasClosestByClassName(target, "sy__backlink--bottom", true);
    const bottomBacklink = bottomBacklinkElement ? getAllModels().backlink.find(item =>
        item.type === "bottom" && item.element === bottomBacklinkElement) : undefined;
    const activePanelElement = bottomBacklinkElement ||
        target.closest(".layout__tab--active, .layout__wnd--active .layout-tab-container > div") ||
        (target === document.body ? document.querySelector(".layout__tab--active") : undefined);
    if (!activePanelElement) {
        return false;
    }
    if (activePanelElement.className.indexOf("sy__") === -1) {
        return false;
    }

    if (!bottomBacklink && dispatchPluginShortcut(app, event, "dockShortcut", () => captureCommandContext({
        app, source: "dockShortcut", dockElement: activePanelElement as HTMLElement,
    }))) {
        return true;
    }
    const matchCollapse = matchHotKey(window.siyuan.config.keymap.editor.general.collapse, event);
    const matchExpand = matchHotKey(window.siyuan.config.keymap.editor.general.expand, event);
    if (bottomBacklink && (matchCollapse || matchExpand)) {
        return false;
    }
    if (!matchCollapse && !matchExpand &&
        !event.key.startsWith("Arrow") && event.key !== "Enter") {
        return false;
    }
    if (!event.repeat && (matchCollapse || matchExpand) && activePanelElement.classList.contains("sy__outline")) {
        const outline = getAllModels().outline.find(item => item.element.parentElement === activePanelElement);
        if (outline) {
            outline.setAllExpanded(!matchCollapse);
            event.preventDefault();
            return true;
        }
    }
    if (!event.repeat && matchCollapse) {
        const collapseElement = activePanelElement.querySelector('.block__icon[data-type="collapse"]');
        if (collapseElement) {
            collapseElement.dispatchEvent(new CustomEvent("click"));
            event.preventDefault();
            return true;
        }
    }
    if (!event.repeat && matchExpand) {
        const expandElement = activePanelElement.querySelector('.block__icon[data-type="expand"]');
        if (expandElement) {
            expandElement.dispatchEvent(new CustomEvent("click"));
            event.preventDefault();
            return true;
        }
    }
    if (activePanelElement.classList.contains("sy__inbox") ||
        activePanelElement.classList.contains("sy__globalGraph") ||
        activePanelElement.classList.contains("sy__graph")) {
        return false;
    }
    const model = bottomBacklink ||
        (getInstanceById(activePanelElement.getAttribute("data-id"), window.siyuan.layout.layout) as Tab)?.model;
    if (!model) {
        return false;
    }
    const visibleTreeElements = bottomBacklink ? [bottomBacklink.tree.element, bottomBacklink.mTree.element].filter(item =>
        !item.classList.contains("fn__none")) : [];
    let activeItemElement: Element;
    if (bottomBacklink) {
        visibleTreeElements.find(item => {
            activeItemElement = item.querySelector(".b3-list-item--focus");
            return !!activeItemElement;
        });
    } else {
        activeItemElement = activePanelElement.querySelector(".b3-list-item--focus");
    }
    if (!activeItemElement) {
        if (bottomBacklink) {
            visibleTreeElements.find(item => {
                activeItemElement = item.querySelector(".b3-list-item");
                return !!activeItemElement;
            });
        } else {
            activeItemElement = activePanelElement.querySelector(".b3-list .b3-list-item");
        }
        if (activeItemElement) {
            activeItemElement.classList.add("b3-list-item--focus");
        }
        return false;
    }

    const backlinkModel = model as Backlink;
    let tree = backlinkModel.tree;
    if (backlinkModel.mTree?.element.contains(activeItemElement)) {
        tree = backlinkModel.mTree;
    }
    if (!tree) {
        return false;
    }
    if (event.key === "Enter") {
        tree.click(activeItemElement);
        event.preventDefault();
        return true;
    }
    const arrowElement = activeItemElement.querySelector(".b3-list-item__arrow");
    if ((event.key === "ArrowRight" && !arrowElement.classList.contains("b3-list-item__arrow--open") && !arrowElement.parentElement.classList.contains("fn__hidden")) ||
        (event.key === "ArrowLeft" && arrowElement.classList.contains("b3-list-item__arrow--open") && !arrowElement.parentElement.classList.contains("fn__hidden"))) {
        tree.toggleBlocks(activeItemElement);
        event.preventDefault();
        return true;
    }
    if (activeItemElement.closest(".backlinkList__item")) {
        if (event.key === "ArrowLeft") {
            event.preventDefault();
            return true;
        }
        if (event.key === "ArrowDown" || event.key === "ArrowRight" || event.key === "ArrowUp") {
            const itemElements = backlinkModel.getDocumentItemElements(tree);
            const currentIndex = itemElements.indexOf(activeItemElement as HTMLLIElement);
            const nextIndex = currentIndex + (event.key === "ArrowUp" ? -1 : 1);
            const nextElement = itemElements[nextIndex];
            if (nextElement) {
                activeItemElement.classList.remove("b3-list-item--focus");
                nextElement.classList.add("b3-list-item--focus");
                const nextRect = nextElement.getBoundingClientRect();
                const scrollElement = backlinkModel.getScrollElement(tree);
                const scrollRect = scrollElement.getBoundingClientRect();
                if (nextRect.top < scrollRect.top) {
                    scrollElement.scrollTop += nextRect.top - scrollRect.top;
                } else if (nextRect.bottom > scrollRect.bottom) {
                    scrollElement.scrollTop += nextRect.bottom - scrollRect.bottom;
                }
            }
            event.preventDefault();
            return true;
        }
    }
    const ulElement = hasClosestByClassName(activeItemElement, "b3-list");
    if (!ulElement) {
        return false;
    }
    if (event.key === "ArrowLeft") {
        let parentElement = activeItemElement.parentElement.previousElementSibling;
        if (parentElement) {
            if (parentElement.tagName !== "LI") {
                parentElement = ulElement.querySelector(".b3-list-item");
            }
            activeItemElement.classList.remove("b3-list-item--focus");
            parentElement.classList.add("b3-list-item--focus");
            const parentRect = parentElement.getBoundingClientRect();
            const scrollRect = ulElement.parentElement.getBoundingClientRect();
            if (parentRect.top < scrollRect.top || parentRect.bottom > scrollRect.bottom) {
                parentElement.scrollIntoView(parentRect.top < scrollRect.top);
            }
        }
        event.preventDefault();
        return true;
    }
    if (event.key === "ArrowDown" || event.key === "ArrowRight") {
        let nextElement = activeItemElement;
        while (nextElement) {
            if (nextElement.nextElementSibling) {
                if (nextElement.nextElementSibling.tagName === "UL") {
                    if (nextElement.nextElementSibling.classList.contains("fn__none")) {   // 遇到折叠内容
                        if (nextElement.nextElementSibling.nextElementSibling) {
                            nextElement = nextElement.nextElementSibling.nextElementSibling;
                        }
                    } else {
                        nextElement = nextElement.nextElementSibling.firstElementChild;
                    }
                } else if (nextElement.nextElementSibling.classList.contains("protyle")) { // backlink
                    if (nextElement.nextElementSibling.nextElementSibling) {
                        nextElement = nextElement.nextElementSibling.nextElementSibling;
                    }
                } else {
                    nextElement = nextElement.nextElementSibling;
                }
                break;
            } else {
                if (nextElement.parentElement.classList.contains("fn__flex-1")) {
                    break;
                } else {
                    nextElement = nextElement.parentElement;
                }
            }
        }
        if (nextElement.classList.contains("b3-list-item") && !nextElement.classList.contains("b3-list-item--focus")) {
            activeItemElement.classList.remove("b3-list-item--focus");
            nextElement.classList.add("b3-list-item--focus");
            const nextRect = nextElement.getBoundingClientRect();
            const scrollRect = ulElement.parentElement.getBoundingClientRect();
            if (nextRect.top < scrollRect.top || nextRect.bottom > scrollRect.bottom) {
                nextElement.scrollIntoView(nextRect.top < scrollRect.top);
            }
        }
        event.preventDefault();
        return true;
    }
    if (event.key === "ArrowUp") {
        let previousElement = activeItemElement;
        while (previousElement) {
            if (previousElement.previousElementSibling) {
                if (previousElement.previousElementSibling.tagName === "LI") {
                    previousElement = previousElement.previousElementSibling;
                } else if (previousElement.previousElementSibling.classList.contains("protyle")) {
                    if (previousElement.previousElementSibling.previousElementSibling) {
                        previousElement = previousElement.previousElementSibling.previousElementSibling;
                    }
                } else if (previousElement.previousElementSibling.tagName === "UL" && previousElement.previousElementSibling.classList.contains("fn__none")) {   // 遇到折叠内容
                    if (previousElement.previousElementSibling.previousElementSibling) {
                        previousElement = previousElement.previousElementSibling.previousElementSibling;
                    }
                } else {
                    const liElements = previousElement.previousElementSibling.querySelectorAll(".b3-list-item");
                    previousElement = liElements[liElements.length - 1];
                }
                break;
            } else {
                if (previousElement.parentElement.classList.contains("fn__flex-1")) {
                    break;
                } else {
                    previousElement = previousElement.parentElement;
                }
            }
        }
        if (previousElement.classList.contains("b3-list-item") && !previousElement.classList.contains("b3-list-item--focus")) {
            activeItemElement.classList.remove("b3-list-item--focus");
            previousElement.classList.add("b3-list-item--focus");
            const previousRect = previousElement.getBoundingClientRect();
            const scrollRect = ulElement.parentElement.getBoundingClientRect();
            if (previousRect.top < scrollRect.top || previousRect.bottom > scrollRect.bottom) {
                previousElement.scrollIntoView(previousRect.top < scrollRect.top);
            }
        }
        event.preventDefault();
        return true;
    }
    return false;
};

let switchDialog: Dialog;
export const windowKeyDown = (app: App, event: KeyboardEvent) => {
    if (event.defaultPrevented || filterHotkey(event, app)) {
        return;
    }
    if (switchDialog &&
        matchAuxiliaryHotKey(switchDialog.element.dataset.shortcut || window.siyuan.config.keymap.general.goToEditTabNext, event)
        && event.key.startsWith("Arrow")) {
        dialogArrow(app, switchDialog.element, event);
        return;
    }

    if (searchKeydown(app, event)) {
        event.preventDefault();
        event.stopPropagation();
        return;
    }

    const isTabWindow = isWindow();
    if (bindMenuKeydown(event)) {
        event.preventDefault();
        return;
    }

    if (bindAVPanelKeydown(event)) {
        event.preventDefault();
        return;
    }

    if (handleDatabaseRowShortcut(app, event)) {
        return;
    }

    let readonlyBlockSelection: IProtyle;
    if (event.key === "Escape" && !event.isComposing && !event.repeat) {
        const selection = getSelection();
        if (selection.rangeCount > 0) {
            readonlyBlockSelection = getReadonlyBlockSelectionProtyle(selection.getRangeAt(0));
        }
    }

    // 当前焦点范围先处理快捷键,未命中再按固定顺序处理通用操作。
    // 按键目标为 body 时,优先使用活动面板,否则回退到活动窗口的当前页签。
    const shortcutTarget = event.target === document.body ?
        document.querySelector<HTMLElement>(".layout__tab--active") || getActiveTab()?.panelElement || document.body :
        event.target as HTMLElement;
    // 只读正文无法获得焦点,跨块选区的 Esc 不应按上一次活动面板分派。
    if (!readonlyBlockSelection && !shortcutTarget.closest("input, textarea, .b3-menu, .av__panel, .av__mask")) {
        if (shortcutTarget.closest(".protyle") && editKeydown(app, event)) {
            return;
        }
        if (!isTabWindow && shortcutTarget.closest(".sy__file") && fileTreeKeydown(app, event)) {
            return;
        }
        if (!shortcutTarget.closest(".protyle, .sy__file") &&
            (!isTabWindow || shortcutTarget.closest(".sy__backlink--bottom")) &&
            shortcutTarget.closest(".layout__tab--active, .sy__backlink--bottom, .layout__wnd--active .layout-tab-container > div") &&
            panelTreeKeydown(app, event)) {
            return;
        }
    }

    const switchHotkey = [...getKeymapBindings(window.siyuan.config.keymap.general.goToEditTabNext),
        ...getKeymapBindings(window.siyuan.config.keymap.general.goToEditTabPrev)].find(key => matchHotKey(key, event));
    if (switchHotkey) {
        if (switchDialog && switchDialog.element.parentElement) {
            switchDialog.element.dataset.shortcut = switchHotkey;
            return;
        }
        let tabHtml = "";
        let currentTabElement = document.querySelector(".layout__wnd--active ul.layout-tab-bar > .item--focus");
        if (!currentTabElement) {
            currentTabElement = document.querySelector("ul.layout-tab-bar > .item--focus");
        }
        if (currentTabElement) {
            const currentId = currentTabElement.getAttribute("data-id");
            getAllTabs().sort((itemA, itemB) => {
                return itemA.headElement.getAttribute("data-activetime") > itemB.headElement.getAttribute("data-activetime") ? -1 : 1;
            }).forEach((item, index) => {
                let icon = `<svg class="b3-list-item__graphic"><use xlink:href="#${item.icon}"></use></svg>`;
                let rootId = "";
                const initData = item.headElement.getAttribute("data-initdata");
                if (item.model instanceof Editor) {
                    rootId = ` data-node-id="${item.model.editor.protyle.block.rootID}"`;
                    icon = getFileTreeIconHTML(item.docIcon, "file", "b3-list-item__graphic", true);
                } else if (initData) {
                    const initDataObj = JSON.parse(initData);
                    if (initDataObj.instance === "Editor") {
                        rootId = ` data-node-id="${initDataObj.rootId}"`;
                        icon = getFileTreeIconHTML(item.docIcon, "file", "b3-list-item__graphic", true);
                    }
                }
                tabHtml += `<li data-index="${index}" data-id="${item.id}"${rootId} class="b3-list-item${currentId === item.id ? " b3-list-item--focus" : ""}"${currentId === item.id ? ' data-original="true"' : ""}>${icon}<span class="b3-list-item__text">${escapeHtml(item.title)}</span></li>`;
            });
        }
        let dockHtml = "";
        if (!isTabWindow) {
            dockHtml = `<ul class="b3-list b3-list--background" style="overflow: auto;width: 200px;">
<li data-type="riffCard" data-index="0" class="b3-list-item${!tabHtml ? " b3-list-item--focus" : ""}">
    <svg class="b3-list-item__graphic"><use xlink:href="#iconRiffCard"></use></svg>
    <span class="b3-list-item__text">${window.siyuan.languages.riffCard}</span>
    <span class="b3-list-item__meta">${updateHotkeyTip(window.siyuan.config.keymap.general.riffCard.custom)}</span>
</li>`;
            getAllDocks().forEach((item, index) => {
                dockHtml += `<li data-type="${item.type}" data-index="${index + 1}" class="b3-list-item">
    <svg class="b3-list-item__graphic"><use xlink:href="#${item.icon}"></use></svg>
    <span class="b3-list-item__text">${item.title}</span>
    <span class="b3-list-item__meta">${updateHotkeyTip(getDockHotkey(item))}</span>
</li>`;
            });
            dockHtml = dockHtml + "</ul>";
        }
        hideElements(["dialog"]);
        switchDialog = new Dialog({
            positionId: Constants.DIALOG_SWITCHTAB,
            title: window.siyuan.languages.switchTab,
            content: `<div class="fn__flex-column switch-doc">
    <input style="opacity: 0;height: 0.1px;box-sizing: border-box;margin: 0;padding: 0;border: 0;">
    <div class="fn__flex" style="overflow:auto;">${dockHtml}
        <ul${!isTabWindow ? "" : ' style="border-left:0"'} class="b3-list b3-list--background fn__flex-1">${tabHtml}</ul>
    </div>
    <div class="switch-doc__path"></div>
</div>`,
        });
        switchDialog.element.setAttribute("data-key", Constants.DIALOG_SWITCHTAB);
        switchDialog.element.dataset.shortcut = switchHotkey;
        // 需移走光标,否则编辑器会继续监听并执行按键操作
        switchDialog.element.querySelector("input").focus();
        if (isMac()) {
            switchDialog.element.addEventListener("contextmenu", (event) => {
                switchDialogEvent(app, event);
            });
        }
        switchDialog.element.addEventListener("click", (event) => {
            switchDialogEvent(app, event);
        });
        return;
    }

    if (isNotCtrl(event) && !event.shiftKey && !event.altKey &&
        (event.key.startsWith("Arrow") || event.key === "Enter")) {
        const openRecentDocsDialog = window.siyuan.dialogs.find(item => {
            if (item.element.getAttribute("data-key") === Constants.DIALOG_RECENTDOCS) {
                return true;
            }
        });
        if (openRecentDocsDialog && openRecentDocsDialog.element.contains(event.target as Node) &&
            !openRecentDocsDialog.element.hasAttribute("data-dialog-closing")) {
            // 下拉菜单和按钮需要自行处理按键,Enter 不能转发为打开当前选中文档
            if ((event.target as HTMLElement).closest("select, button")) {
                return;
            }
            event.preventDefault();
            dialogArrow(app, openRecentDocsDialog.element, event);
            return;
        }
    }

    if (matchHotKey(window.siyuan.config.keymap.general.recentDocs, event)) {
        openRecentDocs(true);
        event.preventDefault();
        return;
    }

    if (["Home", "End", "ArrowUp", "ArrowDown"].includes(event.key)) {
        let matchDialog: Dialog;
        // 需找到最顶层的,因此不能用 find
        window.siyuan.dialogs.forEach(item => {
            if ([Constants.DIALOG_VIEWCARDS, Constants.DIALOG_HISTORYCOMPARE].includes(item.element.getAttribute("data-key"))) {
                matchDialog = item;
            }
        });
        if (matchDialog?.element.querySelector(".history__doc-compare") && ["Home", "End"].includes(event.key)) {
            matchDialog = undefined;
        }
        if (matchDialog) {
            let handled = false;
            if (matchDialog.element.getAttribute("data-key") === Constants.DIALOG_VIEWCARDS) {
                matchDialog.element.dispatchEvent(new CustomEvent("click", {detail: event.key.toLowerCase()}));
                handled = true;
            } else if (matchDialog.element.getAttribute("data-key") === Constants.DIALOG_HISTORYCOMPARE) {
                handled = historyKeydown(event, matchDialog);
            }
            if (handled) {
                event.preventDefault();
                return;
            }
        }
    }

    const target = event.target as HTMLElement;
    /// #if !BROWSER
    if (matchHotKey("⌘=", event) && !hasClosestByClassName(target, "pdf__outer")) {
        setZoom("zoomIn");
        event.preventDefault();
        return;
    }
    if (matchHotKey("⌘0", event)) {
        setZoom("restore");
        event.preventDefault();
        return;
    }
    if (matchHotKey("⌘-", event) && !hasClosestByClassName(target, "pdf__outer")) {
        setZoom("zoomOut");
        event.preventDefault();
        return;
    }
    /// #endif

    if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.syncNow, event)) {
        event.preventDefault();
        syncGuide(app);
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.commandPanel, event)) {
        event.preventDefault();
        commandPanel(app, {openOnly: true});
        return;
    }
    const editorFontSizeCommand = EDITOR_FONT_SIZE_COMMANDS.find((item) =>
        matchHotKey(window.siyuan.config.keymap.general[item.command], event));
    if (editorFontSizeCommand) {
        event.preventDefault();
        adjustEditorFontSize(editorFontSizeCommand.action);
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.editReadonly, event)) {
        event.preventDefault();
        editorConfigApi.patch("editor.readOnly", !window.siyuan.config.editor.readOnly);
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.lockScreen, event)) {
        lockScreen();
        event.preventDefault();
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.dataHistory, event)) {
        openHistory(app, "doc", true);
        event.preventDefault();
        return;
    }
    if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.toggleDock, event)) {
        toggleDockBar(document.querySelector("#barDock use"));
        event.preventDefault();
        return;
    }
    if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.switchLeftDock, event)) {
        window.siyuan.layout.leftDock.togglePin();
        event.preventDefault();
        return;
    }
    if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.switchRightDock, event)) {
        window.siyuan.layout.rightDock.togglePin();
        event.preventDefault();
        return;
    }
    if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.switchBottomDock, event)) {
        window.siyuan.layout.bottomDock.togglePin();
        event.preventDefault();
        return;
    }
    if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.toggleLeftDockPanel, event)) {
        toggleDockPanel("Left");
        event.preventDefault();
        return;
    }
    if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.toggleRightDockPanel, event)) {
        toggleDockPanel("Right");
        event.preventDefault();
        return;
    }
    if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.toggleBottomDockPanel, event)) {
        toggleDockPanel("Bottom");
        event.preventDefault();
        return;
    }
    if (!window.siyuan.config.readonly && matchHotKey(window.siyuan.config.keymap.general.config, event)) {
        openSetting(app);
        event.preventDefault();
        return;
    }
    if (matchHotKey("⌘A", event) && !["INPUT", "TEXTAREA"].includes(target.tagName)) {
        event.preventDefault();
        return;
    }
    const matchDock = getAllDocks().find(item => {
        if (matchHotKey(getDockKeymap(item), event)) {
            getDockByType(item.type).toggleModel(item.type);
            event.preventDefault();
            return true;
        }
    });
    if (matchDock) {
        return;
    }
    if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.riffCard, event)) {
        openCard(app, true);
        if (document.activeElement && !window.siyuan.dialogs.some(item =>
            item.element.getAttribute("data-key") === Constants.DIALOG_OPENCARD)) {
            (document.activeElement as HTMLElement).blur();
        }
        event.preventDefault();
        return;
    }
    if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.dailyNote, event)) {
        newDailyNote(app);
        event.stopPropagation();
        event.preventDefault();
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.newFile, event)) {
        newFile(app);
        event.preventDefault();
        return;
    }
    // https://github.com/siyuan-note/siyuan/issues/8913#issuecomment-1679720605
    const confirmDialogElement = document.querySelector('.b3-dialog--open[data-key="dialog-confirm"]');
    if (confirmDialogElement) {
        if (event.key === "Enter") {
            const activeElement = document.activeElement;
            if (activeElement instanceof HTMLButtonElement && confirmDialogElement.contains(activeElement)) {
                activeElement.click();
            } else {
                confirmDialogElement.dispatchEvent(new CustomEvent("click", {detail: event.key}));
            }
            event.preventDefault();
            return;
        } else if (event.key === "Escape") {
            confirmDialogElement.dispatchEvent(new CustomEvent("click", {detail: event.key}));
            event.preventDefault();
            return;
        }
    }

    if (event.key === "Escape" && !event.isComposing) {
        if (formatPainter.deactivate()) {
            event.preventDefault();
            return;
        }
        cancelDrag();
        const imgPreviewElement = document.querySelector(".protyle-img");
        if (imgPreviewElement) {
            imgPreviewElement.remove();
            return;
        }

        if (!window.siyuan.menus.menu.element.classList.contains("fn__none")) {
            if (window.siyuan.dialogs.length > 0 &&
                isAbove(window.siyuan.dialogs[0].element.querySelector(".b3-dialog"), window.siyuan.menus.menu.element)) {
                // 窗口高于菜单时,先关闭窗口,如 av 修改列 icon 时
            } else {
                window.siyuan.menus.menu.remove(true);
                return;
            }
        }

        // 需放在 menus 后,否则资源列中添加资源会先关闭菜单
        // 需放在 dialog 前,否则属性面板中修改日期会先关闭 dialog,只剩修改界面
        const avElement = document.querySelector(".av__panel");
        if (avElement) {
            const blockElement = getAVCellPanelTarget(avElement);
            if (blockElement?.classList.contains("av") && blockElement.getClientRects().length > 0) {
                focusBlock(blockElement);
            }
            avElement.remove();
            return;
        }

        // 闪卡长按 Esc 光标定位到闪卡按钮上 https://github.com/siyuan-note/siyuan/issues/12989
        // https://github.com/siyuan-note/siyuan/issues/14730
        if (event.repeat && document.activeElement && hasClosestByClassName(document.activeElement, "card__action")) {
            return;
        }

        if (window.siyuan.dialogs.length > 0) {
            window.siyuan.dialogs[window.siyuan.dialogs.length - 1].destroy();
            return;
        }

        // remove blockpopover
        const maxEditLevels: { [key: string]: number } = {oid: 0};
        window.siyuan.blockPanels.forEach((item) => {
            if ((item.targetElement || typeof item.x === "number") && item.element.getAttribute("data-pin") === "true") {
                const level = parseInt(item.element.getAttribute("data-level"));
                const oid = item.element.getAttribute("data-oid");
                if (maxEditLevels[oid]) {
                    if (level > maxEditLevels[oid]) {
                        maxEditLevels[oid] = level;
                    }
                } else {
                    maxEditLevels[oid] = 1;
                }
            }
        });
        let destroyBlock = false;
        for (let i = 0; i < window.siyuan.blockPanels.length; i++) {
            const item = window.siyuan.blockPanels[i];
            if ((item.targetElement || typeof item.x === "number") && item.element.getAttribute("data-pin") === "false") {
                item.destroy();
                destroyBlock = true;
                i--;
            }
        }
        if (destroyBlock) {
            return;
        }

        // 光标在文档树等面板中,按 Esc 回到编辑器中 https://github.com/siyuan-note/siyuan/issues/4289
        if (getSelection().rangeCount > 0) {
            const range = getSelection().getRangeAt(0);
            if (hasClosestByClassName(range.startContainer, "protyle-content", true)) {
                if (!event.repeat && selectReadonlyBlocksByRange(range)) {
                    event.preventDefault();
                    return;
                }
                focusByRange(range);
                return;
            }
        }
        const lastBackStack = window.siyuan.backStack[window.siyuan.backStack.length - 1];
        if (lastBackStack && lastBackStack.protyle.toolbar.range) {
            focusByRange(lastBackStack.protyle.toolbar.range);
        } else {
            const editor = getAllModels().editor[0];
            if (editor) {
                focusBlock(editor.editor.protyle.wysiwyg.element.firstElementChild);
            }
        }
        event.preventDefault();
        return;
    }

    if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.mainMenu, event)) {
        const target = document.querySelector("#barWorkspace");
        workspaceMenu(app, target.getBoundingClientRect(), true, target);
        event.preventDefault();
        return;
    }

    if (matchHotKey(window.siyuan.config.keymap.general.goForward, event)) {
        goForward(app);
        event.preventDefault();
        return;
    }

    if (matchHotKey(window.siyuan.config.keymap.general.goBack, event)) {
        goBack(app);
        event.preventDefault();
        return;
    }

    // close tab
    if (matchHotKey(window.siyuan.config.keymap.general.closeTab, event) && !event.repeat) {
        execByCommand({
            command: "closeTab"
        });
        event.preventDefault();
        return;
    }

    if (matchHotKey(window.siyuan.config.keymap.general.recentClosed, event)) {
        execByCommand({
            command: "recentClosed",
            app
        });
        event.preventDefault();
        return;
    }

    if (matchHotKey(window.siyuan.config.keymap.general.switchTab, event)) {
        if (!event.repeat) {
            globalCommand("switchTab", app);
        }
        event.preventDefault();
        return;
    }

    if (matchHotKey(window.siyuan.config.keymap.general.goToTab1, event) && !event.repeat) {
        switchTabByIndex(0);
        event.preventDefault();
        return;
    }

    if (matchHotKey(window.siyuan.config.keymap.general.goToTab2, event) && !event.repeat) {
        switchTabByIndex(1);
        event.preventDefault();
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.goToTab3, event) && !event.repeat) {
        switchTabByIndex(2);
        event.preventDefault();
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.goToTab4, event) && !event.repeat) {
        switchTabByIndex(3);
        event.preventDefault();
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.goToTab5, event) && !event.repeat) {
        switchTabByIndex(4);
        event.preventDefault();
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.goToTab6, event) && !event.repeat) {
        switchTabByIndex(5);
        event.preventDefault();
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.goToTab7, event) && !event.repeat) {
        switchTabByIndex(6);
        event.preventDefault();
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.goToTab8, event) && !event.repeat) {
        switchTabByIndex(7);
        event.preventDefault();
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.goToTab9, event) && !event.repeat) {
        switchTabByIndex(-1);
        event.preventDefault();
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.goToTabNext, event) && !event.repeat) {
        switchTabByIndex(-3);
        event.preventDefault();
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.goToTabPrev, event) && !event.repeat) {
        switchTabByIndex(-2);
        event.preventDefault();
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.closeOthers, event) && !event.repeat) {
        execByCommand({
            command: "closeOthers"
        });
        event.preventDefault();
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.closeAll, event) && !event.repeat) {
        execByCommand({
            command: "closeAll"
        });
        event.preventDefault();
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.closeUnmodified, event) && !event.repeat) {
        execByCommand({
            command: "closeUnmodified"
        });
        event.preventDefault();
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.closeLeft, event) && !event.repeat) {
        execByCommand({
            command: "closeLeft"
        });
        event.preventDefault();
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.closeRight, event) && !event.repeat) {
        execByCommand({
            command: "closeRight"
        });
        event.preventDefault();
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.splitLR, event) && !event.repeat) {
        event.preventDefault();
        globalCommand("splitLR", app);
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.splitMoveR, event) && !event.repeat) {
        event.preventDefault();
        globalCommand("splitMoveR", app);
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.splitTB, event) && !event.repeat) {
        event.preventDefault();
        globalCommand("splitTB", app);
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.tabToWindow, event) && !event.repeat) {
        event.preventDefault();
        globalCommand("tabToWindow", app);
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.splitMoveB, event) && !event.repeat) {
        event.preventDefault();
        globalCommand("splitMoveB", app);
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.stickSearch, event)) {
        globalCommand("stickSearch", app);
        event.preventDefault();
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.unsplit, event) && !event.repeat) {
        event.preventDefault();
        globalCommand("unsplit", app);
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.unsplitAll, event) && !event.repeat) {
        event.preventDefault();
        globalCommand("unsplitAll", app);
        return;
    }
    if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.selectOpen1, event)) {
        event.preventDefault();
        globalCommand("selectOpen1", app);
        return;
    }
    if (dispatchPluginShortcut(app, event, "shortcut", () => captureShortcutContext(app, event))) {
        return true;
    }

    if (matchHotKey(window.siyuan.config.keymap.general.replace, event)) {
        execByCommand({
            command: "replace",
            app,
        });
        event.preventDefault();
        return;
    }
    if (matchHotKey(window.siyuan.config.keymap.general.globalSearch, event)) {
        execByCommand({
            command: "globalSearch",
            app,
        });
        event.preventDefault();
        return;
    }
    if (!hasClosestByClassName(target, "pdf__outer") && matchHotKey(window.siyuan.config.keymap.general.search, event)) {
        execByCommand({
            command: "search",
            app,
        });
        event.preventDefault();
        return;
    }
    // https://github.com/siyuan-note/insider/issues/445
    if (matchHotKey("⌘S", event)) {
        event.preventDefault();
        return true;
    }
};