Skip to content

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

142 KB
Raw Blame
import {escapeHtmlTextAndAttr} from "../../util/escape";
import {fetchPost, fetchSyncPost} from "../../util/fetch";
import dayjs from "dayjs";
import {restoreInlineElementBoundaryHTML} from "../util/inlineElementBoundary";
import {getEditorTransaction} from "../util/transactionContract";
import {
    focusBlock,
    focusByWbr,
    focusSideBlock,
    getEditorRange,
    getUndoFocusContext,
    restoreUndoFocus
} from "../util/selection";
import {
    getContenteditableElement,
    getEmbedChildOperationContext,
    getEmbedChildOperationParentID,
    getFirstBlock,
    getNextBlockSibling,
    getParentBlock,
    getPreviousBlockSibling,
    getSbChildBlockCount,
    getTopAloneElement
} from "./getBlock";
import {Constants} from "../../constants";
import {CALLOUT_PRESETS, type ICalloutPreset} from "./calloutType";
import {blockRender} from "../render/blockRender";
import {renderBlockDirection, syncBlockDirection} from "../render/blockDirection";
import {renderEmbedHeadings} from "../render/embedHeading";
import {processRender} from "../util/processCode";
import {renderImageDisplay} from "../render/imageDisplay";
import {highlightRender} from "../render/highlightRender";
import {hasClosestBlock, hasClosestByAttribute, hasTopClosestByAttribute, isInEmbedBlock} from "../util/hasClosest";
import {zoomOut} from "../../menus/protyle";
import {disabledProtyle, enableProtyle} from "../util/onGet";
/// #if !MOBILE
import {getAllModels} from "../../layout/getAll";
/// #endif
import {avRender, refreshAV} from "../render/av/render";
import {removeFoldHeading} from "../util/heading";
import {cancelSB, genEmptyElement, genSBElement, refreshSbResize} from "../../block/util";
import {hideElements} from "../ui/hideElements";
import {reloadProtyle} from "../util/reload";
import {countBlockWord} from "../../layout/status";
import {resize} from "../util/resize";
import {scrollCenter} from "../../util/highlightById";
import {isUndoViewportPreserved} from "../undo/viewport";
import {consumeGutterFoldRestore} from "../ui/gutterVisibility";
import {setFold} from "../util/blockFold";
import {refreshHeadingFoldIndicators} from "../util/headingFoldIndicator";
import {queueTransaction, queueTransactionBatch} from "../util/transactionQueue";
import {
    cleanHeadingNumberHTML,
    cleanHeadingNumberOperations,
    queueHeadingNumberRefresh
} from "../util/headingNumber";
import {MERMAID_LAYOUT_ATTR} from "../render/mermaidLayout";
import {
    getPartialUpdateCleanupElements,
    shouldDeferCodeBlockCaretRestore,
    shouldReloadForHeadingBatch,
} from "./transactionUpdate";
import {getMoveAffectedEmbedElements, shouldSyncMoveCopies} from "./transactionEmbed";
import {getVisibleMoveElements} from "./transactionMove";
import {normalizeHTMLAssetIFrameBlockDOM} from "../../asset/html";
import {sanitizeKernelHTML} from "../../util/hostCapabilities";
import {disposeCustomBlocksInElement} from "../../plugin/customBlockRender";
import {
    applyViewFoldStates,
    handleViewFoldSourceOperation,
    hasViewFoldContext,
    invalidateViewFoldRequests,
    prepareViewFoldTransaction,
    setViewFoldTransient,
} from "../util/viewFold";
import {
    captureBlockSelectionModeState,
    cleanBlockSelectionModeHTML,
    getBlockSelectionStatusIDs,
    restoreBlockSelectionModeState
} from "./blockSelection";
import {isEmptyParagraph} from "./emptyTextBlock";
import {isListHeadingContainer} from "./headingConversion";
import {cleanTableCellRichHTML, getTableBlockHTML, retainTableCellRichMetadata} from "../util/tableCellRich";
import {cleanTableVirtualizationHTML, TABLE_VIRTUAL_ID} from "../util/tableVirtualizationDOM";
import {
    cleanListMindmapHTML, convertListMindmapToList, hasListMindmapRootTitle,
    isListMindmapListConversion, listMindmapConversionSource,
} from "../render/listMindmap/model";
import {prepareListMindmapConversion} from "../render/listMindmap/conversion";
import {buildCancelListOperations} from "./cancelList";
import {markMirror, refreshUndoButtons} from "../undo/globalUndo";
import type {TransactionListConversionResult} from "../../types/api";
import {getProtyleTransactionOwner} from "../runtimeCapabilities";
import {completeTabsListSource, convertTabsList, isTabsListConversion} from "./tabsList";
import {preserveTabTask} from "../util/tabsCopy";
import {waitForPendingTransactions} from "../util/transactionQueue";
import {replayListMindmap} from "../render/listMindmap/render";
import {
    invalidateTrackedRangesByOperations,
    type ITrackedRangeInsertion,
    syncTrackedRanges,
} from "../util/trackedRange";

const cleanBlockSelectionModeOperations = (operations?: IOperation[]) => {
    operations?.forEach(operation => {
        if (["appendInsert", "insert", "prependInsert", "update"].includes(operation.action) &&
            typeof operation.data === "string") {
            operation.data = cleanListMindmapHTML(cleanTableCellRichHTML(cleanBlockSelectionModeHTML(
                cleanTableVirtualizationHTML(operation.data))));
        }
        if (operation.action === "unfoldHeading" && typeof operation.retData === "string") {
            operation.retData = cleanBlockSelectionModeHTML(operation.retData);
        }
    });
};

const focusRestoredBlockSelectionMode = (selectionModeElement?: Element) => {
    if (!selectionModeElement?.isConnected) {
        return;
    }
    const selection = getSelection();
    if (selection.rangeCount === 0 || !selectionModeElement.contains(selection.getRangeAt(0).startContainer)) {
        focusBlock(selectionModeElement);
    }
};

const removeTopElement = (updateElement: Element, protyle: IProtyle) => {
    // 移动到其他文档中,该块需移除
    // TODO 文档没有打开时,需要通过后台获取 getTopAloneElement
    const topAloneElement = getTopAloneElement(updateElement);
    const doOperations: IOperation[] = [];
    if (topAloneElement !== updateElement) {
        updateElement.remove();
        doOperations.push({
            action: "delete",
            id: topAloneElement.getAttribute("data-node-id")
        });
    }
    topAloneElement.remove();
    if (protyle.wysiwyg.element.childElementCount === 0) {
        if (protyle.block.rootID === protyle.block.id) {
            const newId = Lute.NewNodeID();
            const newElement = genEmptyElement(false, false, newId);
            doOperations.push({
                action: "insert",
                data: newElement.outerHTML,
                id: newId,
                parentID: protyle.block.parentID
            });
            protyle.wysiwyg.element.innerHTML = newElement.outerHTML;
        } else {
            zoomOut({
                protyle,
                id: protyle.block.rootID,
                isPushBack: false,
                focusId: protyle.block.id,
            });
        }
    }
    if (doOperations.length > 0) {
        transaction(protyle, doOperations, []);
    }
};

const canSyncListFoldInPlace = (embedElement: Element, operation: Extract<IOperation, {action: "setAttrs"}>) => {
    const attrs = JSON.parse(operation.data);
    if (Object.keys(attrs).length !== 1 || !Object.prototype.hasOwnProperty.call(attrs, "fold")) {
        return false;
    }
    const items = Array.from(embedElement.querySelectorAll(`[data-node-id="${operation.id}"]`));
    // 列表子块已在 DOM 中时只同步折叠属性,展开缺少子块的片段仍需重新查询。
    return items.length > 0 && items.every(item => item.getAttribute("data-type") === "NodeListItem" &&
        (attrs.fold === "1" || item.childElementCount > 3));
};

const syncBlockAttrs = (element: Element, operation: Extract<IOperation, {action: "setAttrs"}>) => {
    const attrs = JSON.parse(operation.data);
    const hasFold = Object.prototype.hasOwnProperty.call(attrs, "fold");
    const hasStyle = Object.prototype.hasOwnProperty.call(attrs, "style");
    const hasMindmapView = Object.prototype.hasOwnProperty.call(attrs, Constants.CUSTOM_SY_LIST_MINDMAP);
    const hasMindmapMetadata = Object.prototype.hasOwnProperty.call(attrs, Constants.CUSTOM_SY_LIST_MINDMAP_DATA);
    const tabsAttrs = ["tabs-active-id", "tabs-position", "tabs-task"]
        .filter(name => Object.prototype.hasOwnProperty.call(attrs, name));
    if (!hasFold && !hasStyle && !hasMindmapView && !hasMindmapMetadata && tabsAttrs.length === 0) {
        return;
    }
    element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach(item => {
        if (hasMindmapMetadata) {
            if (attrs[Constants.CUSTOM_SY_LIST_MINDMAP_DATA]) {
                item.setAttribute(Constants.CUSTOM_SY_LIST_MINDMAP_DATA, attrs[Constants.CUSTOM_SY_LIST_MINDMAP_DATA]);
            } else {
                item.removeAttribute(Constants.CUSTOM_SY_LIST_MINDMAP_DATA);
            }
        }
        // 同步脑图视图属性,由列表监听器刷新各分屏中的视图。
        if (hasMindmapView) {
            if (attrs[Constants.CUSTOM_SY_LIST_MINDMAP]) {
                item.setAttribute(Constants.CUSTOM_SY_LIST_MINDMAP, attrs[Constants.CUSTOM_SY_LIST_MINDMAP]);
            } else {
                item.removeAttribute(Constants.CUSTOM_SY_LIST_MINDMAP);
            }
        }
        if (hasFold) {
            if (attrs.fold === "1") {
                item.setAttribute("fold", "1");
            } else {
                item.removeAttribute("fold");
            }
        }
        if (hasStyle) {
            if (attrs.style) {
                item.setAttribute("style", attrs.style);
            } else {
                item.removeAttribute("style");
            }
        }
        // 撤销恢复的页签属性同步到 DOM,后续拖动据此捕获有效的选择和布局状态。
        tabsAttrs.forEach(name => {
            if (attrs[name]) {
                item.setAttribute(name, attrs[name]);
            } else {
                item.removeAttribute(name);
            }
        });
    });
};

const getVisibleFoldHeadingHTML = (html: string) => {
    html = normalizeHTMLAssetIFrameBlockDOM(html);
    if (!html.includes('data-type="NodeHeading"') || !html.includes('fold="1"')) {
        return html;
    }

    const template = document.createElement("template");
    template.innerHTML = html;
    Array.from(template.content.querySelectorAll('[data-type="NodeHeading"][fold="1"]')).reverse().forEach(item => {
        removeFoldHeading(item);
    });
    return template.innerHTML;
};

// 按插入前的相邻边界收集新增根元素,避免把已有兄弟块或光标定位块当作完整渲染范围。
const insertTransactionHTML = (element: Element, position: "beforebegin" | "afterend" | "afterbegin", html: string) => {
    const parent = position === "afterbegin" ? element : element.parentElement;
    const previous = position === "beforebegin" ? element.previousElementSibling :
        position === "afterend" ? element : null;
    const next = position === "beforebegin" ? element :
        position === "afterend" ? element.nextElementSibling : element.firstElementChild;
    element.insertAdjacentHTML(position, html);
    const inserted: Element[] = [];
    let current = previous ? previous.nextElementSibling : parent.firstElementChild;
    while (current && current !== next) {
        inserted.push(current);
        current = current.nextElementSibling;
    }
    return inserted;
};

