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/17955
Vanessae4f4e38fe1f4
diff --git a/app/src/block/util.ts b/app/src/block/util.tsindex 27cf1cb5d6..1cac18f694 100644--- a/app/src/block/util.ts+++ b/app/src/block/util.ts@@ -2,6 +2,7 @@ import {focusByWbr, getEditorRange} from "../protyle/util/selection";import {hasClosestBlock, hasClosestByClassName} from "../protyle/util/hasClosest";import {getContenteditableElement,+ getEmbedChildOperationParentID,getParentBlock,getPreviousBlockSibling,getTopAloneElement@@ -29,7 +30,7 @@ export const cancelSB = async (protyle: IProtyle, nodeElement: Element, range?:nodeElement.querySelectorAll(".sb__resize").forEach(handle => handle.remove());const sbElement = nodeElement.cloneNode() as HTMLElement;sbElement.innerHTML = nodeElement.lastElementChild.outerHTML;- let parentID = getParentBlock(nodeElement)?.getAttribute("data-node-id");+ let parentID = getEmbedChildOperationParentID(nodeElement) || getParentBlock(nodeElement)?.getAttribute("data-node-id");// 缩放和反链需要接口获取if (!previousId && !parentID) {if (protyle.block.showAll || protyle.options.backlinkData) {diff --git a/app/src/protyle/render/blockRender.ts b/app/src/protyle/render/blockRender.tsindex 09cd4aa329..342dc62be3 100644--- a/app/src/protyle/render/blockRender.ts+++ b/app/src/protyle/render/blockRender.ts@@ -99,7 +99,8 @@ export const blockRender = (protyle: IProtyle, element: Element, top?: number, oconst renderEmbed = (blocks: {block: IBlock,- blockPaths: IBreadcrumb[]+ blockPaths: IBreadcrumb[],+ allowChildOperation: boolean}[], protyle: IProtyle, item: HTMLElement, top?: number, errorTip?: string, onEmbedRender?: () => void) => {const rotateElement = item.querySelector(".fn__rotate");if (rotateElement) {@@ -120,7 +121,8 @@ const renderEmbed = (blocks: {popoverElement.setAttribute("data-id", blocksItem.block.id);}}- html += `<div class="protyle-wysiwyg__embed" data-id="${blocksItem.block.id}">+ const childOperationAttr = blocksItem.allowChildOperation ? " data-allow-child-operation=\"true\"" : "";+ html += `<div class="protyle-wysiwyg__embed" data-id="${blocksItem.block.id}"${childOperationAttr}>${popover}${breadcrumbHTML}${blocksItem.block.content}</div>`;});diff --git a/app/src/protyle/util/hasClosest.ts b/app/src/protyle/util/hasClosest.tsindex e628a3ade8..e18bacd0f8 100644--- a/app/src/protyle/util/hasClosest.ts+++ b/app/src/protyle/util/hasClosest.ts@@ -116,8 +116,9 @@ export const isBlockElement = (nodeElement: Element) => {return nodeElement && nodeElement.tagName !== "BUTTON" && nodeElement.getAttribute("data-type")?.startsWith("Node");};-export const isInEmbedBlock = (element: Element) => {- const embedElement = hasTopClosestByAttribute(element, "data-type", "NodeBlockQueryEmbed");+export const isInEmbedBlock = (element: Element, top = true) => {+ const embedElement = top ? hasTopClosestByAttribute(element, "data-type", "NodeBlockQueryEmbed") :+ hasClosestByAttribute(element, "data-type", "NodeBlockQueryEmbed");if (embedElement) {if (embedElement === element) {return false;diff --git a/app/src/protyle/wysiwyg/enter.ts b/app/src/protyle/wysiwyg/enter.tsindex da7a28f189..042756b34a 100644--- a/app/src/protyle/wysiwyg/enter.ts+++ b/app/src/protyle/wysiwyg/enter.ts@@ -2,11 +2,14 @@ import {genEmptyElement, genHeadingElement, insertEmptyBlock} from "../../block/import {focusByRange, focusByWbr, getSelectionOffset, setLastNodeRange} from "../util/selection";import {getContenteditableElement, getParentBlock,+ getEmbedChildOperationContext,+ getEmbedChildOperationParentID,getPreviousBlockSibling,getTopEmptyElement,hasNextSibling,hasPreviousSibling,- isNotEditBlock+ isNotEditBlock,+ IEmbedChildOperationContext} from "./getBlock";import {transaction, turnsIntoOneTransaction, updateTransaction} from "./transaction";import {breakList, genListItemElement, listOutdent, updateListOrder} from "./list";@@ -22,7 +25,9 @@ import {hasClosestByAttribute, hasClosestByClassName} from "../util/hasClosest";import {blockRender} from "../render/blockRender";export const enter = async (blockElement: HTMLElement, range: Range, protyle: IProtyle) => {- if (hasClosestByClassName(blockElement, "protyle-wysiwyg__embed") && !blockElement.classList.contains("code-block")) {+ const embedResultElement = hasClosestByClassName(blockElement, "protyle-wysiwyg__embed");+ const embedContext = getEmbedChildOperationContext(blockElement);+ if (embedResultElement && !embedContext && !blockElement.classList.contains("code-block")) {return;}const disableElement = isNotEditBlock(blockElement);@@ -128,8 +133,11 @@ export const enter = async (blockElement: HTMLElement, range: Range, protyle: IP((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;+ }range.insertNode(document.createElement("wbr"));- const topElement = getTopEmptyElement(blockElement);+ const topElement = getTopEmptyElement(blockElement, embedContext?.boundaryElement);const blockId = blockElement.getAttribute("data-node-id");const topId = topElement.getAttribute("data-node-id");const doInsert: IOperation = {@@ -149,7 +157,8 @@ export const enter = async (blockElement: HTMLElement, range: Range, protyle: IPparentBlockElement.after(blockElement);} else {doInsert.previousID = getPreviousBlockSibling(topElement)?.getAttribute("data-node-id");- doInsert.parentID = getParentBlock(topElement).getAttribute("data-node-id") || protyle.block.parentID;+ 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);@@ -190,9 +199,14 @@ export const enter = async (blockElement: HTMLElement, range: Range, protyle: IP(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"- ) && listEnter(protyle, blockElement, range)- ) {- return true;+ )) {+ const embedListEnterMode = embedContext ? getEmbedListEnterMode(blockElement, embedContext) : "list";+ if ("none" === embedListEnterMode) {+ return;+ }+ if ("list" === embedListEnterMode && listEnter(protyle, blockElement, range)) {+ return true;+ }}// 段首换行@@ -389,6 +403,23 @@ export const enter = async (blockElement: HTMLElement, range: Range, protyle: IPreturn 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 = ["", "\n"].includes(editableElement.textContent) &&+ blockElement.previousElementSibling.classList.contains("protyle-action") &&+ !blockElement.querySelector("img");+ if (exitsList && listElement.parentElement === embedContext.resultElement) {+ return "none";+ }+ return embedContext.boundaryElement.contains(exitsList ? listElement.parentElement : listElement) ? "list" : "none";+};+const listEnter = (protyle: IProtyle, blockElement: HTMLElement, range: Range) => {const listItemElement = blockElement.parentElement;const editableElement = getContenteditableElement(blockElement);diff --git a/app/src/protyle/wysiwyg/getBlock.ts b/app/src/protyle/wysiwyg/getBlock.tsindex 346c29f13d..0c6f586640 100644--- a/app/src/protyle/wysiwyg/getBlock.ts+++ b/app/src/protyle/wysiwyg/getBlock.ts@@ -1,6 +1,42 @@-import {hasClosestBlock, isInEmbedBlock} from "../util/hasClosest";+import {hasClosestBlock, hasClosestByClassName, isInEmbedBlock} from "../util/hasClosest";import {Constants} from "../../constants";+export interface IEmbedChildOperationContext {+ resultElement: HTMLElement;+ targetID: string;+ targetElement?: Element;+ boundaryElement: Element;+}++export const getEmbedChildOperationContext = (element: Node): IEmbedChildOperationContext | undefined => {+ const resultElement = hasClosestByClassName(element, "protyle-wysiwyg__embed");+ if (!resultElement || resultElement.getAttribute("data-allow-child-operation") !== "true") {+ return;+ }++ const targetID = resultElement.getAttribute("data-id");+ if (!targetID) {+ return;+ }+ // 单独查询列表项时,渲染器会在目标外补充一个无 ID 的列表节点。+ const targetElement = Array.from(resultElement.querySelectorAll(`[data-node-id="${targetID}"]`)).find(item =>+ item.getAttribute("data-type")?.startsWith("Node") &&+ hasClosestByClassName(item, "protyle-wysiwyg__embed") === resultElement);+ return {+ resultElement,+ targetID,+ targetElement,+ // 文档块不会渲染自身节点,查询结果容器就是它的子块边界。+ boundaryElement: targetElement || resultElement,+ };+};++export const getEmbedChildOperationParentID = (element: Element, context = getEmbedChildOperationContext(element)) => {+ if (context && !context.targetElement && element.parentElement === context.resultElement) {+ return context.targetID;+ }+};+export const getParentBlock = (element: Element) => {if (element.parentElement.classList.contains("callout-content") ||element.parentElement.classList.contains("protyle-wysiwyg__embed")) {@@ -24,6 +60,10 @@ export const getPreviousBlock = (element: Element) => {if (previous) {return previous;}+ if (parentElement.parentElement?.classList.contains("protyle-wysiwyg__embed") &&+ parentElement.parentElement.getAttribute("data-allow-child-operation") === "true") {+ return false;+ }const pElement = hasClosestBlock(parentElement.parentElement);if (pElement) {parentElement = pElement;@@ -84,6 +124,10 @@ export const getNextBlock = (element: Element) => {if (next) {return next as HTMLElement;}+ if (parentElement.parentElement?.classList.contains("protyle-wysiwyg__embed") &&+ parentElement.parentElement.getAttribute("data-allow-child-operation") === "true") {+ return false;+ }const pElement = hasClosestBlock(parentElement.parentElement);if (pElement) {parentElement = pElement;@@ -160,9 +204,10 @@ export const isNotEditBlock = (element: Element) => {(element.getAttribute("data-type") === "NodeCodeBlock" && element.classList.contains("render-node"));};-export const getTopEmptyElement = (element: Element) => {+export const getTopEmptyElement = (element: Element, boundaryElement?: Element) => {let topElement = element;- while (topElement.parentElement && !topElement.parentElement.classList.contains("protyle-wysiwyg")) {+ while (topElement.parentElement && topElement.parentElement !== boundaryElement &&+ !topElement.parentElement.classList.contains("protyle-wysiwyg")) {if (!topElement.parentElement.getAttribute("data-node-id") && !topElement.parentElement.classList.contains("callout-content")) {topElement = topElement.parentElement;} else {diff --git a/app/src/protyle/wysiwyg/list.ts b/app/src/protyle/wysiwyg/list.tsindex ad81a957ae..80272015e5 100644--- a/app/src/protyle/wysiwyg/list.ts+++ b/app/src/protyle/wysiwyg/list.ts@@ -5,7 +5,7 @@ import * as dayjs from "dayjs";import {Constants} from "../../constants";import {moveToPrevious, removeBlock} from "./remove";import {hasClosestByClassName, isBlockElement} from "../util/hasClosest";-import {getParentBlock, getPreviousBlockSibling} from "./getBlock";+import {getEmbedChildOperationContext, getParentBlock, getPreviousBlockSibling} from "./getBlock";import {setFold} from "../util/blockFold";import {scrollCenter} from "../../util/highlightById";@@ -485,8 +485,11 @@ export const listOutdent = async (protyle: IProtyle, liItemElements: Element[],}const parentLiItemElement = getParentBlock(liElement);const parentParentElement = parentLiItemElement.parentElement;- if (parentLiItemElement.classList.contains("protyle-wysiwyg__embed") ||- parentParentElement.classList.contains("protyle-wysiwyg__embed")) {+ const embedContext = getEmbedChildOperationContext(liElement);+ if (embedContext?.targetElement === parentLiItemElement ||+ (embedContext && !embedContext.boundaryElement.contains(parentLiItemElement)) ||+ (!embedContext && (parentLiItemElement.classList.contains("protyle-wysiwyg__embed") ||+ parentParentElement.classList.contains("protyle-wysiwyg__embed")))) {return;}if (liElement.previousElementSibling?.classList.contains("protyle-action") && !parentParentElement.getAttribute("data-node-id")) {diff --git a/app/src/protyle/wysiwyg/remove.ts b/app/src/protyle/wysiwyg/remove.tsindex 1abdfff9cc..ee77e50290 100644--- a/app/src/protyle/wysiwyg/remove.ts+++ b/app/src/protyle/wysiwyg/remove.ts@@ -1,6 +1,8 @@import {focusBlock, focusByRange, focusByWbr, getSelectionOffset, setLastNodeRange} from "../util/selection";import {getContenteditableElement,+ getEmbedChildOperationContext,+ getEmbedChildOperationParentID,getLastBlock,getNextBlock,getParentBlock,@@ -10,7 +12,8 @@ import {getTopAloneElement,getTopEmptyElement,hasNextSibling,- hasPreviousSibling+ hasPreviousSibling,+ IEmbedChildOperationContext} from "./getBlock";import {transaction, turnsIntoOneTransaction, turnsIntoTransaction, updateTransaction} from "./transaction";import {cancelSB, genEmptyElement, rebalanceSbWidth, refreshSbResize} from "../../block/util";@@ -39,6 +42,18 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rangpreventScroll(protyle);const selectElements = Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));if (selectElements?.length > 0) {+ const embedSelectElements = selectElements.filter(item => isInEmbedBlock(item));+ if (embedSelectElements.length > 0) {+ // 嵌入块内暂不支持跨边界或多块删除,避免上溯时删除查询目标。+ if (embedSelectElements.length !== selectElements.length || embedSelectElements.length !== 1) {+ return;+ }+ const embedContext = getEmbedChildOperationContext(embedSelectElements[0]);+ const topElement = getTopAloneElement(embedSelectElements[0]);+ if (!embedContext || !canDeleteEmbedElement(topElement, type, embedContext)) {+ return;+ }+ }const deletes: IOperation[] = [];const inserts: IOperation[] = [];let sideElement: Element | boolean;@@ -70,9 +85,6 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rangconst item = selectElements[i];const topElement = getTopAloneElement(item);topParentElement = topElement.parentElement;- if (isInEmbedBlock(item)) {- continue;- }const id = topElement.getAttribute("data-node-id");deletes.push({action: "delete",@@ -155,7 +167,7 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rangdata,id,previousID,- parentID: getParentBlock(topElement)?.getAttribute("data-node-id") || protyle.block.parentID+ parentID: getOperationParentID(topElement, protyle.block.parentID)});if (topElement.getAttribute("data-subtype") === "o" && topElement.classList.contains("li")) {listElement = topElement.parentElement;@@ -321,7 +333,9 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rang}, Constants.TIMEOUT_COUNT);// 需等待滚动阻塞、后台处理完成。否则会加载已删除的内容return;}- if (isInEmbedBlock(blockElement)) {+ const embedBlockElement = isInEmbedBlock(blockElement);+ const embedContext = getEmbedChildOperationContext(blockElement);+ if (embedBlockElement && (!embedContext || embedContext.targetElement === blockElement)) {return;}const blockType = blockElement.getAttribute("data-type");@@ -350,6 +364,9 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rangblockParentElement.parentElement.classList.contains("sb"))))) {+ if (embedContext && !embedContext.boundaryElement.contains(blockParentElement.parentElement)) {+ return;+ }if (type !== "Delete") {range.insertNode(document.createElement("wbr"));}@@ -362,7 +379,7 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rangaction: "move",id: blockElement.getAttribute("data-node-id"),previousID,- parentID: getParentBlock(blockParentElement).getAttribute("data-node-id") || protyle.block.parentID+ parentID: getOperationParentID(blockParentElement, protyle.block.parentID)}, {action: "delete",id: blockParentElement.getAttribute("data-node-id")@@ -371,7 +388,7 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rangid: blockParentElement.getAttribute("data-node-id"),data: blockParentElement.outerHTML,previousID,- parentID: getParentBlock(blockElement).getAttribute("data-node-id") || protyle.block.parentID+ parentID: getOperationParentID(blockElement, protyle.block.parentID)}, {action: "move",id: blockElement.getAttribute("data-node-id"),@@ -383,7 +400,7 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rangaction: "move",id: blockElement.getAttribute("data-node-id"),previousID,- parentID: getParentBlock(blockParentElement).getAttribute("data-node-id") || protyle.block.parentID+ parentID: getOperationParentID(blockParentElement, protyle.block.parentID)}], [{action: "move",id: blockElement.getAttribute("data-node-id"),@@ -405,17 +422,26 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rangif (blockElement.parentElement.classList.contains("li") && blockType !== "NodeHeading" &&blockElement.previousElementSibling.classList.contains("protyle-action")) {+ if (embedContext && !canRemoveLiInEmbed(blockElement, embedContext)) {+ return;+ }removeLi(protyle, blockElement, range, type === "Delete");return;}if (type === "Delete") {const liElement = hasClosestByClassName(blockElement, "li");if (liElement && getContenteditableElement(liElement) === getContenteditableElement(blockElement)) {+ if (embedContext && !canRemoveLiInEmbed(liElement.firstElementChild.nextElementSibling, embedContext)) {+ return;+ }removeLi(protyle, liElement.firstElementChild.nextElementSibling, range, true);return;}}const previousElement = getPreviousBlock(blockElement) as HTMLElement;+ if (embedContext && (!previousElement || !embedContext.boundaryElement.contains(previousElement))) {+ return;+ }// 设置 bq 和代码块光标// 需放在列表处理后 https://github.com/siyuan-note/siyuan/issues/11606if (["NodeCodeBlock", "NodeTable", "NodeAttributeView"].includes(blockType)) {@@ -430,7 +456,7 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rangaction: "insert",data: previousElement.outerHTML,id: previousElement.getAttribute("data-node-id"),- parentID: getParentBlock(previousElement).getAttribute("data-node-id") || protyle.block.parentID,+ parentID: getOperationParentID(previousElement, protyle.block.parentID),previousID: (ppElement && (!previousElement.previousElementSibling || !previousElement.previousElementSibling.classList.contains("protyle-action"))) ? ppElement.getAttribute("data-node-id") : undefined}]);previousElement.remove();@@ -493,7 +519,7 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rangdata: previousLastElement.outerHTML,id: previousLastElement.getAttribute("data-node-id"),previousID: getPreviousBlockSibling(previousLastElement)?.getAttribute("data-node-id"),- parentID: getParentBlock(previousLastElement).getAttribute("data-node-id")+ parentID: getOperationParentID(previousLastElement, protyle.block.parentID)}]);previousLastElement.remove();return;@@ -519,7 +545,7 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rangdata: blockElement.outerHTML,id: id,previousID: getPreviousBlockSibling(blockElement)?.getAttribute("data-node-id"),- parentID: getParentBlock(blockElement).getAttribute("data-node-id")+ parentID: getOperationParentID(blockElement, protyle.block.parentID)}];blockElement.remove();// 取消超级块@@ -543,7 +569,12 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rang}}- const removeElement = getTopEmptyElement(blockElement);+ const removeElement = getTopEmptyElement(blockElement, embedContext?.boundaryElement);+ if (embedContext && (embedContext.targetElement === removeElement ||+ (parentElement === embedContext.targetElement && parentElement.getAttribute("data-type") === "NodeSuperBlock" &&+ getSbChildBlockCount(parentElement) <= 2))) {+ return;+ }const removeId = removeElement.getAttribute("data-node-id");range.insertNode(document.createElement("wbr"));const undoOperations: IOperation[] = [{@@ -555,7 +586,7 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rangdata: removeElement.outerHTML,id: removeId,previousID: getPreviousBlockSibling(blockElement)?.getAttribute("data-node-id"),- parentID: parentElement ? parentElement.getAttribute("data-node-id") : protyle.block.parentID+ parentID: getOperationParentID(removeElement, protyle.block.parentID)}];const doOperations: IOperation[] = [{action: "delete",@@ -662,6 +693,44 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rangfocusByWbr(protyle.wysiwyg.element, range);};+const canDeleteEmbedElement = (element: Element, type: "Delete" | "Backspace" | "remove",+ embedContext: IEmbedChildOperationContext) => {+ if (embedContext.targetElement === element || !embedContext.boundaryElement.contains(element)) {+ return false;+ }++ const parentElement = getParentBlock(element);+ if (parentElement === embedContext.targetElement && parentElement.getAttribute("data-type") === "NodeSuperBlock" &&+ getSbChildBlockCount(parentElement) <= 2) {+ return false;+ }++ let sideElement: Element | false;+ if (type === "Backspace") {+ sideElement = getPreviousBlock(element) || getNextBlock(element);+ } else {+ sideElement = getNextBlock(element) || getPreviousBlock(element);+ }+ return !!sideElement && embedContext.boundaryElement.contains(sideElement);+};++const getOperationParentID = (element: Element, fallbackID: string) => {+ return getEmbedChildOperationParentID(element) || getParentBlock(element)?.getAttribute("data-node-id") || fallbackID;+};++const canRemoveLiInEmbed = (blockElement: Element, embedContext: IEmbedChildOperationContext) => {+ const listItemElement = blockElement.parentElement;+ const listElement = listItemElement.parentElement;+ const previousListItemElement = listItemElement.previousElementSibling;+ if (previousListItemElement?.getAttribute("data-node-id")) {+ return embedContext.boundaryElement.contains(previousListItemElement);+ }+ if (listElement.parentElement === embedContext.resultElement) {+ return false;+ }+ return embedContext.boundaryElement.contains(listElement.parentElement);+};+export const moveToPrevious = (blockElement: Element, range: Range, isDelete: boolean) => {if (isDelete) {const previousBlockElement = getPreviousBlock(blockElement);@@ -762,7 +831,7 @@ const removeLi = async (protyle: IProtyle, blockElement: Element, range: Range,id: item.getAttribute("data-node-id"),data: item.outerHTML,previousID: index === 0 ? getPreviousBlockSibling(listElement)?.getAttribute("data-node-id") : doOperations[index - 1].id,- parentID: getParentBlock(listElement).getAttribute("data-node-id") || protyle.block.parentID+ parentID: getOperationParentID(listElement, protyle.block.parentID)});undoOperations.push({action: "delete",diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex 6df6e6f407..cfc0782a56 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -2,6 +2,7 @@ import {fetchPost, fetchSyncPost} from "../../util/fetch";import {focusBlock, focusByWbr, focusSideBlock, getEditorRange} from "../util/selection";import {getContenteditableElement,+ getEmbedChildOperationContext,getFirstBlock,getNextBlockSibling,getParentBlock,@@ -80,7 +81,7 @@ const promiseTransaction = (options: {}) => {const protyle = options.protyle;// 受影响的嵌入块需推迟到事务提交后再渲染,否则其查询请求会早于写入到达内核而拿到旧数据- const pendingEmbedElements: Element[] = [];+ const pendingEmbedElements = new Set<Element>();/// #if MOBILEif (((0 !== window.siyuan.config.sync.provider && isPaidUser()) ||(0 === window.siyuan.config.sync.provider && !needSubscribe(""))) &&@@ -92,14 +93,24 @@ const promiseTransaction = (options: {if (getSelection().rangeCount > 0) {range = getSelection().getRangeAt(0);}+ const isEmbedChildOperation = !!(range && getEmbedChildOperationContext(range.startContainer));if (!options.skipSync) {options.doOperations.forEach((operation: IOperation) => {if (operation.action === "update") {// 当前编辑器中的其他块let updatedEmbed = false;- const updateHTML = (item: Element, html: string) => {- if (item.getAttribute(Constants.ATTRIBUTE_EDITING) === "true") {+ 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));+ 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;}@@ -118,16 +129,19 @@ const promiseTransaction = (options: {const allTempElement = document.createElement("template");allTempElement.innerHTML = operation.data;- protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach((item) => {- if (range && (item === range.startContainer || item.contains(range.startContainer))) {+ updateElements.forEach((item) => {+ if ((currentEmbedElement && isInEmbedBlock(item, false) === currentEmbedElement) ||+ (range && (item === range.startContainer || item.contains(range.startContainer)))) {// 正在编辑的块不能进行更新item.removeAttribute(Constants.ATTRIBUTE_EDITING);} else {- updateHTML(item, operation.data);+ // 从可编辑嵌入块发起更新时,同 ID 的普通副本可能带有其他事务遗留的编辑标记,仍需同步。+ updateHTML(item, operation.data, !!currentEmbedElement && !isInEmbedBlock(item));}});protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg__embed").forEach(item => {- if (range && (item === range.startContainer || item.contains(range.startContainer))) {+ if (item === currentEmbedContext?.resultElement ||+ (range && (item === range.startContainer || item.contains(range.startContainer)))) {// 正在编辑的块不能进行更新item.removeAttribute(Constants.ATTRIBUTE_EDITING);} else {@@ -148,17 +162,18 @@ const promiseTransaction = (options: {return;}if (operation.action === "delete" || operation.action === "append") {- if (protyle.options.backlinkData) {+ // 普通编辑流程自行维护本地 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) && !item.contains(range.startContainer)) {+ 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.includes(item)) {- pendingEmbedElements.push(item);+ if (item.querySelector(`[data-node-id="${operation.id}"]`)) {+ pendingEmbedElements.add(item);}});hideElements(["gutter"], protyle);@@ -220,8 +235,8 @@ const promiseTransaction = (options: {}// 更新嵌入块protyle.wysiwyg.element.querySelectorAll('[data-type="NodeBlockQueryEmbed"]').forEach((item) => {- if (item.querySelector(`[data-node-id="${operation.id}"],[data-node-id="${operation.parentID}"],[data-node-id="${operation.previousID}"]`) && !pendingEmbedElements.includes(item)) {- pendingEmbedElements.push(item);+ if (item.querySelector(`[data-node-id="${operation.id}"],[data-node-id="${operation.parentID}"],[data-node-id="${operation.previousID}"]`)) {+ pendingEmbedElements.add(item);}});// 移动块(含撤销移动)后刷新相关超级块的拖拽手柄,避免手柄残留/缺失@@ -232,15 +247,35 @@ const promiseTransaction = (options: {return;}if (operation.action === "insert") {- // 块已被本地 DOM 操作插入时跳过,避免重复 https://github.com/siyuan-note/siyuan/issues/17890- if (protyle.wysiwyg.element.querySelector(`[data-node-id="${operation.id}"]`)) {- return;+ // 块已被本地 DOM 操作插入时仍需同步其他普通副本,并跳过当前副本避免重复+ // https://github.com/siyuan-note/siyuan/issues/17890+ const insertedElement = protyle.wysiwyg.element.querySelector(`[data-node-id="${operation.id}"]`);+ 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[] = [];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;+ }if (getNextBlockSibling(item)?.getAttribute("data-node-id") !== operation.id &&- !item.contains(range.startContainer) && // 当前操作块不再进行操作+ (!range || !item.contains(range.startContainer)) && // 当前操作块不再进行操作// 段落转列表会在段落后插入新列表!hasClosestByAttribute(item, "data-node-id", operation.id) &&// 嵌入块后不能插入@@ -249,9 +284,32 @@ const promiseTransaction = (options: {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;+ }+ if (getPreviousBlockSibling(item)?.getAttribute("data-node-id") !== operation.id &&+ (!range || !item.contains(range.startContainer)) &&+ !item.parentElement.classList.contains("protyle-wysiwyg__embed")) {+ item.insertAdjacentHTML("beforebegin", operation.data);+ cursorElements.push(item.previousElementSibling);+ }+ });} else {Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.parentID}"]`)).forEach(item => {- if (!isInEmbedBlock(item) && !item.contains(range.startContainer)) {+ const embedElement = isInEmbedBlock(item, false);+ if (embedElement) {+ if (embedElement !== currentEmbedElement) {+ pendingEmbedElements.add(embedElement);+ }+ 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) {@@ -267,6 +325,12 @@ const promiseTransaction = (options: {}}});+ 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/4420protyle.wysiwyg.element.querySelectorAll('[data-type="NodeHeading"]').forEach(item => {@@ -298,8 +362,8 @@ const promiseTransaction = (options: {}// 仅在 alt+click 箭头折叠时才会触发protyle.wysiwyg.element.querySelectorAll('[data-type="NodeBlockQueryEmbed"]').forEach((item) => {- if (item.querySelector(`[data-node-id="${operation.id}"]`) && !pendingEmbedElements.includes(item)) {- pendingEmbedElements.push(item);+ if (item.querySelector(`[data-node-id="${operation.id}"]`)) {+ pendingEmbedElements.add(item);}});}@@ -353,6 +417,28 @@ const promiseTransaction = (options: {});};+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>();@@ -455,7 +541,7 @@ const updateBlock = (updateElements: Element[], protyle: IProtyle, operation: IO});};-// 用于推送和撤销+// 用于推送和撤销;普通模式在内核事务完成后回放,lite 模式仅更新本地 DOM。export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUndo: boolean) => {if (protyle.wysiwyg.element.firstElementChild?.classList.contains("protyle-password")) {return;@@ -905,7 +991,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd}} else {previousElement.forEach(item => {- const embedElement = isInEmbedBlock(item);+ const embedElement = isInEmbedBlock(item, false);if (embedElement) {// https://github.com/siyuan-note/siyuan/issues/5524embedElement.removeAttribute("data-render");@@ -918,7 +1004,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd}} else if (operation.nextID) {Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.nextID}"]`)).forEach(item => {- const embedElement = isInEmbedBlock(item);+ const embedElement = isInEmbedBlock(item, false);if (embedElement) {// https://github.com/siyuan-note/siyuan/issues/5524embedElement.removeAttribute("data-render");@@ -930,6 +1016,13 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd});} 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) {protyle.wysiwyg.element.insertAdjacentHTML("afterbegin", operation.data);cursorElements.push(protyle.wysiwyg.element.firstElementChild);@@ -942,7 +1035,11 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd}} else {parentElement.forEach(item => {- if (!isInEmbedBlock(item)) {+ const embedElement = isInEmbedBlock(item, false);+ if (embedElement) {+ embedElement.removeAttribute("data-render");+ blockRender(protyle, embedElement);+ } else {// 列表特殊处理if (item.firstElementChild?.classList.contains("protyle-action")) {item.firstElementChild.insertAdjacentHTML("afterend", operation.data);diff --git a/kernel/model/search.go b/kernel/model/search.goindex 082bdb9717..98a4f5bdf7 100644--- a/kernel/model/search.go+++ b/kernel/model/search.go@@ -188,8 +188,9 @@ func ListInvalidBlockRefs(page, pageSize int) (ret []*Block, matchedBlockCount,}type EmbedBlock struct {- Block *Block `json:"block"`- BlockPaths []*BlockPath `json:"blockPaths"`+ Block *Block `json:"block"`+ BlockPaths []*BlockPath `json:"blockPaths"`+ AllowChildOperation bool `json:"allowChildOperation"`}func UpdateEmbedBlock(id, content string) (err error) {@@ -231,7 +232,7 @@ func getEmbedBlock(embedBlockID string, includeIDs []string, headingMode int, brreturn m[sqlBlocks[i].ID] < m[sqlBlocks[j].ID]})- ret = buildEmbedBlock(embedBlockID, []string{}, headingMode, breadcrumb, sqlBlocks)+ ret = buildEmbedBlock(embedBlockID, []string{}, headingMode, breadcrumb, "", sqlBlocks)return}@@ -248,11 +249,12 @@ func SearchEmbedBlockInBox(embedBlockID, stmt string, excludeIDs []string, headi} else {sqlBlocks = sql.SelectBlocksRawStmtNoParse(stmt, Conf.Search.Limit)}- ret = buildEmbedBlock(embedBlockID, excludeIDs, headingMode, breadcrumb, sqlBlocks)+ ret = buildEmbedBlock(embedBlockID, excludeIDs, headingMode, breadcrumb, treenode.GetEmbedBlockRefID(stmt), sqlBlocks)return}-func buildEmbedBlock(embedBlockID string, excludeIDs []string, headingMode int, breadcrumb bool, sqlBlocks []*sql.Block) (ret []*EmbedBlock) {+func buildEmbedBlock(embedBlockID string, excludeIDs []string, headingMode int, breadcrumb bool, embedBlockRefID string,+ sqlBlocks []*sql.Block) (ret []*EmbedBlock) {var tmp []*sql.Blockfor _, b := range sqlBlocks {if "query_embed" == b.Type { // 嵌入块不再嵌入@@ -289,8 +291,9 @@ func buildEmbedBlock(embedBlockID string, excludeIDs []string, headingMode int,continue}ret = append(ret, &EmbedBlock{- Block: block,- BlockPaths: blockPaths,+ Block: block,+ BlockPaths: blockPaths,+ AllowChildOperation: embedBlockRefID == block.ID && block.IsContainerBlock(),})}diff --git a/kernel/treenode/node.go b/kernel/treenode/node.goindex 260a069654..aaed8a5187 100644--- a/kernel/treenode/node.go+++ b/kernel/treenode/node.go@@ -66,43 +66,47 @@ func GetEmbedBlockRef(embedNode *ast.Node) (blockRefID string) {return}- stmt := scriptNode.TokensStr()+ return GetEmbedBlockRefID(scriptNode.TokensStr())+}++func GetEmbedBlockRefID(stmt string) (blockRefID string) {parsedStmt, err := sqlparser.Parse(stmt)if err != nil {return}- switch parsedStmt.(type) {- case *sqlparser.Select:- slct := parsedStmt.(*sqlparser.Select)- if nil == slct.Where || nil == slct.Where.Expr {- return+ slct, ok := parsedStmt.(*sqlparser.Select)+ if !ok || nil == slct.Where || nil == slct.Where.Expr {+ return+ }++ expr := slct.Where.Expr+ for {+ paren, isParen := expr.(*sqlparser.ParenExpr)+ if !isParen {+ break}+ expr = paren.Expr+ }- switch slct.Where.Expr.(type) {- case *sqlparser.ComparisonExpr: // WHERE id = '20060102150405-1a2b3c4'- comp := slct.Where.Expr.(*sqlparser.ComparisonExpr)- switch comp.Left.(type) {- case *sqlparser.ColName:- col := comp.Left.(*sqlparser.ColName)- if nil == col || "id" != col.Name.Lowered() {- return- }- }- switch comp.Right.(type) {- case *sqlparser.SQLVal:- val := comp.Right.(*sqlparser.SQLVal)- if nil == val || sqlparser.StrVal != val.Type {- return- }+ comp, ok := expr.(*sqlparser.ComparisonExpr) // 仅匹配 WHERE id = '20060102150405-1a2b3c4'+ if !ok || sqlparser.EqualStr != comp.Operator {+ return+ }- idVal := string(val.Val)- if !ast.IsNodeIDPattern(idVal) {- return- }- blockRefID = idVal- }- }+ col, ok := comp.Left.(*sqlparser.ColName)+ if !ok || nil == col || "id" != col.Name.Lowered() {+ return+ }++ val, ok := comp.Right.(*sqlparser.SQLVal)+ if !ok || nil == val || sqlparser.StrVal != val.Type {+ return+ }++ idVal := string(val.Val)+ if ast.IsNodeIDPattern(idVal) {+ blockRefID = idVal}return}diff --git a/kernel/treenode/node_test.go b/kernel/treenode/node_test.goindex 8b2a7f146a..9087449675 100644--- a/kernel/treenode/node_test.go+++ b/kernel/treenode/node_test.go@@ -57,3 +57,43 @@ func TestGetDocTitleImgPath(t *testing.T) {})}}++func TestGetEmbedBlockRef(t *testing.T) {+ const blockID = "20060102150405-1a2b3c4"+ tests := []struct {+ name string+ stmt string+ expected string+ }{+ {name: "exact ID", stmt: "SELECT * FROM blocks WHERE id = '" + blockID + "'", expected: blockID},+ {name: "quoted ID column", stmt: "SELECT * FROM blocks WHERE `id` = '" + blockID + "'", expected: blockID},+ {name: "qualified ID column", stmt: "SELECT * FROM blocks WHERE blocks.id = '" + blockID + "'", expected: blockID},+ {name: "parenthesized condition", stmt: "SELECT * FROM blocks WHERE ((id = '" + blockID + "'))", expected: blockID},+ {name: "limited exact ID", stmt: "SELECT * FROM blocks WHERE id = '" + blockID + "' LIMIT 1", expected: blockID},+ {name: "not equal", stmt: "SELECT * FROM blocks WHERE id != '" + blockID + "'"},+ {name: "additional condition", stmt: "SELECT * FROM blocks WHERE id = '" + blockID + "' AND type = 'd'"},+ {name: "alternative condition", stmt: "SELECT * FROM blocks WHERE id = '" + blockID + "' OR type = 'd'"},+ {name: "ID list", stmt: "SELECT * FROM blocks WHERE id IN ('" + blockID + "')"},+ {name: "ID pattern", stmt: "SELECT * FROM blocks WHERE id LIKE '" + blockID + "'"},+ {name: "reversed comparison", stmt: "SELECT * FROM blocks WHERE '" + blockID + "' = id"},+ {name: "other column", stmt: "SELECT * FROM blocks WHERE parent_id = '" + blockID + "'"},+ {name: "numeric value", stmt: "SELECT * FROM blocks WHERE id = 20060102150405"},+ {name: "invalid ID", stmt: "SELECT * FROM blocks WHERE id = 'invalid'"},+ {name: "non-select statement", stmt: "DELETE FROM blocks WHERE id = '" + blockID + "'"},+ {name: "invalid SQL", stmt: "SELECT FROM"},+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ if actual := GetEmbedBlockRefID(test.stmt); test.expected != actual {+ t.Fatalf("expected raw statement result %q, got %q", test.expected, actual)+ }++ embedNode := &ast.Node{Type: ast.NodeBlockQueryEmbed}+ embedNode.AppendChild(&ast.Node{Type: ast.NodeBlockQueryEmbedScript, Tokens: []byte(test.stmt)})+ if actual := GetEmbedBlockRef(embedNode); test.expected != actual {+ t.Fatalf("expected %q, got %q", test.expected, actual)+ }+ })+ }+}