Skip to content

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

41.4 KB
Raw Blame
import {genEmptyElement, genHeadingElement, insertEmptyBlock} from "../../block/util";
import {focusByWbr, getUndoFocusContext} from "../util/selection";
import {focusByRange, getSelectionOffset, setLastNodeRange} from "../util/selectionOffsets";
import {
    getContenteditableElement, getParentBlock,
    getEmbedChildOperationContext,
    getEmbedChildOperationParentID,
    getPreviousBlockSibling,
    getTopEmptyElement,
    hasNextSibling,
    hasPreviousSibling,
    isNotEditBlock,
    IEmbedChildOperationContext
} from "./getBlock";
import {transaction, turnsIntoOneTransaction, updateTransaction} from "./transaction";
import {
    breakList,
    genListItemElement,
    getFocusedOrderedListInsertOperations,
    getFocusedParentOrderedList,
    getOrderedListStart,
    listOutdent,
    updateListOrder
} from "./list";
import {highlightRender} from "../render/highlightRender";
import {Constants} from "../../constants";
import {scrollCenter} from "../../util/highlightById";
import {hideElements} from "../ui/hideElements";
import {isIPad, setStorageVal} from "../util/compatibility";
import {mathRender} from "../render/mathRender";
import {isMobile} from "../../util/functions";
import {processRender} from "../util/processCode";
import {hasClosestByAttribute, hasClosestByClassName} from "../util/hasClosest";
import {blockRender} from "../render/blockRender";
import {canEnterCodeBlock, hasCodeBlockFence} from "./codeBlockEnter";
import {isEmptyListItemBlock, shouldCreateListItemChildOnEnter} from "./listContext";
import {
    BLOCK_SELECTION_CLASS,
    clearBlockSelectionMode,
    getBlockSelectionModeElement
} from "./blockSelection";
import {getTextWithoutSemanticMarkers} from "../util/inlineElementMarker";
import {prepareInlineElementBoundaryMutation} from "../util/inlineElementBoundary";
import {
    activateTrackedRangeInsertion,
    setTrackedRangeInsertionResult,
    type ITrackedRangeInsertion,
} from "../util/trackedRange";

