Skip to content

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

103 KB
Raw Blame
import {toggleMenu} from "../../menus/menuToggle";
import {listIndent, listOutdent} from "../../protyle/wysiwyg/list";
import {
    hasClosestBlock,
    hasClosestByAttribute,
    hasClosestByClassName,
    hasClosestByTag,
} from "../../protyle/util/hasClosest";
import {moveToDown, moveToUp} from "../../protyle/wysiwyg/move";
import {Constants} from "../../constants";
import {canPickIOSPhotos} from "../../protyle/upload/iosPhotos";
import {getSuperBlockCommand} from "../../block/superBlock";
import {getSelectionPosition} from "../../protyle/util/selection";
import {focusByRange} from "../../protyle/util/selectionOffsets";
import {getCurrentEditor as getDocumentEditor} from "../editor";
import {getMobileToolbarPaddingElement, getMobileToolbarProtyle, getMobileToolbarUndo} from "../../protyle/lite/mobileToolbar";
import {LocalUndo} from "../../protyle/undo";
import {convertFontSize, fontEvent, getFontNodeElements, getFontSizeInfo} from "../../protyle/toolbar/Font";
import {hideElements} from "../../protyle/ui/hideElements";
import {softEnter} from "../../protyle/wysiwyg/enter";
import {endTrackedRangeInsertion, prepareTrackedRangeInsertion} from "../../protyle/util/trackedRange";
import {
    isDisabledFeature,
    isInAndroid,
    isInEdge,
    isInHarmony,
    isInMobileApp,
} from "../../protyle/util/compatibility";
import {tabCodeBlock} from "../../protyle/wysiwyg/codeBlock";
import {armKeyboardLock, callMobileAppShowKeyboard, canInput, keyboardLockUntil} from "./mobileAppUtil";
import {getMirror, getUndoRootID, hasUndoStateMirror, initMirror} from "../../protyle/undo/globalUndo";
import {getMobilePluginToolbarItems} from "./pluginToolbar";
import {escapeHtml} from "../../util/escape";
import {
    encodeStyle1,
    filterHiddenRecentInlineStyles,
    getBuiltinInlineStyleIDFromValue,
    getBuiltinInlineStylePreview,
    getBuiltinInlineStyleApplication,
    getBuiltinInlineStylePropertyValue,
    getInlineStyleByID,
    getInlineStyleByValue,
    getInlineStyleIDFromValue,
    getInlineStylePreview,
    getInlineStylesCache,
    getVisibleOrderedStyleKeys,
    isBuiltinInlineStyleVisible,
    isBuiltinOrderKey,
    TBuiltinInlineStyleID,
    TInlineStyleType,
} from "../../protyle/toolbar/inlineStyle";
import {openInlineStyleDialog} from "../../protyle/toolbar/inlineStyleDialog";
import {forEachPluginSubscriber} from "../../plugin/EventBusCore";
import {getHostCapabilities} from "../../util/hostCapabilities";
import {
    getKeyboardHideResult,
    getMovingSelectionEndpoint,
    hasFixedSelectionEndpointChanged,
    hasVisibleSelectionText,
    isTableCellSelectAll,
    KeyboardHideResult,
    shouldHideKeyboardAfterResize,
    shouldPreserveTableCellSelectAll,
    type TSelectionEndpoint,
} from "./touchSelection";
import {getVisibleViewportBounds} from "./visibleViewport";
import {createInlineMathSelection} from "./inlineMathSelection";
import {isCommittedTextInput} from "../../protyle/wysiwyg/compositionInput";
import {
    getTextWithoutSemanticMarkers,
    stripSemanticMarkersFromRangeText
} from "../../protyle/util/inlineElementMarker";
import {
    getInlineFontFamilyLabel,
    getFontFamilyState,
    getInlineFontFamilyValue,
    openFontFamilyMenu,
} from "../../protyle/toolbar/fontFamilyMenu";
import {notifyMobileKeyboardChange} from "./mobileKeyboardChange";
import {getEditorFocusRange, restoreEditorFocusRange} from "../../protyle/util/editorFocus";
import {captureMenuKeyboard} from "./menuKeyboard";
import {isMobile} from "../../util/functions";
import {createFontSizePicker} from "../../protyle/toolbar/fontControls";
import {applyMobileToolbarEntries} from "./toolbarEntries";
import {getEntryOrder, isEntryVisible} from "../../config/entryVisibility/runtime";
import {MOBILE_TOOLBAR_NAMES} from "../../protyle/toolbar/defaults";
import {getKeyboardPanelHeight} from "./keyboardPanelHeight";
import {isMobileLandscape} from "./orientation";
import {restoreGutterBySelection} from "../../protyle/gutter/restore";
import {isGutterTouchDragging} from "../../protyle/ui/gutterVisibility";
import {getFrequentSlashButtons, mountLiteSlashMenu, prependFrequentSlashButtons} from "./liteSlashMenu";
import {getPluginSlashEntryKey, SLASH_MENU_ROOT_PATH} from "../../config/entryVisibility/catalog";
import {hintSlash} from "../../protyle/hint/extend";
import {getFrequentSlashItems} from "../../protyle/hint/frequentSlashStorage";
import {finishTableCellEditing, getTableCellRichContext, prepareTableCellMenuItems} from "../../protyle/util/tableCellRichContext";
import {insertEmptyBlock} from "../../block/util";
import {getIconByType} from "../../editor/getIcon";
import {MOBILE_TOOLBAR_ACTION_NAMES, MOBILE_TOOLBAR_ACTIONS, MOBILE_TOOLBAR_INSERTS} from "./toolbarActions";
import {pauseMobileBarsScroll} from "./mobileBars";
import {getBlockTypeSelection, openBlockTypeMenu, updateBlockTypeButton} from "../../protyle/toolbar/BlockType";
import {TTextBlockSelection} from "../../protyle/toolbar/blockTypeCore";
import {getMobileToolbarContextPath} from "../../config/entryVisibility/mobileToolbarContext";
import {createKeyboardSelectionScroll} from "./keyboardSelectionScroll";
import {getCaretOverflowDirection, getCaretScrollDelta} from "../../protyle/wysiwyg/caretScrollCore";

const getCurrentEditor = () => getMobileToolbarProtyle()?.getInstance() || getDocumentEditor();
let toolbarProtyle: IProtyle;
let fontFamilyMenu: {element: HTMLElement, protyle: IProtyle} | undefined;
let unmountLiteSlashMenu: (() => void) | undefined;

const applyKeyboardToolbarEntries = (element: HTMLElement, toolbar: Array<string | IMenuItem>) => {
    const protyle = getCurrentEditor()?.protyle;
    const selection = getSelection();
    const range = selection?.rangeCount > 0 && protyle?.wysiwyg.element.contains(selection.anchorNode) &&
        protyle.wysiwyg.element.contains(selection.focusNode) ? selection.getRangeAt(0) : undefined;
    const nodeElement = (range && hasClosestBlock(range.startContainer)) || undefined;
    const inCode = nodeElement?.classList.contains("code-block");
    const hasText = !!range && !!stripSemanticMarkersFromRangeText(range).split(Constants.ZWSP).join("");
    const contextPath = getMobileToolbarContextPath(hasText);
    applyMobileToolbarEntries(element, toolbar, {
        order: getEntryOrder(contextPath),
        isVisible: key => isEntryVisible(`${contextPath}.${key}`),
        isAvailable: name => {
            if (hasText && (name === "block-type" || MOBILE_TOOLBAR_ACTION_NAMES.includes(name))) {
                return false;
            }
            if (name === "block-type") {
                return !!range && !!getBlockTypeSelection(protyle, range);
            }
            if (name === "outdent" || name === "indent") {
                return !!nodeElement?.parentElement.classList.contains("li") || !!inCode && hasText;
            }
            if (name === "block-ref") {
                return !!range && !inCode;
            }
            if (name !== "block-type" && MOBILE_TOOLBAR_NAMES.includes(name)) {
                return !inCode && hasText;
            }
            if (name === "block") {
                return !!protyle?.gutter || !!protyle && !!getTableCellRichContext(protyle);
            }
            return !protyle?.lite || !MOBILE_TOOLBAR_INSERTS.some(item => item.name === name);
        },
    });
};

type TAndroidBoundedSelection = {
    container: HTMLElement,
    anchorNode: Node,
    anchorOffset: number,
    focusNode: Node,
    focusOffset: number,
};

type TAndroidTableCellSelectAll = {
    cell: HTMLTableCellElement,
    editableElement: HTMLElement,
    expiresAt: number,
    range: Range,
};

const ANDROID_TABLE_CELL_SELECT_ALL_TIMEOUT = 2000;
const inlineMathSelection = createInlineMathSelection();

let renderKeyboardToolbarFrame: number | undefined;
let clearRenderGutterAfterScroll: () => void;
const keyboardSelectionScroll = createKeyboardSelectionScroll({
    delay: Constants.TIMEOUT_TRANSITION,
    scroll: container => scrollKeyboardSelection(container),
    onCancel: () => clearRenderGutterAfterScroll?.(),
});
let showUtil = false;
let keyboardPanelTop: number | undefined;
let keyboardPanelClosing = false;
let keyboardPanelCloseTimeout: number | undefined;
let keyboardPanelLandscape: boolean;
let pendingKeyboardFocus: {protyle: IProtyle, range: Range} | undefined;
let showUtilTimeout: number | undefined;
let preventRender = false;
let preventRenderTimeout: number;
let restoringAndroidBoundedSelection = false;
let lastAndroidBoundedSelection: TAndroidBoundedSelection | undefined;
let androidMovingSelectionEndpoint: TSelectionEndpoint | undefined;
let pendingAndroidTableCellSelectAll: TAndroidTableCellSelectAll | undefined;
let restoringAndroidTableCellSelectAll = false;

export const updateMobilePluginToolbar = (protyle: IProtyle) => {
    const currentProtyle = getCurrentEditor()?.protyle;
    if (currentProtyle && currentProtyle !== protyle) {
        return;
    }
    const inlineToolbarElement = document.querySelector<HTMLElement>(
        '#keyboardToolbar .keyboard__action[data-type="inline-memo"]')?.parentElement;
    if (!inlineToolbarElement) {
        return;
    }
    inlineToolbarElement.querySelectorAll('[data-plugin-toolbar="true"]').forEach(item => item.remove());
    getMobilePluginToolbarItems(protyle.options.toolbar, Constants.INLINE_TYPE.concat("font-family", "font-size", "block-type")).forEach(toolbarItem => {
        const itemElement = document.createElement("button");
        itemElement.className = "keyboard__action";
        itemElement.dataset.type = toolbarItem.name;
        itemElement.dataset.pluginToolbar = "true";
        itemElement.innerHTML = `<svg><use xlink:href="#${toolbarItem.icon}"></use></svg>`;
        const label = toolbarItem.tip || (toolbarItem.lang ? window.siyuan.languages[toolbarItem.lang] : "");
        if (label) {
            itemElement.setAttribute("aria-label", label);
        }
        inlineToolbarElement.append(itemElement);
    });
    applyKeyboardToolbarEntries(inlineToolbarElement, protyle.options.toolbar);
};

const clearAndroidBoundedSelection = () => {
    lastAndroidBoundedSelection = undefined;
    androidMovingSelectionEndpoint = undefined;
};

export const resetAndroidBoundedSelectionGesture = () => {
    androidMovingSelectionEndpoint = undefined;
};

const rememberAndroidTableCellSelectAll = () => {
    if (!isInAndroid() || restoringAndroidTableCellSelectAll) {
        return;
    }
    const selection = getSelection();
    if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {
        return;
    }
    const range = selection.getRangeAt(0);
    const startCell = (hasClosestByTag(range.startContainer, "TD") ||
        hasClosestByTag(range.startContainer, "TH")) as HTMLTableCellElement;
    const endCell = (hasClosestByTag(range.endContainer, "TD") ||
        hasClosestByTag(range.endContainer, "TH")) as HTMLTableCellElement;
    if (!startCell || startCell !== endCell || !isTableCellSelectAll(
        stripSemanticMarkersFromRangeText(range), getTextWithoutSemanticMarkers(startCell))) {
        if (pendingAndroidTableCellSelectAll && startCell && startCell !== pendingAndroidTableCellSelectAll.cell) {
            pendingAndroidTableCellSelectAll = undefined;
        }
        return;
    }
    const editor = getCurrentEditor();
    const editableElement = (canInput(document.activeElement) ||
        hasClosestByAttribute(range.startContainer, "contenteditable", "true", true)) as HTMLElement;
    if (!editor || !editableElement || !editor.protyle.wysiwyg.element.contains(startCell) ||
        !(editableElement === startCell || editableElement.contains(startCell) || startCell.contains(editableElement))) {
        return;
    }
    pendingAndroidTableCellSelectAll = {
        cell: startCell,
        editableElement,
        expiresAt: Date.now() + ANDROID_TABLE_CELL_SELECT_ALL_TIMEOUT,
        range: range.cloneRange(),
    };
};