// 用于执行操作,外加处理当前编辑器中块引用、嵌入块的更新
const promiseTransaction = (options: {
    protyle: IProtyle,
    doOperations: IOperation[],
    undoOperations: IOperation[],
    skipSync: boolean,
    callback?: () => void,
    templateDocTreePlanID?: string,
    trackedRangeInsertion?: ITrackedRangeInsertion,
}) => {
    const protyle = options.protyle;
    // 受影响的嵌入块需推迟到事务提交后再渲染,否则其查询请求会早于写入到达内核而拿到旧数据
    const pendingEmbedElements = new Set<Element>();
    const pendingAVElements = new Set<Element>();
    let range: Range;
    if (getSelection().rangeCount > 0) {
        range = getSelection().getRangeAt(0);
    }
    const embedChildOperationContext = range && getEmbedChildOperationContext(range.startContainer);
    const isEmbedChildOperation = !!embedChildOperationContext;
    const editingEmbedElement = embedChildOperationContext &&
        (isInEmbedBlock(embedChildOperationContext.resultElement, false) || undefined);
    if (!options.skipSync) {
        options.doOperations.forEach((operation: IOperation) => {
            if (operation.action === "update") {
                // 当前编辑器中的其他块
                let updatedEmbed = false;
                let restoredSelectionModeElement: HTMLElement;

                const updateElements = Array.from(
                    protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)
                );
                // updateTransaction 会在本地编辑元素上设置该属性,用于在存在同 ID 副本时保留当前 DOM 和光标。
                const currentUpdateElement = updateElements.find(item =>
                    item.getAttribute(Constants.ATTRIBUTE_EDITING) === "true" && getEmbedChildOperationContext(item)) ||
                    updateElements.find(item => item.getAttribute(Constants.ATTRIBUTE_EDITING) === "true");
                const currentEmbedContext = currentUpdateElement && getEmbedChildOperationContext(currentUpdateElement);
                const currentEmbedElement = currentEmbedContext && isInEmbedBlock(currentUpdateElement, false);

                const updateHTML = (item: Element, html: string, force = false) => {
                    if (!force && item.getAttribute(Constants.ATTRIBUTE_EDITING) === "true") {
                        item.removeAttribute(Constants.ATTRIBUTE_EDITING);
                        return;
                    }
                    const selectionModeState = captureBlockSelectionModeState(item);
                    const tempElement = document.createElement("template");
                    tempElement.innerHTML = cleanBlockSelectionModeHTML(getVisibleFoldHeadingHTML(html));
                    tempElement.content.querySelectorAll(".protyle-wysiwyg--select").forEach(selectItem => {
                        selectItem.classList.remove("protyle-wysiwyg--select");
                    });
                    const wbrElement = tempElement.content.querySelector("wbr");
                    if (wbrElement) {
                        wbrElement.remove();
                    }
                    disposeCustomBlocksInElement(item);
                    item.insertAdjacentHTML("afterend", tempElement.innerHTML);
                    const replacementElement = item.nextElementSibling;
                    item.remove();
                    if (replacementElement) {
                        restoredSelectionModeElement = restoreBlockSelectionModeState(protyle.wysiwyg.element,
                            replacementElement, selectionModeState) || restoredSelectionModeElement;
                    }
                    updatedEmbed = true;
                };

                let allTempElement: HTMLTemplateElement;
                // 拖拽列宽等操作不移动文本选区,存在明确编辑标记时不能用旧选区保护其他副本。
                updateElements.forEach((item) => {
                    if ((currentEmbedElement && isInEmbedBlock(item, false) === currentEmbedElement) ||
                        (!currentUpdateElement && range && (item === range.startContainer || item.contains(range.startContainer)))) {
                        // 正在编辑的块不能进行更新
                        item.removeAttribute(Constants.ATTRIBUTE_EDITING);
                    } else {
                        // 从可编辑嵌入块发起更新时,同 ID 的普通副本可能带有其他事务遗留的编辑标记,仍需同步。
                        updateHTML(item, operation.data, !!currentEmbedElement && !isInEmbedBlock(item));
                    }
                });
                protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg__embed").forEach(item => {
                    if (item === currentEmbedContext?.resultElement ||
                        (!currentUpdateElement && range && (item === range.startContainer || item.contains(range.startContainer)))) {
                        // 正在编辑的块不能进行更新
                        item.removeAttribute(Constants.ATTRIBUTE_EDITING);
                    } else {
                        // https://github.com/siyuan-note/siyuan/issues/14495
                        // 仅在嵌入副本需要查找子块时解析完整快照,当前块的本地输入无需构建整块 DOM。
                        if (!allTempElement) {
                            allTempElement = document.createElement("template");
                            allTempElement.innerHTML = cleanBlockSelectionModeHTML(getVisibleFoldHeadingHTML(operation.data));
                        }
                        const newTempElement = allTempElement.content.querySelector(`[data-node-id="${item.getAttribute("data-id")}"]`);
                        if (newTempElement && !isInEmbedBlock(newTempElement)) {
                            updateHTML(item.querySelector("[data-node-id]"), newTempElement.outerHTML);
                        } else {
                            item.removeAttribute(Constants.ATTRIBUTE_EDITING);
                        }
                    }
                });
                if (updatedEmbed) {
                    processRender(protyle.wysiwyg.element);
                    highlightRender(protyle.wysiwyg.element);
                    pendingAVElements.add(protyle.wysiwyg.element);
                }
                focusRestoredBlockSelectionMode(restoredSelectionModeElement);
                return;
            }
            if (operation.action === "delete" || operation.action === "append") {
                // 普通编辑流程自行维护本地 DOM;仅嵌入块编辑需要额外删除外层同 ID 副本。
                if ((operation.action === "delete" && isEmbedChildOperation) || protyle.options.backlinkData) {
                    Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)).forEach(item => {
                        if (!isInEmbedBlock(item) && (!range || !item.contains(range.startContainer))) {
                            item.remove();
                        }
                    });
                }
                // 更新嵌入块
                protyle.wysiwyg.element.querySelectorAll('[data-type="NodeBlockQueryEmbed"]').forEach((item) => {
                    if (item.querySelector(`[data-node-id="${operation.id}"]`)) {
                        pendingEmbedElements.add(item);
                    }
                });
                hideElements(["gutter"], protyle);
                return;
            }
            if (operation.action === "move") {
                // 反链和嵌入块编辑中存在同 ID 的普通副本,需同步回放移动操作
                if (shouldSyncMoveCopies(!!protyle.options.backlinkData, isEmbedChildOperation)) {
                    const updateElements: Element[] = [];
                    Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)).forEach(item => {
                        if (!isInEmbedBlock(item)) {
                            const topElement = hasTopClosestByAttribute(item, "data-node-id", null);
                            if (topElement && !topElement.contains(range.startContainer)) {
                                // 当前操作块不再进行操作,否则光标丢失 https://github.com/siyuan-note/siyuan/issues/13946
                                updateElements.push(item);
                            }
                        }
                    });
                    const moveElementGroups = updateElements.map(item => getVisibleMoveElements(item, operation.blockIDs));
                    const primaryMoveElements = moveElementGroups[0] || [];
                    const moveElements = Array.from(new Set(moveElementGroups.flat()));
                    // 移动前记录源块所在的超级块,移动后刷新其拖拽手柄(移出后手柄需清理)
                    const originSbs: Element[] = [];
                    moveElements.forEach(item => {
                        const sb = item.closest('[data-type="NodeSuperBlock"]');
                        if (sb && !originSbs.includes(sb)) {
                            originSbs.push(sb);
                        }
                    });
                    let hasFind = false;
                    if (operation.nextID && updateElements.length > 0) {
                        protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.nextID}"]`).forEach(item => {
                            if (!isInEmbedBlock(item) && !item.contains(range.startContainer)) {
                                item.before(...primaryMoveElements.map(element => element.cloneNode(true)));
                                hasFind = true;
                            }
                        });
                    } else if (operation.previousID && updateElements.length > 0) {
                        Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.previousID}"]`)).forEach(item => {
                            if (!isInEmbedBlock(item) && !getNextBlockSibling(item)?.contains(range.startContainer)) {
                                item.after(...primaryMoveElements.map(element => element.cloneNode(true)));
                                hasFind = true;
                            }
                        });
                    } else if (updateElements.length > 0) {
                        Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.parentID}"]`)).forEach(item => {
                            if (!isInEmbedBlock(item) && !getFirstBlock(item).contains(range.startContainer)) {
                                const cloneElements = primaryMoveElements.map(element => element.cloneNode(true));
                                // 列表特殊处理
                                if (item.firstElementChild?.classList.contains("protyle-action")) {
                                    item.firstElementChild.after(...cloneElements);
                                } else if ((item.classList.contains("callout") || item.classList.contains("tab-item"))) {
                                    item.querySelector(":scope > .callout-content, :scope > .tab-item-content").prepend(...cloneElements);
                                } else {
                                    item.prepend(...cloneElements);
                                }
                                hasFind = true;
                            }
                        });
                    }
                    moveElements.forEach(item => {
                        if (hasFind) {
                            item.remove();
                        } else if (!hasFind && item.parentElement) {
                            removeTopElement(item, protyle);
                        }
                    });
                    // 块移出后刷新源超级块的手柄(originSb 在元素被移除前捕获)
                    refreshSbs(...originSbs);
                }
                // 当前编辑副本已由本地 DOM 操作更新,仅刷新其他受影响的嵌入块
                getMoveAffectedEmbedElements(
                    protyle.wysiwyg.element.querySelectorAll('[data-type="NodeBlockQueryEmbed"]'),
                    operation,
                    editingEmbedElement,
                ).forEach(item => {
                    pendingEmbedElements.add(item);
                });
                // 移动块(含撤销移动)后刷新相关超级块的拖拽手柄,避免手柄残留/缺失
                const moveEls = [operation.id, operation.parentID, operation.previousID, operation.nextID]
                    .map(id => id ? protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`) : null)
                    .filter(Boolean) as Element[];
                refreshSbs(...moveEls);
                return;
            }
            if (operation.action === "insert") {
                if (operation.context?.ignoreProcess === "true") {
                    return;
                }
                const visibleData = getVisibleFoldHeadingHTML(operation.data);
                // 块已被本地 DOM 操作插入时仍需同步其他普通副本,并跳过当前副本避免重复
                // https://github.com/siyuan-note/siyuan/issues/17890
                const insertedElements = Array.from(
                    protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)
                );
                const insertedElement = insertedElements[0];
                const currentEmbedElement = insertedElement && isInEmbedBlock(insertedElement, false);
                if (insertedElement) {
                    protyle.wysiwyg.element.querySelectorAll("[data-type=\"NodeBlockQueryEmbed\"]").forEach(item => {
                        if (item !== currentEmbedElement && containsOperationAnchor(item, operation)) {
                            pendingEmbedElements.add(item);
                        }
                    });
                    getDocumentEmbedResults(protyle.wysiwyg.element, operation.parentID).forEach(item => {
                        const embedElement = isInEmbedBlock(item, false);
                        if (embedElement && embedElement !== currentEmbedElement) {
                            pendingEmbedElements.add(embedElement);
                        }
                    });
                }
                const cursorElements: Element[] = [];
                const renderElements: Element[] = [];
                if (operation.previousID) {
                    Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.previousID}"]`)).forEach(item => {
                        const embedElement = isInEmbedBlock(item, false);
                        if (embedElement) {
                            if (embedElement !== currentEmbedElement) {
                                pendingEmbedElements.add(embedElement);
                            }
                            return;
                        }
                        const hasInsertedSibling = insertedElements.some(insertedItem =>
                            !isInEmbedBlock(insertedItem, false) && insertedItem.parentElement === item.parentElement);
                        if (!hasInsertedSibling &&
                            getNextBlockSibling(item)?.getAttribute("data-node-id") !== operation.id &&
                            (!range || !item.contains(range.startContainer)) && // 当前操作块不再进行操作
                            // 段落转列表会在段落后插入新列表
                            !hasClosestByAttribute(item, "data-node-id", operation.id) &&
                            // 嵌入块后不能插入
                            !item.parentElement.classList.contains("protyle-wysiwyg__embed")) {
                            renderElements.push(...insertTransactionHTML(item, "afterend", visibleData));
                            cursorElements.push(item.nextElementSibling);
                        }
                    });
                } else if (operation.nextID) {
                    Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.nextID}"]`)).forEach(item => {
                        const embedElement = isInEmbedBlock(item, false);
                        if (embedElement) {
                            if (embedElement !== currentEmbedElement) {
                                pendingEmbedElements.add(embedElement);
                            }
                            return;
                        }
                        const hasInsertedSibling = insertedElements.some(insertedItem =>
                            !isInEmbedBlock(insertedItem, false) && insertedItem.parentElement === item.parentElement);
                        if (!hasInsertedSibling &&
                            getPreviousBlockSibling(item)?.getAttribute("data-node-id") !== operation.id &&
                            (!range || !item.contains(range.startContainer)) &&
                            !hasClosestByAttribute(item, "data-node-id", operation.id) &&
                            !item.parentElement.classList.contains("protyle-wysiwyg__embed")) {
                            renderElements.push(...insertTransactionHTML(item, "beforebegin", visibleData));
                            cursorElements.push(item.previousElementSibling);
                        }
                    });
                } else {
                    Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.parentID}"]`)).forEach(item => {
                        const embedElement = isInEmbedBlock(item, false);
                        if (embedElement) {
                            if (embedElement !== currentEmbedElement) {
                                pendingEmbedElements.add(embedElement);
                            }
                            return;
                        }
                        // 本地 DOM 可能已被同一事务的后续操作重排,不能仅根据首个子块判断是否已经插入。
                        if (item.querySelector(`[data-node-id="${operation.id}"]`)) {
                            return;
                        }
                        if (!range || !item.contains(range.startContainer)) {
                            // 列表特殊处理
                            if (item.firstElementChild && item.firstElementChild.classList.contains("protyle-action") &&
                                item.firstElementChild.nextElementSibling?.getAttribute("data-node-id") !== operation.id) {
                                renderElements.push(...insertTransactionHTML(item.firstElementChild, "afterend", visibleData));
                                cursorElements.push(item.firstElementChild.nextElementSibling);
                            } else if ((item.classList.contains("callout") || item.classList.contains("tab-item")) &&
                                item.querySelector("[data-node-id]")?.getAttribute("data-node-id") !== operation.id) {
                                renderElements.push(...insertTransactionHTML(item.querySelector(":scope > .callout-content, :scope > .tab-item-content"), "afterbegin", visibleData));
                                cursorElements.push(item.querySelector("[data-node-id]"));
                            } else if (item.firstElementChild.getAttribute("data-node-id") !== operation.id) {
                                renderElements.push(...insertTransactionHTML(item, "afterbegin", visibleData));
                                cursorElements.push(item.firstElementChild);
                            }
                        }
                    });
                    getDocumentEmbedResults(protyle.wysiwyg.element, operation.parentID).forEach(item => {
                        const embedElement = isInEmbedBlock(item, false);
                        if (embedElement && embedElement !== currentEmbedElement) {
                            pendingEmbedElements.add(embedElement);
                        }
                    });
                }
                // https://github.com/siyuan-note/siyuan/issues/4420
                protyle.wysiwyg.element.querySelectorAll('[data-type="NodeHeading"]').forEach(item => {
                    if (item.lastElementChild.getAttribute("spin") === "1") {
                        item.lastElementChild.remove();
                    }
                });
                renderElements.forEach(item => {
                    processRender(item);
                    highlightRender(item);
                    pendingAVElements.add(item);
                    blockRender(protyle, item);
                });
                cursorElements.forEach(item => {
                    item.querySelectorAll("wbr").forEach(wbrItem => {
                        wbrItem.remove();
                    });
                });
                protyle.wysiwyg.element.querySelectorAll("[parent-heading]").forEach(item => {
                    item.remove();
                });
                // 插入块后刷新所在超级块的拖拽手柄(本地新块已在 DOM 跳过插入时也需刷新)
                const insertedEl = protyle.wysiwyg.element.querySelector(`[data-node-id="${operation.id}"]`);
                refreshSbs(insertedEl);
                return;
            }
            if (operation.action === "setAttrs") {
                syncBlockAttrs(protyle.wysiwyg.element, operation);
                const gutterFoldElement = protyle.gutter.element.querySelector('[data-type="fold"]');
                if (gutterFoldElement) {
                    gutterFoldElement.removeAttribute("disabled");
                }
                // 就地同步列表折叠,保留嵌入内容中的光标节点和布局。
                protyle.wysiwyg.element.querySelectorAll('[data-type="NodeBlockQueryEmbed"]').forEach((item) => {
                    if (item.querySelector(`[data-node-id="${operation.id}"]`) && !canSyncListFoldInPlace(item, operation)) {
                        pendingEmbedElements.add(item);
                    }
                });
            }
        });
        // 删除仅有的折叠标题后展开内容为空
        if (protyle.wysiwyg.element.childElementCount === 0 &&
            // 聚焦时不需要新增块,否则会导致 https://github.com/siyuan-note/siyuan/issues/12326 第一点
            !protyle.block.showAll) {
            const newID = Lute.NewNodeID();
            const emptyElement = genEmptyElement(false, true, newID);
            protyle.wysiwyg.element.insertAdjacentElement("afterbegin", emptyElement);
            const emptyOperation: IOperation = {
                action: "insert",
                data: emptyElement.outerHTML,
                id: newID,
                parentID: protyle.block.parentID
            };
            if (options.templateDocTreePlanID) {
                // 文档树计划必须与父文档的全部变更保持在同一事务中。
                options.doOperations.push(emptyOperation);
                options.undoOperations.unshift({
                    action: "delete",
                    id: newID,
                });
            } else {
                transaction(protyle, [emptyOperation]);
            }
            // 普通编辑不记录撤销,否则会无限循环;文档树计划随主事务统一撤销。
            focusByWbr(emptyElement, range);
        }
    }
    if (!options.skipSync) {
        syncTrackedRanges(protyle, options.doOperations, options.trackedRangeInsertion);
    }
    const queuedTransaction = {
        transaction: {
            doOperations: options.doOperations,
            undoOperations: options.undoOperations,// 目前用于 ws 推送更新大纲
            templateDocTreePlanID: options.templateDocTreePlanID,
        },
        callback: (responseTransaction: {doOperations: IOperation[]}) => {
            // 新增和更新的数据库载体必须在事务成功后渲染,确保内核已登记块及其笔记本归属。
            responseTransaction.doOperations.forEach(operation => {
                if (operation.action === "insert" || operation.action === "update") {
                    protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach(item => {
                        pendingAVElements.add(item);
                    });
                }
            });
            const avElements = new Set<Element>();
            pendingAVElements.forEach(item => {
                if (item.getAttribute("data-type") === "NodeAttributeView") {
                    avElements.add(item);
                } else {
                    item.querySelectorAll('[data-type="NodeAttributeView"]').forEach(avElement => {
                        avElements.add(avElement);
                    });
                }
            });
            avElements.forEach(item => {
                if (item.isConnected) {
                    avRender(item, protyle);
                }
            });
            invalidateViewFoldRequests(protyle);
            const ids = getBlockSelectionStatusIDs(protyle.wysiwyg.element);
            countBlockWord(ids, protyle, true);
            if (!options.skipSync) {
                responseTransaction.doOperations.forEach((operation: IOperation) => {
                    if (operation.action === "swapBlockRef" && operation.retData?.length) {
                        reloadProtyle(protyle, false);
                        return;
                    }
                    if (handleViewFoldSourceOperation(protyle, operation)) {
                        return;
                    }
                    if (operation.action === "unfoldHeading" || operation.action === "foldHeading") {
                        processFold(operation, protyle);
                        return;
                    }
                    if (operation.action === "setAttrs") {
                        syncBlockAttrs(protyle.wysiwyg.element, operation);
                    }
                    // 冻结范围依赖列的 DOM 分组,新增列事务落盘后使用完整数据重建分组。
                    if (operation.action === "addAttrViewCol" &&
                        protyle.wysiwyg.element.querySelector(
                            `.av[data-av-id="${operation.avID}"] [data-freeze="true"]`
                        )) {
                        refreshAV(protyle, operation);
                    }
                });
            }
            // 事务提交后再渲染嵌入块,避免其查询请求早于写入到达内核而拿到旧数据
            pendingEmbedElements.forEach(item => {
                if (item.isConnected) {
                    item.removeAttribute("data-render");
                    blockRender(protyle, item);
                }
            });
            queueHeadingNumberRefresh(protyle, responseTransaction.doOperations);
            refreshHeadingFoldIndicators(protyle);
            void applyViewFoldStates(protyle);
            options.callback?.();
        },
    };
    const submitTransactions = (items: typeof queuedTransaction[]) => fetchPost("/api/transactions", {
        reqId: Date.now(),
        session: protyle.id,
        app: Constants.SIYUAN_APPID,
        transactions: items.map(item => item.transaction),
    }, (response) => {
        items.forEach((item, index) => {
            const result = response.data?.[index];
            if (result) {
                item.callback(getEditorTransaction(result));
            }
        });
    });
    // 仅批量提交无回调的普通块更新,结构事务需要保持逐笔提交语义。
    const batchable = !options.callback && !options.templateDocTreePlanID && options.doOperations.length === 1 &&
        options.doOperations[0].action === "update";
    if (batchable) {
        queueTransactionBatch(protyle, "blockUpdates", queuedTransaction, submitTransactions);
    } else {
        queueTransaction(protyle, () => submitTransactions([queuedTransaction]));
    }
};