export const enter = async (blockElement: HTMLElement, range: Range, protyle: IProtyle,
                            trackedRangeInsertion?: ITrackedRangeInsertion) => {
    const selectionModeElement = getBlockSelectionModeElement(protyle.wysiwyg.element);
    if (selectionModeElement) {
        blockElement = selectionModeElement;
    }
    const embedResultElement = hasClosestByClassName(blockElement, "protyle-wysiwyg__embed");
    const embedContext = getEmbedChildOperationContext(blockElement);
    if (embedResultElement && !embedContext && !blockElement.classList.contains("code-block")) {
        if (selectionModeElement) {
            clearBlockSelectionMode(protyle.wysiwyg.element, true);
        }
        return;
    }
    const disableElement = isNotEditBlock(blockElement);
    const isBlockMode = !!selectionModeElement || blockElement.classList.contains(BLOCK_SELECTION_CLASS);
    if (!disableElement && isBlockMode) {
        setLastNodeRange(getContenteditableElement(blockElement), range, false);
        range.collapse(false);
        if (selectionModeElement) {
            clearBlockSelectionMode(protyle.wysiwyg.element, true);
        } else {
            hideElements(["select"], protyle);
        }
        return;
    }
    protyle.observerLoad?.disconnect();
    // https://github.com/siyuan-note/siyuan/issues/5471
    if (disableElement ||
        // https://github.com/siyuan-note/siyuan/issues/10633
        blockElement.classList.contains("table")) {
        if (selectionModeElement) {
            clearBlockSelectionMode(protyle.wysiwyg.element, true);
        }
        if (isBlockMode && blockElement.classList.contains("render-node")) {
            protyle.toolbar.showRender(protyle, blockElement);
        } else {
            insertEmptyBlock(protyle, "afterend");
        }
        return;
    }
    const editableElement = getContenteditableElement(blockElement) as HTMLElement;
    prepareInlineElementBoundaryMutation(range);
    // 选中图片后回车,应取消图片的选中状态 https://ld246.com/article/1650357135043
    editableElement.querySelectorAll(".img--select").forEach(item => {
        item.classList.remove("img--select");
    });
    // 数据库
    if (blockElement.getAttribute("data-type") === "NodeAttributeView") {
        return true;
    }

    const position = getSelectionOffset(editableElement, protyle.wysiwyg.element, range);
    const enableCodeBlockMiddleDot = window.siyuan.config.editor.markdown.codeBlockMiddleDot !== false;
    const codeBlockMarkerRegExp = enableCodeBlockMiddleDot ? /·|~/g : /~/g;
    const codeBlockFenceStartRegExp = enableCodeBlockMiddleDot ? /^(~|·|`){3,}/g : /^(~|`){3,}/g;
    const codeBlockFenceLineRegExp = enableCodeBlockMiddleDot ? /\n(~|·|`){3,}/g : /\n(~|`){3,}/g;
    // 光标位于代码块围栏之前或内部时按普通换行处理 https://github.com/siyuan-note/siyuan/issues/18873
    if (blockElement.classList.contains("p") && canEnterCodeBlock(editableElement, position.start, enableCodeBlockMiddleDot)) {
        activateTrackedRangeInsertion(trackedRangeInsertion);
        range.insertNode(document.createElement("wbr"));
        const oldHTML = blockElement.outerHTML;
        // https://github.com/siyuan-note/siyuan/issues/16744
        range.extractContents();
        const wbrElement = document.createElement("wbr");
        range.insertNode(wbrElement);
        wbrElement.after(document.createTextNode("\n"));
        let replaceInnerHTML = editableElement.innerHTML
            .replace(codeBlockFenceLineRegExp, "\n```").trim()
            .replace(codeBlockFenceStartRegExp, "```");
        if (!replaceInnerHTML.endsWith("\n```")) {
            replaceInnerHTML += "\n```";
        }
        editableElement.innerHTML = replaceInnerHTML;
        const template = document.createElement("template");
        template.innerHTML = protyle.lute.SpinBlockDOM(blockElement.outerHTML);
        const replacements = Array.from(template.content.children) as HTMLElement[];
        // 软换行前的正文保留为段落,渲染和光标定位使用实际生成的代码块。
        const codeElement = template.content.querySelector("wbr")?.closest<HTMLElement>('[data-type="NodeCodeBlock"]');
        blockElement.replaceWith(template.content);
        blockElement = codeElement || replacements[0];
        const languageElement = blockElement.querySelector(".protyle-action__language");
        if (languageElement) {
            if (window.siyuan.storage[Constants.LOCAL_CODELANG] && languageElement.textContent === "") {
                languageElement.textContent = window.siyuan.storage[Constants.LOCAL_CODELANG];
            } else if (!Constants.SIYUAN_RENDER_CODE_LANGUAGES.includes(languageElement.textContent)) {
                window.siyuan.storage[Constants.LOCAL_CODELANG] = languageElement.textContent;
                setStorageVal(Constants.LOCAL_CODELANG, window.siyuan.storage[Constants.LOCAL_CODELANG]);
            }
            if (Constants.SIYUAN_RENDER_CODE_LANGUAGES.includes(languageElement.textContent)) {
                blockElement.dataset.content = "";
                blockElement.dataset.subtype = languageElement.textContent;
                blockElement.className = "render-node";
                blockElement.innerHTML = `<div spin="1"></div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div>`;
                protyle.toolbar.showRender(protyle, blockElement);
                processRender(blockElement);
            } else {
                highlightRender(blockElement);
            }
        } else {
            protyle.toolbar.showRender(protyle, blockElement);
            processRender(blockElement);
        }
        // 转换产生多个块时,将新增块一起记入事务,撤销可完整恢复原段落。
        updateTransaction(protyle, replacements[0], oldHTML, undefined, replacements.length > 1 ? {
            doOperations: replacements.slice(1).map((element, index) => ({
                action: "insert", id: element.dataset.nodeId, data: element.outerHTML,
                previousID: replacements[index].dataset.nodeId,
            })),
            undoOperations: replacements.slice(1).map(element => ({action: "delete", id: element.dataset.nodeId})),
        } : undefined, {trackedRangeInsertion});
        return true;
    }
    // 代码块
    if (blockElement.getAttribute("data-type") === "NodeCodeBlock") {
        activateTrackedRangeInsertion(trackedRangeInsertion);
        const wbrElement = document.createElement("wbr");
        range.insertNode(wbrElement);
        const oldHTML = blockElement.outerHTML;
        wbrElement.remove();
        range.extractContents();
        if (!editableElement.textContent.endsWith("\n")) {
            editableElement.insertAdjacentText("beforeend", "\n");
        }
        range.insertNode(document.createTextNode("\n"));
        range.collapse(false);
        range.insertNode(wbrElement);
        editableElement.parentElement.removeAttribute("data-render");
        highlightRender(blockElement);
        updateTransaction(protyle, blockElement, oldHTML, undefined, undefined, {trackedRangeInsertion});
        scrollCenter(protyle);
        return true;
    }

    // bq || callout
    if (getTextWithoutSemanticMarkers(editableElement).split(Constants.ZWSP).join("").replace(/\n/g, "") === "" &&
        ((blockElement.nextElementSibling && blockElement.nextElementSibling.classList.contains("protyle-attr") &&
                blockElement.parentElement.getAttribute("data-type") === "NodeBlockquote") ||
            (blockElement.parentElement.classList.contains("callout-content") && !blockElement.nextElementSibling))) {
        if (embedContext && !embedContext.boundaryElement.contains(getParentBlock(blockElement).parentElement)) {
            return;
        }
        activateTrackedRangeInsertion(trackedRangeInsertion);
        range.insertNode(document.createElement("wbr"));
        const topElement = getTopEmptyElement(blockElement, embedContext?.boundaryElement);
        const blockId = blockElement.getAttribute("data-node-id");
        const topId = topElement.getAttribute("data-node-id");
        const doInsert: IOperation = {
            action: "insert",
            id: blockId,
            data: blockElement.outerHTML,
        };
        const undoInsert: IOperation = {
            action: "insert",
            id: topId,
            data: topElement.outerHTML,
        };
        let parentBlockElement = getParentBlock(blockElement);
        if (topId === blockId) {
            doInsert.previousID = parentBlockElement.getAttribute("data-node-id");
            undoInsert.previousID = blockElement.previousElementSibling.getAttribute("data-node-id");
            parentBlockElement.after(blockElement);
        } else {
            doInsert.previousID = getPreviousBlockSibling(topElement)?.getAttribute("data-node-id");
            doInsert.parentID = getEmbedChildOperationParentID(topElement, embedContext) ||
                getParentBlock(topElement).getAttribute("data-node-id") || protyle.block.parentID;
            undoInsert.previousID = doInsert.previousID;
            undoInsert.parentID = doInsert.parentID;
            topElement.after(blockElement);
            topElement.remove();
        }
        parentBlockElement = getParentBlock(blockElement);
        const enterDoOperations: IOperation[] = [{
            action: "delete",
            id: topId
        }, doInsert];
        const enterUndoOperations: IOperation[] = [{
            action: "delete",
            id: blockId,
        }, undoInsert];
        if (topId === blockId && parentBlockElement.classList.contains("sb") &&
            parentBlockElement.getAttribute("data-sb-layout") === "col") {
            // 合并到同一个 transaction,避免新块 id 在第二个 transaction 中找不到
            const sbOperations = await turnsIntoOneTransaction({
                protyle,
                selectsElement: [blockElement.previousElementSibling, blockElement],
                type: "BlocksMergeSuperBlock",
                level: "row",
                unfocus: true,
                getOperations: true,
            });
            enterDoOperations.push(...sbOperations.doOperations);
            enterUndoOperations.splice(0, 0, ...sbOperations.undoOperations);
        }
        transaction(protyle, enterDoOperations, enterUndoOperations, {trackedRangeInsertion});
        focusByWbr(blockElement, range);
        return true;
    }

    if (blockElement.parentElement.getAttribute("data-type") === "NodeListItem" &&
        (
            blockElement.nextElementSibling.classList.contains("protyle-attr") ||
            (blockElement.nextElementSibling.classList.contains("list") && blockElement.previousElementSibling?.classList.contains("protyle-action")) ||
            (position.start === 0 && blockElement.previousElementSibling.classList.contains("protyle-action")) ||
            blockElement.parentElement.getAttribute("fold") === "1"
        )) {
        const embedListEnterMode = embedContext ? getEmbedListEnterMode(blockElement, embedContext) : "list";
        if ("none" === embedListEnterMode) {
            return;
        }
        if ("list" === embedListEnterMode &&
            await listEnter(protyle, blockElement, range, trackedRangeInsertion)) {
            return true;
        }
    }

    // 段首换行
    if (editableElement.textContent !== "" && range.toString() === "" && position.start === 0) {
        const undoFocusContext = getUndoFocusContext(protyle.wysiwyg.element, range);
        let newElement;
        const previousBlockElement = getPreviousBlockSibling(blockElement);
        if (previousBlockElement?.getAttribute("data-type") === "NodeHeading" &&
            previousBlockElement.getAttribute("fold") === "1") {
            newElement = genHeadingElement(previousBlockElement, false, true) as HTMLDivElement;
        } else {
            newElement = genEmptyElement(false, true);
        }
        activateTrackedRangeInsertion(trackedRangeInsertion);
        blockElement.insertAdjacentElement("beforebegin", newElement);
        const newId = newElement.getAttribute("data-node-id");
        const doOperations: IOperation[] = [{
            action: "insert",
            data: newElement.outerHTML,
            id: newId,
            nextID: blockElement.getAttribute("data-node-id"),
        }];
        const undoOperations: IOperation[] = [{
            action: "delete",
            id: newId,
            context: undoFocusContext,
        }];
        if (blockElement.parentElement.classList.contains("sb") &&
            blockElement.parentElement.getAttribute("data-sb-layout") === "col") {
            const mergeOperations = await turnsIntoOneTransaction({
                protyle,
                selectsElement: [newElement, blockElement],
                type: "BlocksMergeSuperBlock",
                level: "row",
                unfocus: true,
                getOperations: true,
                widthSourceElement: blockElement,
            });
            doOperations.push(...mergeOperations.doOperations);
            undoOperations.splice(0, 0, ...mergeOperations.undoOperations);
        }
        transaction(protyle, doOperations, undoOperations, {trackedRangeInsertion});
        newElement.querySelector("wbr").remove();
        removeEmptyNode(newElement);
        return true;
    }
    const undoFocusContext = getUndoFocusContext(protyle.wysiwyg.element, range);
    activateTrackedRangeInsertion(trackedRangeInsertion);
    range.insertNode(document.createElement("wbr"));
    const html = blockElement.outerHTML;
    const parentHTML = getParentBlock(blockElement).outerHTML;
    if (range.toString() !== "") {
        // 选中数学公式后回车取消选中 https://github.com/siyuan-note/siyuan/issues/12637#issuecomment-2381106949
        const mathElement = hasClosestByAttribute(range.startContainer, "data-type", "inline-math");
        if (mathElement) {
            const nextSibling = hasNextSibling(mathElement);
            if (nextSibling) {
                range = getSelection().getRangeAt(0);
                range.setEnd(nextSibling, nextSibling.textContent.startsWith(Constants.ZWSP) ? 1 : 0);
                range.collapse(false);
            }
            mathElement.querySelector("wbr")?.remove();
            return true;
        }
        range.extractContents();
        range.insertNode(document.createElement("wbr"));
    }
    if (editableElement.lastChild) {
        range.setEndAfter(editableElement.lastChild);
    }
    const id = blockElement.getAttribute("data-node-id");
    const newElement = document.createElement("div");
    if (blockElement.getAttribute("data-type") === "NodeHeading" && blockElement.getAttribute("fold") === "1") {
        newElement.innerHTML = genHeadingElement(blockElement, true) as string;
    } else {
        newElement.appendChild(genEmptyElement(false, false));
    }
    const newEditableElement = newElement.querySelector('[contenteditable="true"]');
    newEditableElement.appendChild(range.extractContents());
    const selectWbrElement = newEditableElement.querySelector("wbr");
    if (selectWbrElement && selectWbrElement.parentElement.tagName === "SPAN" && selectWbrElement.parentElement.innerHTML === "<wbr>") {
        selectWbrElement.parentElement.outerHTML = "<wbr>";
    }
    const newHTML = newEditableElement.innerHTML.trimStart();
    const newText = newEditableElement.textContent.trimStart();
    // https://github.com/siyuan-note/siyuan/issues/10759
    if (hasCodeBlockFence(newHTML, newText, enableCodeBlockMiddleDot)) {
        if (newHTML.indexOf("\n") === -1 &&
            newHTML.replace(codeBlockMarkerRegExp, "`").replace(/^`{3,}/g, "").indexOf("`") > -1) {
            // ```test` 不处理,正常渲染为段落块
        } else {
            let replaceNewHTML = newEditableElement.innerHTML
                .replace(codeBlockFenceLineRegExp, "\n```").trim()
                .replace(codeBlockFenceStartRegExp, "```");
            if (!replaceNewHTML.endsWith("\n```")) {
                replaceNewHTML += "\n```";
            }
            newEditableElement.innerHTML = replaceNewHTML;
        }
    }
    // https://github.com/siyuan-note/insider/issues/480
    newElement.innerHTML = protyle.lute.SpinBlockDOM(newElement.innerHTML);

    // https://github.com/siyuan-note/siyuan/issues/3850
    // https://github.com/siyuan-note/siyuan/issues/6018
    // https://github.com/siyuan-note/siyuan/issues/9682
    // 图片后的零宽空格前回车 https://github.com/siyuan-note/siyuan/issues/5690
    const enterElement = document.createElement("div");
    enterElement.innerHTML = protyle.lute.SpinBlockDOM(editableElement.parentElement.outerHTML);
    const doOperation: IOperation[] = [];
    const undoOperation: IOperation[] = [];
    let currentElement = blockElement;
    // 回车之前的块为 1\n\n2 时会产生多个块
    const selectsElement: Element[] = [];
    Array.from(enterElement.children).forEach((item: HTMLElement) => {
        if (item.dataset.nodeId === id) {
            blockElement.before(item);
            blockElement.remove();
            item.setAttribute(Constants.ATTRIBUTE_EDITING, "true");
            doOperation.push({
                action: "update",
                data: item.outerHTML,
                id,
            });
            undoOperation.push({
                action: "update",
                data: html,
                id,
                context: undoFocusContext,
            });
        } else {
            doOperation.push({
                action: "insert",
                data: item.outerHTML,
                id: item.dataset.nodeId,
                nextID: id,
            });
            currentElement.insertAdjacentElement("afterend", item);
            undoOperation.push({
                action: "delete",
                id: item.dataset.nodeId,
            });
        }
        if (item.dataset.type === "NodeBlockQueryEmbed") {
            blockRender(protyle, item);
        } else {
            mathRender(item);
        }
        currentElement = item;
        selectsElement.push(item);
    });

    Array.from(newElement.children).forEach((item: HTMLElement) => {
        const newId = item.getAttribute("data-node-id");
        doOperation.push({
            action: "insert",
            data: item.outerHTML,
            id: newId,
            previousID: currentElement.getAttribute("data-node-id"),
        });
        undoOperation.push({
            action: "delete",
            id: newId,
        });
        currentElement.insertAdjacentElement("afterend", item);
        if (item.classList.contains("code-block")) {
            highlightRender(item);
        } else if (item.dataset.type === "NodeBlockQueryEmbed") {
            blockRender(protyle, item);
        } else {
            mathRender(currentElement.nextElementSibling);
        }
        currentElement = item;
        selectsElement.push(item);
    });
    let parentElement = currentElement.parentElement;
    if (parentElement.classList.contains("bq") && parentElement.childElementCount > 2 &&
        currentElement.previousElementSibling.classList.contains("p") && currentElement.classList.contains("p") &&
        currentElement.previousElementSibling.textContent.startsWith("[!") && parentHTML) {
        const calloutHTML = protyle.lute.SpinBlockDOM(parentElement.outerHTML);
        if (calloutHTML.indexOf('data-type="NodeCallout"') > -1) {
            parentElement.insertAdjacentHTML("afterend", calloutHTML);
            parentElement = parentElement.nextElementSibling as HTMLElement;
            parentElement.previousElementSibling.remove();
            mathRender(protyle.wysiwyg.element);
            updateTransaction(protyle, parentElement, parentHTML, undefined, undefined, {trackedRangeInsertion});
            focusByWbr(protyle.wysiwyg.element, range);
            scrollCenter(protyle);
            return true;
        }
    }
    undoOperation.find((item, index) => {
        if (item.action === "update") {
            undoOperation.splice(index, 1);
            undoOperation.push(item);
            return true;
        }
    });
    if (parentElement.classList.contains("sb") &&
        parentElement.getAttribute("data-sb-layout") === "col") {
        // 合并到同一个 transaction,避免新块 id 在第二个 transaction 中找不到
        const sbOperations = await turnsIntoOneTransaction({
            protyle,
            selectsElement,
            type: "BlocksMergeSuperBlock",
            level: "row",
            unfocus: true,
            getOperations: true,
        });
        doOperation.push(...sbOperations.doOperations);
        undoOperation.splice(0, 0, ...sbOperations.undoOperations);
    }
    transaction(protyle, doOperation, undoOperation, {trackedRangeInsertion});
    focusByWbr(currentElement, range);
    scrollCenter(protyle);
    return true;
};

const getEmbedListEnterMode = (blockElement: HTMLElement, embedContext: IEmbedChildOperationContext) => {
    const listItemElement = blockElement.parentElement;
    // 单独查询列表项时外层列表是渲染器补充的,回车只能在目标列表项内部创建普通子块。
    if (listItemElement === embedContext.targetElement) {
        return "block";
    }
    const listElement = listItemElement.parentElement;
    const editableElement = getContenteditableElement(blockElement);
    const exitsList = isEmptyListItemBlock(editableElement.textContent, !!blockElement.querySelector("img")) &&
        blockElement.previousElementSibling.classList.contains("protyle-action");
    if (exitsList && listElement.parentElement === embedContext.resultElement) {
        return "none";
    }
    return embedContext.boundaryElement.contains(exitsList ? listElement.parentElement : listElement) ? "list" : "none";
};

const listEnter = async (protyle: IProtyle, blockElement: HTMLElement, range: Range,
                         trackedRangeInsertion?: ITrackedRangeInsertion) => {
    const listItemElement = blockElement.parentElement;
    const editableElement = getContenteditableElement(blockElement);
    const isPrimaryBlock = blockElement.previousElementSibling.classList.contains("protyle-action");
    const isEmptyBlock = isEmptyListItemBlock(editableElement.textContent, !!blockElement.querySelector("img"));
    // 列表项的非空末尾子块按普通块处理,空子块再次回车时仍创建后续列表项。
    if (shouldCreateListItemChildOnEnter(isPrimaryBlock,
        blockElement.nextElementSibling.classList.contains("protyle-attr"), isEmptyBlock)) {
        return false;
    }
    if (// \n 是因为 https://github.com/siyuan-note/siyuan/issues/3846
        isEmptyBlock &&
        isPrimaryBlock // https://ld246.com/article/1651820644238
    ) {
        if (listItemElement.nextElementSibling?.classList.contains("protyle-attr")) {
            await listOutdent(protyle, [blockElement.parentElement], range, false, undefined, trackedRangeInsertion);
            return true;
        } else if (!listItemElement.parentElement.classList.contains("protyle-wysiwyg")) {
            // 打断列表
            await breakList(protyle, blockElement, range, trackedRangeInsertion);
            return true;
        }
    }

    const position = getSelectionOffset(editableElement, protyle.wysiwyg.element, range);
    if (range.toString() === "" && position.start === 0 &&
        // 段首为图片是 start 也为 0
        !hasPreviousSibling(range.startContainer)) {
        // 段首换行
        if (listItemElement.parentElement.classList.contains("protyle-wysiwyg")) {
            return true;
        }
        // https://github.com/siyuan-note/siyuan/issues/8935
        activateTrackedRangeInsertion(trackedRangeInsertion);
        const wbrElement = document.createElement("wbr");
        range.insertNode(wbrElement);
        const listElement = listItemElement.parentElement;
        const html = listElement.outerHTML;
        const listStart = getOrderedListStart(listElement);
        wbrElement.remove();
        let newElement = genListItemElement(listItemElement, -1, true);
        if (!isPrimaryBlock) {
            // 列表项中有多个块,最后一个块为空,换行应进行缩进
            if (!isEmptyBlock) {
                return false;
            }
            blockElement.remove();
            newElement = genListItemElement(listItemElement, -1, true);
            listItemElement.insertAdjacentElement("afterend", newElement);
        } else if (isEmptyBlock) {
            listItemElement.insertAdjacentElement("afterend", newElement);
        } else {
            listItemElement.insertAdjacentElement("beforebegin", newElement);
        }
        if (listItemElement.getAttribute("data-subtype") === "o") {
            updateListOrder(listElement, listStart);
        }
        updateTransaction(protyle, listElement, html, undefined, undefined, {trackedRangeInsertion});
        focusByWbr(newElement, range);
        scrollCenter(protyle);
        removeEmptyNode(newElement);
        return true;
    }

    const shouldUpdateParentList = listItemElement.getAttribute("data-subtype") === "o" &&
        listItemElement.parentElement.classList.contains("protyle-wysiwyg");
    const focusedParentListElement = shouldUpdateParentList ?
        await getFocusedParentOrderedList(protyle, listItemElement.parentElement) : undefined;
    if (shouldUpdateParentList && !focusedParentListElement) {
        return true;
    }
    if (!listItemElement.isConnected) {
        return true;
    }
    prepareInlineElementBoundaryMutation(range);
    activateTrackedRangeInsertion(trackedRangeInsertion);
    const subListElement = listItemElement.querySelector(".list");
    let newElement;
    if (subListElement && listItemElement.getAttribute("fold") !== "1" &&
        // 子列表下的段落块回车 https://ld246.com/article/1623919354587
        blockElement.nextElementSibling === subListElement) {
        // 含有子列表的换行
        if (position.end >= editableElement.textContent.length -
            // 数学公式结尾会有 zwsp https://github.com/siyuan-note/siyuan/issues/6679
            (editableElement.textContent.endsWith(Constants.ZWSP) ? 1 : 0)) {
            // 段末换行,在子列表中插入
            range.insertNode(document.createElement("wbr"));
            const html = listItemElement.outerHTML;
            const listStart = getOrderedListStart(subListElement);
            blockElement.querySelector("wbr").remove();
            newElement = genListItemElement(subListElement.firstElementChild, -1, true);
            subListElement.firstElementChild.before(newElement);
            if (subListElement.getAttribute("data-subtype") === "o") {
                updateListOrder(subListElement, listStart);
            }
            updateTransaction(protyle, listItemElement, html, undefined, undefined, {trackedRangeInsertion});
            focusByWbr(listItemElement, range);
            scrollCenter(protyle);
        } else {
            // 文字中间换行
            range.insertNode(document.createElement("wbr"));
            const listItemHTML = listItemElement.outerHTML;
            const html = listItemElement.parentElement.outerHTML;
            if (range.toString() !== "") {
                range.extractContents();
                range.insertNode(document.createElement("wbr"));
            }
            range.setEndAfter(editableElement.lastChild);
            newElement = genListItemElement(listItemElement, 0, false);
            const newEditElement = getContenteditableElement(newElement);
            newEditElement.appendChild(range.extractContents());
            const subWbrElement = newEditElement.querySelector("wbr");
            if (subWbrElement && subWbrElement.parentElement.tagName === "SPAN" && subWbrElement.parentElement.innerHTML === "<wbr>") {
                subWbrElement.parentElement.outerHTML = "<wbr>";
            }
            newEditElement.parentElement.outerHTML = protyle.lute.SpinBlockDOM(newEditElement.parentElement.outerHTML);
            let subListNextElement = subListElement.nextElementSibling;
            newElement.lastElementChild.before(subListElement);
            // https://github.com/siyuan-note/siyuan/issues/13016
            while (!subListNextElement.classList.contains("protyle-attr")) {
                subListNextElement = subListNextElement.nextElementSibling;
                newElement.lastElementChild.before(subListNextElement.previousElementSibling);
            }
            listItemElement.insertAdjacentElement("afterend", newElement);
            blockRender(protyle, newElement);
            mathRender(newElement);
            processRender(newElement);
            if (listItemElement.getAttribute("data-subtype") === "o") {
                updateListOrder(listItemElement.parentElement);
            }
            if (listItemElement.parentElement.classList.contains("protyle-wysiwyg")) {
                const orderOperations = focusedParentListElement ?
                    getFocusedOrderedListInsertOperations(focusedParentListElement, listItemElement, newElement) :
                    {doOperations: [], undoOperations: []};
                listItemElement.setAttribute(Constants.ATTRIBUTE_EDITING, "true");
                transaction(protyle, [{
                    action: "update",
                    data: listItemElement.outerHTML,
                    id: listItemElement.getAttribute("data-node-id")
                }, {
                    action: "insert",
                    id: newElement.getAttribute("data-node-id"),
                    data: newElement.outerHTML,
                    previousID: listItemElement.getAttribute("data-node-id")
                }, ...orderOperations.doOperations], [{
                    action: "delete",
                    id: newElement.getAttribute("data-node-id"),
                }, {
                    action: "update",
                    data: listItemHTML,
                    id: listItemElement.getAttribute("data-node-id")
                }, ...orderOperations.undoOperations], {trackedRangeInsertion});
            } else {
                updateTransaction(protyle, listItemElement.parentElement, html, undefined, undefined,
                    {trackedRangeInsertion});
            }
            focusByWbr(newElement, range);
            scrollCenter(protyle);
        }
        removeEmptyNode(newElement);
        return true;
    }
    if ((range.toString() === "" || range.toString() === Constants.ZWSP) && range.startContainer.nodeType === 3 && range.startOffset === 0) {
        // 图片后的零宽空格前回车 https://github.com/siyuan-note/siyuan/issues/5690
        // 列表中的图片后双击换行图片光标错误 https://ld246.com/article/1660987186727/comment/1662181221732?r=Vanessa#comments
        let nextSibling = range.startContainer;
        while (nextSibling) {
            if (nextSibling.textContent === Constants.ZWSP) {
                range.setStart(nextSibling, 1);
                range.collapse(false);
                break;
            } else {
                nextSibling = nextSibling.nextSibling;
            }
        }
    }
    range.insertNode(document.createElement("wbr"));
    const listItemHTML = listItemElement.outerHTML;
    const oldHTML = listItemElement.parentElement.outerHTML;
    if (range.toString() !== "") {
        // 选中数学公式后回车取消选中 https://github.com/siyuan-note/siyuan/issues/12637#issuecomment-2381106949
        const mathElement = hasClosestByAttribute(range.startContainer, "data-type", "inline-math");
        if (mathElement) {
            const nextSibling = hasNextSibling(mathElement);
            if (nextSibling) {
                range = getSelection().getRangeAt(0);
                range.setEnd(nextSibling, nextSibling.textContent.startsWith(Constants.ZWSP) ? 1 : 0);
                range.collapse(false);
            }
            mathElement.querySelector("wbr")?.remove();
            return true;
        }
        range.extractContents();
        range.insertNode(document.createElement("wbr"));
    }
    if (editableElement.lastChild) {
        range.setEndAfter(editableElement.lastChild);
    }
    newElement = genListItemElement(listItemElement, 0, false);
    const newEditableElement = getContenteditableElement(newElement);
    newEditableElement.appendChild(range.extractContents());
    const selectWbrElement = newEditableElement.querySelector("wbr");
    if (selectWbrElement && selectWbrElement.parentElement.tagName === "SPAN" && selectWbrElement.parentElement.innerHTML === "<wbr>") {
        selectWbrElement.parentElement.outerHTML = "<wbr>";
    }
    // 回车移除空元素 https://github.com/siyuan-note/insider/issues/480
    // https://github.com/siyuan-note/siyuan/issues/12273
    // 文字和图片中间回车后图片前需添加 zwsp
    newEditableElement.parentElement.outerHTML = protyle.lute.SpinBlockDOM(newEditableElement.parentElement.outerHTML);
    listItemElement.insertAdjacentElement("afterend", newElement);
    blockRender(protyle, newElement);
    mathRender(newElement);
    processRender(newElement);
    // https://github.com/siyuan-note/siyuan/issues/3850
    // https://github.com/siyuan-note/siyuan/issues/6018
    // img 后有文字,在 img 后换行
    editableElement.parentElement.outerHTML = protyle.lute.SpinBlockDOM(editableElement.parentElement.outerHTML);
    blockRender(protyle, listItemElement);
    mathRender(listItemElement);
    processRender(listItemElement);
    if (listItemElement.getAttribute("data-subtype") === "o") {
        updateListOrder(listItemElement.parentElement);
    }
    if (listItemElement.parentElement.classList.contains("protyle-wysiwyg")) {
        const orderOperations = focusedParentListElement ?
            getFocusedOrderedListInsertOperations(focusedParentListElement, listItemElement, newElement) :
            {doOperations: [], undoOperations: []};
        listItemElement.setAttribute(Constants.ATTRIBUTE_EDITING, "true");
        transaction(protyle, [{
            action: "update",
            id: listItemElement.getAttribute("data-node-id"),
            data: listItemElement.outerHTML,
        }, {
            action: "insert",
            id: newElement.getAttribute("data-node-id"),
            data: newElement.outerHTML,
            previousID: listItemElement.getAttribute("data-node-id")
        }, ...orderOperations.doOperations], [{
            action: "delete",
            id: newElement.getAttribute("data-node-id"),
        }, {
            action: "update",
            id: listItemElement.getAttribute("data-node-id"),
            data: listItemHTML
        }, ...orderOperations.undoOperations], {trackedRangeInsertion});
    } else {
        updateTransaction(protyle, listItemElement.parentElement, oldHTML, undefined, undefined,
            {trackedRangeInsertion});
    }
    focusByWbr(newElement, range);
    scrollCenter(protyle);
    removeEmptyNode(newElement);
    return true;
};

const removeEmptyNode = (newElement: Element) => {
    const children = getContenteditableElement(newElement).childNodes;
    for (let i = 0; i < children.length; i++) {
        if (children[i].nodeType === 3 && children[i].textContent.length === 0) {
            children[i].remove();
            i--;
        }
    }
};

export const softEnter = (range: Range, nodeElement: HTMLElement, protyle: IProtyle,
                          trackedRangeInsertion?: ITrackedRangeInsertion) => {
    prepareInlineElementBoundaryMutation(range);
    if (range.collapsed && nodeElement.getAttribute("data-type") === "NodeParagraph") {
        const editableElement = getContenteditableElement(nodeElement);
        if (editableElement?.contains(range.startContainer)) {
            const prefixRange = range.cloneRange();
            prefixRange.setStart(editableElement, 0);
            const prefix = prefixRange.cloneContents();
            // 段落开头和空段落不插入软换行,列表项内的段落遵循相同规则。
            // https://github.com/siyuan-note/siyuan/issues/12200
            if (getTextWithoutSemanticMarkers(prefix).split(Constants.ZWSP).join("") === "" &&
                !prefix.querySelector("br, img, .img, .emoji, [data-type='inline-math']")) {
                return true;
            }
        }
    }
    let startElement = range.startContainer as HTMLElement;
    const nextSibling = hasNextSibling(startElement) as Element;
    if (nodeElement.getAttribute("data-type") === "NodeAttributeView") {
        return true;
    }
    if (nextSibling && nextSibling.nodeType !== 3) {
        const textPosition = getSelectionOffset(range.startContainer, protyle.wysiwyg.element, range);
        if (textPosition.end === range.endContainer.textContent.length) {
            // 图片之前软换行 || 数学公式之前软换行 https://github.com/siyuan-note/siyuan/issues/13621
            if (nextSibling.classList.contains("img") || nextSibling.getAttribute("data-type") === "inline-math") {
                activateTrackedRangeInsertion(trackedRangeInsertion);
                nextSibling.insertAdjacentHTML("beforebegin", "<wbr>");
                const oldHTML = nodeElement.outerHTML;
                nextSibling.previousElementSibling.remove();
                const newlineNode = document.createTextNode("\n");
                startElement.after(document.createTextNode(Constants.ZWSP));
                startElement.after(newlineNode);
                range.selectNode(newlineNode);
                range.collapse(false);
                updateTransaction(protyle, nodeElement, oldHTML, undefined, undefined, {trackedRangeInsertion});
                return true;
            }
        }
    }
    // 行内元素末尾软换行 https://github.com/siyuan-note/insider/issues/886
    if (startElement.nodeType === 3) {
        startElement = startElement.parentElement;
    }
    if (startElement && protyle.toolbar.getCurrentType(range).length > 0 &&
        getSelectionOffset(startElement, startElement, range).end === startElement.textContent.length) {
        addNewLineToEnd(range, nodeElement, protyle, startElement, trackedRangeInsertion);
        return true;
    }
    if (isIPad() || isMobile()) {
        // iPad shift+enter 无效
        startElement = range.startContainer as HTMLElement;
        const nextSibling = hasNextSibling(startElement);
        if (nextSibling && nextSibling.textContent.trim() !== "") {
            document.execCommand("insertHTML", false, "\n");
            return true;
        }
        addNewLineToEnd(range, nodeElement, protyle, startElement, trackedRangeInsertion);
        return true;
    }
    return false;
};

const addNewLineToEnd = (range: Range, nodeElement: HTMLElement, protyle: IProtyle, startElement: Element,
                         trackedRangeInsertion?: ITrackedRangeInsertion) => {
    activateTrackedRangeInsertion(trackedRangeInsertion);
    const wbrElement = document.createElement("wbr");
    if (startElement.nodeType === 3) {
        range.insertNode(wbrElement);
    } else {
        startElement.insertAdjacentElement("afterend", wbrElement);
    }
    const oldHTML = nodeElement.outerHTML;
    wbrElement.remove();
    let endNewlineNode;
    if (!hasNextSibling(startElement)) {
        endNewlineNode = document.createTextNode("\n");
        startElement.after(endNewlineNode);
    }
    const newlineNode = document.createTextNode("\n");
    startElement.after(newlineNode);
    const beforeRange = document.createRange();
    beforeRange.setStartBefore(newlineNode);
    beforeRange.collapse(true);
    const afterRange = document.createRange();
    afterRange.setStartAfter(newlineNode);
    afterRange.collapse(true);
    setTrackedRangeInsertionResult(trackedRangeInsertion, beforeRange, afterRange);
    if (endNewlineNode) {
        range.setStart(endNewlineNode, 0);
    } else {
        range.setStart(newlineNode, 1);
    }
    range.collapse(true);
    focusByRange(range);
    updateTransaction(protyle, nodeElement, oldHTML, undefined, undefined, {trackedRangeInsertion});
};