const hasRecentAndroidTableCellSelectAll = (pendingSelection = pendingAndroidTableCellSelectAll) =>
    !!pendingSelection && shouldPreserveTableCellSelectAll(pendingSelection.expiresAt, Date.now()) &&
    pendingSelection.cell.isConnected && pendingSelection.editableElement.isConnected &&
    pendingSelection.range.startContainer.isConnected && pendingSelection.range.endContainer.isConnected;

const restoreRecentAndroidTableCellSelectAll = () => {
    const pendingSelection = pendingAndroidTableCellSelectAll;
    pendingAndroidTableCellSelectAll = undefined;
    if (!pendingSelection || !hasRecentAndroidTableCellSelectAll(pendingSelection)) {
        return false;
    }
    restoringAndroidTableCellSelectAll = true;
    try {
        armKeyboardLock();
        pendingSelection.editableElement.focus({preventScroll: true});
        const selection = getSelection();
        selection.removeAllRanges();
        selection.addRange(pendingSelection.range);
    } finally {
        window.setTimeout(() => {
            restoringAndroidTableCellSelectAll = false;
        });
    }
    return true;
};

const getAndroidBoundedSelection = (selection: Selection, container: HTMLElement): TAndroidBoundedSelection => ({
    container,
    anchorNode: selection.anchorNode,
    anchorOffset: selection.anchorOffset,
    focusNode: selection.focusNode,
    focusOffset: selection.focusOffset,
});

const hasSelectionPointChanged = (node: Node, offset: number, previousNode: Node, previousOffset: number) =>
    node !== previousNode || offset !== previousOffset;

const restoreAndroidBoundedSelection = (selection: Selection, restored: TAndroidBoundedSelection) => {
    lastAndroidBoundedSelection = restored;
    restoringAndroidBoundedSelection = true;
    try {
        selection.setBaseAndExtent(
            restored.anchorNode,
            restored.anchorOffset,
            restored.focusNode,
            restored.focusOffset,
        );
    } finally {
        window.setTimeout(() => {
            restoringAndroidBoundedSelection = false;
        });
    }
    return true;
};

const getAndroidSelectionContainer = (selection: Selection) => {
    const previousContainer = lastAndroidBoundedSelection?.container;
    if (previousContainer?.classList.contains("agent-chat__body") &&
        (previousContainer.contains(selection.anchorNode) || previousContainer.contains(selection.focusNode))) {
        return previousContainer;
    }
    const anchorAgentBody = hasClosestByClassName(selection.anchorNode, "agent-chat__body", true);
    const focusAgentBody = hasClosestByClassName(selection.focusNode, "agent-chat__body", true);
    if (anchorAgentBody && anchorAgentBody === focusAgentBody) {
        return anchorAgentBody;
    }

    const protyle = getCurrentEditor()?.protyle;
    const previewVisible = protyle && !protyle.preview.element.classList.contains("fn__none");
    if (!protyle || (!protyle.disabled && !previewVisible)) {
        return;
    }
    return previewVisible ? protyle.preview.previewElement : protyle.wysiwyg.element;
};

const preserveAndroidBoundedSelection = () => {
    if (!isInAndroid() || restoringAndroidBoundedSelection) {
        return false;
    }
    const selection = getSelection();
    if (!selection || selection.rangeCount === 0 || selection.isCollapsed ||
        !selection.anchorNode || !selection.focusNode) {
        clearAndroidBoundedSelection();
        return false;
    }
    const container = getAndroidSelectionContainer(selection);
    if (!container) {
        clearAndroidBoundedSelection();
        return false;
    }
    const contains = (node: Node) => node === container || container.contains(node);
    const anchorInside = contains(selection.anchorNode);
    const focusInside = contains(selection.focusNode);
    const current = getAndroidBoundedSelection(selection, container);
    const previous = lastAndroidBoundedSelection;
    const previousAvailable = previous?.container === container &&
        previous.anchorNode.isConnected && previous.focusNode.isConnected &&
        contains(previous.anchorNode) && contains(previous.focusNode);
    if (container.classList.contains("agent-chat__body")) {
        if (!previousAvailable) {
            androidMovingSelectionEndpoint = undefined;
            if (anchorInside && focusInside) {
                lastAndroidBoundedSelection = current;
            } else {
                clearAndroidBoundedSelection();
            }
            return false;
        }
        const anchorChanged = hasSelectionPointChanged(
            current.anchorNode,
            current.anchorOffset,
            previous.anchorNode,
            previous.anchorOffset,
        );
        const focusChanged = hasSelectionPointChanged(
            current.focusNode,
            current.focusOffset,
            previous.focusNode,
            previous.focusOffset,
        );
        androidMovingSelectionEndpoint = getMovingSelectionEndpoint(
            androidMovingSelectionEndpoint,
            anchorChanged,
            focusChanged,
        );
        if (!androidMovingSelectionEndpoint) {
            if (anchorInside && focusInside) {
                lastAndroidBoundedSelection = current;
                return false;
            }
            return restoreAndroidBoundedSelection(selection, previous);
        }
        const movingAnchor = androidMovingSelectionEndpoint === "anchor";
        const movingEndpointInside = movingAnchor ? anchorInside : focusInside;
        if (!movingEndpointInside || hasFixedSelectionEndpointChanged(
            androidMovingSelectionEndpoint,
            anchorChanged,
            focusChanged,
        )) {
            return restoreAndroidBoundedSelection(selection, {
                container,
                anchorNode: movingAnchor && anchorInside ? current.anchorNode : previous.anchorNode,
                anchorOffset: movingAnchor && anchorInside ? current.anchorOffset : previous.anchorOffset,
                focusNode: !movingAnchor && focusInside ? current.focusNode : previous.focusNode,
                focusOffset: !movingAnchor && focusInside ? current.focusOffset : previous.focusOffset,
            });
        }
        lastAndroidBoundedSelection = current;
        return false;
    }
    androidMovingSelectionEndpoint = undefined;
    if (anchorInside && focusInside) {
        lastAndroidBoundedSelection = current;
        return false;
    }
    if (!previousAvailable || anchorInside === focusInside) {
        clearAndroidBoundedSelection();
        return false;
    }
    return restoreAndroidBoundedSelection(selection, {
        container,
        anchorNode: anchorInside ? current.anchorNode : previous.anchorNode,
        anchorOffset: anchorInside ? current.anchorOffset : previous.anchorOffset,
        focusNode: focusInside ? current.focusNode : previous.focusNode,
        focusOffset: focusInside ? current.focusOffset : previous.focusOffset,
    });
};

const preventKeyboardToolbarRender = () => {
    preventRender = true;
    clearTimeout(preventRenderTimeout);
    preventRenderTimeout = window.setTimeout(() => {
        preventRender = false;
    }, 1000);
};

const updateKeyboardToolbarPosition = () => {
    updateKeyboardPanelHeight();
    scrollKeyboardSelectionIntoView();
    if (isInMobileApp() || !window.visualViewport) {
        return;
    }
    const toolbarElement = document.getElementById("keyboardToolbar");
    const viewportBottom = window.visualViewport.offsetTop + window.visualViewport.height;
    const toolbarHeight = toolbarElement.getBoundingClientRect().height || 48;
    toolbarElement.style.transform = "";
    toolbarElement.style.bottom = "auto";
    toolbarElement.style.top = `${viewportBottom - toolbarHeight}px`;
};

const getKeyboardViewportBottom = () => !isInMobileApp() && window.visualViewport ?
    window.visualViewport.offsetTop + window.visualViewport.height : document.documentElement.getBoundingClientRect().height;

const updateKeyboardPanelHeight = () => {
    if (keyboardPanelTop === undefined) {
        return;
    }
    if (keyboardPanelLandscape !== isMobileLandscape()) {
        keyboardPanelClosing = false;
        hideKeyboardToolbarUtil();
        return;
    }
    const toolbarElement = document.getElementById("keyboardToolbar");
    // 与展开入口保持相同高度口径,避免边框和整数取整导致交接时上下跳动。
    const barHeight = toolbarElement.querySelector<HTMLElement>(".keyboard__bar").clientHeight;
    const height = getKeyboardPanelHeight(getKeyboardViewportBottom(), keyboardPanelTop, barHeight);
    if (keyboardPanelClosing && height <= barHeight) {
        keyboardPanelClosing = false;
        hideKeyboardToolbarUtil();
        return;
    }
    // 原生端占位随视口同步变化,避免等待 resize 时编辑器短暂增高,导致滚动位置被截断。
    const panelHeight = isInMobileApp() ?
        `max(${barHeight}px, calc(100vh - ${keyboardPanelTop}px))` : `${height}px`;
    toolbarElement.style.height = panelHeight;
    const editor = getCurrentEditor();
    if (editor) {
        getMobileToolbarPaddingElement(editor.protyle).style.paddingBottom = panelHeight;
    }
};

const getSlashItem = (entryKey: string, value: string, icon: string, text: string, focus = "false") => {
    let iconHTML;
    if (icon && icon.startsWith("icon")) {
        iconHTML = `<svg class="keyboard__slash-icon"><use xlink:href="#${icon}"></use></svg>`;
    } else {
        iconHTML = icon;
    }
    return `<button class="keyboard__slash-item"${entryKey ? ` data-slash-entry-key="${escapeHtml(entryKey)}"` : ""} data-focus="${focus}" data-value="${encodeURIComponent(value)}">
    ${iconHTML}
    <span class="keyboard__slash-text">${text}</span>
</button>`;
};

const getBuiltinStyleLabel = (id: TBuiltinInlineStyleID) => ({
    error: window.siyuan.languages.errorStyle,
    warning: window.siyuan.languages.warningStyle,
    info: window.siyuan.languages.infoStyle,
    success: window.siyuan.languages.successStyle,
})[id];

const getBuiltinStyleCSS = (id: TBuiltinInlineStyleID) =>
    `color: ${getBuiltinInlineStylePropertyValue(id, "color")};` +
    `background-color: ${getBuiltinInlineStylePropertyValue(id, "backgroundColor")};`;