const containsOperationAnchor = (element: Element, operation: IOperation) => {
    const ids = new Set<string>();
    [operation.previousID, operation.nextID, operation.parentID].forEach(id => {
        if (id) {
            ids.add(id);
        }
    });
    return Array.from(element.querySelectorAll("[data-node-id]")).some(item => {
        const id = item.getAttribute("data-node-id");
        return isInEmbedBlock(item, false) === element && !!id && ids.has(id);
    });
};

const getDocumentEmbedResults = (element: Element, targetID?: string) => {
    if (!targetID) {
        return [];
    }
    return Array.from(element.querySelectorAll<HTMLElement>(
        ".protyle-wysiwyg__embed[data-allow-child-operation=\"true\"]"
    )).filter(item => item.getAttribute("data-id") === targetID && !getEmbedChildOperationContext(item)?.targetElement);
};

// 刷新一组块元素所在超级块的拖拽手柄(自动去重,跳过已脱离 DOM 的)
const refreshSbs = (...elements: (Element | undefined | null)[]) => {
    const sbs = new Set<Element>();
    elements.forEach(el => {
        if (el) {
            const sb = el.closest('[data-type="NodeSuperBlock"]');
            if (sb && sb.parentElement) {
                sbs.add(sb);
            }
        }
    });
    sbs.forEach(sb => refreshSbResize(sb));
};

const deleteBlock = (updateElements: Element[], id: string, protyle: IProtyle, isUndo: boolean,
                     deferUndoFocus = false) => {
    if (isUndo && updateElements[0] && !deferUndoFocus) {
        focusSideBlock(updateElements[0]);
    }
    // 删除前记录所在超级块,删除后刷新其拖拽手柄
    const sbParents: Element[] = [];
    updateElements.forEach(item => {
        const sbAncestor = item.closest('[data-type="NodeSuperBlock"]');
        if (sbAncestor && !sbParents.includes(sbAncestor)) {
            sbParents.push(sbAncestor);
        }
        if (isUndo) {
            // https://github.com/siyuan-note/siyuan/issues/13617
            item.remove();
        } else {
            // 需移除顶层,否则删除唯一的列表项后列表无法清除干净 https://github.com/siyuan-note/siyuan/issues/12326 第一点
            const topElement = getTopAloneElement(item);
            if (topElement) {
                topElement.remove();
            }
        }
    });
    // 更新 ws 嵌入块
    protyle.wysiwyg.element.querySelectorAll('[data-type="NodeBlockQueryEmbed"]').forEach((item) => {
        if (item.querySelector(`[data-node-id="${id}"]`)) {
            item.removeAttribute("data-render");
            blockRender(protyle, item);
        }
    });
    // 删除块后刷新所在超级块的拖拽手柄(被删块两侧的手柄需移除/重建,即使只剩 0/1 块也清残留)
    refreshSbs(...sbParents);
};

const updateBlock = (updateElements: Element[], protyle: IProtyle, operation: Extract<IOperation, {action: "update"}>, isUndo: boolean) => {
    const range = getSelection().rangeCount > 0 ? getSelection().getRangeAt(0) : null;
    // 撤销按快照中的光标返回操作块;同 ID 副本优先使用当前选区所在的实例,其次使用源块。
    const focusElement = isUndo ? updateElements.find(item => range && item.contains(range.startContainer)) ||
        updateElements.find(item => !isInEmbedBlock(item, false)) || updateElements[0] : undefined;
    updateElements.forEach(item => {
        // 前序局部回放可能已替换包含该块的祖先,跳过失效引用。
        if (!item.parentElement) {
            return;
        }
        // 完整脑图快照保留画布实例;必须先于折叠正文裁剪和整个视图的销毁。
        if (isUndo && operation.context?.mindmapSnapshotId === operation.id) {
            const selectionModeState = captureBlockSelectionModeState(item);
            if (replayListMindmap(protyle.wysiwyg.element, item, operation)) {
                focusRestoredBlockSelectionMode(restoreBlockSelectionModeState(protyle.wysiwyg.element, item,
                    selectionModeState));
                return;
            }
        }
        let isRangeBlock = false;
        if (range && item.contains(range.startContainer)) {
            isRangeBlock = true;
        }
        const isFocusBlock = item === focusElement;
        // 表格的横向、纵向滚动均发生在首个子节点(contenteditable 容器,overflow:auto)上,
        // 更新块后需一并还原,否则固定表头长表格撤销/重做会跳回开头
        // https://github.com/siyuan-note/siyuan/issues/3650 https://github.com/siyuan-note/siyuan/issues/18035
        // https://github.com/siyuan-note/siyuan/issues/18235
        let tableScrollLeft: number;
        let tableScrollTop: number;
        let contentScrollTop: number;
        if (item.classList.contains("table")) {
            tableScrollLeft = (item.firstElementChild as HTMLElement).scrollLeft;
            tableScrollTop = (item.firstElementChild as HTMLElement).scrollTop;
            if (isRangeBlock) {
                contentScrollTop = protyle.contentElement.scrollTop;
            }
        }
        const data = item.getAttribute("data-subtype") === "echarts" ?
            // 图标撤销后无法渲染
            protyle.lute.SpinBlockDOM(operation.data) : operation.data;
        const selectionModeState = captureBlockSelectionModeState(item);
        disposeCustomBlocksInElement(item);
        item.insertAdjacentHTML("afterend", getVisibleFoldHeadingHTML(data));
        item = item.nextElementSibling;
        item.previousElementSibling.remove();
        const restoredSelectionModeElement = restoreBlockSelectionModeState(protyle.wysiwyg.element, item,
            selectionModeState);

        const wbrElement = item.querySelector("wbr");
        const codeElement = item.getAttribute("data-type") === "NodeCodeBlock" ? item.querySelector(".hljs") : undefined;
        const restoreCaret = isFocusBlock && !!wbrElement;
        // 未高亮的代码块由 highlightRender 使用 wbr 记录偏移,并在重建 DOM 后恢复光标。
        const deferCodeBlockCaretRestore = shouldDeferCodeBlockCaretRestore({
            isRangeBlock: restoreCaret,
            isReplay: isUndo,
            hasCaret: !!wbrElement,
            isCodeBlock: !!codeElement,
            isRendered: codeElement?.getAttribute("data-render") === "true",
        });
        if (isUndo && (restoreCaret || isRangeBlock)) {
            if (wbrElement) {
                focusByWbr(item, range || document.createRange(), deferCodeBlockCaretRestore);
            } else {
                focusBlock(item);
            }
        }
        if (!deferCodeBlockCaretRestore) {
            wbrElement?.remove();
        }
        // update 操作会生成新表格并替换旧节点,聚焦后需还原滚动,避免表格跳回开头
        if (tableScrollLeft > 0) {
            (item.firstElementChild as HTMLElement).scrollLeft = tableScrollLeft;
        }
        if (tableScrollTop > 0) {
            (item.firstElementChild as HTMLElement).scrollTop = tableScrollTop;
        }
        if (contentScrollTop > 0) {
            protyle.contentElement.scrollTop = contentScrollTop;
            protyle.scroll.lastScrollTop = contentScrollTop - 1;
        }

        processRender(item);
        highlightRender(item);
        avRender(item, protyle);
        blockRender(protyle, item);
        focusRestoredBlockSelectionMode(restoredSelectionModeElement);
    });
};

