An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: https://github.com/siyuan-note/siyuan/issues/8554
Vanessacfba5dffbd26
diff --git a/app/src/protyle/util/insertHTML.ts b/app/src/protyle/util/insertHTML.tsindex b08440aaf8..90d72d1e9e 100644--- a/app/src/protyle/util/insertHTML.ts+++ b/app/src/protyle/util/insertHTML.ts@@ -1,14 +1,27 @@-import {hasClosestBlock, hasClosestByAttribute, hasClosestByClassName, hasClosestByTag} from "./hasClosest";+import {+ hasClosestBlock,+ hasClosestByAttribute,+ hasClosestByClassName,+ hasClosestByTag,+ isInEmbedBlock+} from "./hasClosest";import * as dayjs from "dayjs";import {transaction, updateTransaction} from "../wysiwyg/transaction";-import {fixAdjacentTags, getContenteditableElement, getParentBlock, getPreviousBlockSibling} from "../wysiwyg/getBlock";+import {+ fixAdjacentTags,+ getContenteditableElement,+ getParentBlock,+ getPreviousBlockSibling+} from "../wysiwyg/getBlock";import {fixTableRange,focusBlock,focusByRange,focusByWbr,+ getBlockRanges,getEditorRange,getSelectionOffset,+ getUndoFocusContext,setLastNodeRange,} from "./selection";import {Constants} from "../../constants";@@ -31,6 +44,7 @@ import {} from "../render/av/paste";import {Dialog} from "../../dialog";import {isMobile} from "../../util/functions";+import {getCrossBlockMergeRemoveElement} from "../wysiwyg/removeRange";// 粘贴时临时插入的占位行标记,遍历结束后统一移除,避免污染虚拟滚动的 renderedStart/renderedEnd/spacer 状态const PLACEHOLDER_ROW_CLASS = "av__row--placeholder";@@ -777,6 +791,25 @@ export const insertHTML = (html: string, protyle: IProtyle, isBlock = false,return;}const range = useProtyleRange ? protyle.toolbar.range : getEditorRange(protyle.wysiwyg.element);+ const rangeStartBlockElement = hasClosestBlock(range.startContainer);+ const rangeEndBlockElement = hasClosestBlock(range.endContainer);+ if (!range.collapsed && rangeStartBlockElement && rangeEndBlockElement &&+ rangeStartBlockElement !== rangeEndBlockElement) {+ const hasUnsupportedBoundary = [+ {blockElement: rangeStartBlockElement, container: range.startContainer},+ {blockElement: rangeEndBlockElement, container: range.endContainer},+ ].some(item => {+ if (item.blockElement.classList.contains("av") || isInEmbedBlock(item.blockElement)) {+ return true;+ }+ const editableElement = getContenteditableElement(item.blockElement);+ return !editableElement ||+ (item.container !== item.blockElement && !editableElement.contains(item.container));+ });+ if (hasUnsupportedBoundary) {+ return;+ }+ }const tablePasteTarget = getTablePasteTarget(range);fixTableRange(range);let unSpinHTML;@@ -814,15 +847,134 @@ export const insertHTML = (html: string, protyle: IProtyle, isBlock = false,return;}+ const blockRanges = !range.collapsed ? getBlockRanges(protyle.wysiwyg.element, range) : [];+ const isCrossBlockRange = blockRanges.length > 1 && blockRanges[0].blockElement === blockElement;+ const crossBlockUndoFocusContext = isCrossBlockRange ?+ getUndoFocusContext(protyle.wysiwyg.element, range, true) : undefined;+ const removeElements: HTMLElement[] = [];+ if (isCrossBlockRange) {+ const startElement = blockRanges[0].blockElement;+ const endElement = blockRanges[blockRanges.length - 1].blockElement;+ const selectedElements: HTMLElement[] = [];+ range.cloneContents().querySelectorAll<HTMLElement>("[data-node-id]").forEach(item => {+ const element = protyle.wysiwyg.element.querySelector<HTMLElement>(+ `[data-node-id="${item.getAttribute("data-node-id")}"]`+ );+ if (!element || selectedElements.includes(element) || element === startElement || element === endElement ||+ element.contains(startElement) || element.contains(endElement) || isInEmbedBlock(element)) {+ return;+ }+ const elementRange = document.createRange();+ elementRange.selectNode(element);+ if (range.compareBoundaryPoints(Range.START_TO_START, elementRange) <= 0 &&+ range.compareBoundaryPoints(Range.END_TO_END, elementRange) >= 0) {+ selectedElements.push(element);+ }+ });+ const selectedSet = new Set(selectedElements);+ removeElements.push(...selectedElements.filter(item =>+ !selectedSet.has(item.parentElement.closest<HTMLElement>("[data-node-id]"))+ ));++ const endBlockRange = blockRanges.slice().reverse().find(item => item.blockElement === endElement);+ if (endBlockRange && endElement.getAttribute("data-type") !== "NodeTable") {+ const contentRange = document.createRange();+ contentRange.selectNodeContents(endBlockRange.editableElement);+ const selectedPosition = getSelectionOffset(+ endBlockRange.editableElement, undefined, endBlockRange.range, true+ );+ const contentPosition = getSelectionOffset(+ endBlockRange.editableElement, undefined, contentRange, true+ );+ const mediaSelector = "img, video, audio, iframe, canvas";+ const fullySelected = selectedPosition.start === 0 && selectedPosition.end === contentPosition.end &&+ endBlockRange.range.cloneContents().querySelectorAll(mediaSelector).length ===+ contentRange.cloneContents().querySelectorAll(mediaSelector).length;+ if (fullySelected) {+ const topElement = getCrossBlockMergeRemoveElement(+ protyle.wysiwyg.element, startElement, endElement);+ if (topElement) {+ for (let i = removeElements.length - 1; i >= 0; i--) {+ if (topElement.contains(removeElements[i])) {+ removeElements.splice(i, 1);+ }+ }+ removeElements.push(topElement);+ }+ }+ }+ }+ const crossBlockData = removeElements.map(element => ({+ element,+ oldHTML: element.outerHTML,+ previousID: getPreviousBlockSibling(element)?.getAttribute("data-node-id"),+ parentID: getParentBlock(element)?.getAttribute("data-node-id") || protyle.block.parentID,+ remove: true+ }));+ if (isCrossBlockRange) {+ Array.from(new Set(blockRanges.map(item => item.blockElement))).slice(1).forEach(element => {+ if (removeElements.some(removeElement => removeElement.contains(element))) {+ return;+ }+ crossBlockData.push({+ element,+ oldHTML: element.outerHTML,+ previousID: getPreviousBlockSibling(element)?.getAttribute("data-node-id"),+ parentID: getParentBlock(element)?.getAttribute("data-node-id") || protyle.block.parentID,+ remove: false+ });+ });+ }let id = blockElement.getAttribute("data-node-id");- range.insertNode(document.createElement("wbr"));+ const rangeStartWbrElement = document.createElement("wbr");+ range.insertNode(rangeStartWbrElement);+ if (isCrossBlockRange) {+ range.setStartAfter(rangeStartWbrElement);+ }let oldHTML = blockElement.outerHTML;const type = blockElement.getAttribute("data-type");const isNodeCodeBlock = type === "NodeCodeBlock";const editableElement = getContenteditableElement(blockElement);+ const crossBlockDoOperations: IOperation[] = [];+ const crossBlockUndoOperations: IOperation[] = [];+ const processCrossBlockData = () => {+ crossBlockData.forEach(item => {+ if (item.remove) {+ item.element.remove();+ crossBlockDoOperations.push({+ action: "delete",+ id: item.element.getAttribute("data-node-id")+ });+ crossBlockUndoOperations.push({+ action: "insert",+ id: item.element.getAttribute("data-node-id"),+ data: item.oldHTML,+ previousID: item.previousID,+ parentID: item.parentID+ });+ } else if (item.element.isConnected && item.oldHTML !== item.element.outerHTML) {+ item.element.setAttribute("updated", dayjs().format("YYYYMMDDHHmmss"));+ item.element.setAttribute(Constants.ATTRIBUTE_EDITING, "true");+ crossBlockDoOperations.push({+ action: "update",+ id: item.element.getAttribute("data-node-id"),+ data: item.element.outerHTML+ });+ crossBlockUndoOperations.push({+ action: "update",+ id: item.element.getAttribute("data-node-id"),+ data: item.oldHTML+ });+ }+ });+ };if (!isBlock &&(isNodeCodeBlock || protyle.toolbar.getCurrentType(range).includes("code"))) {range.deleteContents();+ if (isCrossBlockRange && rangeStartWbrElement.isConnected) {+ range.setStartAfter(rangeStartWbrElement);+ range.collapse(true);+ }// 代码块需保持至少一个 \n https://github.com/siyuan-note/siyuan/pull/13271#issuecomment-2502672155let codeBlockIsEmpty = false;if (isNodeCodeBlock && editableElement.textContent === "") {@@ -843,7 +995,22 @@ export const insertHTML = (html: string, protyle: IProtyle, isBlock = false,focusByWbr(blockElement, range);}blockElement.setAttribute("updated", dayjs().format("YYYYMMDDHHmmss"));- updateTransaction(protyle, blockElement, oldHTML);+ if (isCrossBlockRange) {+ processCrossBlockData();+ blockElement.setAttribute(Constants.ATTRIBUTE_EDITING, "true");+ transaction(protyle, [{+ action: "update",+ id,+ data: blockElement.outerHTML+ }, ...crossBlockDoOperations], [{+ action: "update",+ id,+ data: oldHTML,+ context: crossBlockUndoFocusContext+ }, ...crossBlockUndoOperations]);+ } else {+ updateTransaction(protyle, blockElement, oldHTML);+ }setTimeout(() => {scrollCenter(protyle, undefined, "nearest", "smooth");}, Constants.TIMEOUT_LOAD);@@ -852,7 +1019,7 @@ export const insertHTML = (html: string, protyle: IProtyle, isBlock = false,const undoOperation: IOperation[] = [];const doOperation: IOperation[] = [];- if (range.toString() !== "") {+ if (range.toString() !== "" || isCrossBlockRange) {const inlineMathElement = hasClosestByAttribute(range.commonAncestorContainer, "data-type", "inline-math");if (inlineMathElement) {// 表格内选中数学公式 https://ld246.com/article/1631708573504@@ -874,13 +1041,15 @@ export const insertHTML = (html: string, protyle: IProtyle, isBlock = false,undoOperation.push({action: "update",id,- data: oldHTML+ data: oldHTML,+ context: crossBlockUndoFocusContext});doOperation.push({action: "update",id,data: blockElement.outerHTML});+ processCrossBlockData();}const tempElement = document.createElement("template");@@ -904,9 +1073,11 @@ export const insertHTML = (html: string, protyle: IProtyle, isBlock = false,tempElement.content.childElementCount === 1 &&tempElement.content.firstChild.nodeType !== 3 &&tempElement.content.firstElementChild.getAttribute("data-type") === "NodeHeading") {- // https://github.com/siyuan-note/siyuan/issues/14114- isBlock = false;- block2text = true;+ if (!isCrossBlockRange) {+ // https://github.com/siyuan-note/siyuan/issues/14114+ isBlock = false;+ block2text = true;+ }}// 使用 lute 方法会添加 p 元素,只有一个 p 元素或者只有一个字符串或者为 <u>b</u> 时的时候只拷贝内部if (!isBlock) {@@ -937,6 +1108,12 @@ export const insertHTML = (html: string, protyle: IProtyle, isBlock = false,range.collapse(true);splitElements.push(spanElement, afterElement);}+ if (isCrossBlockRange) {+ if (rangeStartWbrElement.isConnected) {+ range.setStartAfter(rangeStartWbrElement);+ range.collapse(true);+ }+ }range.insertNode(tempElement.content.cloneNode(true));range.collapse(false);blockElement.querySelector("wbr")?.remove();@@ -949,7 +1126,11 @@ export const insertHTML = (html: string, protyle: IProtyle, isBlock = false,// 相邻标签之间插入空格区隔,避免后续 SpinBlockDOM 解析时合并为一个标签 https://github.com/siyuan-note/siyuan/issues/18191fixAdjacentTags(getContenteditableElement(blockElement));protyle.wysiwyg.lastHTMLs[id] = oldHTML;- input(protyle, blockElement as HTMLElement, range);+ input(protyle, blockElement as HTMLElement, range, true, undefined, isCrossBlockRange ? {+ doOperations: crossBlockDoOperations,+ undoOperations: crossBlockUndoOperations,+ undoContext: crossBlockUndoFocusContext,+ } : undefined);return;}}@@ -1111,7 +1292,14 @@ export const insertHTML = (html: string, protyle: IProtyle, isBlock = false,lastElement = item;}});- if (editableElement && editableElement.textContent === "" && blockElement.classList.contains("p") && !keepEmptyBlock) {+ const emptyStartType = blockElement.getAttribute("data-type");+ const canRemoveEmptyStart = emptyStartType === "NodeParagraph" ||+ emptyStartType === "NodeCodeBlock" ||+ (emptyStartType === "NodeHeading" && blockElement.getAttribute("fold") !== "1");+ const startTextIsEmpty = editableElement &&+ editableElement.textContent.split(Constants.ZWSP).join("").replace(/\n/g, "") === "";+ if (startTextIsEmpty && canRemoveEmptyStart && !keepEmptyBlock &&+ !editableElement?.querySelector("img, video, audio, iframe, canvas, .emoji")) {// 选中当前块所有内容粘贴再撤销会导致异常 https://ld246.com/article/1662542137636doOperation.find((item, index) => {if (item.id === id) {@@ -1135,7 +1323,8 @@ export const insertHTML = (html: string, protyle: IProtyle, isBlock = false,data: oldHTML,id,previousID: getPreviousBlockSibling(blockElement)?.getAttribute("data-node-id") || "",- parentID: getParentBlock(blockElement).getAttribute("data-node-id") || protyle.block.parentID+ parentID: getParentBlock(blockElement).getAttribute("data-node-id") || protyle.block.parentID,+ context: crossBlockUndoFocusContext});blockElement.remove();}@@ -1150,6 +1339,8 @@ export const insertHTML = (html: string, protyle: IProtyle, isBlock = false,protyle.wysiwyg.element.querySelectorAll("[parent-heading]").forEach(item => {item.remove();});+ doOperation.push(...crossBlockDoOperations);+ undoOperation.push(...crossBlockUndoOperations);let foldData;if (blockElement.getAttribute("data-type") === "NodeHeading" &&blockElement.getAttribute("fold") === "1" && !insertBefore) {diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.tsindex d4e9655917..f212c2398d 100644--- a/app/src/protyle/util/paste.ts+++ b/app/src/protyle/util/paste.ts@@ -3,7 +3,7 @@ import {uploadFiles, uploadLocalFiles} from "../upload";import {processPasteCode, processRender} from "./processCode";import {getLocalFiles, getTextSiyuanFromTextHTML, readText} from "./compatibility";import {hasClosestBlock, hasClosestByAttribute, hasClosestByClassName} from "./hasClosest";-import {getEditorRange, getSelectionOffset} from "./selection";+import {focusByOffset, getEditorRange, getSelectionOffset, getUndoFocusContext} from "./selection";import {blockRender} from "../render/blockRender";import {highlightRender} from "../render/highlightRender";import {fetchPost, fetchSyncPost} from "../../util/fetch";@@ -13,11 +13,15 @@ import {scrollCenter} from "../../util/highlightById";import {hideElements} from "../ui/hideElements";import {avRender} from "../render/av/render";import {cellScrollIntoView, getCellText} from "../render/av/cell";-import {getCalloutInfo, getContenteditableElement} from "../wysiwyg/getBlock";+import {fixAdjacentTags, getCalloutInfo, getContenteditableElement} from "../wysiwyg/getBlock";import {clearBlockElement} from "./clear";import {removeZWJ} from "./normalizeText";import {base64ToURL} from "../../util/image";import {resolveLinkDest} from "../toolbar/util";+import {updateTransaction} from "../wysiwyg/transaction";+import * as dayjs from "dayjs";+import {updateListOrder} from "../wysiwyg/list";+import {refreshSbAndPersistWidth} from "../../block/util";export const beforePaste = (protyle: IProtyle, blockElement: HTMLElement) => {// 链接,备注,样式,引用,pdf标注粘贴 https://github.com/siyuan-note/siyuan/issues/11572@@ -271,6 +275,193 @@ const readLocalFile = async (protyle: IProtyle, localFiles: ILocalFiles[]) => {uploadLocalFiles(localFiles, protyle, true);};+const convertPastedListItemSubtype = (listItemElement: HTMLElement, subtype: string) => {+ const actionElement = listItemElement.querySelector<HTMLElement>(".protyle-action");+ if (!actionElement || !["u", "o", "t"].includes(subtype)) {+ return;+ }+ listItemElement.setAttribute("data-subtype", subtype);+ listItemElement.classList.remove("protyle-task--done");+ if (subtype === "o") {+ listItemElement.removeAttribute("data-task");+ listItemElement.setAttribute("data-marker", "1.");+ actionElement.className = "protyle-action protyle-action--order";+ actionElement.setAttribute("contenteditable", "false");+ actionElement.textContent = "1.";+ } else if (subtype === "t") {+ listItemElement.setAttribute("data-marker", "*");+ listItemElement.setAttribute("data-task", " ");+ actionElement.className = "protyle-action protyle-action--task";+ actionElement.removeAttribute("contenteditable");+ actionElement.innerHTML = "<svg><use xlink:href=\"#iconUncheck\"></use></svg>";+ } else {+ listItemElement.removeAttribute("data-task");+ listItemElement.setAttribute("data-marker", "*");+ actionElement.className = "protyle-action";+ actionElement.removeAttribute("contenteditable");+ actionElement.innerHTML = "<svg><use xlink:href=\"#iconDot\"></use></svg>";+ }+};++const pasteCrossBlockRange = (protyle: IProtyle, tempElement: HTMLElement, range: Range) => {+ const pastedRoots = Array.from(tempElement.children) as HTMLElement[];+ if (!range.collapsed || pastedRoots.length < 2) {+ return false;+ }+ const textBlockTypes = ["NodeParagraph", "NodeHeading"];+ const firstBlockElement = pastedRoots[0];+ if (!textBlockTypes.includes(firstBlockElement.getAttribute("data-type"))) {+ return false;+ }+ const targetBlockElement = hasClosestBlock(range.startContainer) as HTMLElement;+ if (!targetBlockElement) {+ return false;+ }++ const lastRootElement = pastedRoots[pastedRoots.length - 1];+ const containerType = lastRootElement.getAttribute("data-type");+ const isTextBlockPaste = pastedRoots.every(item => textBlockTypes.includes(item.getAttribute("data-type")));+ const pastedContainerElement = !isTextBlockPaste && pastedRoots.length === 2 &&+ ["NodeList", "NodeBlockquote", "NodeCallout", "NodeSuperBlock"].includes(containerType) ?+ lastRootElement : undefined;+ if (!isTextBlockPaste && !pastedContainerElement) {+ return false;+ }++ const targetContainerElement = pastedContainerElement ?+ targetBlockElement.closest<HTMLElement>(`[data-type="${containerType}"]`) : undefined;+ const pastedContentElement = containerType === "NodeCallout" ?+ pastedContainerElement?.querySelector<HTMLElement>(":scope > .callout-content") : pastedContainerElement;+ const targetContentElement = containerType === "NodeCallout" ?+ targetContainerElement?.querySelector<HTMLElement>(":scope > .callout-content") : targetContainerElement;+ const pastedChildren = isTextBlockPaste ? pastedRoots.slice(1) :+ Array.from(pastedContentElement?.children || []).filter(item =>+ item.hasAttribute("data-node-id")) as HTMLElement[];+ const endBlockElement = isTextBlockPaste ? lastRootElement :+ Array.from(pastedContainerElement.querySelectorAll<HTMLElement>(+ '[data-type="NodeParagraph"], [data-type="NodeHeading"]'+ )).reverse().find(item => !item.querySelector(":scope > .protyle-attr"));+ let targetChildElement: HTMLElement = targetBlockElement;+ if (pastedContainerElement) {+ while (targetChildElement.parentElement && targetChildElement.parentElement !== targetContentElement) {+ targetChildElement = targetChildElement.parentElement;+ }+ }+ if (!endBlockElement || pastedChildren.length === 0 ||+ (pastedContainerElement && (!targetContainerElement || !targetContentElement ||+ targetChildElement.parentElement !== targetContentElement))) {+ return false;+ }+ if (containerType === "NodeList") {+ if (targetChildElement.getAttribute("data-type") !== "NodeListItem" ||+ targetBlockElement.previousElementSibling?.classList.contains("protyle-action") !== true) {+ return false;+ }+ const targetSubtype = targetContainerElement.getAttribute("data-subtype");+ pastedChildren.forEach(item => {+ if (item.getAttribute("data-subtype") !== targetSubtype) {+ convertPastedListItemSubtype(item, targetSubtype);+ }+ });+ }+ const targetEditableElement = getContenteditableElement(targetBlockElement);+ const firstEditableElement = getContenteditableElement(firstBlockElement);+ const endEditableElement = getContenteditableElement(endBlockElement);+ if (!targetEditableElement?.contains(range.startContainer) || !firstEditableElement || !endEditableElement) {+ return false;+ }++ const oldHTML = targetChildElement.outerHTML;+ const oldListItemHTML = containerType === "NodeList" ? new Map(Array.from(+ targetContainerElement.querySelectorAll<HTMLElement>(":scope > .li")+ ).map(item => [item.getAttribute("data-node-id"), item.outerHTML])) : undefined;+ const undoFocusContext = getUndoFocusContext(protyle.wysiwyg.element, range, true);+ const markerElement = document.createElement("wbr");+ range.insertNode(markerElement);+ const suffixRange = document.createRange();+ suffixRange.setStartAfter(markerElement);+ suffixRange.setEnd(targetEditableElement, targetEditableElement.childNodes.length);+ const suffixFragment = suffixRange.extractContents();+ const pastedEndRange = document.createRange();+ pastedEndRange.selectNodeContents(endEditableElement);+ const pastedEnd = getSelectionOffset(endEditableElement, undefined, pastedEndRange, true).end;+ while (firstEditableElement.firstChild) {+ markerElement.before(firstEditableElement.firstChild);+ }+ markerElement.remove();+ endEditableElement.append(suffixFragment);+ let boundaryElement = endBlockElement;+ while (boundaryElement) {+ if (boundaryElement.hasAttribute("data-node-id") &&+ !boundaryElement.querySelector(":scope > .protyle-attr")) {+ boundaryElement.insertAdjacentHTML("beforeend",+ `<div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div>`);+ }+ if (boundaryElement === (pastedContainerElement || endBlockElement)) {+ break;+ }+ boundaryElement = boundaryElement.parentElement;+ }+ fixAdjacentTags(targetEditableElement);+ fixAdjacentTags(endEditableElement);+ targetChildElement.after(...pastedChildren);+ if (containerType === "NodeList") {+ updateListOrder(targetContainerElement);+ }+ targetChildElement.setAttribute("updated", dayjs().format("YYYYMMDDHHmmss"));++ const widthDoOperations: IOperation[] = [];+ const widthUndoOperations: IOperation[] = [];+ const superBlockElement = targetChildElement.parentElement?.getAttribute("data-type") === "NodeSuperBlock" ?+ targetChildElement.parentElement : undefined;+ if (superBlockElement) {+ refreshSbAndPersistWidth(superBlockElement, widthDoOperations, widthUndoOperations);+ }+ const doOperations: IOperation[] = [];+ const undoOperations: IOperation[] = [];+ pastedChildren.slice().reverse().forEach(item => {+ doOperations.push({+ action: "insert",+ id: item.getAttribute("data-node-id"),+ data: item.outerHTML,+ previousID: targetChildElement.getAttribute("data-node-id")+ });+ undoOperations.push({+ action: "delete",+ id: item.getAttribute("data-node-id")+ });+ });+ if (oldListItemHTML) {+ targetContainerElement.querySelectorAll<HTMLElement>(":scope > .li").forEach(item => {+ const itemOldHTML = oldListItemHTML.get(item.getAttribute("data-node-id"));+ if (!itemOldHTML || item === targetChildElement || itemOldHTML === item.outerHTML) {+ return;+ }+ item.setAttribute("updated", dayjs().format("YYYYMMDDHHmmss"));+ item.setAttribute(Constants.ATTRIBUTE_EDITING, "true");+ doOperations.push({+ action: "update",+ id: item.getAttribute("data-node-id"),+ data: item.outerHTML+ });+ undoOperations.push({+ action: "update",+ id: item.getAttribute("data-node-id"),+ data: itemOldHTML+ });+ });+ }+ doOperations.push(...widthDoOperations);+ undoOperations.unshift(...widthUndoOperations);+ focusByOffset(endBlockElement, pastedEnd, pastedEnd, true, true);+ updateTransaction(protyle, targetChildElement, oldHTML, undoFocusContext, {+ doOperations,+ undoOperations,+ context: getUndoFocusContext(protyle.wysiwyg.element, getEditorRange(protyle.wysiwyg.element), true)+ });+ return true;+};+export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvent | IClipboardData) & {target: HTMLElement}) => {@@ -440,6 +631,22 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven} else {tempElement.innerHTML = siyuanHTML;}+ const startRangeBlockElement = hasClosestBlock(range.startContainer);+ const endRangeBlockElement = hasClosestBlock(range.endContainer);+ if (startRangeBlockElement && endRangeBlockElement && startRangeBlockElement !== endRangeBlockElement) {+ const selectedElement = document.createElement("div");+ selectedElement.append(range.cloneContents());+ selectedElement.querySelectorAll(".protyle-attr").forEach(item => {+ item.textContent = Constants.ZWSP;+ });+ if (selectedElement.isEqualNode(tempElement)) {+ range.collapse(false);+ getSelection().removeAllRanges();+ getSelection().addRange(range);+ protyle.toolbar.range = range;+ return;+ }+ }if (range.toString()) {let types: string[] = [];let linkElement: HTMLElement;@@ -509,6 +716,13 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEventempElement.querySelectorAll('[contenteditable="false"][spellcheck]').forEach((e) => {e.setAttribute("contenteditable", "true");});+ if (isBlock && pasteCrossBlockRange(protyle, tempElement, range)) {+ blockRender(protyle, protyle.wysiwyg.element);+ processRender(protyle.wysiwyg.element);+ highlightRender(protyle.wysiwyg.element);+ avRender(protyle.wysiwyg.element, protyle);+ return;+ }let tempInnerHTML = tempElement.innerHTML;@@ -630,6 +844,10 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven}return;}+ if (nodeElement.classList.contains("av") && tempElement.querySelector("table")) {+ insertHTML(tempElement.innerHTML, protyle, false, false, true);+ return;+ }fetchPost("/api/lute/html2BlockDOM", {dom: tempElement.innerHTML}, (response) => {diff --git a/app/src/protyle/wysiwyg/input.ts b/app/src/protyle/wysiwyg/input.tsindex 27795f8395..c31334cb79 100644--- a/app/src/protyle/wysiwyg/input.ts+++ b/app/src/protyle/wysiwyg/input.ts@@ -24,7 +24,14 @@ import {updateAVName} from "../render/av/action";import {setFold} from "../util/blockFold";import {nbsp2space} from "../util/normalizeText";-export const input = async (protyle: IProtyle, blockElement: HTMLElement, range: Range, needRender = true, event?: InputEvent) => {+interface IInputOperations {+ doOperations: IOperation[];+ undoOperations: IOperation[];+ undoContext?: Record<string, string>;+}++export const input = async (protyle: IProtyle, blockElement: HTMLElement, range: Range, needRender = true,+ event?: InputEvent, inputOperations?: IInputOperations) => {if (!blockElement.parentElement) {// 不同 windows 版本下输入法会多次触发 input,导致 outerhtml 赋值的块丢失return;@@ -99,17 +106,28 @@ export const input = async (protyle: IProtyle, blockElement: HTMLElement, range:}}const id = blockElement.getAttribute("data-node-id");+ const conversionOperations: IInputOperations | undefined = inputOperations ? {+ doOperations: inputOperations.doOperations,+ undoOperations: [{+ id,+ data: protyle.wysiwyg.lastHTMLs[id],+ action: "update",+ context: inputOperations.undoContext,+ }, ...inputOperations.undoOperations]+ } : undefined;if ((type !== "NodeCodeBlock" && type !== "NodeHeading") && // https://github.com/siyuan-note/siyuan/issues/11851(editElement.innerHTML.endsWith("\n<wbr>") || editElement.innerHTML.endsWith("\n<wbr>\n"))) {// 软换行- updateTransaction(protyle, blockElement, protyle.wysiwyg.lastHTMLs[id] || blockElement.outerHTML.replace("\n<wbr>", "<wbr>"));+ updateTransaction(protyle, blockElement,+ protyle.wysiwyg.lastHTMLs[id] || blockElement.outerHTML.replace("\n<wbr>", "<wbr>"),+ inputOperations?.undoContext, inputOperations);wbrElement.remove();return;}- if (turnIntoTaskList(protyle, type, blockElement, editElement, range)) {+ if (turnIntoTaskList(protyle, type, blockElement, editElement, range, conversionOperations)) {return;}- if (headingTurnIntoList(protyle, type, blockElement, editElement, range)) {+ if (headingTurnIntoList(protyle, type, blockElement, editElement, range, conversionOperations)) {return;}// table、粗体 中也会有 br,仅用于类似#a#,删除后会产生的 br@@ -136,7 +154,8 @@ export const input = async (protyle: IProtyle, blockElement: HTMLElement, range:} else if ((trimStartHTML.startsWith("```") || trimStartHTML.startsWith("···") || trimStartHTML.startsWith("~~~")) &&trimStartHTML.indexOf("\n") === -1 && trimStartHTML.replace(/·|~/g, "`").replace(/^`{3,}/g, "").indexOf("`") === -1) {// ```test` 后续处理,```test 不处理- updateTransaction(protyle, blockElement, protyle.wysiwyg.lastHTMLs[id]);+ updateTransaction(protyle, blockElement, protyle.wysiwyg.lastHTMLs[id],+ inputOperations?.undoContext, inputOperations);wbrElement.remove();return;}@@ -356,10 +375,10 @@ export const input = async (protyle: IProtyle, blockElement: HTMLElement, range:protyle.hint.render(protyle);}hideElements(["gutter"], protyle);- updateInput(html, protyle, id);+ updateInput(html, protyle, id, inputOperations);};-const updateInput = (html: string, protyle: IProtyle, id: string) => {+const updateInput = (html: string, protyle: IProtyle, id: string, inputOperations?: IInputOperations) => {const tempElement = document.createElement("template");tempElement.innerHTML = html;const doOperations: IOperation[] = [];@@ -378,7 +397,8 @@ const updateInput = (html: string, protyle: IProtyle, id: string) => {undoOperations.push({id,data: protyle.wysiwyg.lastHTMLs[id],- action: "update"+ action: "update",+ context: inputOperations?.undoContext,});protyle.wysiwyg.lastHTMLs[id] = item.outerHTML;} else {@@ -399,5 +419,9 @@ const updateInput = (html: string, protyle: IProtyle, id: string) => {});}});+ if (inputOperations) {+ doOperations.push(...inputOperations.doOperations);+ undoOperations.push(...inputOperations.undoOperations);+ }transaction(protyle, doOperations, undoOperations);};diff --git a/app/src/protyle/wysiwyg/remove.ts b/app/src/protyle/wysiwyg/remove.tsindex 4d9b5c04fc..9296ee317f 100644--- a/app/src/protyle/wysiwyg/remove.ts+++ b/app/src/protyle/wysiwyg/remove.ts@@ -45,6 +45,7 @@ import {isEncryptedBox} from "../../util/pathName";import {highlightRender} from "../render/highlightRender";import * as dayjs from "dayjs";import {mergeSameInlineElement} from "../toolbar/util";+import {getCrossBlockMergeRemoveElement} from "./removeRange";export const removeCrossBlockRange = (protyle: IProtyle, selectedRange: Range,startElement: HTMLElement, endElement: HTMLElement) => {@@ -86,12 +87,15 @@ export const removeCrossBlockRange = (protyle: IProtyle, selectedRange: Range,["NodeParagraph", "NodeHeading"].includes(blockType) &&blockType === endElement.getAttribute("data-type") &&endElement.getAttribute("fold") !== "1") {- const topElement = getTopAloneElement(endElement);- const hasChildList = topElement === endElement && endElement.parentElement.classList.contains("li") &&- !!endElement.parentElement.querySelector(":scope > .list");- if (!hasChildList && !topElement.contains(startElement)) {+ const topElement = getCrossBlockMergeRemoveElement(editorElement, startElement, endElement);+ if (topElement) {removeEndElement = topElement;- removeElements.push(topElement as HTMLElement);+ for (let i = removeElements.length - 1; i >= 0; i--) {+ if (topElement.contains(removeElements[i])) {+ removeElements.splice(i, 1);+ }+ }+ removeElements.push(topElement);}}diff --git a/app/src/protyle/wysiwyg/removeRange.test.ts b/app/src/protyle/wysiwyg/removeRange.test.tsnew file mode 100644index 0000000000..164cf7b233--- /dev/null+++ b/app/src/protyle/wysiwyg/removeRange.test.ts@@ -0,0 +1,142 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {getCrossBlockMergeRemoveElement} from "./removeRange";++class TestElement {+ parentElement: TestElement | null = null;+ children: TestElement[] = [];+ private attributes = new Map<string, string>();++ constructor(public name: string, type?: string) {+ if (type) {+ this.attributes.set("data-node-id", name);+ this.attributes.set("data-type", type);+ }+ }++ append(...elements: TestElement[]) {+ elements.forEach(element => {+ element.parentElement = this;+ this.children.push(element);+ });+ return this;+ }++ get nextElementSibling() {+ if (!this.parentElement) {+ return null;+ }+ const index = this.parentElement.children.indexOf(this);+ return this.parentElement.children[index + 1] || null;+ }++ getAttribute(name: string) {+ return this.attributes.get(name) || null;+ }++ hasAttribute(name: string) {+ return this.attributes.has(name);+ }++ contains(element: TestElement) {+ let currentElement: TestElement | null = element;+ while (currentElement) {+ if (currentElement === this) {+ return true;+ }+ currentElement = currentElement.parentElement;+ }+ return false;+ }+}++const block = (name: string, type: string, ...children: TestElement[]) =>+ new TestElement(name, type).append(...children);+const attr = (name: string) => new TestElement(name);+const asHTMLElement = (element: TestElement) => element as unknown as HTMLElement;++describe("getCrossBlockMergeRemoveElement", () => {+ it("删除多层列表中起点下方的完整分支", () => {+ const start = block("start", "NodeParagraph");+ const second = block("second", "NodeParagraph");+ const third = block("third", "NodeParagraph");+ const end = block("end", "NodeParagraph");+ const fourthItem = block("fourthItem", "NodeListItem", end, attr("fourthAttr"));+ const fourthList = block("fourthList", "NodeList", fourthItem, attr("fourthListAttr"));+ const thirdItem = block("thirdItem", "NodeListItem", third, fourthList, attr("thirdAttr"));+ const thirdList = block("thirdList", "NodeList", thirdItem, attr("thirdListAttr"));+ const secondItem = block("secondItem", "NodeListItem", second, thirdList, attr("secondAttr"));+ const secondList = block("secondList", "NodeList", secondItem, attr("secondListAttr"));+ const firstItem = block("firstItem", "NodeListItem", start, secondList, attr("firstAttr"));+ const firstList = block("firstList", "NodeList", firstItem, attr("firstListAttr"));+ const editor = new TestElement("editor").append(firstList);++ const result = getCrossBlockMergeRemoveElement(+ asHTMLElement(editor), asHTMLElement(start), asHTMLElement(end));++ assert.equal(result, asHTMLElement(secondList));+ });++ it("保留终点列表项之后的兄弟项", () => {+ const start = block("start", "NodeParagraph");+ const end = block("end", "NodeParagraph");+ const endItem = block("endItem", "NodeListItem", end, attr("endAttr"));+ const siblingItem = block("siblingItem", "NodeListItem",+ block("sibling", "NodeParagraph"), attr("siblingAttr"));+ const list = block("list", "NodeList", endItem, siblingItem, attr("listAttr"));+ const editor = new TestElement("editor").append(start, list);++ const result = getCrossBlockMergeRemoveElement(+ asHTMLElement(editor), asHTMLElement(start), asHTMLElement(end));++ assert.equal(result, asHTMLElement(endItem));+ });++ it("终点后存在未选中的子列表时不删除终点块", () => {+ const start = block("start", "NodeParagraph");+ const end = block("end", "NodeParagraph");+ const childList = block("childList", "NodeList",+ block("childItem", "NodeListItem", block("child", "NodeParagraph"), attr("childAttr")),+ attr("childListAttr"));+ const endItem = block("endItem", "NodeListItem", end, childList, attr("endAttr"));+ const list = block("list", "NodeList", endItem, attr("listAttr"));+ const editor = new TestElement("editor").append(start, list);++ const result = getCrossBlockMergeRemoveElement(+ asHTMLElement(editor), asHTMLElement(start), asHTMLElement(end));++ assert.equal(result, undefined);+ });++ it("同一列表项内保留起点块并删除终点块", () => {+ const start = block("start", "NodeParagraph");+ const end = block("end", "NodeParagraph");+ const childList = block("childList", "NodeList",+ block("childItem", "NodeListItem", block("child", "NodeParagraph"), attr("childAttr")),+ attr("childListAttr"));+ const item = block("item", "NodeListItem", start, end, childList, attr("itemAttr"));+ const list = block("list", "NodeList", item, attr("listAttr"));+ const editor = new TestElement("editor").append(list);++ const result = getCrossBlockMergeRemoveElement(+ asHTMLElement(editor), asHTMLElement(start), asHTMLElement(end));++ assert.equal(result, asHTMLElement(end));+ });++ it("终点之前的子列表不阻止合并", () => {+ const start = block("start", "NodeParagraph");+ const end = block("end", "NodeParagraph");+ const childList = block("childList", "NodeList",+ block("childItem", "NodeListItem", block("child", "NodeParagraph"), attr("childAttr")),+ attr("childListAttr"));+ const item = block("item", "NodeListItem", start, childList, end, attr("itemAttr"));+ const list = block("list", "NodeList", item, attr("listAttr"));+ const editor = new TestElement("editor").append(list);++ const result = getCrossBlockMergeRemoveElement(+ asHTMLElement(editor), asHTMLElement(start), asHTMLElement(end));++ assert.equal(result, asHTMLElement(end));+ });+});diff --git a/app/src/protyle/wysiwyg/removeRange.ts b/app/src/protyle/wysiwyg/removeRange.tsnew file mode 100644index 0000000000..fd35dcebdd--- /dev/null+++ b/app/src/protyle/wysiwyg/removeRange.ts@@ -0,0 +1,36 @@+const getNextBlockSibling = (element: Element) => {+ let nextElement = element.nextElementSibling;+ while (nextElement && !nextElement.hasAttribute("data-node-id")) {+ nextElement = nextElement.nextElementSibling;+ }+ return nextElement;+};++const getListItemElement = (element: HTMLElement, editorElement: HTMLElement) => {+ let currentElement = element.parentElement;+ while (currentElement && currentElement !== editorElement) {+ if (currentElement.getAttribute("data-type") === "NodeListItem") {+ return currentElement;+ }+ currentElement = currentElement.parentElement;+ }+};++export const getCrossBlockMergeRemoveElement = (editorElement: HTMLElement, startElement: HTMLElement,+ endElement: HTMLElement) => {+ let topElement = endElement;+ const endListItemElement = getListItemElement(endElement, editorElement);+ let currentElement = endElement;+ while (currentElement.parentElement && currentElement.parentElement !== editorElement &&+ !currentElement.parentElement.contains(startElement) && !getNextBlockSibling(currentElement)) {+ currentElement = currentElement.parentElement;+ if (currentElement.hasAttribute("data-node-id")) {+ topElement = currentElement;+ }+ }+ const nextBlockElement = getNextBlockSibling(currentElement);+ const hasChildList = !!endListItemElement && !endListItemElement.contains(startElement) &&+ nextBlockElement?.getAttribute("data-type") === "NodeList" &&+ nextBlockElement.parentElement === endListItemElement;+ return hasChildList ? undefined : topElement;+};diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex c8da441d06..8d2df3b7f5 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -1990,24 +1990,36 @@ const processFold = (operation: IOperation, protyle: IProtyle) => {}};-export const updateTransaction = (protyle: IProtyle, element: Element, oldHTML: string, undoContext?: Record<string, string>) => {+export const updateTransaction = (protyle: IProtyle, element: Element, oldHTML: string,+ undoContext?: Record<string, string>, additionalOperations?: {+ doOperations: IOperation[],+ undoOperations: IOperation[],+ context?: Record<string, string>,+ }) => {const id = element.getAttribute("data-node-id");const newHTML = cleanHeadingNumberHTML(element.outerHTML);const cleanOldHTML = cleanHeadingNumberHTML(oldHTML);- if (newHTML === cleanOldHTML.replace("<wbr>", "")) {+ if (newHTML === cleanOldHTML.replace("<wbr>", "") && !additionalOperations) {return;}element.setAttribute(Constants.ATTRIBUTE_EDITING, "true");- transaction(protyle, [{+ const doOperations: IOperation[] = [{id,data: newHTML,- action: "update"- }], [{+ 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);};export const updateBatchTransaction = (nodeElements: Element[], protyle: IProtyle, cb: (e: HTMLElement) => void,diff --git a/app/src/protyle/wysiwyg/turnIntoList.ts b/app/src/protyle/wysiwyg/turnIntoList.tsindex a7d8eeeedb..44bedc3652 100644--- a/app/src/protyle/wysiwyg/turnIntoList.ts+++ b/app/src/protyle/wysiwyg/turnIntoList.ts@@ -4,7 +4,22 @@ import * as dayjs from "dayjs";import {decodeHTML, escapeAttr} from "../../util/escape";import {Constants} from "../../constants";-export const turnIntoTaskList = (protyle: IProtyle, type: string, blockElement: HTMLElement, editElement: HTMLElement, range: Range) => {+interface IAdditionalOperations {+ doOperations: IOperation[];+ undoOperations: IOperation[];+}++const transactionWithAdditionalOperations = (protyle: IProtyle, doOperations: IOperation[],+ undoOperations: IOperation[],+ additionalOperations?: IAdditionalOperations) => {+ transaction(protyle, additionalOperations ?+ additionalOperations.doOperations.concat(doOperations) : doOperations, additionalOperations ?+ undoOperations.concat(additionalOperations.undoOperations) : undoOperations);+};++export const turnIntoTaskList = (protyle: IProtyle, type: string, blockElement: HTMLElement,+ editElement: HTMLElement, range: Range,+ additionalOperations?: IAdditionalOperations) => {const html = decodeHTML(editElement.innerHTML);const dataTask = html.substring(0, 3).match(/^[\[【]([^\x80-\uffff\[\]【】])[\]】]$/);if (type !== "NodeCodeBlock" &&@@ -41,7 +56,7 @@ export const turnIntoTaskList = (protyle: IProtyle, type: string, blockElement:}blockElement.previousElementSibling.outerHTML = `<div class="protyle-action protyle-action--task" draggable="true"><svg><use xlink:href="#icon${isDone ? "C" : "Unc"}heck"></use></svg></div>`;editElement.innerHTML = html.substring(contextStartIndex);- updateTransaction(protyle, liElement, oldHTML);+ updateTransaction(protyle, liElement, oldHTML, undefined, additionalOperations);focusByWbr(protyle.wysiwyg.element, range);return true;}@@ -54,7 +69,7 @@ export const turnIntoTaskList = (protyle: IProtyle, type: string, blockElement:const oldHTML = blockElement.outerHTML;editElement.innerHTML = html.substring(contextStartIndex);blockElement.setAttribute(Constants.ATTRIBUTE_EDITING, "true");- transaction(protyle, [{+ transactionWithAdditionalOperations(protyle, [{action: "update",id,data: blockElement.outerHTML,@@ -81,7 +96,7 @@ export const turnIntoTaskList = (protyle: IProtyle, type: string, blockElement:action: "update",id,data: oldHTML,- }]);+ }], additionalOperations);blockElement.outerHTML = `<div data-subtype="t" data-node-id="${newId}" data-type="NodeList" class="list" updated="${newId.split("-")[0]}"><div data-task="${dataTask ? escapeAttr(dataTask[1]) : " "}" data-marker="*" data-subtype="t" data-node-id="${liItemId}" data-type="NodeListItem" class="li${isDone ? " protyle-task--done" : ""}" updated="${liItemId.split("-")[0]}"><div class="protyle-action protyle-action--task" draggable="true"><svg><use xlink:href="#icon${isDone ? "C" : "Unc"}heck"></use></svg></div>${blockElement.outerHTML}<div class="protyle-attr" contenteditable="false"></div></div><div class="protyle-attr" contenteditable="false"></div></div>`;focusByWbr(protyle.wysiwyg.element, range);return true;@@ -90,7 +105,9 @@ export const turnIntoTaskList = (protyle: IProtyle, type: string, blockElement:return false;};-export const headingTurnIntoList = (protyle: IProtyle, type: string, blockElement: HTMLElement, editElement: HTMLElement, range: Range) => {+export const headingTurnIntoList = (protyle: IProtyle, type: string, blockElement: HTMLElement,+ editElement: HTMLElement, range: Range,+ additionalOperations?: IAdditionalOperations) => {if (type === "NodeHeading" && ["* ", "- "].includes(editElement.innerHTML.substring(0, 2)) &&blockElement.parentElement.getAttribute("data-type") !== "NodeListItem") {const id = blockElement.getAttribute("data-node-id");@@ -101,7 +118,7 @@ export const headingTurnIntoList = (protyle: IProtyle, type: string, blockElemenconst marker = editElement.innerHTML.substring(0, 1);editElement.innerHTML = editElement.innerHTML.substring(2);blockElement.setAttribute(Constants.ATTRIBUTE_EDITING, "true");- transaction(protyle, [{+ transactionWithAdditionalOperations(protyle, [{action: "update",id,data: blockElement.outerHTML,@@ -128,7 +145,7 @@ export const headingTurnIntoList = (protyle: IProtyle, type: string, blockElemen}, {action: "delete",id: newId- }]);+ }], additionalOperations);blockElement.outerHTML = `<div data-subtype="u" data-node-id="${newId}" data-type="NodeList" class="list" updated="${newId.split("-")[0]}"><div data-marker="${marker}" data-subtype="u" data-node-id="${liItemId}" data-type="NodeListItem" class="li" updated="${liItemId.split("-")[0]}"><div class="protyle-action" draggable="true"><svg><use xlink:href="#iconDot"></use></svg></div>${blockElement.outerHTML}<div class="protyle-attr" contenteditable="false"></div></div><div class="protyle-attr" contenteditable="false"></div></div>`;focusByWbr(protyle.wysiwyg.element, range);return true;