export const renderTextMenu = (protyle: IProtyle, toolbarElement: Element) => {
    const renderOrderedItems = (type: TInlineStyleType) => {
        const data = getInlineStylesCache();
        return getVisibleOrderedStyleKeys(type, data).map(key => {
            if (isBuiltinOrderKey(type, key)) {
                if (type === "color") {
                    const index = Number(key);
                    return `<button class="keyboard__slash-item" data-type="color">
    <span class="keyboard__slash-icon" style="color:var(--b3-font-color${index})">A</span>
    <span class="keyboard__slash-text">${window.siyuan.languages.colorFont} ${index}</span>
</button>`;
                }
                if (type === "backgroundColor") {
                    const index = Number(key);
                    return `<button class="keyboard__slash-item" data-type="backgroundColor">
    <span class="keyboard__slash-icon" style="background-color:var(--b3-font-background${index})">A</span>
    <span class="keyboard__slash-text">${window.siyuan.languages.colorPrimary} ${index}</span>
</button>`;
                }
                const preview = getBuiltinInlineStylePreview(key as TBuiltinInlineStyleID);
                return `<button class="keyboard__slash-item" data-type="style1" data-builtin-style-id="${key}">
    <span class="keyboard__slash-icon" style="color:${preview.color};background-color:${preview.backgroundColor};">A</span>
    <span class="keyboard__slash-text">${getBuiltinStyleLabel(key as TBuiltinInlineStyleID)}</span>
</button>`;
            }
            const style = getInlineStyleByID(key, data);
            if (!style) {
                return "";
            }
            const preview = getInlineStylePreview(style);
            return `<button class="keyboard__slash-item" data-type="${type}" data-inline-style-id="${style.id}">
    <span class="keyboard__slash-icon" style="${preview.color ? `color:${preview.color};` : ""}${preview.backgroundColor ? `background-color:${preview.backgroundColor};` : ""}">A</span>
    <span class="keyboard__slash-text">${escapeHtml(style.name)}</span>
</button>`;
        }).join("");
    };
    let colorHTML = `<button class="keyboard__slash-item" data-type="color">
    <span class="keyboard__slash-icon">A</span>
    <span class="keyboard__slash-text">${window.siyuan.languages.colorFont} ${window.siyuan.languages.default}</span>
</button>`;
    colorHTML += renderOrderedItems("color");
    let bgHTML = `<button class="keyboard__slash-item" data-type="backgroundColor">
    <span class="keyboard__slash-icon">A</span>
    <span class="keyboard__slash-text">${window.siyuan.languages.colorPrimary} ${window.siyuan.languages.default}</span>
</button>`;
    bgHTML += renderOrderedItems("backgroundColor");
    const getManageHTML = (type: TInlineStyleType) => window.siyuan.config.readonly || window.siyuan.isPublish ? "" :
        `<button class="keyboard__slash-item" data-action="manageInlineStyle" data-inline-style-type="${type}">
    <svg class="keyboard__slash-icon"><use xlink:href="#iconSettings"></use></svg>
    <span class="keyboard__slash-text">${window.siyuan.languages.manageColors}</span>
</button>`;

    const nodeElements = getFontNodeElements(protyle);
    let disableFont = false;
    nodeElements?.find((item: HTMLElement) => {
        if (item.classList.contains("li")) {
            disableFont = true;
            return true;
        }
    });

    let lastColorHTML = "";
    const lastFonts = filterHiddenRecentInlineStyles(window.siyuan.storage[Constants.LOCAL_FONTSTYLES]);
    if (lastFonts.length > 0) {
        lastColorHTML = `<div data-id="lastUsed" class="keyboard__slash-title">
    ${window.siyuan.languages.lastUsed}
</div>
<div data-id="lastUsedWrap" class="keyboard__slash-block">`;
        lastFonts.forEach((item: string) => {
            const lastFontStatus = item.split(Constants.ZWSP);
            const inlineStyleID = getInlineStyleIDFromValue(item);
            const inlineStyle = getInlineStyleByValue(item);
            const customLabel = inlineStyle ? escapeHtml(inlineStyle.name) :
                (inlineStyleID ? window.siyuan.languages.custom : "");
            switch (lastFontStatus[0]) {
                case "color":
                    lastColorHTML += `<button class="keyboard__slash-item" data-type="${lastFontStatus[0]}">
    <span class="keyboard__slash-icon" ${lastFontStatus[1] ? `style="color:${lastFontStatus[1]}"` : ""} >A</span>
    <span class="keyboard__slash-text">${customLabel || window.siyuan.languages.colorFont + " " + (lastFontStatus[1]?.match(/^var\(--b3-font-color(\d+)\)$/)?.[1] || window.siyuan.languages.default)}</span>
</button>`;
                    break;
                case "backgroundColor":
                    lastColorHTML += `<button class="keyboard__slash-item" data-type="${lastFontStatus[0]}">
    <span class="keyboard__slash-icon" ${lastFontStatus[1] ? `style="background-color:${lastFontStatus[1]}"` : ""}>A</span>
    <span class="keyboard__slash-text">${customLabel || window.siyuan.languages.colorPrimary + " " + (lastFontStatus[1]?.match(/^var\(--b3-font-background(\d+)\)$/)?.[1] || window.siyuan.languages.default)}</span>
</button>`;
                    break;
                case "style2":
                    lastColorHTML += `<button class="keyboard__slash-item" data-type="${lastFontStatus[0]}">
    <span class="keyboard__slash-text" style="-webkit-text-stroke: 0.2px var(--b3-theme-on-background);-webkit-text-fill-color : transparent;">${window.siyuan.languages.hollow}</span>
</button>`;
                    break;
                case "style4":
                    lastColorHTML += `<button class="keyboard__slash-item" data-type="${lastFontStatus[0]}">
    <span class="keyboard__slash-text" style="text-shadow: 1px 1px var(--b3-theme-surface-lighter), 2px 2px var(--b3-theme-surface-lighter), 3px 3px var(--b3-theme-surface-lighter), 4px 4px var(--b3-theme-surface-lighter)">${window.siyuan.languages.shadow}</span>
</button>`;
                    break;
                case "fontSize":
                    if (!disableFont) {
                        lastColorHTML += `<button class="keyboard__slash-item" data-type="${lastFontStatus[0]}">
    <span class="keyboard__slash-text">${lastFontStatus[1]}</span>
</button>`;
                    }
                    break;
                case "style1":
                    if (lastFontStatus[1]) {
                        const builtInStyle = getBuiltinInlineStyleIDFromValue(item);
                        const preview = builtInStyle ? getBuiltinInlineStylePreview(builtInStyle) : {
                            backgroundColor: lastFontStatus[1],
                            color: lastFontStatus[2],
                        };
                        lastColorHTML += `<button class="keyboard__slash-item" data-builtin-style-id="${builtInStyle || ""}" data-type="${lastFontStatus[0]}">
    <span class="keyboard__slash-icon" style="background-color:${preview.backgroundColor};color:${preview.color}">A</span>
    <span class="keyboard__slash-text">${customLabel || (builtInStyle ? getBuiltinStyleLabel(builtInStyle) : window.siyuan.languages.color)}</span>
</button>`;
                    } else {
                        lastColorHTML += `<button class="keyboard__slash-item" data-type="${lastFontStatus[0]}">
    <span class="keyboard__slash-icon">A</span>
    <span class="keyboard__slash-text">${window.siyuan.languages.color} ${window.siyuan.languages.default}</span>
</button>`;
                    }
                    break;
                case "clear":
                    lastColorHTML += `<button class="keyboard__slash-item" data-type="${lastFontStatus[0]}">
    <span class="keyboard__slash-text">${window.siyuan.languages.clearFontStyle}</span>
</button>`;
                    break;
            }
        });
        lastColorHTML += "</div>";
    }
    const {fontSize, baseFontSize} = getFontSizeInfo(protyle, nodeElements);
    const fontFamilyState = getFontFamilyState(protyle, nodeElements);
    const disableFontFamily = disableFont || fontFamilyState.disabled;
    const utilElement = toolbarElement.querySelector(".keyboard__util") as HTMLElement;
    utilElement.innerHTML = `${lastColorHTML}
<div data-id="color" class="keyboard__slash-title">${window.siyuan.languages.color}</div>
<div data-id="colorWrap" class="keyboard__slash-block">
    <button class="keyboard__slash-item" data-type="style1">
        <span class="keyboard__slash-icon">A</span>
        <span class="keyboard__slash-text">${window.siyuan.languages.color} ${window.siyuan.languages.default}</span>
    </button>
    ${renderOrderedItems("style1")}
    ${getManageHTML("style1")}
</div>
<div data-id="colorFont" class="keyboard__slash-title">${window.siyuan.languages.colorFont}</div>
<div data-id="colorFontWrap" class="keyboard__slash-block">
    ${colorHTML}
    ${getManageHTML("color")}
</div>
<div data-id="colorPrimary" class="keyboard__slash-title">${window.siyuan.languages.colorPrimary}</div>
<div data-id="colorPrimaryWrap" class="keyboard__slash-block">
    ${bgHTML}
    ${getManageHTML("backgroundColor")}
</div>
<div data-id="fontStyle" class="keyboard__slash-title">${window.siyuan.languages.fontStyle}</div>
<div data-id="fontStyleWrap" class="keyboard__slash-block">
    <button class="keyboard__slash-item" data-type="style2">
        <span class="keyboard__slash-text" style="-webkit-text-stroke: 0.2px var(--b3-theme-on-background);-webkit-text-fill-color : transparent;">${window.siyuan.languages.hollow}</span>
    </button>
    <button class="keyboard__slash-item" data-type="style4">
        <span class="keyboard__slash-text" style="text-shadow: 1px 1px var(--b3-theme-surface-lighter), 2px 2px var(--b3-theme-surface-lighter), 3px 3px var(--b3-theme-surface-lighter), 4px 4px var(--b3-theme-surface-lighter)">${window.siyuan.languages.shadow}</span>
    </button>
    <button class="keyboard__slash-item" data-type="clear">
        <svg class="keyboard__slash-icon"><use xlink:href="#iconTrashcan"></use></svg>
        <span class="keyboard__slash-text">${window.siyuan.languages.clearFontStyle}</span>
    </button>
</div>
<div data-id="fontFamily" class="keyboard__slash-title${disableFontFamily ? " fn__none" : ""}">${window.siyuan.languages.fontFamily}</div>
<div data-id="fontFamilyWrap" class="keyboard__slash-block${disableFontFamily ? " fn__none" : ""}">
    <button class="b3-select keyboard__font-family fn__flex-1" data-action="fontFamilyMenu" data-menu="true" aria-haspopup="listbox" aria-expanded="false">
        <span data-type="fontFamilyPreview">${escapeHtml(getInlineFontFamilyLabel(fontFamilyState))}</span>
    </button>
</div>
<div data-id="fontSize" class="keyboard__slash-title${disableFont ? " fn__none" : ""}">${window.siyuan.languages.fontSize}</div>
<div data-id="fontSizeWrap" class="keyboard__slash-block${disableFont ? " fn__none" : ""}">
    <label class="keyboard__font-size-toggle">
        ${window.siyuan.languages.relativeFontSize}
        <span class="fn__flex-1"></span>
        <input class="b3-switch fn__flex-center" ${fontSize.endsWith("em") ? "checked" : ""} type="checkbox">
    </label>
    <label class="keyboard__font-size${fontSize.endsWith("em") ? " fn__none" : ""}">
        <input class="b3-slider fn__flex-1" data-type="fontSizePX" max="72" min="9" step="1" type="range" value="${parseFloat(fontSize)}">
        <span data-type="fontSizeValue">${parseFloat(fontSize)}px</span>
    </label>
    <label class="keyboard__font-size${fontSize.endsWith("em") ? "" : " fn__none"}">
        <input class="b3-slider fn__flex-1" data-type="fontSizeEM" max="4.5" min="0.56" step="0.01" type="range" value="${parseFloat(fontSize)}">
        <span data-type="fontSizeValue">${(parseFloat(fontSize) * 100).toFixed(0)}%</span>
    </label>
</div>`;
    if (fontFamilyState.family) {
        (utilElement.querySelector('[data-type="fontFamilyPreview"]') as HTMLElement).style.fontFamily =
            getInlineFontFamilyValue(fontFamilyState.family);
    }
    const switchElement = utilElement.querySelector('[data-id="fontSizeWrap"] .b3-switch') as HTMLInputElement;
    const fontSizePXElement = utilElement.querySelector('[data-type="fontSizePX"]') as HTMLInputElement;
    const fontSizeEMElement = utilElement.querySelector('[data-type="fontSizeEM"]') as HTMLInputElement;
    const updatePXValue = () => {
        fontSizePXElement.nextElementSibling.textContent = fontSizePXElement.value + "px";
    };
    const updateEMValue = () => {
        fontSizeEMElement.nextElementSibling.textContent = (parseFloat(fontSizeEMElement.value) * 100).toFixed(0) + "%";
    };
    [switchElement, fontSizePXElement, fontSizeEMElement].forEach(item => {
        item.addEventListener("pointerdown", preventKeyboardToolbarRender);
    });
    switchElement.addEventListener("change", () => {
        preventKeyboardToolbarRender();
        if (switchElement.checked) {
            const em = convertFontSize(fontSizePXElement.value + "px", "em", baseFontSize);
            fontSizeEMElement.value = parseFloat(em).toString();
            updateEMValue();
            fontSizePXElement.parentElement.classList.add("fn__none");
            fontSizeEMElement.parentElement.classList.remove("fn__none");
            fontEvent(protyle, nodeElements, "fontSize", fontSizeEMElement.value + "em", false);
        } else {
            const px = convertFontSize(fontSizeEMElement.value + "em", "px", baseFontSize);
            fontSizePXElement.value = parseFloat(px).toString();
            updatePXValue();
            fontSizePXElement.parentElement.classList.remove("fn__none");
            fontSizeEMElement.parentElement.classList.add("fn__none");
            fontEvent(protyle, nodeElements, "fontSize", fontSizePXElement.value + "px", false);
        }
    });
    fontSizePXElement.addEventListener("input", updatePXValue);
    fontSizeEMElement.addEventListener("input", updateEMValue);
    fontSizePXElement.addEventListener("change", () => {
        preventKeyboardToolbarRender();
        fontEvent(protyle, nodeElements, "fontSize", fontSizePXElement.value + "px", false);
    });
    fontSizeEMElement.addEventListener("change", () => {
        preventKeyboardToolbarRender();
        fontEvent(protyle, nodeElements, "fontSize", fontSizeEMElement.value + "em", false);
    });
};