// 用于推送和撤销;普通模式在内核事务完成后回放,lite 模式仅更新本地 DOM。
export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUndo: boolean,
                              preserveTrackedRanges = isUndo) => {
    if (protyle.wysiwyg.element.firstElementChild?.classList.contains("protyle-password")) {
        return;
    }
    if (!preserveTrackedRanges) {
        invalidateTrackedRangesByOperations(protyle, operations);
    }
    invalidateViewFoldRequests(protyle);
    const undoFocusContext = isUndo ? operations.find(item => item.context?.undoFocusId)?.context : undefined;
    const deferUndoFocus = !!undoFocusContext?.undoFocusEmbedId;
    const pendingUndoEmbedElements = new Set<Element>();
    operations.forEach(operation => {
        if (operation.action === "convertList") {
            refreshListConversion(protyle, operation.retData, isUndo);
            return;
        }
        if (operation.action === "swapBlockRef") {
            if (operation.retData?.includes(protyle.block.rootID)) {
                reloadProtyle(protyle, false);
            } else if (operation.retData?.length) {
                protyle.wysiwyg.element.querySelectorAll('[data-type="NodeBlockQueryEmbed"]').forEach(item => {
                    item.removeAttribute("data-render");
                    blockRender(protyle, item);
                });
            }
            return;
        }
        if (handleViewFoldSourceOperation(protyle, operation)) {
            return;
        }
        const updateElements: Element[] = [];
        Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)).forEach(item => {
            updateElements.push(item);
        });
        if (operation.action === "setAttrs") {
            syncBlockAttrs(protyle.wysiwyg.element, operation);
            return;
        }
        if (operation.action === "unfoldHeading") {
            const visibleRetData = typeof operation.retData === "string" ?
                getVisibleFoldHeadingHTML(operation.retData) : "";
            protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach(item => {
                item.removeAttribute("fold");
                if (isUndo) {
                    // kernel 权威撤销:retData 已由 doUnfoldHeading 填充,需要插入子块 HTML 恢复折叠的内容
                    if (visibleRetData) {
                        removeUnfoldRepeatBlock(visibleRetData, protyle);
                        item.insertAdjacentHTML("afterend", visibleRetData);
                    }
                    return;
                }
                const embedElement = isInEmbedBlock(item);
                if (embedElement) {
                    embedElement.removeAttribute("data-render");
                    blockRender(protyle, embedElement);
                    return;
                }
                if (visibleRetData) {
                    removeUnfoldRepeatBlock(visibleRetData, protyle);
                    item.insertAdjacentHTML("afterend", visibleRetData);
                }
                if (operation.data === "remove") {
                    item.remove();
                }
            });
            if (visibleRetData) {
                if (protyle.disabled) {
                    disabledProtyle(protyle);
                }
                processRender(protyle.wysiwyg.element);
                highlightRender(protyle.wysiwyg.element);
                avRender(protyle.wysiwyg.element, protyle);
                blockRender(protyle, protyle.wysiwyg.element);
                // 展开标题插入的块可能落在超级块内,刷新手柄避免与既有手柄重复/错位
                refreshSbs(...Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)));
            }
            return;
        }
        if (operation.action === "foldHeading") {
            const hadContent = protyle.wysiwyg.element.childElementCount > 0;
            protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach(item => {
                item.setAttribute("fold", "1");
                if (!operation.retData) {
                    removeFoldHeading(item);
                }
            });
            if (Array.isArray(operation.retData)) {
                operation.retData.forEach((item: string) => {
                    let embedElement: HTMLElement | false;
                    Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${item}"]`)).find(itemElement => {
                        embedElement = isInEmbedBlock(itemElement);
                        if (embedElement) {
                            return true;
                        }
                        itemElement.remove();
                    });
                    // 折叠嵌入块的父级
                    if (embedElement) {
                        embedElement.removeAttribute("data-render");
                        blockRender(protyle, embedElement);
                    }
                });
                // 折叠移除子块后,刷新折叠标题所在超级块的拖拽手柄(子块数变化)
                refreshSbs(...Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)));
                if (hadContent && protyle.block.rootID && protyle.wysiwyg.element.childElementCount === 0) {
                    zoomOut({
                        protyle,
                        id: protyle.block.rootID,
                        isPushBack: false,
                        focusId: operation.id,
                    });
                }
            }
            return;
        }
        if (operation.action === "delete") {
            if (updateElements.length > 0 || !isUndo) {
                deleteBlock(updateElements, operation.id, protyle, isUndo, deferUndoFocus);
            } else if (isUndo) {
                zoomOut({
                    protyle,
                    id: protyle.block.rootID,
                    isPushBack: false,
                    focusId: operation.id,
                    callback() {
                        Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)).forEach(item => {
                            if (!isInEmbedBlock(item)) {
                                updateElements.push(item);
                            }
                        });
                        deleteBlock(updateElements, operation.id, protyle, isUndo, deferUndoFocus);
                    }
                });
            }
            return;
        }
        if (operation.action === "update") {
            // 缩放后仅更新局部 https://github.com/siyuan-note/siyuan/issues/14326
            if (updateElements.length === 0) {
                const newUpdateElement = protyle.wysiwyg.element.querySelector("[data-node-id]");
                if (newUpdateElement) {
                    const newUpdateId = newUpdateElement.getAttribute("data-node-id");
                    const tempElement = document.createElement("template");
                    tempElement.innerHTML = operation.data;
                    const newTempElement = tempElement.content.querySelector(`[data-node-id="${newUpdateId}"]`);
                    if (newTempElement) {
                        // 局部回放脱离容器前,保留页签项继承的任务状态。
                        preserveTabTask(newTempElement, newTempElement);
                        updateElements.push(newUpdateElement);
                        operation.data = newTempElement.outerHTML;
                        operation.id = newUpdateId;
                        // https://github.com/siyuan-note/siyuan/issues/14326#issuecomment-2746140335
                        // 普通缩放编辑器只保留局部更新块;反向链接包含面包屑和其他上下文,不能清理根节点。
                        const rootElements = Array.from(protyle.wysiwyg.element.children);
                        const updateRootElement = rootElements.find(item =>
                            item === newUpdateElement || item.contains(newUpdateElement));
                        getPartialUpdateCleanupElements(
                            rootElements,
                            updateRootElement,
                            Boolean(protyle.options.backlinkData),
                        ).forEach(item => item.remove());
                    }
                }
            }
            if (updateElements.length > 0) {
                updateBlock(updateElements, protyle, operation, isUndo);
            } else if (isUndo) {
                zoomOut({
                    protyle,
                    id: protyle.block.rootID,
                    isPushBack: false,
                    focusId: operation.id,
                    callback() {
                        Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)).forEach(item => {
                            if (!isInEmbedBlock(item)) {
                                updateElements.push(item);
                            }
                        });
                        updateBlock(updateElements, protyle, operation, isUndo);
                    }
                });
            }
            return;
        }
        if (operation.action === "updateAttrs") { // 调用接口才推送
            const data = operation.data as any;
            const mermaidLayoutChanged = data.new[MERMAID_LAYOUT_ATTR] !== data.old[MERMAID_LAYOUT_ATTR];
            const attrsResult: Record<string, string> = {};
            let bookmarkHTML = "";
            let nameHTML = "";
            let aliasHTML = "";
            let memoHTML = "";
            let avHTML = "";
            Object.keys(data.new).forEach(key => {
                attrsResult[key] = data.new[key];
                const escapeHTML = escapeHtmlTextAndAttr(data.new[key]);
                if (key === "bookmark") {
                    bookmarkHTML = `<div class="protyle-attr--bookmark">${escapeHTML}</div>`;
                } else if (key === "name") {
                    nameHTML = `<div class="protyle-attr--name"><svg><use xlink:href="#iconN"></use></svg>${escapeHTML}</div>`;
                } else if (key === "alias") {
                    aliasHTML = `<div class="protyle-attr--alias"><svg><use xlink:href="#iconA"></use></svg>${escapeHTML}</div>`;
                } else if (key === "memo") {
                    memoHTML = `<div class="protyle-attr--memo ariaLabel" aria-label="${escapeHTML}" data-position="north"><svg><use xlink:href="#iconM"></use></svg></div>`;
                } else if (key === "custom-avs" && data.new["av-names"]) {
                    avHTML = `<div class="protyle-attr--av"><svg><use xlink:href="#iconDatabase"></use></svg>${(data.new["av-names"])}</div>`;
                }
            });
            let nodeAttrHTML = bookmarkHTML + nameHTML + aliasHTML + memoHTML + avHTML;
            if (protyle.block.rootID === operation.id) {
                // 文档
                if (protyle.title) {
                    if (data.new["custom-avs"] && !data.new["av-names"]) {
                        nodeAttrHTML += protyle.title.element.querySelector(".protyle-attr--av")?.outerHTML || "";
                    }
                    const refElement = protyle.title.element.querySelector(".protyle-attr--refcount");
                    if (refElement) {
                        nodeAttrHTML += refElement.outerHTML;
                    }
                    if (data.new[Constants.CUSTOM_RIFF_DECKS] && data.new[Constants.CUSTOM_RIFF_DECKS] !== data.old[Constants.CUSTOM_RIFF_DECKS]) {
                        protyle.title.element.style.animation = "addCard 450ms linear";
                        protyle.title.element.setAttribute(Constants.CUSTOM_RIFF_DECKS, data.new[Constants.CUSTOM_RIFF_DECKS]);
                        setTimeout(() => {
                            protyle.title.element.style.animation = "";
                        }, 450);
                    } else if (!data.new[Constants.CUSTOM_RIFF_DECKS]) {
                        protyle.title.element.removeAttribute(Constants.CUSTOM_RIFF_DECKS);
                    }
                    protyle.title.element.querySelector(".protyle-attr").innerHTML = nodeAttrHTML;
                }
                protyle.wysiwyg.renderCustom(attrsResult);
                if (data.new[Constants.CUSTOM_SY_FULLWIDTH] !== data.old[Constants.CUSTOM_SY_FULLWIDTH]) {
                    resize(protyle);
                }
                if (data.new[Constants.CUSTOM_SY_READONLY] !== data.old[Constants.CUSTOM_SY_READONLY]) {
                    let customReadOnly = data.new[Constants.CUSTOM_SY_READONLY];
                    if (!customReadOnly) {
                        customReadOnly = window.siyuan.config.editor.readOnly ? "true" : "false";
                    }
                    if (customReadOnly === "true") {
                        disabledProtyle(protyle);
                    } else {
                        enableProtyle(protyle);
                    }
                }
                const backgroundChanged = data.new.icon !== data.old.icon ||
                    data.new["title-img"] !== data.old["title-img"] ||
                    data.new.tags !== data.old.tags;
                if (backgroundChanged) {
                    /// #if MOBILE
                    protyle = window.siyuan.mobile.editor.protyle;
                    /// #endif
                    if (protyle.background) {
                        protyle.background.ial.icon = data.new.icon;
                        protyle.background.ial.tags = data.new.tags;
                        protyle.background.ial["title-img"] = data.new["title-img"];
                        protyle.background.render(protyle.background.ial, protyle.block.rootID);
                    }
                    if (data.new.icon !== data.old.icon) {
                        protyle.model?.parent.setDocIcon(data.new.icon);
                    }
                }
                return;
            }
            protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach((item: HTMLElement) => {
                if (item.getAttribute("data-type") === "NodeThematicBreak") {
                    return;
                }
                Object.keys(data.old).forEach(key => {
                    item.removeAttribute(key);
                    if (key === "custom-avs") {
                        item.removeAttribute("av-names");
                    }
                });
                if (data.new.style && data.new[Constants.CUSTOM_RIFF_DECKS] && data.new[Constants.CUSTOM_RIFF_DECKS] !== data.old[Constants.CUSTOM_RIFF_DECKS]) {
                    data.new.style += ";animation:addCard 450ms linear";
                }
                Object.keys(data.new).forEach(key => {
                    if ("id" === key) {
                        // 设置属性以后不应该给块元素添加 id 属性 No longer add the `id` attribute to block elements after setting the attribute https://github.com/siyuan-note/siyuan/issues/15327
                        return;
                    }

                    item.setAttribute(key, data.new[key]);
                    if (key === Constants.CUSTOM_RIFF_DECKS &&
                        data.new[Constants.CUSTOM_RIFF_DECKS] !== data.old[Constants.CUSTOM_RIFF_DECKS]) {
                        item.style.animation = "addCard 450ms linear";
                        setTimeout(() => {
                            if (item.parentElement) {
                                item.style.animation = "";
                            } else {
                                protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach((realItem: HTMLElement) => {
                                    realItem.style.animation = "";
                                });
                            }
                        }, 450);
                    }
                });
                syncBlockDirection(item);
                // 已渲染数据库的布局类型随新内容一起更新,避免旧内容提前套用新布局样式。
                if (data["data-av-type"] && !item.querySelector(".av__container")) {
                    item.setAttribute("data-av-type", data["data-av-type"]);
                }
                const attrElements = item.querySelectorAll(".protyle-attr");
                const attrElement = attrElements[attrElements.length - 1];
                if (data.new["custom-avs"] && !data.new["av-names"]) {
                    nodeAttrHTML += attrElement.querySelector(".protyle-attr--av")?.outerHTML || "";
                }
                const refElement = attrElement.querySelector(".protyle-attr--refcount");
                if (refElement) {
                    nodeAttrHTML += refElement.outerHTML;
                }
                attrElement.innerHTML = nodeAttrHTML + Constants.ZWSP;
                if (data.new["custom-heading-level"] !== data.old["custom-heading-level"] &&
                    item.getAttribute("data-type") === "NodeBlockQueryEmbed") {
                    renderEmbedHeadings(item);
                }
                if (mermaidLayoutChanged && item.getAttribute("data-subtype") === "mermaid") {
                    item.removeAttribute("data-render");
                    processRender(item);
                }
            });
            return;
        }
        if (operation.action === "move") {
            if (operation.context?.ignoreProcess === "true") {
                return;
            }
            /// #if !MOBILE
            if (updateElements.length === 0) {
                // 打开两个相同的文档 A、A1,从 A 拖拽块 B 到 A1,在后续 ws 处理中,无法获取到拖拽出去的 B
                getAllModels().editor.forEach(editor => {
                    const updateCloneElement = editor.editor.protyle.wysiwyg.element.querySelector(`[data-node-id="${operation.id}"]`);
                    if (updateCloneElement) {
                        updateElements.push(updateCloneElement.cloneNode(true) as Element);
                    }
                });
            }
            if (updateElements.length === 0) {
                // 页签拖入浮窗 https://github.com/siyuan-note/siyuan/issues/6647
                window.siyuan.blockPanels.forEach((item) => {
                    const updateCloneElement = item.element.querySelector(`[data-node-id="${operation.id}"]`);
                    if (updateCloneElement) {
                        updateElements.push(updateCloneElement.cloneNode(true) as Element);
                    }
                });
            }
            /// #endif
            // 折叠标题移动到横向超级块的第一个块上后撤销
            if (updateElements.length === 0) {
                const tempEl = document.createElement("div");
                tempEl.setAttribute("data-node-id", operation.id);
                tempEl.setAttribute("data-protyle-id", protyle.element.getAttribute("data-id"));
                updateElements.push(tempEl);
                fetchPost("/api/block/getBlockDOM", {
                    id: operation.id,
                    notebook: protyle.notebookId,
                }, (response) => {
                    document.querySelectorAll(`.protyle-wysiwyg [data-node-id="${response.data.id}"]`).forEach(item => {
                        if (item.getAttribute("data-protyle-id") === protyle.element.getAttribute("data-id") &&
                            item.closest(".protyle-wysiwyg") === protyle.wysiwyg.element) {
                            const template = document.createElement("template");
                            template.innerHTML = getVisibleFoldHeadingHTML(response.data.dom);
                            const replacements = Array.from(template.content.children);
                            if (replacements.length) {
                                item.replaceWith(template.content);
                                replacements.forEach(replacement => { void avRender(replacement, protyle); });
                            }
                        }
                    });
                });
            }
            const moveElementGroups = updateElements.map(item => getVisibleMoveElements(item, operation.blockIDs));
            const primaryMoveElements = moveElementGroups[0] || [];
            const moveElements = Array.from(new Set(moveElementGroups.flat()));
            let range;
            if (isUndo && getSelection().rangeCount > 0) {
                range = getSelection().getRangeAt(0);
                const rangeBlockElement = hasClosestBlock(range.startContainer);
                if (rangeBlockElement) {
                    if (getContenteditableElement(rangeBlockElement)) {
                        range.insertNode(document.createElement("wbr"));
                    } else {
                        getContenteditableElement(updateElements[0])?.insertAdjacentHTML("afterbegin", "<wbr>");
                    }
                }
            }
            let hasFind = false;
            // 移动前记录源块所在的超级块,移动后刷新其拖拽手柄(移出后手柄需清理)
            // https://github.com/siyuan-note/siyuan/issues/9521
            const originSbs: Element[] = [];
            moveElements.forEach(item => {
                const sb = item.closest('[data-type="NodeSuperBlock"]');
                if (sb && !originSbs.includes(sb)) {
                    originSbs.push(sb);
                }
            });
            if (operation.nextID && updateElements.length > 0) {
                protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.nextID}"]`).forEach(item => {
                    if (!isInEmbedBlock(item)) {
                        item.before(...primaryMoveElements.map(element => element.cloneNode(true)));
                        hasFind = true;
                    }
                });
            } else if (operation.previousID && updateElements.length > 0) {
                const previousElement = protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.previousID}"]`);
                if (previousElement.length === 0 && protyle.options.backlinkData && isUndo && getSelection().rangeCount > 0) {
                    // 反链面板删除超级块中的最后一个段落块后撤销重做
                    const blockElement = hasTopClosestByAttribute(range.startContainer, "data-node-id", null);
                    if (blockElement) {
                        blockElement.before(...primaryMoveElements.map(element => element.cloneNode(true)));
                        hasFind = true;
                    }
                } else {
                    previousElement.forEach(item => {
                        if (!isInEmbedBlock(item)) {
                            item.after(...primaryMoveElements.map(element => element.cloneNode(true)));
                            hasFind = true;
                        }
                    });
                }
            } else if (updateElements.length > 0) {
                const parentElement = protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.parentID}"]`);
                if (!protyle.options.backlinkData && operation.parentID === protyle.block.parentID && !protyle.block.showAll) {
                    protyle.wysiwyg.element.prepend(...primaryMoveElements.map(element => element.cloneNode(true)));
                    hasFind = true;
                } else if (parentElement.length === 0 && protyle.options.backlinkData && isUndo && getSelection().rangeCount > 0) {
                    // 反链面板删除超级块中的段落块后撤销再重做 https://github.com/siyuan-note/siyuan/issues/14496#issuecomment-2771372486
                    const topBlockElement = hasTopClosestByAttribute(getSelection().getRangeAt(0).startContainer, "data-node-id", null);
                    if (topBlockElement) {
                        topBlockElement.before(...primaryMoveElements.map(element => element.cloneNode(true)));
                        hasFind = true;
                    }
                } else {
                    parentElement.forEach(item => {
                        if (!isInEmbedBlock(item)) {
                            const cloneElements = primaryMoveElements.map(element => element.cloneNode(true));
                            // 列表特殊处理
                            if (item.firstElementChild?.classList.contains("protyle-action")) {
                                item.firstElementChild.after(...cloneElements);
                            } else if ((item.classList.contains("callout") || item.classList.contains("tab-item"))) {
                                item.querySelector(":scope > .callout-content, :scope > .tab-item-content").prepend(...cloneElements);
                            } else {
                                item.prepend(...cloneElements);
                            }
                            hasFind = true;
                        }
                    });
                }
            }
            moveElements.forEach(item => {
                if (hasFind) {
                    item.remove();
                } else if (!hasFind && item.parentElement) {
                    removeTopElement(item, protyle);
                }
            });
            if (isUndo && range) {
                if (operation.data === "focus") {
                    // 标记需要 focus,https://ld246.com/article/1650018446988/comment/1650081404993?r=Vanessa#comments
                    Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)).find(item => {
                        if (!isInEmbedBlock(item)) {
                            focusBlock(item);
                            return true;
                        }
                    });
                    document.querySelectorAll("wbr").forEach(item => {
                        item.remove();
                    });
                } else {
                    focusByWbr(protyle.wysiwyg.element, range);
                }
            }
            // 更新嵌入块。undo 已由 kernel 执行事务后广播,查询能拿到最新数据,无竞态。
            getMoveAffectedEmbedElements(
                protyle.wysiwyg.element.querySelectorAll('[data-type="NodeBlockQueryEmbed"]'),
                operation,
            ).forEach(item => {
                if (undoFocusContext?.undoFocusEmbedId === item.getAttribute("data-node-id")) {
                    // 当前嵌入块需在撤销操作全部回放后渲染,否则中途移除选区会把光标带到源块
                    pendingUndoEmbedElements.add(item);
                } else {
                    item.removeAttribute("data-render");
                    blockRender(protyle, item);
                }
            });
            // 移动块(含重做/同步)后刷新相关超级块的拖拽手柄
            const moveEls = [operation.id, operation.parentID, operation.previousID, operation.nextID]
                .map(id => id ? protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`) : null)
                .filter(Boolean) as Element[];
            refreshSbs(...moveEls);
            // 块移出后刷新源超级块的手柄(originSb 在元素被移除前捕获,仅含移出侧的超级块)
            // https://github.com/siyuan-note/siyuan/issues/9521
            refreshSbs(...originSbs);
            return;
        }
        if (operation.action === "insert") {
            if (operation.context?.ignoreProcess === "true") {
                return;
            }
            const visibleData = getVisibleFoldHeadingHTML(operation.data);
            const cursorElements: Element[] = [];
            const renderElements: Element[] = [];
            if (operation.previousID) {
                const previousElement = protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.previousID}"]`);
                if (previousElement.length === 0 && isUndo && protyle.wysiwyg.element.childElementCount === 0) {
                    // https://github.com/siyuan-note/siyuan/issues/15396 操作后撤销
                    protyle.wysiwyg.element.innerHTML = visibleData;
                    renderElements.push(...Array.from(protyle.wysiwyg.element.children));
                    cursorElements.push(protyle.wysiwyg.element.firstElementChild);
                } else if (previousElement.length === 0 && protyle.options.backlinkData && isUndo && getSelection().rangeCount > 0) {
                    // 反链面板删除超级块中的最后一个段落块后撤销
                    const blockElement = hasClosestBlock(getSelection().getRangeAt(0).startContainer);
                    if (blockElement) {
                        renderElements.push(...insertTransactionHTML(blockElement, "beforebegin", visibleData));
                        cursorElements.push(blockElement.previousElementSibling);
                    }
                } else {
                    previousElement.forEach(item => {
                        const embedElement = isInEmbedBlock(item, false);
                        if (embedElement) {
                            // https://github.com/siyuan-note/siyuan/issues/5524
                            embedElement.removeAttribute("data-render");
                            blockRender(protyle, embedElement);
                        } else {
                            renderElements.push(...insertTransactionHTML(item, "afterend", visibleData));
                            cursorElements.push(item.nextElementSibling);
                        }
                    });
                }
            } else if (operation.nextID) {
                Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.nextID}"]`)).forEach(item => {
                    const embedElement = isInEmbedBlock(item, false);
                    if (embedElement) {
                        // https://github.com/siyuan-note/siyuan/issues/5524
                        embedElement.removeAttribute("data-render");
                        blockRender(protyle, embedElement);
                    } else {
                        renderElements.push(...insertTransactionHTML(item, "beforebegin", visibleData));
                        cursorElements.push(item.previousElementSibling);
                    }
                });
            } else {
                const parentElement = protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.parentID}"]`);
                getDocumentEmbedResults(protyle.wysiwyg.element, operation.parentID).forEach(item => {
                    const embedElement = isInEmbedBlock(item, false);
                    if (embedElement) {
                        embedElement.removeAttribute("data-render");
                        blockRender(protyle, embedElement);
                    }
                });
                if (!protyle.options.backlinkData && operation.parentID === protyle.block.parentID && !protyle.block.showAll) {
                    renderElements.push(...insertTransactionHTML(protyle.wysiwyg.element, "afterbegin", visibleData));
                    cursorElements.push(protyle.wysiwyg.element.firstElementChild);
                } else if (parentElement.length === 0 && protyle.options.backlinkData && isUndo && getSelection().rangeCount > 0) {
                    // 反链面板删除超级块中的段落块后撤销
                    const blockElement = hasClosestBlock(getSelection().getRangeAt(0).startContainer);
                    if (blockElement) {
                        renderElements.push(...insertTransactionHTML(blockElement, "beforebegin", visibleData));
                        cursorElements.push(blockElement.previousElementSibling);
                    }
                } else {
                    parentElement.forEach(item => {
                        const embedElement = isInEmbedBlock(item, false);
                        if (embedElement) {
                            embedElement.removeAttribute("data-render");
                            blockRender(protyle, embedElement);
                        } else {
                            // 列表特殊处理
                            if (item.firstElementChild?.classList.contains("protyle-action")) {
                                renderElements.push(...insertTransactionHTML(item.firstElementChild, "afterend", visibleData));
                                cursorElements.push(item.firstElementChild.nextElementSibling);
                            } else if ((item.classList.contains("callout") || item.classList.contains("tab-item"))) {
                                renderElements.push(...insertTransactionHTML(item.querySelector(":scope > .callout-content, :scope > .tab-item-content"), "afterbegin", visibleData));
                                cursorElements.push(item.querySelector("[data-node-id]"));
                            } else {
                                renderElements.push(...insertTransactionHTML(item, "afterbegin", visibleData));
                                cursorElements.push(item.firstElementChild);
                            }
                        }
                    });
                }
            }
            // https://github.com/siyuan-note/siyuan/issues/4420
            protyle.wysiwyg.element.querySelectorAll('[data-type="NodeHeading"]').forEach(item => {
                if (item.lastElementChild.getAttribute("spin") === "1") {
                    item.lastElementChild.remove();
                }
            });
            if (cursorElements.length === 0) {
                return;
            }
            cursorElements.forEach(item => {
                // https://github.com/siyuan-note/siyuan/issues/16554
                item.querySelector(".protyle-attr--av")?.remove();
                item.removeAttribute("custom-avs");
                item.getAttributeNames().forEach(attr => {
                    if (attr.startsWith(Constants.CUSTOM_SY_AV_STATIC_TEXT)) {
                        item.removeAttribute(attr);
                    }
                });
            });
            renderElements.forEach(item => {
                processRender(item);
                highlightRender(item);
                avRender(item, protyle);
                blockRender(protyle, item);
                // 插入块后刷新所在超级块的拖拽手柄(撤销/重做/同步)
                refreshSbs(item);
            });
            cursorElements.forEach(item => {
                const wbrElement = item.querySelector("wbr");
                if (isUndo) {
                    if (operation.context?.setRange === "true") {
                        const range = getEditorRange(item);
                        if (wbrElement) {
                            focusByWbr(item, range);
                        } else {
                            focusBlock(item);
                        }
                    }
                } else if (wbrElement) {
                    wbrElement.remove();
                }
            });
            protyle.wysiwyg.element.querySelectorAll("[parent-heading]").forEach(item => {
                item.remove();
            });
            return;
        }
        if (operation.action === "append") {
            // 目前只有移动块的时候会调用,反连面板就自己点击刷新处理。
            if (!protyle.options.backlinkData) {
                reloadProtyle(protyle, false);
            }
            return;
        }
        if (operation.action === "sortAttrViewBinding") {
            protyle.databaseAttributePanel?.refreshForOperation(operation);
            return;
        }
        if (["addAttrViewCol", "updateAttrViewCol", "updateAttrViewColOptions",
            "updateAttrViewColOption", "updateAttrViewCell", "updateAttrViewCells", "sortAttrViewRow", "sortAttrViewCol", "setAttrViewColHidden",
            "setAttrViewColWrap", "setAttrViewColWidth", "setAttrViewColsWidth", "setAttrViewColAlign", "removeAttrViewColOption", "setAttrViewName", "setAttrViewFilters",
            "setAttrViewSorts", "setAttrViewNewItemTemplates", "setAttrViewAutomations", "collectAttrViewBlocks", "setAttrViewCustomColors", "setAttrViewColCalc", "removeAttrViewCol", "updateAttrViewColNumberFormat", "setAttrViewColDateFormat", "removeAttrViewBlock",
            "replaceAttrViewBlock", "updateAttrViewColTemplate", "setAttrViewColPin", "addAttrViewView", "setAttrViewColIcon",
            "removeAttrViewView", "setAttrViewViewName", "setAttrViewViewIcon", "duplicateAttrViewView", "duplicateAttrViewRow", "sortAttrViewView",
            "updateAttrViewColRelation", "setAttrViewColRelationFilters", "setAttrViewPageSize", "updateAttrViewColRollup",
            "setAttrViewColRollupFilters", "sortAttrViewKey", "setAttrViewColDesc", "setAttrViewColAttributePanelVisibility",
            "duplicateAttrViewKey", "setAttrViewViewDesc", "setAttrViewCoverFrom", "setAttrViewCoverFromAssetKeyID", "setAttrViewCardCoverPosition",
            "setAttrViewBlockView", "setAttrViewBlockVisibleViews", "setAttrViewContextFilter", "setAttrViewCardSize", "setAttrViewCardWidth", "setAttrViewCardAspectRatio",
            "setAttrViewConditionalColors", "setAttrViewCalendar", "setAttrViewCardAspectRatioValue", "setAttrViewCardLayout", "setAttrViewColFullRow", "hideAttrViewName", "setAttrViewShowIcon",
            "setAttrViewWrapField", "setAttrViewGroup", "removeAttrViewGroup", "hideAttrViewGroup", "sortAttrViewGroup",
            "foldAttrViewGroup", "foldAttrViewGroups", "hideAttrViewAllGroups", "setAttrViewFitImage", "setAttrViewDisplayFieldName", "setAttrViewDisplayEmptyFields",
            "insertAttrViewBlock", "setAttrViewColDateFillSpecificTime", "setAttrViewFillColBackgroundColor", "setAttrViewUpdatedIncludeTime",
            "setAttrViewCreatedIncludeTime"].includes(operation.action)) {
            protyle.databaseAttributePanel?.refreshForOperation(operation);
            // 撤销 transaction 会进行推送,需使用推送来进行刷新最新数据 https://github.com/siyuan-note/siyuan/issues/13607
            if (!isUndo) {
                refreshAV(protyle, operation);
            } else if (operation.action === "setAttrViewName") {
                // setAttrViewName 同文档不会推送,需手动刷新
                Array.from(protyle.wysiwyg.element.querySelectorAll(`.av[data-av-id="${operation.id}"]`)).forEach((item: HTMLElement) => {
                    const titleElement = item.querySelector(".av__title") as HTMLElement;
                    if (!titleElement) {
                        return;
                    }
                    titleElement.textContent = operation.data;
                    titleElement.dataset.title = operation.data;
                });
            }
            return;
        }
        if (operation.action === "doUpdateUpdated") {
            updateElements.forEach(item => {
                item.setAttribute("updated", operation.data);
            });
            return;
        }
    });
    if (preserveTrackedRanges) {
        syncTrackedRanges(protyle, operations);
    }
    void applyViewFoldStates(protyle);
    const preserveViewport = isUndoViewportPreserved(protyle.wysiwyg.element);
    pendingUndoEmbedElements.forEach(item => {
        if (!item.isConnected) {
            return;
        }
        item.removeAttribute("data-render");
        blockRender(protyle, item, undefined, () => {
            if (restoreUndoFocus(protyle, operations) && !preserveViewport) {
                scrollCenter(protyle);
            }
        });
    });
    queueHeadingNumberRefresh(protyle, operations);
    refreshHeadingFoldIndicators(protyle);
    if (shouldReloadForHeadingBatch(protyle.block.rootID, operations)) {
        reloadProtyle(protyle, false);
    }
};