const renderSlashMenu = (protyle: IProtyle, toolbarElement: Element) => {
    protyle.hint.splitChar = "/";
    protyle.hint.lastIndex = -1;
    if (protyle.lite) {
        // 轻量编辑器沿用自己的插入候选,保留单元格内容限制和智能体技能入口。
        unmountLiteSlashMenu = mountLiteSlashMenu(protyle, toolbarElement.querySelector(".keyboard__util"));
        return;
    }
    let pluginHTML = "";
    protyle.app.plugins.forEach((plugin) => {
        plugin.protyleSlash.forEach(slash => {
            pluginHTML += getSlashItem(slash.html === "separator" ? "" : getPluginSlashEntryKey(plugin.name, slash.id),
                `plugin${Constants.ZWSP}${plugin.name}${Constants.ZWSP}${slash.id}`, "", slash.html, "true");
        });
    });
    if (pluginHTML) {
        pluginHTML = `<div class="keyboard__slash-title"></div><div class="keyboard__slash-block">${pluginHTML}</div>`;
    }
    let builtinStyleHTML = "";
    (["info", "success", "warning", "error"] as TBuiltinInlineStyleID[]).forEach(id => {
        if (!isBuiltinInlineStyleVisible("style1", id)) {
            return;
        }
        const style = getBuiltinStyleCSS(id);
        const preview = getBuiltinInlineStylePreview(id);
        builtinStyleHTML += getSlashItem(id + "Style", `style${Constants.ZWSP}${style}`,
            `<div style="color:${preview.color};background-color:${preview.backgroundColor};" class="keyboard__slash-icon">A</div>`,
            getBuiltinStyleLabel(id), "true");
    });
    const utilElement = toolbarElement.querySelector(".keyboard__util") as HTMLElement;
    utilElement.innerHTML = `<div class="keyboard__slash-title"></div>
<div class="keyboard__slash-block">
    ${getSlashItem("template", Constants.ZWSP, "iconMarkdown", window.siyuan.languages.template)}
    ${getHostCapabilities().widgets ? getSlashItem("widget", Constants.ZWSP + 1, "iconBoth", window.siyuan.languages.widget) : ""}
    ${getSlashItem("assets", Constants.ZWSP + 2, "iconImage", window.siyuan.languages.assets)}
    ${getSlashItem("ref", "((", "iconRef", window.siyuan.languages.ref, "true")}
    ${getSlashItem("blockEmbed", "{{", "iconSQL", window.siyuan.languages.blockEmbed, "true")}
    ${isDisabledFeature("ai") ? "" : getSlashItem("aiWriting", Constants.ZWSP + 5, "iconSparkles", window.siyuan.languages.aiWriting)}
    ${getSlashItem("database", '<div data-type="NodeAttributeView" data-av-type="table"></div>', "iconDatabase", window.siyuan.languages.database, "true")}
    ${getSlashItem("newSubDocRef", Constants.ZWSP + 6, "iconFile", window.siyuan.languages.newSubDocRef)}
</div>
<div class="keyboard__slash-title"></div>
<div class="keyboard__slash-block">
    ${isInAndroid() || canPickIOSPhotos() ? getSlashItem("insertAsset", Constants.ZWSP + 3, "iconImage", window.siyuan.languages.insertImage + '<input class="b3-form__upload" data-native-photos="true" type="file" multiple="multiple" accept="image/*,application/x-siyuan-image-picker"/>', "true") : ""}
    ${isInAndroid() ? getSlashItem("insertAsset", Constants.ZWSP + 3, "iconCamera", window.siyuan.languages.insertPhoto + '<input class="b3-form__upload" capture="user" type="file"' + (protyle.options.upload.accept ? (' multiple="' + protyle.options.upload.accept + '"') : "") + "/>", "true") : ""}
    ${getSlashItem("insertAsset", Constants.ZWSP + 3, "iconUpload", window.siyuan.languages.insertAsset + '<input class="b3-form__upload" type="file" multiple="multiple"' + (protyle.options.upload.accept ? (' accept="' + protyle.options.upload.accept + '"') : "") + "/>", "true")}
    ${getHostCapabilities().remoteKernel ? "" : getSlashItem("insertIframeURL", '<iframe sandbox="allow-forms allow-presentation allow-same-origin allow-scripts allow-modals allow-popups allow-storage-access-by-user-activation" src="" border="0" frameborder="no" framespacing="0" allowfullscreen="true"></iframe>', "iconGlobe", window.siyuan.languages.insertIframeURL, "true")}
    ${getSlashItem("insertImgURL", "![]()", "iconImage", window.siyuan.languages.insertImgURL, "true")}
    ${getSlashItem("insertVideoURL", '<video controls="controls" src=""></video>', "iconVideo", window.siyuan.languages.insertVideoURL, "true")}
    ${getSlashItem("insertAudioURL", '<audio controls="controls" src=""></audio>', "iconRecord", window.siyuan.languages.insertAudioURL, "true")}
    ${getSlashItem("emoji", "emoji", "iconEmoji", window.siyuan.languages.emoji, "true")}
</div>
<div class="keyboard__slash-title"></div>
<div class="keyboard__slash-block">
    ${getSlashItem("heading1", "# " + Lute.Caret, "iconH1", window.siyuan.languages.heading1, "true")}
    ${getSlashItem("heading2", "## " + Lute.Caret, "iconH2", window.siyuan.languages.heading2, "true")}
    ${getSlashItem("heading3", "### " + Lute.Caret, "iconH3", window.siyuan.languages.heading3, "true")}
    ${getSlashItem("heading4", "#### " + Lute.Caret, "iconH4", window.siyuan.languages.heading4, "true")}
    ${getSlashItem("heading5", "##### " + Lute.Caret, "iconH5", window.siyuan.languages.heading5, "true")}
    ${getSlashItem("heading6", "###### " + Lute.Caret, "iconH6", window.siyuan.languages.heading6, "true")}
    ${getSlashItem("list", "- " + Lute.Caret, "iconList", window.siyuan.languages.list, "true")}
    ${getSlashItem("orderedList", "1. " + Lute.Caret, "iconOrderedList", window.siyuan.languages["ordered-list"], "true")}
    ${getSlashItem("check", "- [ ] " + Lute.Caret, "iconCheck", window.siyuan.languages.check, "true")}
    ${getSlashItem("quote", "> " + Lute.Caret, "iconQuote", window.siyuan.languages.quote, "true")}
    ${getSlashItem("horizontalSuperBlock", getSuperBlockCommand("col"), "iconSuper", window.siyuan.languages.horizontalSuperBlock, "true")}
    ${getSlashItem("verticalSuperBlock", getSuperBlockCommand("row"), "iconSuper", window.siyuan.languages.verticalSuperBlock, "true")}
    ${getSlashItem("tabs", `::: tabs\n@tab\n\n${Lute.Caret}\n\n@tab\n\n:::\n`, "iconTabs", window.siyuan.languages.tabs, "true")}
    ${getSlashItem("mindmap", `- ${Lute.Caret}\n{: ${Constants.CUSTOM_SY_LIST_MINDMAP}="1"}`, "iconMindmap", window.siyuan.languages.mindmap, "true")}
    ${getSlashItem("calloutNote", `> [!NOTE]\n> ${Lute.Caret}`, '<span class="keyboard__slash-icon">✏️</span>', `${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-note)">Note</span>`, "true")}
    ${getSlashItem("calloutTip", `> [!TIP]\n> ${Lute.Caret}`, '<span class="keyboard__slash-icon">💡</span>', `${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-tip)">Tip</span>`, "true")}
    ${getSlashItem("calloutImportant", `> [!IMPORTANT]\n> ${Lute.Caret}`, '<span class="keyboard__slash-icon">❗</span>', `${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-important)">Important</span>`, "true")}
    ${getSlashItem("calloutWarning", `> [!WARNING]\n> ${Lute.Caret}`, '<span class="keyboard__slash-icon">⚠️</span>', `${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-warning)">Warning</span>`, "true")}
    ${getSlashItem("calloutCaution", `> [!CAUTION]\n> ${Lute.Caret}`, '<span class="keyboard__slash-icon">🚨</span>', `${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-caution)">Caution</span>`, "true")}
    ${getSlashItem("code", "```", "iconCode", window.siyuan.languages.code, "true")}
    ${getSlashItem("table", `| ${Lute.Caret} |  |  |\n| --- | --- | --- |\n|  |  |  |\n|  |  |  |`, "iconTable", window.siyuan.languages.table, "true")}
    ${getSlashItem("line", "---", "iconLine", window.siyuan.languages.line, "true")}
    ${getSlashItem("math", "$$", "iconMath", window.siyuan.languages.math)}
    ${getSlashItem("html", "<div>", "iconHTML5", "HTML")}
</div>
<div class="keyboard__slash-title"></div>
<div class="keyboard__slash-block">
    ${getSlashItem("staff", "```abc\n```", "", window.siyuan.languages.staff, "true")}
    ${getSlashItem("chart", "```echarts\n```", "", window.siyuan.languages.chart, "true")}
    ${getSlashItem("flowChart", "```flowchart\n```", "", "Flow Chart", "true")}
    ${getSlashItem("graph", "```graphviz\n```", "", "Graph", "true")}
    ${getSlashItem("mermaid", "```mermaid\n```", "", "Mermaid", "true")}
    ${getSlashItem("UML", "```plantuml\n```", "", "UML", "true")}
</div>
<div class="keyboard__slash-title"></div>
<div class="keyboard__slash-block">
    ${builtinStyleHTML}
    ${getSlashItem("clearFontStyle", `style${Constants.ZWSP}`, '<div class="keyboard__slash-icon">A</div>', window.siyuan.languages.clearFontStyle, "true")}
</div>${pluginHTML}`;
    const eligibleItems = hintSlash("", protyle, false, {visibilityRoot: SLASH_MENU_ROOT_PATH});
    const buttons = getFrequentSlashButtons(utilElement, eligibleItems
        .filter(item => item.html !== "separator").map(item => item.entryKey));
    prependFrequentSlashButtons(utilElement, getFrequentSlashItems(buttons, button => button.dataset.slashEntryKey));
    protyle.hint.bindUploadEvent(protyle, utilElement);
};

export const showKeyboardToolbarUtil = (oldScrollTop: number) => {
    pendingKeyboardFocus = undefined;
    window.siyuan.menus.menu.remove();
    showUtil = true;
    clearTimeout(keyboardPanelCloseTimeout);
    keyboardPanelClosing = false;
    clearTimeout(showUtilTimeout);
    const toolHeight = document.querySelector(".keyboard__bar").clientHeight;
    let keyboardHeight = window.innerHeight / 2 - toolHeight;
    if (window.siyuan.mobile.size.isLandscape) {
        if (window.siyuan.mobile.size.landscape.height1 !== window.siyuan.mobile.size.landscape.height2) {
            keyboardHeight = window.siyuan.mobile.size.landscape.height1 - window.siyuan.mobile.size.landscape.height2 + toolHeight;
        }
    } else {
        if (window.siyuan.mobile.size.portrait.height1 !== window.siyuan.mobile.size.portrait.height2) {
            keyboardHeight = window.siyuan.mobile.size.portrait.height1 - window.siyuan.mobile.size.portrait.height2 + toolHeight;
        }
    }
    const editor = getCurrentEditor();
    const size = window.siyuan.mobile.size;
    const orientationSize = size.isLandscape ? size.landscape : size.portrait;
    const fullHeight = Math.max(window.innerHeight, orientationSize.height1);
    const viewportBottom = getKeyboardViewportBottom();
    keyboardPanelTop = keyboardPanelTop ?? (viewportBottom < fullHeight - 100 ?
        viewportBottom - toolHeight : fullHeight - keyboardHeight);
    keyboardPanelLandscape = size.isLandscape;
    updateKeyboardToolbarPosition();
    if (editor) {
        editor.protyle.contentElement.scrollTop = oldScrollTop;
    }
    showUtilTimeout = window.setTimeout(() => {
        showUtil = false;
        showUtilTimeout = undefined;
    }, 1000);   // 防止光标改变后斜杆菜单消失
};

const hideAndroidKeyboardForPanel = (protyle: IProtyle) => {
    if (!window.JSAndroid?.hideKeyboard) {
        return;
    }
    const blurEditor = () => {
        const activeElement = document.activeElement as HTMLElement;
        if (protyle.wysiwyg.element.contains(activeElement)) {
            activeElement.blur();
        }
    };
    // 键盘收起时移走编辑焦点,避免输入法立即重新弹出;选区由面板和原生回调保留。
    window.addEventListener("siyuan-mobile-keyboard-hiding", blurEditor, {once: true});
    window.JSAndroid.hideKeyboard();
    window.setTimeout(() => {
        window.removeEventListener("siyuan-mobile-keyboard-hiding", blurEditor);
        blurEditor();
    }, 100);
};

const openMobileFontFamilyMenu = (protyle: IProtyle, target: HTMLElement, appearance = false) => {
    if (!protyle || protyle.disabled || window.siyuan.config.readonly) {
        return;
    }
    const range = protyle.toolbar.range.cloneRange();
    const nodes = getFontNodeElements(protyle);
    const state = getFontFamilyState(protyle, nodes);
    const valid = () => getCurrentEditor()?.protyle === protyle && !protyle.disabled &&
        !window.siyuan.config.readonly && target.isConnected &&
        range.startContainer.isConnected && range.endContainer.isConnected;
    preventKeyboardToolbarRender();
    void openFontFamilyMenu(target, {
        ...state,
        isOpenValid: valid,
        onInteraction: preventKeyboardToolbarRender,
        onOpen: element => { fontFamilyMenu = {element, protyle}; },
        onClose() {
            const searchFocused = fontFamilyMenu?.element.contains(document.activeElement);
            fontFamilyMenu = undefined;
            if (searchFocused) {
                activeBlur(true);
            }
        },
        onSelect(family) {
            if (!valid()) {
                return;
            }
            protyle.toolbar.range = range;
            fontEvent(protyle, nodes, "fontFamily", getInlineFontFamilyValue(family), false);
            if (appearance) {
                const toolbarElement = document.getElementById("keyboardToolbar");
                const utilElement = toolbarElement.querySelector(".keyboard__util");
                const scrollTop = utilElement.scrollTop;
                renderTextMenu(protyle, toolbarElement);
                utilElement.scrollTop = scrollTop;
            } else {
                restoreKeyboardToolbarRange(protyle, protyle.toolbar.range);
            }
        },
    });
};

const resetKeyboardToolbarUtilButtons = () => {
    unmountLiteSlashMenu?.();
    unmountLiteSlashMenu = undefined;
    const toolbarElement = document.getElementById("keyboardToolbar");
    toolbarElement.querySelectorAll('[data-type="add"], [data-type="text"], [data-type="font-family"], [data-type="font-size"]')
        .forEach(item => item.classList.remove("protyle-toolbar__item--current"));
    toolbarElement.querySelector('.keyboard__action[data-type="done"] use').setAttribute("xlink:href", "#iconKeyboardHide");
};

const hideKeyboardToolbarUtil = (restoreKeyboard = false) => {
    if (keyboardPanelClosing) {
        return;
    }
    if (restoreKeyboard && keyboardPanelTop !== undefined) {
        keyboardPanelClosing = true;
        showUtil = true;
        resetKeyboardToolbarUtilButtons();
        clearTimeout(showUtilTimeout);
        // 键盘未能弹出时也要释放菜单,避免保留失效的占位。
        keyboardPanelCloseTimeout = window.setTimeout(() => {
            keyboardPanelClosing = false;
            hideKeyboardToolbarUtil();
        }, 1000);
        updateKeyboardToolbarPosition();
        return;
    }
    clearTimeout(keyboardPanelCloseTimeout);
    keyboardPanelTop = undefined;
    clearTimeout(showUtilTimeout);
    showUtilTimeout = undefined;
    showUtil = false;
    const toolbarElement = document.getElementById("keyboardToolbar");
    if (!toolbarElement) {
        return;
    }
    toolbarElement.style.height = "";
    updateKeyboardToolbarPosition();
    const editor = getCurrentEditor();
    if (editor) {
        getMobileToolbarPaddingElement(editor.protyle).style.paddingBottom = "48px";
    }
    resetKeyboardToolbarUtilButtons();
};

export const hideKeyboardToolbarUtilOnEditorClick = () => {
    if (fontFamilyMenu && fontFamilyMenu.protyle === getCurrentEditor()?.protyle &&
        fontFamilyMenu.element.contains(document.activeElement)) {
        return;
    }
    const toolbarElement = document.getElementById("keyboardToolbar");
    if (!showUtil && (!toolbarElement || toolbarElement.clientHeight <= 100)) {
        return;
    }
    hideKeyboardToolbarUtil(true);
};

const restoreKeyboardToolbarRange = (protyle: IProtyle | undefined, range?: Range) => {
    if (protyle) {
        const editorRange = getEditorFocusRange(protyle.wysiwyg.element, range, protyle.toolbar.range);
        if (editorRange && (isInAndroid() || isInHarmony())) {
            // 原生端恢复 WebView 焦点后,通过键盘显示回调再次恢复编辑器选区。
            pendingKeyboardFocus = {protyle, range: editorRange};
            callMobileAppShowKeyboard();
        }
        if (restoreEditorFocusRange(protyle.wysiwyg.element, editorRange)) {
            return;
        }
    }
    if (range?.startContainer.isConnected && range.endContainer.isConnected) {
        focusByRange(range);
    }
};

export const resumeMobileEditorAfterInsertion = (protyle: IProtyle, range: Range) => {
    hideKeyboardToolbarUtilOnEditorClick();
    restoreKeyboardToolbarRange(protyle, range);
    showKeyboardToolbar();
};

export const bindMobileMenuKeyboard = (element: HTMLElement, selector: string, getProtyle: () => IProtyle) => {
    let restoreKeyboard: (() => void) | undefined;
    if (isMobile()) {
        // 在按钮默认行为改变焦点之前保存状态,异步菜单请求使用本次操作独立的恢复回调。
        element.addEventListener("pointerdown", event => {
            restoreKeyboard = undefined;
            if (!(event.target as Element).closest(selector)) {
                return;
            }
            const protyle = getProtyle();
            const toolbarElement = document.getElementById("keyboardToolbar");
            restoreKeyboard = captureMenuKeyboard({
                protyle,
                keyboardOpen: Boolean(toolbarElement && !toolbarElement.classList.contains("fn__none") && !showUtil),
                isCurrent: () => getCurrentEditor()?.protyle === protyle,
                restore: range => restoreKeyboardToolbarRange(protyle, range),
            });
        }, true);
    }
    return () => {
        const restore = restoreKeyboard;
        restoreKeyboard = undefined;
        return restore;
    };
};

const keepBlockHintKeyboard = (protyle: IProtyle) => {
    // 引用和嵌入候选没有输入框,关闭插入菜单后保留软键盘用于继续筛选。
    hideKeyboardToolbarUtil();
    callMobileAppShowKeyboard();
    if (isInHarmony() || isInAndroid()) {
        const range = protyle.toolbar.range;
        setTimeout(() => {
            if (getCurrentEditor()?.protyle === protyle && protyle.toolbar.range === range &&
                range.startContainer.isConnected && range.endContainer.isConnected &&
                protyle.wysiwyg.element.contains(range.startContainer) &&
                protyle.wysiwyg.element.contains(range.endContainer)) {
                focusByRange(range);
            }
        }, Constants.TIMEOUT_TRANSITION);
    }
};

const renderKeyboardToolbar = () => {
    if (renderKeyboardToolbarFrame !== undefined) {
        return;
    }
    // 合并同一帧内的选区变化,在浏览器更新选区后及时显示工具栏。
    renderKeyboardToolbarFrame = window.requestAnimationFrame(() => {
        renderKeyboardToolbarFrame = undefined;
        if (!canInput(document.activeElement)) {
            hideKeyboardToolbar(false);
            return;
        }
        const selection = getSelection();
        if (!selection || selection.rangeCount === 0) {
            return;
        }
        if (!showUtil && keyboardPanelTop === undefined) {
            hideKeyboardToolbarUtil();
        }
        showKeyboardToolbarElement();
        updateKeyboardToolbarPosition();
        if (document.getElementById("keyboardToolbar").classList.contains("fn__none")) {
            return;
        }
        const actions = document.querySelector<HTMLElement>("#keyboardToolbar .keyboard__dynamic");
        const range = selection.getRangeAt(0);
        const protyle = getCurrentEditor()?.protyle;
        const nodeElement = hasClosestBlock(range.startContainer);
        const endNodeElement = hasClosestBlock(range.endContainer);
        if (!protyle || !nodeElement ||
            hasClosestByClassName(range.startContainer, "protyle-wysiwyg", true) !== protyle.wysiwyg.element ||
            hasClosestByAttribute(range.startContainer, "data-type", "av-search")) {
            actions.classList.add("fn__none");
            return;
        }
        actions.classList.remove("fn__none");
        applyKeyboardToolbarEntries(actions, protyle.options.toolbar);
        protyle.toolbar.range = range;
        updateBlockTypeButton(protyle, actions.querySelector('[data-type="block-type"]'), range);

        const blockButton = actions.querySelector<HTMLElement>('[data-type="block"]');
        const blockType = nodeElement.getAttribute("data-type");
        const inCode = nodeElement.classList.contains("code-block");
        blockButton.querySelector("use").setAttribute("xlink:href",
            `#${getIconByType(blockType, nodeElement.getAttribute("data-subtype")) || "iconParagraph"}`);
        blockButton.setAttribute("aria-label", blockType === "NodeCodeBlock" ? window.siyuan.languages.code :
            blockType === "NodeMathBlock" ? window.siyuan.languages.math :
                blockType === "NodeParagraph" ? window.siyuan.languages.paragraph : window.siyuan.languages.contentBlock);

        const startCell = hasClosestByTag(range.startContainer, "TD") || hasClosestByTag(range.startContainer, "TH");
        const endCell = hasClosestByTag(range.endContainer, "TD") || hasClosestByTag(range.endContainer, "TH");
        const disableLink = inCode || (!!endNodeElement && nodeElement !== endNodeElement) ||
            (!!startCell && !!endCell && startCell !== endCell);
        actions.querySelector('[data-type="a"]').toggleAttribute("disabled", disableLink);
        actions.querySelector('[data-type="block-ref"]').toggleAttribute("disabled", disableLink);
        actions.querySelectorAll<HTMLElement>("[data-type]").forEach(item => {
            if (Constants.INLINE_TYPE.includes(item.dataset.type) && !["a", "block-ref"].includes(item.dataset.type) ||
                ["font-family", "font-size", "text", "clear"].includes(item.dataset.type)) {
                item.toggleAttribute("disabled", inCode);
            }
        });

        // 撤销状态沿用所属编辑器的权威镜像,列表缩进按钮独立定位,允许任意排序。
        const undoProtyle = getMobileToolbarUndo(protyle)?.owner || protyle;
        const undoRootID = undoProtyle.lite ? undefined : getUndoRootID(undoProtyle, range);
        if (undoRootID && !hasUndoStateMirror(undoRootID)) {
            initMirror(undoRootID).then(initialized => {
                if (initialized && getCurrentEditor()?.protyle === protyle) {
                    renderKeyboardToolbar();
                }
            });
        }
        const undoState = undoProtyle.undo instanceof LocalUndo ? {
            canUndo: undoProtyle.undo.undoStack.length > 0,
            canRedo: undoProtyle.undo.redoStack.length > 0,
        } : undoRootID ? getMirror(undoRootID) : {canUndo: false, canRedo: false};
        actions.querySelector('[data-type="undo"]').toggleAttribute("disabled", !undoState.canUndo);
        actions.querySelector('[data-type="redo"]').toggleAttribute("disabled", !undoState.canRedo);
        const inList = nodeElement.parentElement.classList.contains("li");
        const indentCode = inCode && !range.collapsed;
        actions.querySelector('[data-type="outdent"]').toggleAttribute("disabled", !inList && !indentCode);
        actions.querySelector('[data-type="indent"]').toggleAttribute("disabled",
            !(inList && nodeElement.parentElement.previousElementSibling) && !indentCode);
        const types = protyle.toolbar.getCurrentToolbarType(protyle, range);
        actions.querySelectorAll<HTMLElement>("[data-type]").forEach(item => {
            if (["add", "text", "font-family", "font-size"].includes(item.dataset.type)) {
                return;
            }
            item.classList.toggle("protyle-toolbar__item--current", types.includes(item.dataset.type));
        });
    });
};