export const turnsIntoOneTransaction = async (options: {
    protyle: IProtyle,
    selectsElement: Element[],
    type: TTurnIntoOne,
    level?: TTurnIntoOneSub,
    unfocus?: boolean,
    getOperations?: boolean,
    parentID?: string,
    widthSourceElement?: HTMLElement,
    callout?: ICalloutPreset,
}) => {
    let parentElement: Element;
    let widthSourceOldStyle: string;
    let widthSourceElement: HTMLElement;
    const id = Lute.NewNodeID();
    if (options.type === "BlocksMergeSuperBlock") {
        parentElement = genSBElement(options.level, id);
        // 回车生成竖排超级块时,将横向超级块子块的宽度迁移到新超级块,并清除子块宽度
        // https://github.com/siyuan-note/siyuan/issues/9521
        widthSourceElement = options.widthSourceElement || options.selectsElement[0] as HTMLElement;
        if (widthSourceElement.style.width) {
            (parentElement as HTMLElement).style.width = widthSourceElement.style.width;
            (parentElement as HTMLElement).style.flex = widthSourceElement.style.flex;
            if (options.selectsElement.includes(widthSourceElement)) {
                widthSourceOldStyle = widthSourceElement.getAttribute("style") || "";
                widthSourceElement.style.width = "";
                widthSourceElement.style.flex = "";
            }
        }
    } else if (options.type === "Blocks2Blockquote") {
        parentElement = document.createElement("div");
        parentElement.classList.add("bq");
        parentElement.setAttribute("data-node-id", id);
        parentElement.setAttribute("data-type", "NodeBlockquote");
        parentElement.innerHTML = `<div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div>`;
    } else if (options.type === "Blocks2Callout") {
        const preset = options.callout || CALLOUT_PRESETS[0];
        parentElement = document.createElement("div");
        parentElement.classList.add("callout");
        parentElement.setAttribute("data-node-id", id);
        parentElement.setAttribute("data-type", "NodeCallout");
        parentElement.setAttribute("data-subtype", preset.type);
        parentElement.innerHTML = `<div class="callout-info" contenteditable="false"><span class="callout-icon">${preset.icon}</span><span contenteditable="true" spellcheck="${window.siyuan.config.editor.spellcheck}" class="callout-title">${preset.title}</span></div><div class="callout-content"></div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div>`;
    } else if (options.type.endsWith("Ls")) {
        parentElement = document.createElement("div");
        parentElement.classList.add("list");
        parentElement.setAttribute("data-node-id", id);
        parentElement.setAttribute("data-type", "NodeList");
        if (options.type === "Blocks2ULs") {
            parentElement.setAttribute("data-subtype", "u");
        } else if (options.type === "Blocks2OLs") {
            parentElement.setAttribute("data-subtype", "o");
        } else {
            parentElement.setAttribute("data-subtype", "t");
        }
        let html = "";
        options.selectsElement.forEach((item, index) => {
            if (options.type === "Blocks2ULs") {
                html += `<div data-marker="*" data-subtype="u" data-node-id="${Lute.NewNodeID()}" data-type="NodeListItem" class="li"><div class="protyle-action" draggable="true"><svg><use xlink:href="#iconDot"></use></svg></div><div class="protyle-attr" contenteditable="false"></div></div>`;
            } else if (options.type === "Blocks2OLs") {
                html += `<div data-marker="${index + 1}." data-subtype="o" data-node-id="${Lute.NewNodeID()}" data-type="NodeListItem" class="li"><div class="protyle-action protyle-action--order" contenteditable="false" draggable="true">${index + 1}.</div><div class="protyle-attr" contenteditable="false"></div></div>`;
            } else {
                html += `<div data-marker="*" data-task=" " data-subtype="t" data-node-id="${Lute.NewNodeID()}" data-type="NodeListItem" class="li"><div class="protyle-action protyle-action--task" draggable="true"><svg><use xlink:href="#iconUncheck"></use></svg></div><div class="protyle-attr" contenteditable="false"></div></div>`;
            }
        });
        parentElement.innerHTML = html + '<div class="protyle-attr" contenteditable="false"></div>';
    }
    const previousId = options.selectsElement[0].getAttribute("data-node-id");
    const parentId = options.parentID || getEmbedChildOperationParentID(options.selectsElement[0]) ||
        getParentBlock(options.selectsElement[0]).getAttribute("data-node-id") || options.protyle.block.parentID;
    const doOperations: IOperation[] = [{
        action: "insert",
        id,
        data: parentElement.outerHTML,
        nextID: previousId,
        parentID: parentId
    }];
    const undoOperations: IOperation[] = [];
    if (options.selectsElement[0].previousElementSibling) {
        options.selectsElement[0].before(parentElement);
    } else {
        options.selectsElement[0].parentElement.prepend(parentElement);
    }
    let itemPreviousId: string;
    options.selectsElement.forEach((item, index) => {
        item.classList.remove("protyle-wysiwyg--select");
        item.removeAttribute("select-start");
        item.removeAttribute("select-end");
        const itemId = item.getAttribute("data-node-id");
        undoOperations.push({
            action: "move",
            id: itemId,
            previousID: itemPreviousId || id,
            parentID: parentId
        });
        if (options.type.endsWith("Ls")) {
            doOperations.push({
                action: "move",
                id: itemId,
                parentID: parentElement.children[index].getAttribute("data-node-id")
            });
            parentElement.children[index].firstElementChild.after(item);
        } else if (options.type === "Blocks2Callout") {
            doOperations.push({
                action: "move",
                id: itemId,
                previousID: itemPreviousId,
                parentID: id
            });
            parentElement.querySelector(".callout-content").insertAdjacentElement("beforeend", item);
        } else {
            doOperations.push({
                action: "move",
                id: itemId,
                previousID: itemPreviousId,
                parentID: id
            });
            parentElement.lastElementChild.before(item);
        }
        itemPreviousId = item.getAttribute("data-node-id");

        if (index === options.selectsElement.length - 1) {
            undoOperations.push({
                action: "delete",
                id,
            });
        }
        // 超级块内嵌入块无面包屑,需重新渲染 https://github.com/siyuan-note/siyuan/issues/7574
        if (item.getAttribute("data-type") === "NodeBlockQueryEmbed") {
            item.removeAttribute("data-render");
            blockRender(options.protyle, item);
        }
    });
    if (widthSourceOldStyle !== undefined) {
        doOperations.push({
            action: "setAttrs",
            id: widthSourceElement.getAttribute("data-node-id"),
            data: JSON.stringify({style: widthSourceElement.getAttribute("style") || ""})
        });
        undoOperations.splice(undoOperations.length - 1, 0, {
            action: "setAttrs",
            id: widthSourceElement.getAttribute("data-node-id"),
            data: JSON.stringify({style: widthSourceOldStyle})
        });
    }
    // 子块移入完成后刷新超级块拖拽手柄
    if (parentElement.classList.contains("sb")) {
        refreshSbs(parentElement);
    } else if (parentElement.parentElement?.classList.contains("sb")) {
        // 引述/列表/标注嵌入超级块时刷新父超级块
        refreshSbs(parentElement.parentElement);
    }
    if ((["Blocks2Blockquote", "Blocks2Callout"].includes(options.type) || options.type.endsWith("Ls")) &&
        parentElement.parentElement?.classList.contains("sb") && getSbChildBlockCount(parentElement.parentElement) === 1) {
        const cancelOperations = await cancelSB(options.protyle, parentElement.parentElement);
        doOperations.push(...cancelOperations.doOperations);
        undoOperations.splice(0, 0, ...cancelOperations.undoOperations);
    }
    if (options.getOperations) {
        return {
            doOperations,
            undoOperations,
        };
    }
    transaction(options.protyle, doOperations, undoOperations);
    if (!options.unfocus) {
        focusBlock(options.protyle.wysiwyg.element.querySelector(`[data-node-id="${options.selectsElement[0].getAttribute("data-node-id")}"]`));
    }
    hideElements(["gutter"], options.protyle);
};