const showKeyboardToolbarElement = () => {
    const toolbarElement = document.getElementById("keyboardToolbar");
    if (["INPUT", "TEXTAREA"].includes(document.activeElement?.tagName) &&
        !toolbarElement.contains(document.activeElement)) {
        if (keyboardPanelTop !== undefined && fontFamilyMenu && fontFamilyMenu.protyle === getCurrentEditor()?.protyle &&
            fontFamilyMenu.element.contains(document.activeElement)) {
            // 字体搜索使用独立菜单,保留底层外观面板及选区。
            notifyMobileKeyboardChange(true);
            return;
        }
        // 普通输入框可能保留文档选区,不能据此恢复编辑焦点或显示文档工具栏。
        keyboardPanelClosing = false;
        hideKeyboardToolbarUtil();
        hideKeyboardToolbar(false);
        notifyMobileKeyboardChange(true);
        return;
    }
    const pendingFocus = pendingKeyboardFocus;
    pendingKeyboardFocus = undefined;
    if (pendingFocus && getCurrentEditor()?.protyle === pendingFocus.protyle && !pendingFocus.protyle.disabled) {
        restoreEditorFocusRange(pendingFocus.protyle.wysiwyg.element, pendingFocus.range);
    }
    if (!showUtil && keyboardPanelTop === undefined) {
        hideKeyboardToolbarUtil();
    }
    const selection = getSelection();
    // 空块恢复焦点时 Selection 可能暂时为空,但原生键盘已经显示,仍需隐藏普通底栏。
    notifyMobileKeyboardChange(true);
    const protyle = getCurrentEditor()?.protyle;
    if (!protyle || (selection.rangeCount > 0 && (
        hasClosestByClassName(selection.getRangeAt(0).startContainer, "protyle-wysiwyg", true) !== protyle.wysiwyg.element ||
        hasClosestByClassName(selection.getRangeAt(0).endContainer, "protyle-wysiwyg", true) !== protyle.wysiwyg.element))) {
        toolbarElement.classList.add("fn__none");
        return;
    }
    if (toolbarProtyle !== protyle) {
        keyboardPanelClosing = false;
        hideKeyboardToolbarUtil();
        if (toolbarProtyle) {
            getMobileToolbarPaddingElement(toolbarProtyle).style.paddingBottom = "";
        }
        toolbarProtyle = protyle;
        updateMobilePluginToolbar(protyle);
    }
    const done = toolbarElement.querySelector('.keyboard__action[data-type="done"]');
    done.setAttribute("aria-label", window.siyuan.languages.close);
    done.querySelector("use").setAttribute("xlink:href",
        keyboardPanelTop !== undefined ? "#iconCloseRound" : "#iconKeyboardHide");
    if (!toolbarElement.classList.contains("fn__none")) {
        return;
    }
    if (selection.rangeCount === 0) {
        return;
    }
    toolbarElement.classList.remove("fn__none");
    toolbarElement.style.zIndex = (++window.siyuan.zIndex).toString();
    updateKeyboardToolbarPosition();
    const modelElement = document.getElementById("model");
    if (modelElement.style.transform === "translateX(0px)") {
        modelElement.style.paddingBottom = "48px";
    }
    const range = getSelection().getRangeAt(0);
    const editor = getCurrentEditor();
    if (editor) {
        if (editor.protyle.wysiwyg.element.contains(range.startContainer)) {
            getMobileToolbarPaddingElement(editor.protyle).style.paddingBottom = "48px";
        }
        forEachPluginSubscriber("mobile-keyboard-show", eventBus => {
            eventBus.emit("mobile-keyboard-show");
        });
    }
    scrollKeyboardSelectionIntoView();
};

export const showKeyboardToolbar = () => {
    showKeyboardToolbarElement();
    if (!document.getElementById("keyboardToolbar").classList.contains("fn__none") &&
        !getCurrentEditor()?.protyle.toolbar.isMultiSelectMode()) {
        // 原生键盘显示回调也需要刷新操作按钮,避免选区事件被抑制后仅显示工具栏外框。
        renderKeyboardToolbar();
    }
};

const scrollKeyboardSelectionIntoView = (force = false) => {
    const toolbarElement = document.getElementById("keyboardToolbar");
    if (!toolbarElement || toolbarElement.classList.contains("fn__none") || showUtil) {
        return;
    }
    const editor = getCurrentEditor();
    const selection = getSelection();
    if (!editor || selection.rangeCount === 0 ||
        !editor.protyle.wysiwyg.element.contains(selection.anchorNode) ||
        !editor.protyle.wysiwyg.element.contains(selection.focusNode)) {
        return;
    }
    const container = hasClosestByClassName(selection.focusNode, "protyle-content", true);
    if (!container) {
        return;
    }
    const viewport = getVisibleViewportBounds();
    const contentRect = container.getBoundingClientRect();
    keyboardSelectionScroll.request({
        container,
        anchorNode: selection.anchorNode,
        anchorOffset: selection.anchorOffset,
        focusNode: selection.focusNode,
        focusOffset: selection.focusOffset,
        viewportTop: Math.max(viewport.top, contentRect.top),
        viewportBottom: Math.min(viewport.bottom, contentRect.bottom, toolbarElement.getBoundingClientRect().top),
    }, force);
};

const scrollKeyboardSelection = (container: HTMLElement) => {
    clearRenderGutterAfterScroll?.();
    const toolbarElement = document.getElementById("keyboardToolbar");
    const editor = getCurrentEditor();
    const selection = getSelection();
    if (!editor || !container.isConnected || !toolbarElement ||
        editor.protyle.toolbar.isMultiSelectMode() || selection.rangeCount === 0 ||
        !editor.protyle.wysiwyg.element.contains(document.activeElement) ||
        toolbarElement.classList.contains("fn__none") || showUtil) {
        return false;
    }
    // 视口稳定后读取当前选区,避免键盘动画期间使用已经移动的光标位置。
    const range = selection.getRangeAt(0);
    if (!editor.protyle.wysiwyg.element.contains(range.startContainer) ||
        !editor.protyle.wysiwyg.element.contains(range.endContainer)) {
        return false;
    }
    const contentElement = hasClosestByClassName(range.startContainer, "protyle-content", true);
    if (contentElement !== container) {
        return false;
    }
    const renderGutter = () => {
        restoreGutterBySelection(editor.protyle);
    };
    const cursorTop = getSelectionPosition(contentElement, range.cloneRange()).top;
    const viewportBounds = getVisibleViewportBounds();
    const cursorElement = range.startContainer.nodeType === Node.ELEMENT_NODE ?
        range.startContainer as Element : range.startContainer.parentElement;
    // 自动滚动时额外预留一行,避免输入文字被键盘工具栏遮挡。
    const extraLineHeight = parseFloat(getComputedStyle(cursorElement).lineHeight) ||
        window.siyuan.config.editor.fontSize * 1.625;
    const visibleBottom = Math.min(viewportBounds.bottom, contentElement.getBoundingClientRect().bottom,
        toolbarElement.getBoundingClientRect().top);
    const visibleTop = Math.max(contentElement.getBoundingClientRect().top, viewportBounds.top);
    const geometry = {
        caretTop: cursorTop,
        caretHeight: extraLineHeight,
        viewportTop: visibleTop,
        viewportHeight: visibleBottom - visibleTop,
        lineHeight: extraLineHeight,
        surroundingLines: 1,
    };
    const direction = getCaretOverflowDirection(geometry);
    if (!direction) {
        renderGutter();
        return false;
    }
    const clearRenderGutter = () => {
        contentElement.removeEventListener("scrollend", renderGutterAfterScroll);
        contentElement.removeEventListener("touchstart", clearRenderGutter);
        clearTimeout(renderGutterTimeout);
        clearRenderGutterAfterScroll = undefined;
    };
    const renderGutterAfterScroll = () => {
        clearRenderGutter();
        renderGutter();
    };
    const renderGutterTimeout = window.setTimeout(renderGutterAfterScroll, Constants.TIMEOUT_COUNT);
    clearRenderGutterAfterScroll = clearRenderGutter;
    contentElement.addEventListener("scrollend", renderGutterAfterScroll, {once: true});
    contentElement.addEventListener("touchstart", clearRenderGutter, {once: true, passive: true});
    pauseMobileBarsScroll(Constants.TIMEOUT_COUNT);
    contentElement.scroll({
        top: contentElement.scrollTop + getCaretScrollDelta(geometry, direction),
        left: contentElement.scrollLeft,
        behavior: "smooth"
    });
    return true;
};

export const hideKeyboardToolbar = (keyboardClosed = true) => {
    if (renderKeyboardToolbarFrame !== undefined) {
        window.cancelAnimationFrame(renderKeyboardToolbarFrame);
        renderKeyboardToolbarFrame = undefined;
    }
    keyboardSelectionScroll.reset();
    clearRenderGutterAfterScroll?.();
    // 键盘退场时保留已展开的移动端菜单,菜单由用户操作或编辑器切换关闭。
    if (showUtil || keyboardPanelTop !== undefined) {
        return;
    }
    pendingKeyboardFocus = undefined;
    const toolbarElement = document.getElementById("keyboardToolbar");
    const toolbarHidden = toolbarElement.classList.contains("fn__none");
    toolbarElement.classList.add("fn__none");
    keyboardPanelTop = undefined;
    toolbarElement.style.height = "";
    const editor = getCurrentEditor();
    if (editor) {
        getMobileToolbarPaddingElement(editor.protyle).style.paddingBottom = "";
        if (!toolbarHidden) {
            forEachPluginSubscriber("mobile-keyboard-hide", eventBus => {
                eventBus.emit("mobile-keyboard-hide");
            });
        }
    }
    const modelElement = document.getElementById("model");
    if (modelElement.style.transform === "translateX(0px)") {
        modelElement.style.paddingBottom = "";
    }
    // 仅隐藏编辑工具栏时保留系统键盘状态,关闭通知由原生回调或主动收起操作发送。
    if (keyboardClosed) {
        notifyMobileKeyboardChange(false);
    }
};

export const hideKeyboardToolbarByApp = (preserveSelection = false) => {
    inlineMathSelection.reset();
    const gutterElement = getCurrentEditor()?.protyle.gutter?.element;
    if (gutterElement && isGutterTouchDragging(gutterElement)) {
        // 键盘收起时保留块标手势所需的 WebView 焦点,避免原生端取消后续触摸。
        preventKeyboardToolbarRender();
        hideKeyboardToolbar();
        return KeyboardHideResult.PreserveSelection;
    }
    if (preserveSelection && ["INPUT", "TEXTAREA"].includes(document.activeElement?.tagName)) {
        // 输入法切换安全键盘时会临时隐藏,保留普通输入框焦点,避免中断密码输入。
        preventKeyboardToolbarRender();
        hideKeyboardToolbar();
        return KeyboardHideResult.PreserveSelection;
    }
    const tableCellSelectionRestored = preserveSelection && restoreRecentAndroidTableCellSelectAll();
    if (tableCellSelectionRestored) {
        return KeyboardHideResult.RestoreTableCellSelection;
    }
    preventKeyboardToolbarRender();
    hideKeyboardToolbar();
    const editor = getCurrentEditor();
    const selection = getSelection();
    if (!editor) {
        return KeyboardHideResult.Cleanup;
    }
    hideElements(["util"], editor.protyle);
    const range = selection?.rangeCount > 0 ? selection.getRangeAt(0) : undefined;
    const hasEditorRange = !!range &&
        editor.protyle.wysiwyg.element.contains(range.startContainer) &&
        editor.protyle.wysiwyg.element.contains(range.endContainer);
    const hasVisibleEditorSelection = hasEditorRange && !range.collapsed &&
        hasVisibleSelectionText(stripSemanticMarkersFromRangeText(range));
    // 菜单仍需使用当前选区,通知原生端保留 WebView 焦点和选区。
    const result = getKeyboardHideResult(preserveSelection, tableCellSelectionRestored,
        hasVisibleEditorSelection, keyboardPanelTop !== undefined && hasEditorRange);
    if (result === KeyboardHideResult.PreserveSelection || !hasVisibleEditorSelection) {
        return result;
    }
    (document.activeElement as HTMLElement)?.blur();
    selection?.removeAllRanges();
    return result;
};

export const activeBlur = (force = false) => {
    const now = Date.now();
    if (!force && now < keyboardLockUntil) {
        console.warn(`activeBlur blocked by lock (remaining: ${keyboardLockUntil - now}ms)`);
        return;
    }
    inlineMathSelection.reset();

    if (window.JSAndroid && window.JSAndroid.hideKeyboard) {
        window.JSAndroid.hideKeyboard();
        // Android 在键盘退场完成后统一清理焦点,避免中断输入法绘制。
        hideKeyboardToolbar();
        return;
    } else if (window.JSHarmony && window.JSHarmony.hideKeyboard) {
        window.JSHarmony.hideKeyboard();
    }
    hideKeyboardToolbar();
    (document.activeElement as HTMLElement).blur();
};

const updateVideoMaxHeight = () => {
    const size = window.siyuan.mobile.size;
    const height = (size.isLandscape ? size.landscape : size.portrait)?.height1;
    if (height) {
        document.documentElement.style.setProperty("--mobile-video-max-height", `${height * 0.9}px`);
    }
};