const insertEmptyQuoteBlock = (protyle: IProtyle, previousElement: HTMLElement, options?: {
    updateElement: HTMLElement,
    oldHTML: string,
    undoContext?: Record<string, string>,
    additionalOperations?: {
        doOperations: IOperation[],
        undoOperations: IOperation[],
    },
}, callout?: ICalloutPreset) => {
    const range = getEditorRange(protyle.wysiwyg.element);
    const undoFocusContext = getUndoFocusContext(protyle.wysiwyg.element, range, true);
    const template = document.createElement("template");
    template.innerHTML = protyle.lute.SpinBlockDOM(callout ? `> [!${callout.type}]\n> ${Lute.Caret}` : ">" + Lute.Caret);
    const blockquoteElement = template.content.firstElementChild as HTMLElement;
    if (!blockquoteElement || blockquoteElement.getAttribute("data-type") !== (callout ? "NodeCallout" : "NodeBlockquote")) {
        return;
    }

    let foldData;
    if (previousElement.getAttribute("data-type") === "NodeHeading" && previousElement.getAttribute("fold") === "1") {
        foldData = setFold(protyle, previousElement, true, false, true);
    }

    const id = blockquoteElement.getAttribute("data-node-id");
    const doOperations: IOperation[] = [{
        action: "insert",
        id,
        data: blockquoteElement.outerHTML,
        previousID: previousElement.getAttribute("data-node-id"),
        parentID: previousElement.parentElement.getAttribute("data-node-id") ||
            getParentBlock(previousElement).getAttribute("data-node-id"),
    }];
    const undoOperations: IOperation[] = [{
        action: "delete",
        id,
        context: options ? options.undoContext : undoFocusContext,
    }];
    if (options) {
        doOperations.unshift({
            action: "update",
            id: options.updateElement.getAttribute("data-node-id"),
            data: options.updateElement.outerHTML,
        });
        undoOperations.push({
            action: "update",
            id: options.updateElement.getAttribute("data-node-id"),
            data: options.oldHTML,
            context: options.undoContext,
        });
        if (options.additionalOperations) {
            doOperations.unshift(...options.additionalOperations.doOperations);
            undoOperations.push(...options.additionalOperations.undoOperations);
        }
    }
    if (foldData?.doOperations?.length > 0) {
        doOperations.push(...foldData.doOperations);
        undoOperations.push(...foldData.undoOperations);
    }

    previousElement.insertAdjacentElement("afterend", blockquoteElement);
    transaction(protyle, doOperations, undoOperations);
    focusByWbr(blockquoteElement, range);
    hideElements(["gutter"], protyle);
};

export const insertEmptyBlockquote = (protyle: IProtyle, previousElement: HTMLElement,
                                     options?: Parameters<typeof insertEmptyQuoteBlock>[2]) => {
    insertEmptyQuoteBlock(protyle, previousElement, options);
};

export const insertEmptyCallout = (protyle: IProtyle, previousElement: HTMLElement, preset: ICalloutPreset) => {
    insertEmptyQuoteBlock(protyle, previousElement, undefined, preset);
};

export const wrapBlockInBlockquote = async (protyle: IProtyle, blockElement: HTMLElement, options?: {
    oldHTML: string,
    undoContext?: Record<string, string>,
    additionalOperations?: {
        doOperations: IOperation[],
        undoOperations: IOperation[],
    },
}) => {
    const range = getEditorRange(protyle.wysiwyg.element);
    const undoFocusContext = getUndoFocusContext(protyle.wysiwyg.element, range, true);
    const blockID = blockElement.getAttribute("data-node-id");
    const operations = await turnsIntoOneTransaction({
        protyle,
        selectsElement: [blockElement],
        type: "Blocks2Blockquote",
        getOperations: true,
    });
    operations.undoOperations[operations.undoOperations.length - 1].context =
        options?.undoContext || undoFocusContext;
    if (options) {
        operations.doOperations.unshift({
            action: "update",
            id: blockElement.getAttribute("data-node-id"),
            data: blockElement.outerHTML,
        });
        operations.undoOperations.push({
            action: "update",
            id: blockElement.getAttribute("data-node-id"),
            data: options.oldHTML,
            context: options.undoContext,
        });
        if (options.additionalOperations) {
            operations.doOperations.unshift(...options.additionalOperations.doOperations);
            operations.undoOperations.push(...options.additionalOperations.undoOperations);
        }
    }
    transaction(protyle, operations.doOperations, operations.undoOperations);
    const currentBlockElement = protyle.wysiwyg.element.querySelector(`[data-node-id="${blockID}"]`);
    if (currentBlockElement && !focusByWbr(currentBlockElement, document.createRange())) {
        focusBlock(currentBlockElement);
    }
    hideElements(["gutter"], protyle);
};

export const turnsIntoGroupsTransaction = async (options: {
    protyle: IProtyle,
    selectsElementGroups: Element[][],
    type: Exclude<TTurnIntoOne, "BlocksMergeSuperBlock">,
    callout?: ICalloutPreset,
}) => {
    const firstElement = options.selectsElementGroups[0]?.[0];
    if (!firstElement) {
        return;
    }
    const firstID = firstElement.getAttribute("data-node-id");
    const doOperations: IOperation[] = [];
    const undoOperations: IOperation[] = [];
    for (const selectsElement of options.selectsElementGroups) {
        if (selectsElement.length === 0) {
            continue;
        }
        const groupOperations = await turnsIntoOneTransaction({
            protyle: options.protyle,
            selectsElement,
            type: options.type,
            callout: options.callout,
            getOperations: true,
        });
        doOperations.push(...groupOperations.doOperations);
        undoOperations.splice(0, 0, ...groupOperations.undoOperations);
    }
    transaction(options.protyle, doOperations, undoOperations);
    focusBlock(options.protyle.wysiwyg.element.querySelector(`[data-node-id="${firstID}"]`));
    hideElements(["gutter"], options.protyle);
};

const removeUnfoldRepeatBlock = (html: string, protyle: IProtyle) => {
    const temp = document.createElement("template");
    temp.innerHTML = html;
    Array.from(temp.content.children).forEach(item => {
        const repeatedElement = protyle.wysiwyg.element.querySelector(
            `[data-node-id="${item.getAttribute("data-node-id")}"]`);
        if (repeatedElement) {
            disposeCustomBlocksInElement(repeatedElement);
            repeatedElement.remove();
        }
    });
};

export const turnsIntoTransaction = (options: {
    protyle: IProtyle,
    selectsElement?: Element[],
    nodeElement?: Element,
    type: TTurnInto,
    level?: number,
    isContinue?: boolean,
    range?: Range,
    unfocus?: boolean,
}) => {
    let selectsElement: Element[] = options.selectsElement;
    let range: Range;
    // 通过快捷键触发
    if (options.nodeElement) {
        selectsElement = Array.from(options.protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));
        if (selectsElement.length === 0) {
            selectsElement = [options.nodeElement];
        }
    }
    if (selectsElement.some(isListHeadingContainer)) {
        return turnListBlocksInto(options, selectsElement);
    }
    if (selectsElement.length === 0 || options.nodeElement && selectsElement.some(item => item.classList.contains("li"))) {
        return;
    }
    if (options.nodeElement) {
        let isContinue = false;
        selectsElement.find((item, index) => {
            if (selectsElement[index + 1] && getNextBlockSibling(item) === selectsElement[index + 1]) {
                isContinue = true;
            } else if (index !== selectsElement.length - 1) {
                isContinue = false;
                return true;
            }
        });
        if (selectsElement.length === 1 && options.type === "Blocks2Hs" &&
            selectsElement[0].getAttribute("data-type") === "NodeHeading" &&
            options.level === parseInt(selectsElement[0].getAttribute("data-subtype").substr(1))) {
            // 快捷键同级转换,消除标题
            options.type = "Blocks2Ps";
        }
        options.isContinue = isContinue;
        range = getSelection().getRangeAt(0);
        range.insertNode(document.createElement("wbr"));
    }
    // https://github.com/siyuan-note/siyuan/issues/14505
    options.protyle.observerLoad?.disconnect();

    let html = "";
    const doOperations: IOperation[] = [];
    const undoOperations: IOperation[] = [];
    let previousId: string;
    const updateParagraphsIndividually = options.type === "Blocks2Ps" && selectsElement.every(item =>
        ["NodeHeading", "NodeParagraph"].includes(item.getAttribute("data-type")));
    selectsElement.forEach((item: HTMLElement, index) => {
        item.classList.remove("protyle-wysiwyg--select");
        item.removeAttribute("select-start");
        item.removeAttribute("select-end");
        html += item.outerHTML;
        const id = item.getAttribute("data-node-id");

        const tempElement = document.createElement("template");
        if (!options.isContinue || options.level || updateParagraphsIndividually) {
            // @ts-ignore
            let newHTML = options.protyle.lute[options.type](item.outerHTML, options.level);
            tempElement.innerHTML = newHTML;

            if (!tempElement.content.querySelector(`[data-node-id="${id}"]`)) {
                undoOperations.push({
                    action: "insert",
                    id,
                    previousID: previousId || getPreviousBlockSibling(item)?.getAttribute("data-node-id"),
                    data: item.outerHTML,
                    parentID: getEmbedChildOperationParentID(item) || getParentBlock(item)?.getAttribute("data-node-id") ||
                        options.protyle.block.parentID || options.protyle.block.rootID,
                });
                Array.from(tempElement.content.children).forEach((tempItem: HTMLElement) => {
                    const tempItemId = tempItem.getAttribute("data-node-id");
                    doOperations.push({
                        action: "insert",
                        id: tempItemId,
                        previousID: tempItem.previousElementSibling?.getAttribute("data-node-id") || getPreviousBlockSibling(item)?.getAttribute("data-node-id"),
                        data: tempItem.outerHTML,
                        parentID: getEmbedChildOperationParentID(item) || getParentBlock(item)?.getAttribute("data-node-id") ||
                            options.protyle.block.parentID || options.protyle.block.rootID,
                    });
                    undoOperations.splice(0, 0, {
                        action: "delete",
                        id: tempItemId,
                    });
                });
                doOperations.push({
                    action: "delete",
                    id,
                });
                if (selectsElement[index + 1] && item === getPreviousBlockSibling(selectsElement[index + 1])) {
                    previousId = id;
                } else {
                    previousId = undefined;
                }
                disposeCustomBlocksInElement(item);
                item.outerHTML = newHTML;
            } else {
                let foldData;
                if (item.getAttribute("data-type") === "NodeHeading" && item.getAttribute("fold") === "1" &&
                    tempElement.content.firstElementChild.getAttribute("data-subtype") !== item.dataset.subtype) {
                    foldData = setFold(options.protyle, item, undefined, undefined, true);
                    newHTML = newHTML.replace(' fold="1"', "");
                }
                if (foldData && foldData.doOperations?.length > 0) {
                    doOperations.push(...foldData.doOperations);
                }
                undoOperations.push({
                    action: "update",
                    id,
                    data: item.outerHTML,
                });
                doOperations.push({
                    action: "update",
                    id,
                    data: newHTML
                });
                if (foldData && foldData.undoOperations?.length > 0) {
                    undoOperations.push(...foldData.undoOperations);
                }
                disposeCustomBlocksInElement(item);
                item.insertAdjacentHTML("afterend", newHTML);
                item = item.nextElementSibling as HTMLElement;
                item.previousElementSibling.remove();
                item.setAttribute(Constants.ATTRIBUTE_EDITING, "true");
            }
        } else {
            undoOperations.push({
                action: "insert",
                id,
                previousID: doOperations[doOperations.length - 1]?.id || getPreviousBlockSibling(item)?.getAttribute("data-node-id"),
                data: item.outerHTML,
                parentID: getEmbedChildOperationParentID(item) || getParentBlock(item)?.getAttribute("data-node-id") ||
                    options.protyle.block.parentID || options.protyle.block.rootID,
            });
            doOperations.push({
                action: "delete",
                id,
            });
            if (index === selectsElement.length - 1) {
                // @ts-ignore
                const newHTML = options.protyle.lute[options.type](html, options.level);
                tempElement.innerHTML = newHTML;
                Array.from(tempElement.content.children).forEach((tempItem: HTMLElement) => {
                    const tempItemId = tempItem.getAttribute("data-node-id");
                    doOperations.push({
                        action: "insert",
                        id: tempItemId,
                        previousID: tempItem.previousElementSibling?.getAttribute("data-node-id") || getPreviousBlockSibling(item)?.getAttribute("data-node-id"),
                        data: tempItem.outerHTML,
                        parentID: getEmbedChildOperationParentID(item) || getParentBlock(item)?.getAttribute("data-node-id") ||
                            options.protyle.block.parentID || options.protyle.block.rootID,
                    });
                    undoOperations.splice(0, 0, {
                        action: "delete",
                        id: tempItemId,
                    });
                });
                disposeCustomBlocksInElement(item);
                item.outerHTML = newHTML;
            } else {
                disposeCustomBlocksInElement(item);
                item.remove();
            }
        }
    });
    transaction(options.protyle, doOperations, undoOperations);
    processRender(options.protyle.wysiwyg.element);
    highlightRender(options.protyle.wysiwyg.element);
    avRender(options.protyle.wysiwyg.element, options.protyle);
    blockRender(options.protyle, options.protyle.wysiwyg.element);
    if (!options.unfocus) {
        if (range || options.range) {
            focusByWbr(options.protyle.wysiwyg.element, range || options.range);
        } else {
            focusBlock(options.protyle.wysiwyg.element.querySelector(`[data-node-id="${selectsElement[0].getAttribute("data-node-id")}"]`));
        }
    }
    hideElements(["gutter"], options.protyle);
};