export const initKeyboardToolbar = () => {
    window.addEventListener("siyuan-mobile-table-action", () => activeBlur(true));
    window.addEventListener("siyuan-mobile-toolbar-focus", renderKeyboardToolbar);
    window.addEventListener("siyuan-mobile-toolbar-editor", (event: CustomEvent<IProtyle>) => {
        if (event.detail) {
            getMobileToolbarPaddingElement(event.detail).style.paddingBottom = "";
            if (toolbarProtyle === event.detail) {
                toolbarProtyle = undefined;
            }
        }
        keyboardPanelClosing = false;
        hideKeyboardToolbarUtil();
        hideKeyboardToolbar(false);
        renderKeyboardToolbar();
    });
    let composing = false;
    window.addEventListener("siyuan-mobile-keyboard-hiding", () => {
        // 键盘退场前先隐藏工具栏,焦点和选区由原生端在动画结束后清理。
        preventKeyboardToolbarRender();
        hideKeyboardToolbar();
    });
    document.addEventListener("focusin", () => {
        if (["INPUT", "TEXTAREA"].includes(document.activeElement?.tagName) &&
            !document.getElementById("keyboardToolbar").contains(document.activeElement)) {
            showKeyboardToolbar();
        }
    });
    const getMathEditor = () => {
        const protyle = getCurrentEditor()?.protyle;
        return isInAndroid() && protyle && !protyle.disabled && !protyle.toolbar.isMultiSelectMode() &&
            protyle.wysiwyg.element.contains(document.activeElement) ? protyle.wysiwyg.element : undefined;
    };
    document.addEventListener("beforeinput", () => {
        if (!composing) {
            inlineMathSelection.prepareInput(getMathEditor(), getSelection());
        }
    }, true);
    document.addEventListener("keydown", (event) => {
        if (!composing && ["Backspace", "Delete", "Enter"].includes(event.key)) {
            inlineMathSelection.prepareInput(getMathEditor(), getSelection());
        }
    }, true);
    ["copy", "cut", "paste"].forEach(type => {
        document.addEventListener(type, () => {
            if (!composing) {
                inlineMathSelection.prepareInput(getMathEditor(), getSelection());
            }
        }, true);
    });
    document.addEventListener("compositionstart", () => {
        inlineMathSelection.prepareInput(getMathEditor(), getSelection());
        composing = true;
        inlineMathSelection.reset();
    }, true);
    document.addEventListener("compositionend", () => {
        composing = false;
    }, true);
    document.addEventListener("input", (event: InputEvent) => {
        if (isCommittedTextInput(event)) {
            composing = false;
        }
        if (getCurrentEditor()?.protyle.wysiwyg.element.contains(event.target as Node)) {
            scrollKeyboardSelectionIntoView(true);
        }
    }, true);
    document.addEventListener("selectionchange", () => {
        inlineMathSelection.update(getMathEditor(), getSelection(), composing);
    }, true);
    document.addEventListener("focusout", () => inlineMathSelection.reset(), true);
    if (!isInMobileApp() && window.visualViewport) {
        let pendingUpdate = false;
        const viewportHandler = () => {
            if (pendingUpdate) {
                return;
            }
            pendingUpdate = true;
            requestAnimationFrame(() => {
                pendingUpdate = false;
                updateKeyboardToolbarPosition();
            });
        };
        window.visualViewport.addEventListener("resize", viewportHandler);
        window.visualViewport.addEventListener("scroll", viewportHandler);
        viewportHandler();
    }
    document.addEventListener("selectionchange", () => {
        if (composing) {
            return;
        }
        rememberAndroidTableCellSelectAll();
        if (preserveAndroidBoundedSelection()) {
            return;
        }
        if (preventRender || (getCurrentEditor()?.protyle?.toolbar.isMultiSelectMode())) {
            return;
        }
        renderKeyboardToolbar();
    }, false);
    window.siyuan.mobile.size.isLandscape = isMobileLandscape();
    if (window.siyuan.mobile.size.isLandscape) {
        window.siyuan.mobile.size.landscape = {
            height1: window.innerHeight,
            height2: window.innerHeight,
        };
    } else {
        window.siyuan.mobile.size.portrait = {
            height1: window.innerHeight,
            height2: window.innerHeight,
        };
    }
    updateVideoMaxHeight();
    if (!isInEdge()) {
        window.addEventListener("resize", () => {
            updateKeyboardToolbarPosition();
            // 获取键盘高度
            window.siyuan.mobile.size.isLandscape = isMobileLandscape();
            if (window.siyuan.mobile.size.isLandscape) {
                if (!window.siyuan.mobile.size.landscape) {
                    window.siyuan.mobile.size.landscape = {
                        height1: window.innerHeight,
                        height2: window.innerHeight,
                    };
                }
                if (window.innerHeight < window.siyuan.mobile.size.landscape.height1 - 100) {
                    window.siyuan.mobile.size.landscape.height2 = window.innerHeight;
                }
                if (window.innerHeight > window.siyuan.mobile.size.landscape.height1) {
                    window.siyuan.mobile.size.landscape.height1 = window.innerHeight;
                }
                if (window.siyuan.mobile.size.landscape.height2 < window.innerHeight) {
                    const isInputFocused = document.activeElement && (
                        ["INPUT", "TEXTAREA"].includes(document.activeElement.tagName) ||
                        (document.activeElement as HTMLElement).isContentEditable);
                    if (shouldHideKeyboardAfterResize(isInputFocused, hasRecentAndroidTableCellSelectAll())) {
                        activeBlur();
                    }
                } else if (!preventRender) {
                    renderKeyboardToolbar();
                }
            } else {
                if (!window.siyuan.mobile.size.portrait) {
                    window.siyuan.mobile.size.portrait = {
                        height1: window.innerHeight,
                        height2: window.innerHeight,
                    };
                }
                if (window.innerHeight < window.siyuan.mobile.size.portrait.height1 - 100) {
                    window.siyuan.mobile.size.portrait.height2 = window.innerHeight;
                }
                if (window.innerHeight > window.siyuan.mobile.size.portrait.height1) {
                    window.siyuan.mobile.size.portrait.height1 = window.innerHeight;
                }
                if (window.siyuan.mobile.size.portrait.height2 < window.innerHeight) {
                    const isInputFocused = document.activeElement && (
                        ["INPUT", "TEXTAREA"].includes(document.activeElement.tagName) ||
                        (document.activeElement as HTMLElement).isContentEditable);
                    if (shouldHideKeyboardAfterResize(isInputFocused, hasRecentAndroidTableCellSelectAll())) {
                        activeBlur();
                    }
                } else if (!preventRender) {
                    renderKeyboardToolbar();
                }
            }
            updateVideoMaxHeight();
        });
    }
    const toolbarElement = document.getElementById("keyboardToolbar");
    toolbarElement.innerHTML = `<div class="fn__flex keyboard__bar">
    <div class="fn__flex-1">
        <div class="fn__none keyboard__dynamic">
            ${[...MOBILE_TOOLBAR_ACTIONS, ...MOBILE_TOOLBAR_INSERTS].map(item =>
        `<button class="keyboard__action" data-type="${item.name}" aria-label="${window.siyuan.languages[item.lang]}"><svg><use xlink:href="#${item.icon}"></use></svg></button>`).join("")}
            <span class="keyboard__split" data-id="mobile-separator"></span>
            <button class="keyboard__action" data-type="block-type" aria-haspopup="menu" aria-label="${window.siyuan.languages.turnInto}">${window.siyuan.languages.paragraph}</button>
            <button class="keyboard__action" data-type="block-ref" aria-label="${window.siyuan.languages.ref}"><svg><use xlink:href="#iconRef"></use></svg></button>
            <button class="keyboard__action" data-type="a" aria-label="${window.siyuan.languages.link}"><svg><use xlink:href="#iconLink"></use></svg></button>
            <span class="keyboard__split" data-id="separator_1"></span>
            <button class="keyboard__action" data-type="font-family" aria-label="${window.siyuan.languages.fontFamily}">${window.siyuan.languages.fontFamily}</button>
            <button class="keyboard__action" data-type="font-size" aria-label="${window.siyuan.languages.fontSize}">${window.siyuan.languages.fontSize}</button>
            <button class="keyboard__action" data-type="text" aria-label="${window.siyuan.languages.fontStyle}"><svg><use xlink:href="#iconFont"></use></svg></button>
            <button class="keyboard__action" data-type="strong" aria-label="${window.siyuan.languages.bold}"><svg><use xlink:href="#iconBold"></use></svg></button>
            <button class="keyboard__action" data-type="em" aria-label="${window.siyuan.languages.italic}"><svg><use xlink:href="#iconItalic"></use></svg></button>
            <button class="keyboard__action" data-type="u" aria-label="${window.siyuan.languages.underline}"><svg><use xlink:href="#iconUnderline"></use></svg></button>
            <button class="keyboard__action" data-type="s" aria-label="${window.siyuan.languages.strike}"><svg><use xlink:href="#iconStrike"></use></svg></button>
            <button class="keyboard__action" data-type="mark" aria-label="${window.siyuan.languages.mark}"><svg><use xlink:href="#iconMark"></use></svg></button>
            <button class="keyboard__action" data-type="sup" aria-label="${window.siyuan.languages.sup}"><svg><use xlink:href="#iconSup"></use></svg></button>
            <button class="keyboard__action" data-type="sub" aria-label="${window.siyuan.languages.sub}"><svg><use xlink:href="#iconSub"></use></svg></button>
            <button class="keyboard__action" data-type="code" aria-label="${window.siyuan.languages["inline-code"]}"><svg><use xlink:href="#iconInlineCode"></use></svg></button>
            <button class="keyboard__action" data-type="kbd" aria-label="${window.siyuan.languages.kbd}"><svg><use xlink:href="#iconKeymap"></use></svg></button>
            <button class="keyboard__action" data-type="tag" aria-label="${window.siyuan.languages.tag}"><svg><use xlink:href="#iconTag"></use></svg></button>
            <button class="keyboard__action" data-type="inline-math" aria-label="${window.siyuan.languages["inline-math"]}"><svg><use xlink:href="#iconMath"></use></svg></button>
            <button class="keyboard__action" data-type="inline-memo" aria-label="${window.siyuan.languages.memo}"><svg><use xlink:href="#iconM"></use></svg></button>
            <span class="keyboard__split" data-id="separator_2"></span>
            <button class="keyboard__action" data-type="clear" aria-label="${window.siyuan.languages.clearInline}"><svg><use xlink:href="#iconEraser"></use></svg></button>
        </div>
    </div>
    <span class="keyboard__split"></span>
    <button class="keyboard__action" data-type="done" aria-label="${window.siyuan.languages.close}"><svg style="width: 36px"><use xlink:href="#iconKeyboardHide"></use></svg></button>
</div>
<div class="keyboard__util"></div>`;
    const refreshEntries = () => {
        const protyle = getCurrentEditor()?.protyle;
        const inline = toolbarElement.querySelector<HTMLElement>(".keyboard__dynamic");
        applyKeyboardToolbarEntries(inline, protyle?.options.toolbar || []);
        hideKeyboardToolbarUtil();
    };
    refreshEntries();
    window.addEventListener("siyuan-entry-visibility", refreshEntries);
    let startY = 0;
    let startX = 0;
    let moved = false;
    const takeMenuKeyboard = bindMobileMenuKeyboard(toolbarElement, 'button[data-type="block"], button[data-type="block-type"]',
        () => getCurrentEditor()?.protyle);
    let blockTypeSelection: {protyle: IProtyle, snapshot: TTextBlockSelection} | undefined;
    toolbarElement.addEventListener("pointerdown", event => {
        blockTypeSelection = undefined;
        if (!(event.target as Element).closest('button[data-type="block-type"]')) {
            return;
        }
        const protyle = getCurrentEditor()?.protyle;
        const selection = getSelection();
        if (protyle && selection?.rangeCount > 0) {
            blockTypeSelection = {protyle, snapshot: getBlockTypeSelection(protyle, selection.getRangeAt(0))};
        }
    }, true);
    toolbarElement.addEventListener("touchstart", e => {
        startY = e.touches[0].clientY;
        startX = e.touches[0].clientX;
        moved = false;
    });
    toolbarElement.addEventListener("touchmove", e => {
        if (Math.abs(e.touches[0].clientY - startY) > 10 || Math.abs(e.touches[0].clientX - startX) > 10) {
            moved = true;
        }
    });
    toolbarElement.addEventListener("mousedown", event => {
        const buttonElement = hasClosestByTag(event.target as HTMLElement, "BUTTON");
        const type = buttonElement && buttonElement.getAttribute("data-type");
        if (type === "undo" || type === "redo" || type === "block" || type === "block-type") {
            // 保持编辑器焦点,避免工具栏操作期间软键盘收起。
            event.preventDefault();
        }
    });
    toolbarElement.addEventListener(isInAndroid() || isInHarmony() ? "touchend" : "click", async (event) => {
        const restoreMenuKeyboard = takeMenuKeyboard();
        if (moved) {
            return;
        }
        const protyle = getCurrentEditor()?.protyle;
        const target = event.target as HTMLElement;
        const liteSlashBtnElement = target.closest<HTMLElement>(".keyboard__util .protyle-hint .keyboard__slash-item[data-value]");
        const slashBtnElement = liteSlashBtnElement || hasClosestByClassName(target, "keyboard__slash-item");
        const fontFamilyButton = target.closest<HTMLElement>('[data-action="fontFamilyMenu"]');
        if (fontFamilyButton) {
            openMobileFontFamilyMenu(protyle, fontFamilyButton, true);
            event.preventDefault();
            event.stopPropagation();
            return;
        }
        if (slashBtnElement && slashBtnElement.dataset.action === "manageInlineStyle") {
            openInlineStyleDialog(slashBtnElement.dataset.inlineStyleType as TInlineStyleType, () => {
                renderTextMenu(protyle, toolbarElement);
            });
            event.preventDefault();
            event.stopPropagation();
            return;
        }
        if (slashBtnElement && !slashBtnElement.getAttribute("data-type")) {
            const dataValue = decodeURIComponent(slashBtnElement.getAttribute("data-value"));
            if (dataValue === Constants.ZWSP + 3) {
                return;
            }
            if (liteSlashBtnElement) {
                event.preventDefault();
                event.stopPropagation();
                if (!dataValue) {
                    return;
                }
                hideKeyboardToolbarUtil();
            }
            protyle.hint.fillCommand(dataValue, protyle, false, slashBtnElement.dataset.slashEntryKey);   // 点击后 range 会改变
            event.preventDefault();
            event.stopPropagation();
            if (dataValue === "((" || dataValue === "{{") {
                keepBlockHintKeyboard(protyle);
            } else if (slashBtnElement.getAttribute("data-focus") === "true" ||
                liteSlashBtnElement && slashBtnElement.getAttribute("data-focus") !== "false") {
                const selection = getSelection();
                const editorRange = getEditorFocusRange(protyle.wysiwyg.element,
                    selection?.rangeCount ? selection.getRangeAt(0) : undefined, protyle.toolbar.range);
                if (editorRange && (document.activeElement === document.body ||
                    protyle.wysiwyg.element.contains(document.activeElement))) {
                    hideKeyboardToolbarUtil(true);
                    restoreKeyboardToolbarRange(protyle, editorRange);
                    showKeyboardToolbar();
                }
            }
            return;
        }
        const buttonElement = hasClosestByTag(target, "BUTTON");
        if (!buttonElement || buttonElement.hasAttribute("disabled")) {
            return;
        }
        const type = buttonElement.getAttribute("data-type");
        // appearance
        if (["clear", "style2", "style4", "color", "backgroundColor", "fontSize", "style1"].includes(type)) {
            preventRender = true;
            const nodeElements = getFontNodeElements(protyle);
            const itemElement = buttonElement.firstElementChild as HTMLElement;
            const focusRange = !buttonElement.classList.contains("keyboard__slash-item");
            if (type === "style1") {
                const builtinID = buttonElement.dataset.builtinStyleId as TBuiltinInlineStyleID;
                fontEvent(protyle, nodeElements, type,
                    builtinID ? getBuiltinInlineStyleApplication(builtinID).color :
                        encodeStyle1(itemElement.style.backgroundColor, itemElement.style.color), focusRange);
            } else if (type === "fontSize") {
                fontEvent(protyle, nodeElements, type, itemElement.textContent.trim(), focusRange);
            } else if (type === "backgroundColor") {
                fontEvent(protyle, nodeElements, type, itemElement.style.backgroundColor, focusRange);
            } else if (type === "color") {
                fontEvent(protyle, nodeElements, type, itemElement.style.color, focusRange);
            } else {
                fontEvent(protyle, nodeElements, type, undefined, focusRange);
            }
            setTimeout(() => {
                preventRender = false;
            }, 1000);
        }

        event.preventDefault();
        event.stopPropagation();
        const selection = getSelection();
        const currentRange = selection.rangeCount > 0 ? selection.getRangeAt(0) : undefined;
        if (type === "block-type") {
            const saved = blockTypeSelection;
            blockTypeSelection = undefined;
            if (protyle && (!saved || saved.protyle === protyle)) {
                const snapshot = saved?.snapshot || (currentRange ? getBlockTypeSelection(protyle, currentRange) : undefined);
                openBlockTypeMenu(protyle, buttonElement, snapshot, {
                    onClose: () => restoreMenuKeyboard?.(),
                    isCurrent: () => getCurrentEditor()?.protyle === protyle,
                });
            }
            return;
        }
        // 收起菜单不依赖实时选区,编辑器失焦后使用保存的选区恢复光标。
        const closeAddMenu = type === "add" && buttonElement.classList.contains("protyle-toolbar__item--current");
        if (type === "done" || closeAddMenu) {
            if (closeAddMenu || toolbarElement.clientHeight > 100 ||
                toolbarElement.querySelector('.keyboard__action.protyle-toolbar__item--current[data-type="add"]')) {
                const range = protyle ? getEditorFocusRange(protyle.wysiwyg.element,
                    currentRange, protyle.toolbar.range) : currentRange?.cloneRange();
                hideKeyboardToolbarUtil(true);
                restoreKeyboardToolbarRange(protyle, range);
            } else {
                // 主动收起前先结束编辑焦点,避免 WebView 在触摸结束后重新唤起输入法。
                (document.activeElement as HTMLElement)?.blur();
                // 用户主动收起键盘时跳过弹出保护锁。
                activeBlur(true);
            }
            return;
        }
        // 块菜单允许在编辑器失焦后使用当前文档中保存的选区。
        const range = type === "block" && protyle ?
            getEditorFocusRange(protyle.wysiwyg.element, currentRange, protyle.toolbar.range) : currentRange;
        if (!range) {
            return;
        }
        if (window.siyuan.config.readonly || !protyle || protyle.disabled) {
            return;
        }
        if (type === "undo") {
            const undoContext = getMobileToolbarUndo(protyle);
            if (undoContext) {
                undoContext.run(false);
            } else {
                protyle.undo.undo(protyle);
            }
            renderKeyboardToolbar();
            return;
        } else if (type === "redo") {
            const undoContext = getMobileToolbarUndo(protyle);
            if (undoContext) {
                undoContext.run(true);
            } else {
                protyle.undo.redo(protyle);
            }
            renderKeyboardToolbar();
            return;
        }
        if (type !== "block" && getSelection().rangeCount === 0) {
            return;
        }
        const nodeElement = hasClosestBlock(range.startContainer);
        if (!nodeElement) {
            return;
        }
        // inline element
        const insert = MOBILE_TOOLBAR_INSERTS.find(item => item.name === type);
        if (insert) {
            protyle.toolbar.range = range.cloneRange();
            protyle.hint.fillCommand(insert.value(Constants), protyle, false);
            return;
        } else if (["a", "block-ref", "inline-math", "inline-memo"].includes(type)) {
            if (!hasClosestByAttribute(range.startContainer, "data-type", "NodeCodeBlock")) {
                hideElements(["util"], protyle);
                if (type === "block-ref" && range.collapsed) {
                    protyle.toolbar.range = range.cloneRange();
                    protyle.hint.fillCommand("((", protyle, false);
                    keepBlockHintKeyboard(protyle);
                    return;
                }
                protyle.toolbar.element.querySelector(`[data-type="${type}"]`).dispatchEvent(new CustomEvent("click"));
            }
            return;
        } else if (buttonElement.classList.contains("keyboard__action") && ["strong", "em", "s", "code", "mark", "tag", "u", "sup", "clear", "sub", "kbd"].includes(type)) {
            if (!hasClosestByAttribute(range.startContainer, "data-type", "NodeCodeBlock")) {
                protyle.toolbar.setInlineMark(protyle, type, "toolbar");
            }
            return;
        } else if (type === "font-family") {
            hideKeyboardToolbarUtil();
            openMobileFontFamilyMenu(protyle, buttonElement);
            return;
        } else if (type === "font-size") {
            if (buttonElement.classList.contains("protyle-toolbar__item--current")) {
                hideKeyboardToolbarUtil(true);
                restoreKeyboardToolbarRange(protyle, range);
                return;
            }
            resetKeyboardToolbarUtilButtons();
            buttonElement.classList.add("protyle-toolbar__item--current");
            toolbarElement.querySelector('.keyboard__action[data-type="done"] use').setAttribute("xlink:href", "#iconCloseRound");
            const savedRange = range.cloneRange();
            protyle.toolbar.range = savedRange;
            const nodes = getFontNodeElements(protyle);
            const util = toolbarElement.querySelector<HTMLElement>(".keyboard__util");
            const valid = () => getCurrentEditor()?.protyle === protyle && !protyle.disabled &&
                savedRange.startContainer.isConnected && savedRange.endContainer.isConnected &&
                buttonElement.classList.contains("protyle-toolbar__item--current");
            const finish = () => {
                hideKeyboardToolbarUtil(true);
                restoreKeyboardToolbarRange(protyle, protyle.toolbar.range);
            };
            const apply = (style: string, value: string) => {
                if (!valid()) {
                    return;
                }
                protyle.toolbar.range = savedRange;
                fontEvent(protyle, nodes, style, value, false);
                finish();
            };
            preventKeyboardToolbarRender();
            util.replaceChildren(createFontSizePicker(protyle, value => apply("fontSize", value), preventKeyboardToolbarRender, () => {
                if (valid()) {
                    protyle.toolbar.range = savedRange;
                    finish();
                }
            }));
            showKeyboardToolbarUtil(protyle.contentElement.scrollTop);
            hideAndroidKeyboardForPanel(protyle);
            return;
        } else if (type === "text") {
            if (buttonElement.classList.contains("protyle-toolbar__item--current")) {
                hideKeyboardToolbarUtil(true);
                restoreKeyboardToolbarRange(protyle, range);
            } else {
                resetKeyboardToolbarUtilButtons();
                buttonElement.classList.add("protyle-toolbar__item--current");
                toolbarElement.querySelector('.keyboard__action[data-type="done"] use').setAttribute("xlink:href", "#iconCloseRound");
                const oldScrollTop = protyle.contentElement.scrollTop;
                renderTextMenu(protyle, toolbarElement);
                showKeyboardToolbarUtil(oldScrollTop);
                hideAndroidKeyboardForPanel(protyle);
                if (!window.JSAndroid) {
                    setTimeout(() => {
                        focusByRange(range);
                        preventRender = true;
                        setTimeout(() => {
                            preventRender = false;
                        }, 1000);
                    }, Constants.TIMEOUT_TRANSITION);
                }
            }
            return;
        } else if (type === "moveup") {
            moveToUp(protyle, nodeElement, range);
            return;
        } else if (type === "movedown") {
            moveToDown(protyle, nodeElement, range);
            return;
        } else if (type === "softLine") {
            const trackedRangeInsertion = prepareTrackedRangeInsertion(protyle, range);
            try {
                range.extractContents();
                softEnter(range, nodeElement, protyle, trackedRangeInsertion);
            } finally {
                endTrackedRangeInsertion(trackedRangeInsertion);
            }
            focusByRange(range);
            return;
        } else if (type === "add") {
            protyle.toolbar.range = range.cloneRange();
            resetKeyboardToolbarUtilButtons();
            buttonElement.classList.add("protyle-toolbar__item--current");
            toolbarElement.querySelector('.keyboard__action[data-type="done"] use').setAttribute("xlink:href", "#iconCloseRound");
            const oldScrollTop = protyle.contentElement.scrollTop;
            renderSlashMenu(protyle, toolbarElement);
            showKeyboardToolbarUtil(oldScrollTop);
            (document.activeElement as HTMLElement)?.blur();
            hideAndroidKeyboardForPanel(protyle);
            return;
        } else if (type === "block") {
            await toggleMenu({
                target: target,
                build: async (_menu, session) => {
                    event.preventDefault();
                    protyle.toolbar.range = range;
                    keyboardPanelClosing = false;
                    hideKeyboardToolbarUtil();
                    if (!protyle.gutter && getTableCellRichContext(protyle)) {
                        const [{MenuItem}, {tableMenu}] = await Promise.all([
                            import("../../menus/Menu"), import("../../menus/protyle"),
                        ]);
                        if (!session.isCurrent()) {
                            return;
                        }
                        if (!nodeElement.isConnected || protyle.disabled || !getTableCellRichContext(protyle)) {
                            return;
                        }
                        const context = getTableCellRichContext(protyle);
                        const table = context.cell.closest('[data-type="NodeTable"]');
                        const tableRange = document.createRange();
                        tableRange.selectNodeContents(context.cell);
                        tableRange.collapse(true);
                        const tableMenus = tableMenu(context.owner, table, context.cell, tableRange, true).menus;
                        prepareTableCellMenuItems(tableMenus, () => finishTableCellEditing(context.cell));
                        window.siyuan.menus.menu.remove();
                        window.siyuan.menus.menu.append(new MenuItem({
                            id: "tableSelectRange",
                            icon: "iconSelect",
                            label: window.siyuan.languages.tableSelectRange,
                            click: () => {
                                context.owner.wysiwyg.tableControl?.startTouchSelection(context.cell);
                            },
                        }).element);
                        window.siyuan.menus.menu.append(new MenuItem({
                            id: "table",
                            icon: "iconTable",
                            label: window.siyuan.languages.table,
                            submenu: tableMenus,
                        }).element);
                        window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);
                        window.siyuan.menus.menu.append(new MenuItem({
                            id: "insertBefore",
                            icon: "iconBefore",
                            label: window.siyuan.languages.insertBefore,
                            click: () => insertEmptyBlock(protyle, "beforebegin", nodeElement),
                        }).element);
                        window.siyuan.menus.menu.append(new MenuItem({
                            id: "insertAfter",
                            icon: "iconAfter",
                            label: window.siyuan.languages.insertAfter,
                            click: () => insertEmptyBlock(protyle, "afterend", nodeElement),
                        }).element);
                        session.show(() => window.siyuan.menus.menu.fullscreen("all", restoreMenuKeyboard));
                        return;
                    }
                    // 多选时以已选块打开共享块菜单,使列表项转换作用于整个选区。
                    const selectedBlock = protyle.wysiwyg.element.querySelector<HTMLElement>(".protyle-wysiwyg--select");
                    protyle.gutter?.renderMenu(protyle, selectedBlock || nodeElement);
                    session.show(() => window.siyuan.menus.menu.fullscreen("all", restoreMenuKeyboard));

                },
            });
        return;
        } else if (type === "outdent") {
            if (nodeElement.classList.contains("code-block")) {
                tabCodeBlock(protyle, nodeElement, range, true);
            } else {
                await listOutdent(protyle, [nodeElement.parentElement], range);

            }
            focusByRange(range);
            return;
        } else if (type === "indent") {
            if (nodeElement.classList.contains("code-block")) {
                tabCodeBlock(protyle, nodeElement, range);
            } else {
                await listIndent(protyle, [nodeElement.parentElement], range);

            }
            focusByRange(range);
            return;
        } else if (type) {
            protyle.toolbar.element.querySelector(`[data-type="${type}"]`)?.dispatchEvent(new CustomEvent("click"));
        }
    });
};