type TRecursiveListConversion = {
    type: "CancelListRecursively",
} | {
    type: "ConvertListType",
    targetListType: "u" | "o" | "t",
};

const unfoldListHeadings = async (protyle: IProtyle, nodeElements: Element[]) => {
    const unfoldedIds = new Set<string>();
    const foldOperations: IOperation[] = [];
    while (true) {
        let foldedHeading: Element;
        nodeElements.find((nodeElement) => {
            foldedHeading = Array.from(nodeElement.querySelectorAll('[data-type="NodeHeading"][fold="1"]')).find((item) => {
                return !unfoldedIds.has(item.getAttribute("data-node-id"));
            });
            return !!foldedHeading;
        });
        if (!foldedHeading) {
            break;
        }
        const itemId = foldedHeading.getAttribute("data-node-id");
        unfoldedIds.add(itemId);
        if (hasViewFoldContext(protyle)) {
            await setViewFoldTransient(protyle, foldedHeading, false);
            foldOperations.push({
                action: "foldHeading",
                id: itemId,
            });
            continue;
        }
        foldedHeading.removeAttribute("fold");
        const response = await fetchSyncPost("/api/transactions", {
            reqId: Date.now(),
            session: protyle.id,
            app: Constants.SIYUAN_APPID,
            transactions: [{
                doOperations: [{
                    action: "unfoldHeading",
                    id: itemId,
                }],
                undoOperations: [{
                    action: "foldHeading",
                    id: itemId
                }],
            }]
        });
        if (response.code === 0 && Array.isArray(response.data)) {
            const operation = response.data[0]?.doOperations?.[0];
            if (operation?.action === "unfoldHeading" && typeof operation.retData === "string") {
                foldedHeading.insertAdjacentHTML("afterend", normalizeHTMLAssetIFrameBlockDOM(operation.retData));
            }
        }
        foldOperations.push({
            action: "foldHeading",
            id: itemId
        });
    }
    return foldOperations.reverse();
};

export const removeListStructure = (protyle: IProtyle, nodeElements: Element[], recursively = false) =>
    turnListBlocksInto({protyle, recursively}, nodeElements.filter(isListHeadingContainer));

const refreshListConversion = (protyle: IProtyle, result: TransactionListConversionResult, focus = false) => {
    if (!result?.rootIDs?.length) {
        return;
    }
    if (result.rootIDs.includes(protyle.block.rootID)) {
        if (result.removedIDs.includes(protyle.block.id)) {
            protyle.block.id = result.focusID || protyle.block.rootID;
        }
        if (result.removedIDs.includes(protyle.block.parentID)) {
            protyle.block.parentID = protyle.block.rootID;
        }
        reloadProtyle(protyle, false, undefined, () => {
            if (focus && result.focusID) {
                const element = protyle.wysiwyg.element.querySelector(`[data-node-id="${result.focusID}"]`);
                if (element) {
                    focusBlock(element);
                }
            }
        });
    } else {
        protyle.wysiwyg.element.querySelectorAll('[data-type="NodeBlockQueryEmbed"]').forEach(item => {
            item.removeAttribute("data-render");
            blockRender(protyle, item);
        });
    }
};

const turnListBlocksInto = async (options: {
    protyle: IProtyle,
    type?: TTurnInto,
    level?: number,
    range?: Range,
    unfocus?: boolean,
    recursively?: boolean,
}, elements: Element[]) => {
    const protyle = options.protyle;
    const selected = elements.filter(element => !elements.some(parent => parent !== element && parent.contains(element)));
    if (!selected.length) {
        return;
    }
    // 等待已有编辑落盘,再由内核检查完整列表;拒绝时保留页面和折叠状态。
    return queueTransaction(protyle, async () => {
        const response = await fetchSyncPost("/api/transactions", {
            reqId: Date.now(), session: protyle.id, app: Constants.SIYUAN_APPID,
            transactions: [{doOperations: [{
                action: "convertList", id: protyle.block.rootID,
                blockIDs: selected.map(element => element.getAttribute("data-node-id")),
                data: {
                    type: options.type === "Blocks2Hs" ? "heading" : options.type ? "paragraph" : "remove",
                    level: options.level || 0,
                    recursively: options.recursively || false,
                },
            }]}],
        });
        if (response.code !== 0 || !response.data?.length) {
            return;
        }
        const operation = getEditorTransaction(response.data[0]).doOperations.find(item => item.action === "convertList");
        if (operation?.action !== "convertList" || !operation.retData?.rootIDs?.length) {
            return;
        }
        operation.retData.rootIDs.forEach(rootID => markMirror(rootID, {canUndo: true, canRedo: false}));
        protyle.updated = true;
        hideElements(["select", "gutter"], protyle);
        refreshListConversion(protyle, operation.retData, !options.unfocus);
        refreshUndoButtons(protyle);
    });
};

export const turnListsRecursively = async (options: {
    protyle: IProtyle,
    nodeElements: Element[],
} & TRecursiveListConversion) => {
    if (options.type === "CancelListRecursively") {
        return turnListBlocksInto({protyle: options.protyle, type: "Blocks2Ps", recursively: true}, options.nodeElements);
    }
    const listElements = options.nodeElements.filter((item, index, elements) => {
        return item.getAttribute("data-type") === "NodeList" &&
            !elements.some((parent, parentIndex) => parentIndex !== index &&
                parent.getAttribute("data-type") === "NodeList" && parent.contains(item));
    });
    if (listElements.length === 0) {
        return;
    }
    if (!listElements[0].querySelector("wbr")) {
        getContenteditableElement(listElements[0])?.insertAdjacentHTML("afterbegin", "<wbr>");
    }
    options.nodeElements.forEach((nodeElement) => {
        nodeElement.classList.remove("protyle-wysiwyg--select");
        nodeElement.removeAttribute("select-start");
        nodeElement.removeAttribute("select-end");
    });
    const foldOperations = await unfoldListHeadings(options.protyle, listElements);
    const doOperations: IOperation[] = [];
    const undoOperations: IOperation[] = [];
    listElements.forEach((nodeElement) => {
        const oldHTML = cleanHeadingNumberHTML(nodeElement.outerHTML);
        const newHTML = cleanHeadingNumberHTML(options.protyle.lute.ConvertListType(nodeElement.outerHTML, options.targetListType));
        if (newHTML === oldHTML) {
            return;
        }
        doOperations.push({
            action: "update",
            id: nodeElement.getAttribute("data-node-id"),
            data: newHTML
        });
        undoOperations.push({
            action: "update",
            id: nodeElement.getAttribute("data-node-id"),
            data: oldHTML
        });
        disposeCustomBlocksInElement(nodeElement);
        nodeElement.insertAdjacentHTML("afterend", newHTML);
        const newElement = nodeElement.nextElementSibling as HTMLElement;
        nodeElement.remove();
        newElement.setAttribute(Constants.ATTRIBUTE_EDITING, "true");
    });
    const doFoldOperations = foldOperations.map((operation) => ({...operation}));
    const undoFoldOperations = foldOperations.map((operation) => ({...operation}));
    if (doOperations.length === 0) {
        if (doFoldOperations.length > 0) {
            if (hasViewFoldContext(options.protyle)) {
                transaction(options.protyle, doFoldOperations, undoFoldOperations);
            } else {
                await fetchSyncPost("/api/transactions", {
                    reqId: Date.now(),
                    session: options.protyle.id,
                    app: Constants.SIYUAN_APPID,
                    transactions: [{
                        doOperations: doFoldOperations
                    }]
                });
            }
        }
    } else {
        transaction(options.protyle, doOperations.concat(doFoldOperations), undoOperations.concat(undoFoldOperations));
    }
    if (!hasViewFoldContext(options.protyle)) {
        onTransaction(options.protyle, doFoldOperations, false, true);
    }
    focusByWbr(options.protyle.wysiwyg.element, getEditorRange(options.protyle.wysiwyg.element));
    options.protyle.wysiwyg.element.querySelectorAll('[data-type~="block-ref"]').forEach(item => {
        if (item.textContent === "") {
            fetchPost("/api/block/getRefText", {id: item.getAttribute("data-id")}, (response) => {
                item.innerHTML = sanitizeKernelHTML(response.data);
            });
        }
    });
    blockRender(options.protyle, options.protyle.wysiwyg.element);
    processRender(options.protyle.wysiwyg.element);
    highlightRender(options.protyle.wysiwyg.element);
    avRender(options.protyle.wysiwyg.element, options.protyle);
};

export const turnsOneInto = async (options: {
    protyle: IProtyle,
    nodeElement: Element,
    id: string,
    type: string,
    level?: number,
    callout?: Pick<ICalloutPreset, "type" | "title" | "icon">,
    undoElement?: {
        id: string,
        html: string,
    },
    additionalOperations?: {
        doOperations: IOperation[],
        undoOperations: IOperation[],
    },
}) => {
    if (!options.nodeElement.querySelector("wbr")) {
        getContenteditableElement(options.nodeElement)?.insertAdjacentHTML("afterbegin", "<wbr>");
    }
    let foldOperations: IOperation[] = [];
    if (["CancelBlockquote", "CancelList", "CancelCallout"].includes(options.type)) {
        foldOperations = await unfoldListHeadings(options.protyle, [options.nodeElement]);
    }
    const completeMindmap = isListMindmapListConversion(options.nodeElement, options.type) &&
        hasListMindmapRootTitle(options.nodeElement);
    const conversionSource = completeMindmap ?
        await prepareListMindmapConversion(options.protyle, options.nodeElement) : options.nodeElement;
    if (!conversionSource) {
        return;
    }
    const mindmapSnapshot = completeMindmap ? cleanListMindmapHTML(options.nodeElement.outerHTML) : undefined;
    const mindmapRootID = options.protyle.block.rootID;
    const mindmapNotebookID = options.protyle.notebookId;
    let oldHTML = conversionSource.outerHTML;
    if (options.undoElement) {
        const oldElement = conversionSource.cloneNode(true) as HTMLElement;
        const undoElement = oldElement.querySelector(`[data-node-id="${options.undoElement.id}"]`);
        if (undoElement) {
            undoElement.outerHTML = options.undoElement.html;
            oldHTML = oldElement.outerHTML;
        }
    }
    const previousBlockElement = getPreviousBlockSibling(options.nodeElement);
    let previousId = previousBlockElement?.getAttribute("data-node-id");
    if (!previousBlockElement && options.protyle.block.showAll) {
        const response = await fetchSyncPost("/api/block/getBlockRelevantIDs", {
            id: options.id,
            notebook: options.protyle.notebookId,
        });
        if (response.code !== 0) {
            throw new Error(response.msg);
        }
        previousId = response.data.previousID;
    }
    if (completeMindmap && (!options.nodeElement.isConnected || options.protyle.disabled ||
        options.protyle.block.rootID !== mindmapRootID ||
        options.protyle.notebookId !== mindmapNotebookID ||
        options.protyle.options.action.includes(Constants.CB_GET_HISTORY) ||
        options.nodeElement.closest(".protyle-wysiwyg__embed") ||
        options.nodeElement.closest(".protyle-wysiwyg") !== options.protyle.wysiwyg.element ||
        cleanListMindmapHTML(options.nodeElement.outerHTML) !== mindmapSnapshot)) {
        return;
    }
    const parentId = getEmbedChildOperationParentID(options.nodeElement) ||
        getParentBlock(options.nodeElement).getAttribute("data-node-id") || options.protyle.block.parentID;
    let newHTML: string;
    if (isTabsListConversion(options.type)) {
        let source = conversionSource;
        if (!options.protyle.lite && source.querySelector('[fold="1"]')) {
            await waitForPendingTransactions(options.protyle);
            const snapshot = source.outerHTML;
            const response = await fetchSyncPost("/api/block/getBlockDOM", {
                id: options.id,
                notebook: options.protyle.notebookId,
            });
            if (response.code !== 0) {
                return;
            }
            if (!source.isConnected || source.outerHTML !== snapshot) {
                return;
            }
            const template = document.createElement("template");
            template.innerHTML = normalizeHTMLAssetIFrameBlockDOM(response.data?.dom || "");
            const full = template.content.firstElementChild;
            if (full?.getAttribute("data-node-id") !== options.id) {
                return;
            }
            source = completeTabsListSource(source, full);
            oldHTML = source.outerHTML;
        }
        const converted = convertTabsList(source.getAttribute("data-type") === "NodeMindmap" ?
            listMindmapConversionSource(source) : source, options.type, options.protyle.lute);
        if (!converted) {
            return;
        }
        newHTML = converted.outerHTML;
    } else {
        const listHTML = convertListMindmapToList(conversionSource, options.type, options.protyle.lute);
        const sourceHTML = options.type === "CancelList" && options.nodeElement.getAttribute("data-type") === "NodeMindmap" ?
            listMindmapConversionSource(options.nodeElement).outerHTML : cleanListMindmapHTML(options.nodeElement.outerHTML);
        // @ts-ignore
        newHTML = listHTML ?? options.protyle.lute[options.type](sourceHTML, options.level);
    }
    if (options.type === "Blockquote2Callout" && options.callout) {
        const template = document.createElement("template");
        template.innerHTML = newHTML;
        const calloutElement = template.content.firstElementChild as HTMLElement;
        calloutElement.dataset.subtype = options.callout.type;
        calloutElement.querySelector(".callout-title").textContent = options.callout.title;
        calloutElement.querySelector(".callout-icon").textContent = options.callout.icon;
        newHTML = calloutElement.outerHTML;
    }
    const cancelListOperations = options.type === "CancelList" &&
        options.nodeElement.getAttribute("data-type") === "NodeList" ? buildCancelListOperations(options.nodeElement, {
        previousID: previousId,
        parentID: parentId,
    }) : undefined;
    disposeCustomBlocksInElement(options.nodeElement);
    options.nodeElement.insertAdjacentHTML("afterend", newHTML);
    options.nodeElement = options.nodeElement.nextElementSibling as HTMLElement;
    options.nodeElement.previousElementSibling.remove();
    if (["CancelBlockquote", "CancelList", "CancelCallout"].includes(options.type)) {
        const tempElement = document.createElement("template");
        tempElement.innerHTML = newHTML;
        const doOperations: IOperation[] = cancelListOperations?.doOperations || [{
            action: "delete",
            id: options.id
        }];
        const undoOperations: IOperation[] = cancelListOperations?.undoOperations || [];
        let tempPreviousId = previousId;
        if (!cancelListOperations) {
            Array.from(tempElement.content.children).forEach((item) => {
                const tempId = item.getAttribute("data-node-id");
                doOperations.push({
                    action: "insert",
                    data: item.outerHTML,
                    id: tempId,
                    previousID: tempPreviousId,
                    parentID: parentId
                });
                undoOperations.push({
                    action: "delete",
                    id: tempId
                });
                tempPreviousId = tempId;
            });
            undoOperations.push({
                action: "insert",
                data: oldHTML,
                id: options.id,
                previousID: previousId,
                parentID: parentId
            });
        }
        if (options.additionalOperations) {
            doOperations.unshift(...options.additionalOperations.doOperations);
            undoOperations.push(...options.additionalOperations.undoOperations);
        }
        const doFoldOperations = foldOperations.map((operation) => ({...operation}));
        const undoFoldOperations = foldOperations.map((operation) => ({...operation}));
        transaction(options.protyle, doOperations.concat(doFoldOperations), undoOperations.concat(undoFoldOperations));
    } else {
        updateTransaction(options.protyle, options.nodeElement, oldHTML);
    }
    focusByWbr(options.protyle.wysiwyg.element, getEditorRange(options.protyle.wysiwyg.element));
    options.protyle.wysiwyg.element.querySelectorAll('[data-type~="block-ref"]').forEach(item => {
        if (item.textContent === "") {
            fetchPost("/api/block/getRefText", {id: item.getAttribute("data-id")}, (response) => {
                item.innerHTML = sanitizeKernelHTML(response.data);
            });
        }
    });
    blockRender(options.protyle, options.protyle.wysiwyg.element);
    processRender(options.protyle.wysiwyg.element);
    highlightRender(options.protyle.wysiwyg.element);
    avRender(options.protyle.wysiwyg.element, options.protyle);
};

export const transaction = (protyle: IProtyle, doOperations: IOperation[], undoOperations?: IOperation[],
                            options?: {
                                skipSync?: boolean,
                                callback?: () => void,
                                templateDocTreePlanID?: string,
                                trackedRangeInsertion?: ITrackedRangeInsertion,
                            }) => {
    const owner = protyle?.lite && getProtyleTransactionOwner(protyle, doOperations);
    if (owner && !owner.lite && owner !== protyle) {
        transaction(owner, doOperations, undoOperations, options);
        return;
    }
    if (protyle) {
        const prepared = prepareViewFoldTransaction(protyle, doOperations, undoOperations);
        doOperations = prepared.doOperations;
        undoOperations = prepared.undoOperations;
    }
    if (doOperations.length === 0) {
        options?.callback?.();
        return;
    }
    cleanBlockSelectionModeOperations(doOperations);
    cleanBlockSelectionModeOperations(undoOperations);
    [doOperations, undoOperations].forEach(operations => operations?.forEach(operation => {
        if ((operation.action === "update" || operation.action === "insert") && typeof operation.data === "string") {
            operation.data = restoreInlineElementBoundaryHTML(operation.data);
        }
    }));
    doOperations.forEach(operation => {
        if (operation.action === "update" && typeof operation.data === "string") {
            undoOperations?.filter((undo): undo is Extract<IOperation, {action: "update"}> =>
                undo.action === "update" && undo.id === operation.id && typeof undo.data === "string")
                .forEach(undo => undo.data = retainTableCellRichMetadata(undo.data, operation.data));
        }
    });
    cleanHeadingNumberOperations(doOperations);
    cleanHeadingNumberOperations(undoOperations);
    if (!protyle) {
        // 文档树中点开属性->数据库后的变更操作 & 文档树添加到数据库
        fetchPost("/api/transactions", {
            reqId: Date.now(),
            session: Constants.SIYUAN_APPID,
            app: Constants.SIYUAN_APPID,
            transactions: [{
                doOperations
            }]
        }, options?.callback);
        return;
    }
    if (undoOperations) {
        if (window.siyuan.config.fileTree.openFilesUseCurrentTab && protyle.model) {
            protyle.model.headElement.classList.remove("item--unupdate");
        }
        protyle.updated = true;
        protyle.undo.add(doOperations, undoOperations, protyle);
    }
    // 本地插入和正在编辑的块保留现有 DOM,立即补充图片文件名和提示文本。
    doOperations.forEach(operation => {
        if ((operation.action === "insert" || operation.action === "update") &&
            typeof operation.data === "string" && operation.data.includes("<img ")) {
            protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach(renderImageDisplay);
        }
    });
    if (protyle?.lite) {
        if (!options?.skipSync) {
            syncTrackedRanges(protyle, doOperations, options?.trackedRangeInsertion);
        }
        return;
    }
    promiseTransaction({
        protyle: protyle,
        doOperations: doOperations,
        undoOperations: undoOperations,
        skipSync: options?.skipSync,
        callback: options?.callback,
        templateDocTreePlanID: options?.templateDocTreePlanID,
        trackedRangeInsertion: options?.trackedRangeInsertion,
    });
    // 插入块后会导致高度变化,从而产生再次定位 https://github.com/siyuan-note/siyuan/issues/11798
    doOperations.find(item => {
        if (item.action === "insert") {
            protyle.observerLoad?.disconnect();
            return true;
        }
    });
};

const restoreGutterAfterFold = (protyle: IProtyle, id: string) => {
    if (!consumeGutterFoldRestore(protyle.gutter.element, id)) {
        return;
    }
    window.requestAnimationFrame(() => {
        const nodeElement = protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`);
        if (nodeElement) {
            protyle.gutter.render(protyle, nodeElement);
        }
    });
};

const processFold = (operation: IOperation, protyle: IProtyle) => {
    if (operation.action === "unfoldHeading" || operation.action === "foldHeading") {
        const gutterFoldElement = protyle.gutter.element.querySelector('[data-type="fold"]');
        if (gutterFoldElement) {
            gutterFoldElement.removeAttribute("disabled");
        }
        if (operation.action === "unfoldHeading") {
            const visibleRetData = typeof operation.retData === "string" ?
                getVisibleFoldHeadingHTML(operation.retData) : "";
            const scrollTop = protyle.contentElement.scrollTop;
            protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach(item => {
                const embedElement = isInEmbedBlock(item);
                if (embedElement) {
                    embedElement.removeAttribute("data-render");
                    blockRender(protyle, embedElement);
                    return;
                }
                item.removeAttribute("fold");
                if (item.lastElementChild?.getAttribute("spin") === "1") {
                    item.lastElementChild.remove();
                }
                removeUnfoldRepeatBlock(visibleRetData, protyle);
                item.insertAdjacentHTML("afterend", visibleRetData);
                if (operation.data === "remove") {
                    // https://github.com/siyuan-note/siyuan/issues/2188
                    const selection = getSelection();
                    if (selection.rangeCount > 0 && item.contains(selection.getRangeAt(0).startContainer)) {
                        focusBlock(item.nextElementSibling, undefined, true);
                    }
                    item.remove();
                }
            });
            if (protyle.disabled) {
                disabledProtyle(protyle);
            }
            processRender(protyle.wysiwyg.element);
            highlightRender(protyle.wysiwyg.element);
            avRender(protyle.wysiwyg.element, protyle);
            blockRender(protyle, protyle.wysiwyg.element);
            // 展开标题插入的块可能落在超级块内,刷新手柄避免与既有手柄重复/错位
            refreshSbs(...Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)));
            if (operation.context?.focusId) {
                const focusElement = protyle.wysiwyg.element.querySelector(`[data-node-id="${operation.context.focusId}"]`);
                focusBlock(focusElement);
                scrollCenter(protyle, focusElement);
            } else {
                protyle.contentElement.scrollTop = scrollTop;
                protyle.scroll.lastScrollTop = scrollTop;
            }
            restoreGutterAfterFold(protyle, operation.id);
            return;
        }
        protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach(item => {
            const embedElement = isInEmbedBlock(item);
            if (embedElement) {
                embedElement.removeAttribute("data-render");
                blockRender(protyle, embedElement);
            } else {
                item.setAttribute("fold", "1");
                removeFoldHeading(item);
            }
        });
        // 折叠移除子块后,刷新折叠标题所在超级块的拖拽手柄(子块数变化)
        refreshSbs(...Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)));
        // 折叠标题后未触发动态加载 https://github.com/siyuan-note/siyuan/issues/4168
        const needsDynamicLoad = protyle.wysiwyg.element.lastElementChild.getAttribute("data-eof") !== "2" &&
            !protyle.scroll.element.classList.contains("fn__none") &&
            // https://github.com/siyuan-note/siyuan/issues/7785
            protyle.contentElement.scrollHeight - protyle.contentElement.scrollTop < protyle.contentElement.clientHeight * 2;
        if (!needsDynamicLoad || !protyle.scroll.loadDynamic(protyle, 2, {
            onFinish: () => restoreGutterAfterFold(protyle, operation.id),
        })) {
            restoreGutterAfterFold(protyle, operation.id);
        }
        return;
    }
};

export const updateTransaction = (protyle: IProtyle, element: Element, oldHTML: string,
                                  undoContext?: Record<string, string>, additionalOperations?: {
        doOperations: IOperation[],
        undoOperations: IOperation[],
        context?: Record<string, string>,
    }, options?: {trackedRangeInsertion?: ITrackedRangeInsertion}) => {
    if (element.getAttribute("data-type") === "NodeSuperBlock") {
        refreshSbResize(element);
    }
    const id = element.getAttribute("data-node-id");
    const getHTML = () => element.getAttribute("data-type") === "NodeTable" && element.querySelector(`[${TABLE_VIRTUAL_ID}]`) ?
        getTableBlockHTML(element) : element.outerHTML;
    let newHTML = cleanListMindmapHTML(cleanHeadingNumberHTML(cleanTableCellRichHTML(cleanBlockSelectionModeHTML(getHTML()))));
    const cleanOldHTML = cleanListMindmapHTML(cleanHeadingNumberHTML(cleanTableCellRichHTML(cleanBlockSelectionModeHTML(oldHTML))));
    if (newHTML === cleanOldHTML.replace("<wbr>", "") && !additionalOperations) {
        return;
    }
    if (element.getAttribute("data-type") === "NodeTable") {
        element.setAttribute("updated", dayjs().format("YYYYMMDDHHmmss"));
        newHTML = cleanListMindmapHTML(cleanHeadingNumberHTML(cleanTableCellRichHTML(cleanBlockSelectionModeHTML(getHTML()))));
    }
    // 插入相邻块等操作可能在同 ID 的其他副本上遗留编辑标记,本次更新只能保护实际修改的副本。
    protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${id}"]`).forEach(item => {
        if (item !== element) {
            item.removeAttribute(Constants.ATTRIBUTE_EDITING);
        }
    });
    element.setAttribute(Constants.ATTRIBUTE_EDITING, "true");
    const doOperations: IOperation[] = [{
        id,
        data: newHTML,
        action: "update",
        context: additionalOperations?.context,
    }];
    const undoOperations: IOperation[] = [{
        id,
        data: cleanOldHTML,
        action: "update",
        context: undoContext,
    }];
    if (additionalOperations) {
        doOperations.unshift(...additionalOperations.doOperations);
        undoOperations.push(...additionalOperations.undoOperations);
    }
    transaction(protyle, doOperations, undoOperations, options);
};

type TEmptyParagraphTarget = "code" | "table" | "line" | "math";

const EMPTY_PARAGRAPH_TARGET_NODE_TYPES: Record<TEmptyParagraphTarget, string> = {
    code: "NodeCodeBlock",
    table: "NodeTable",
    line: "NodeThematicBreak",
    math: "NodeMathBlock",
};

const getEmptyParagraphTargetMarkdown = (type: TEmptyParagraphTarget) => {
    if (type === "code") {
        const language = window.siyuan.storage[Constants.LOCAL_CODELANG] || "";
        return "```" + (Constants.SIYUAN_RENDER_CODE_LANGUAGES.includes(language) ? "" : language) +
            Lute.Caret + "\n```";
    }
    if (type === "table") {
        return `| ${Lute.Caret} |  |  |
| --- | --- | --- |
|  |  |  |
|  |  |  |`;
    }
    return type === "line" ? "---" : "$$";
};

export const turnEmptyParagraphsIntoTransaction = (options: {
    protyle: IProtyle,
    nodeElements: Element[],
    type: TEmptyParagraphTarget,
}) => {
    if (options.nodeElements.length === 0 || !options.nodeElements.every(isEmptyParagraph)) {
        return;
    }

    const replacements = options.nodeElements.map((nodeElement) => {
        const oldElement = nodeElement.cloneNode(true) as HTMLElement;
        oldElement.classList.remove("protyle-wysiwyg--select");
        oldElement.removeAttribute("select-start");
        oldElement.removeAttribute("select-end");
        const oldHTML = oldElement.outerHTML;
        const editableElement = getContenteditableElement(oldElement);
        editableElement.textContent = getEmptyParagraphTargetMarkdown(options.type);

        const template = document.createElement("template");
        template.innerHTML = options.protyle.lute.SpinBlockDOM(oldElement.outerHTML);
        if (template.content.childElementCount !== 1) {
            return;
        }
        const newElement = template.content.firstElementChild as HTMLElement;
        if (newElement.getAttribute("data-node-id") !== oldElement.getAttribute("data-node-id") ||
            newElement.getAttribute("data-type") !== EMPTY_PARAGRAPH_TARGET_NODE_TYPES[options.type]) {
            return;
        }
        if (newElement.getAttribute("data-type") === "NodeTable") {
            newElement.querySelectorAll("colgroup col").forEach((item: HTMLElement) => {
                item.style.minWidth = "60px";
            });
            newElement.querySelectorAll("wbr").forEach(item => item.remove());
        }
        return {
            nodeElement,
            oldHTML,
            newElement,
        };
    });
    if (replacements.some(item => !item)) {
        return;
    }

    const doOperations: IOperation[] = [];
    const undoOperations: IOperation[] = [];
    const newElements: HTMLElement[] = [];
    replacements.forEach((replacement) => {
        const id = replacement.newElement.getAttribute("data-node-id");
        doOperations.push({
            action: "update",
            id,
            data: replacement.newElement.outerHTML,
        });
        undoOperations.push({
            action: "update",
            id,
            data: replacement.oldHTML,
        });
        replacement.nodeElement.insertAdjacentElement("afterend", replacement.newElement);
        replacement.nodeElement.remove();
        replacement.newElement.setAttribute(Constants.ATTRIBUTE_EDITING, "true");
        newElements.push(replacement.newElement);
    });

    transaction(options.protyle, doOperations, undoOperations);
    processRender(options.protyle.wysiwyg.element);
    highlightRender(options.protyle.wysiwyg.element);
    blockRender(options.protyle, options.protyle.wysiwyg.element);
    if (options.type === "math") {
        options.protyle.toolbar.showRender(options.protyle, newElements[0]);
    } else {
        focusBlock(newElements[0]);
    }
    hideElements(["gutter"], options.protyle);
};

export const updateBatchTransaction = (nodeElements: Element[], protyle: IProtyle, cb: (e: HTMLElement) => void,
                                       focusContext?: Record<string, string>) => {
    const operations: IOperation[] = [];
    const undoOperations: IOperation[] = [];
    nodeElements.forEach((element, index) => {
        const id = element.getAttribute("data-node-id");
        element.classList.remove("protyle-wysiwyg--select");
        element.removeAttribute("select-start");
        element.removeAttribute("select-end");
        undoOperations.push({
            action: "update",
            id,
            data: cleanHeadingNumberHTML(element.outerHTML),
            context: index === 0 ? focusContext : undefined,
        });
        cb(element as HTMLElement);
        renderBlockDirection(element);
        element.setAttribute(Constants.ATTRIBUTE_EDITING, "true");
        operations.push({
            action: "update",
            id,
            data: cleanHeadingNumberHTML(element.outerHTML),
            context: index === 0 ? focusContext : undefined,
        });
    });
    transaction(protyle, operations, undoOperations);
};