An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Improve undo and redo for folded heading moves https://github.com/siyuan-note/siyuan/issues/18838
Danielfa83ceee4bb8
diff --git a/app/src/protyle/util/editorCommonEvent.ts b/app/src/protyle/util/editorCommonEvent.tsindex f2362d33cf..675e89950c 100644--- a/app/src/protyle/util/editorCommonEvent.ts+++ b/app/src/protyle/util/editorCommonEvent.ts@@ -43,6 +43,7 @@ import {hideElements} from "../ui/hideElements";import {insertAttrViewBlockAnimation} from "../render/av/row";import * as dayjs from "dayjs";import {zoomOut} from "../../menus/protyle";+import {isFoldedHeading, shouldUnfoldMovedHeading} from "./foldHeadingMove";/// #if !BROWSERimport {webUtils} from "electron";import {dragUpload} from "../render/av/asset";@@ -109,10 +110,6 @@ const getTargetListItem = (targetElement: Element, isBottom: boolean) => {return targetElement.closest(".li") as HTMLElement;};-const isFoldedHeading = (element: Element) => {- return element.getAttribute("data-type") === "NodeHeading" && element.getAttribute("fold") === "1";-};-type TDragSourcePosition = {previousID: string,parentID: string@@ -283,6 +280,7 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemenlet copyElement;let undoMoveOperation: IOperation;+ const moveGroupID = Lute.NewNodeID();if (isCopy) {undoOperations.push({action: "delete",@@ -296,6 +294,7 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemenid,previousID: srcPos.previousID,parentID: srcPos.parentID,+ context: {moveGroupID},};undoOperations.push(undoMoveOperation);}@@ -394,6 +393,7 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemenaction: "move",id,parentID: newListId,+ context: {moveGroupID},});} else {tempTargetElement.insertAdjacentElement(position, item);@@ -402,6 +402,7 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemenid,previousID: position === "afterbegin" ? null : (position === "afterend" ? targetId : getPreviousBlockSibling(item)?.getAttribute("data-node-id")), // 不能使用常量,移动后会被修改parentID: position === "afterbegin" ? targetId : (getParentBlock(item)?.getAttribute("data-node-id") || protyle.block.parentID || protyle.block.rootID),+ context: {moveGroupID},});newSourceElements.push(item);}@@ -663,10 +664,12 @@ const dragSb = async (protyle: IProtyle, sourceElements: Element[], targetElemen});}const undoOperations: IOperation[] = [];+ const targetMoveGroupID = Lute.NewNodeID();const targetMoveUndo: IOperation = {action: "move",context: {- removeFold: "true"+ removeFold: "true",+ moveGroupID: targetMoveGroupID,},id: targetElement.getAttribute("data-node-id"),previousID: getPreviousBlockSibling(targetElement)?.getAttribute("data-node-id"),@@ -725,14 +728,16 @@ const dragSb = async (protyle: IProtyle, sourceElements: Element[], targetElementargetOperations.push({action: "move",id: targetElement.getAttribute("data-node-id"),- parentID: sbElement.getAttribute("data-node-id")+ parentID: sbElement.getAttribute("data-node-id"),+ context: {moveGroupID: targetMoveGroupID},});} else {sbElement.lastElementChild.insertAdjacentElement("beforebegin", targetElement);targetOperations.push({action: "move",id: targetElement.getAttribute("data-node-id"),- previousID: sourcePreviousID+ previousID: sourcePreviousID,+ context: {moveGroupID: targetMoveGroupID},});}doOperations.splice(removeIndex, 0, ...targetOperations);@@ -861,24 +866,36 @@ const dragSame = async (protyle: IProtyle, sourceElements: Element[], targetElem}undoOperations.push(...wrapUndoOperations);const newSourceParentElement = moveToResult.newSourceElements;- let foldData;const previousBlockElement = getPreviousBlockSibling(targetElement);+ const unfoldHeadingElements = new Set<Element>();if (!isColumnDrop && isBottom &&targetElement.getAttribute("data-type") === "NodeHeading" &&targetElement.getAttribute("fold") === "1") {- foldData = setFold(protyle, targetElement, true, false, false, true);+ unfoldHeadingElements.add(targetElement);} else if (!isColumnDrop && !isBottom &&previousBlockElement?.getAttribute("data-type") === "NodeHeading" &&previousBlockElement.getAttribute("fold") === "1") {- foldData = setFold(protyle, previousBlockElement, true, false, false, true);+ unfoldHeadingElements.add(previousBlockElement);+ }+ if (!isColumnDrop) {+ // 同一落点可由相邻块的上方或下方命中,统一展开会吸收目标内容的源标题。+ newSourceParentElement.forEach(item => {+ if (shouldUnfoldMovedHeading(item, getNextBlockSibling(item))) {+ unfoldHeadingElements.add(item);+ }+ });}- if (foldData) {+ unfoldHeadingElements.forEach(item => {+ const foldData = setFold(protyle, item, true, false, false, true);+ if (!foldData.doOperations) {+ return;+ }foldData.doOperations[0].context = {focusId: sourceElements[0].getAttribute("data-node-id"),};doOperations.push(...foldData.doOperations);undoOperations.push(...foldData.undoOperations);- }+ });if (targetElement.getAttribute("data-type") === "NodeListItem" &&targetElement.getAttribute("data-subtype") === "o") {// https://github.com/siyuan-note/insider/issues/536diff --git a/app/src/protyle/util/foldHeadingMove.test.ts b/app/src/protyle/util/foldHeadingMove.test.tsnew file mode 100644index 0000000000..d9dc346790--- /dev/null+++ b/app/src/protyle/util/foldHeadingMove.test.ts@@ -0,0 +1,44 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {isFoldedHeading, shouldUnfoldMovedHeading} from "./foldHeadingMove";++class TestBlockElement {+ constructor(private attributes: Record<string, string>) {+ }++ getAttribute(name: string) {+ return this.attributes[name] ?? null;+ }+}++const asElement = (attributes: Record<string, string>) =>+ new TestBlockElement(attributes) as unknown as Element;++describe("folded heading moves", () => {+ const foldedHeading = asElement({"data-type": "NodeHeading", "data-subtype": "h2", fold: "1"});++ it("recognizes folded headings", () => {+ assert.equal(isFoldedHeading(foldedHeading), true);+ assert.equal(isFoldedHeading(asElement({"data-type": "NodeHeading", "data-subtype": "h2"})), false);+ });++ it("unfolds when the destination contributes a new heading child", () => {+ assert.equal(shouldUnfoldMovedHeading(foldedHeading, asElement({"data-type": "NodeParagraph"})), true);+ assert.equal(shouldUnfoldMovedHeading(+ foldedHeading,+ asElement({"data-type": "NodeHeading", "data-subtype": "h3"}),+ ), true);+ });++ it("preserves folding at a heading boundary or the end of a container", () => {+ assert.equal(shouldUnfoldMovedHeading(+ foldedHeading,+ asElement({"data-type": "NodeHeading", "data-subtype": "h2"}),+ ), false);+ assert.equal(shouldUnfoldMovedHeading(+ foldedHeading,+ asElement({"data-type": "NodeHeading", "data-subtype": "h1"}),+ ), false);+ assert.equal(shouldUnfoldMovedHeading(foldedHeading), false);+ });+});diff --git a/app/src/protyle/util/foldHeadingMove.ts b/app/src/protyle/util/foldHeadingMove.tsnew file mode 100644index 0000000000..2d393ea783--- /dev/null+++ b/app/src/protyle/util/foldHeadingMove.ts@@ -0,0 +1,22 @@+export const isFoldedHeading = (element?: Element) =>+ element?.getAttribute("data-type") === "NodeHeading" && element.getAttribute("fold") === "1";++const getHeadingLevel = (element: Element) => {+ const subtype = element.getAttribute("data-subtype");+ if (!subtype?.startsWith("h")) {+ return NaN;+ }+ return Number.parseInt(subtype.substring(1));+};++export const shouldUnfoldMovedHeading = (heading: Element, nextBlock?: Element) => {+ if (!isFoldedHeading(heading) || !nextBlock) {+ return false;+ }+ if (nextBlock.getAttribute("data-type") !== "NodeHeading") {+ return true;+ }+ const headingLevel = getHeadingLevel(heading);+ const nextLevel = getHeadingLevel(nextBlock);+ return Number.isNaN(headingLevel) || Number.isNaN(nextLevel) || nextLevel > headingLevel;+};diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex 8b74e2b6d0..cd12317e9d 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -48,6 +48,7 @@ import {import {MERMAID_LAYOUT_ATTR} from "../render/mermaidLayout";import {getPartialUpdateCleanupElements, shouldDeferCodeBlockCaretRestore} from "./transactionUpdate";import {getMoveAffectedEmbedElements, shouldSyncMoveCopies} from "./transactionEmbed";+import {cloneMoveElements, getVisibleMoveElements} from "./transactionMove";import {normalizeHTMLAssetIFrameBlockDOM} from "../../asset/html";const removeTopElement = (updateElement: Element, protyle: IProtyle) => {@@ -251,9 +252,12 @@ const promiseTransaction = (options: {}}});+ const moveElementGroups = updateElements.map(item => getVisibleMoveElements(item, operation.blockIDs));+ const primaryMoveElements = moveElementGroups[0] || [];+ const moveElements = Array.from(new Set(moveElementGroups.flat()));// 移动前记录源块所在的超级块,移动后刷新其拖拽手柄(移出后手柄需清理)const originSbs: Element[] = [];- updateElements.forEach(item => {+ moveElements.forEach(item => {const sb = item.closest('[data-type="NodeSuperBlock"]');if (sb && !originSbs.includes(sb)) {originSbs.push(sb);@@ -263,27 +267,27 @@ const promiseTransaction = (options: {if (operation.previousID && updateElements.length > 0) {Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.previousID}"]`)).forEach(item => {if (!isInEmbedBlock(item) && !getNextBlockSibling(item)?.contains(range.startContainer)) {- item.after(updateElements[0].cloneNode(true));+ item.after(...cloneMoveElements(primaryMoveElements));hasFind = true;}});} else if (updateElements.length > 0) {Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.parentID}"]`)).forEach(item => {if (!isInEmbedBlock(item) && !getFirstBlock(item).contains(range.startContainer)) {- const cloneElement = updateElements[0].cloneNode(true) as Element;+ const cloneElements = cloneMoveElements(primaryMoveElements);// 列表特殊处理if (item.firstElementChild?.classList.contains("protyle-action")) {- item.firstElementChild.after(cloneElement);+ item.firstElementChild.after(...cloneElements);} else if (item.classList.contains("callout")) {- item.querySelector(".callout-content").prepend(cloneElement);+ item.querySelector(".callout-content").prepend(...cloneElements);} else {- item.prepend(cloneElement);+ item.prepend(...cloneElements);}hasFind = true;}});}- updateElements.forEach(item => {+ moveElements.forEach(item => {if (hasFind) {item.remove();} else if (!hasFind && item.parentElement) {@@ -989,6 +993,9 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd});});}+ const moveElementGroups = updateElements.map(item => getVisibleMoveElements(item, operation.blockIDs));+ const primaryMoveElements = moveElementGroups[0] || [];+ const moveElements = Array.from(new Set(moveElementGroups.flat()));let range;if (isUndo && getSelection().rangeCount > 0) {range = getSelection().getRangeAt(0);@@ -1005,7 +1012,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd// 移动前记录源块所在的超级块,移动后刷新其拖拽手柄(移出后手柄需清理)// https://github.com/siyuan-note/siyuan/issues/9521const originSbs: Element[] = [];- updateElements.forEach(item => {+ moveElements.forEach(item => {const sb = item.closest('[data-type="NodeSuperBlock"]');if (sb && !originSbs.includes(sb)) {originSbs.push(sb);@@ -1017,13 +1024,13 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd// 反链面板删除超级块中的最后一个段落块后撤销重做const blockElement = hasTopClosestByAttribute(range.startContainer, "data-node-id", null);if (blockElement) {- blockElement.before(updateElements[0].cloneNode(true));+ blockElement.before(...cloneMoveElements(primaryMoveElements));hasFind = true;}} else {previousElement.forEach(item => {if (!isInEmbedBlock(item)) {- item.after(updateElements[0].cloneNode(true));+ item.after(...cloneMoveElements(primaryMoveElements));hasFind = true;}});@@ -1031,33 +1038,33 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd} else if (updateElements.length > 0) {const parentElement = protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.parentID}"]`);if (!protyle.options.backlinkData && operation.parentID === protyle.block.parentID && !protyle.block.showAll) {- protyle.wysiwyg.element.prepend(updateElements[0].cloneNode(true));+ protyle.wysiwyg.element.prepend(...cloneMoveElements(primaryMoveElements));hasFind = true;} else if (parentElement.length === 0 && protyle.options.backlinkData && isUndo && getSelection().rangeCount > 0) {// 反链面板删除超级块中的段落块后撤销再重做 https://github.com/siyuan-note/siyuan/issues/14496#issuecomment-2771372486const topBlockElement = hasTopClosestByAttribute(getSelection().getRangeAt(0).startContainer, "data-node-id", null);if (topBlockElement) {- topBlockElement.before(updateElements[0].cloneNode(true));+ topBlockElement.before(...cloneMoveElements(primaryMoveElements));hasFind = true;}} else {parentElement.forEach(item => {if (!isInEmbedBlock(item)) {- const cloneElement = updateElements[0].cloneNode(true) as Element;+ const cloneElements = cloneMoveElements(primaryMoveElements);// 列表特殊处理if (item.firstElementChild?.classList.contains("protyle-action")) {- item.firstElementChild.after(cloneElement);+ item.firstElementChild.after(...cloneElements);} else if (item.classList.contains("callout")) {- item.querySelector(".callout-content").prepend(cloneElement);+ item.querySelector(".callout-content").prepend(...cloneElements);} else {- item.prepend(cloneElement);+ item.prepend(...cloneElements);}hasFind = true;}});}}- updateElements.forEach(item => {+ moveElements.forEach(item => {if (hasFind) {item.remove();} else if (!hasFind && item.parentElement) {@@ -1081,15 +1088,16 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd}}// 更新嵌入块。undo 已由 kernel 执行事务后广播,查询能拿到最新数据,无竞态。- 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}"]`)) {- if (item === undoFocusEmbedElement) {- // 当前嵌入块需在撤销操作全部回放后渲染,否则中途移除选区会把光标带到源块- pendingUndoEmbedElements.add(item);- } else {- item.removeAttribute("data-render");- blockRender(protyle, item);- }+ getMoveAffectedEmbedElements(+ protyle.wysiwyg.element.querySelectorAll('[data-type="NodeBlockQueryEmbed"]'),+ operation,+ ).forEach(item => {+ if (item === undoFocusEmbedElement) {+ // 当前嵌入块需在撤销操作全部回放后渲染,否则中途移除选区会把光标带到源块+ pendingUndoEmbedElements.add(item);+ } else {+ item.removeAttribute("data-render");+ blockRender(protyle, item);}});// 移动块(含重做/同步)后刷新相关超级块的拖拽手柄diff --git a/app/src/protyle/wysiwyg/transactionEmbed.test.ts b/app/src/protyle/wysiwyg/transactionEmbed.test.tsindex 6b5c43a83a..12654b7a57 100644--- a/app/src/protyle/wysiwyg/transactionEmbed.test.ts+++ b/app/src/protyle/wysiwyg/transactionEmbed.test.ts@@ -7,8 +7,14 @@ class TestEmbedElement {}querySelector(selector: string) {- const ids = Array.from(selector.matchAll(/\[data-node-id="([^"]+)"\]/g), match => match[1]);- return ids.some(id => this.nodeIDs.includes(id)) ? {} : null;+ const id = selector.match(/\[data-node-id="([^"]+)"\]/)?.[1];+ return id && this.nodeIDs.includes(id) ? {} : null;+ }++ querySelectorAll() {+ return this.nodeIDs.map(id => ({+ getAttribute: (name: string) => name === "data-node-id" ? id : null,+ }));}}@@ -37,6 +43,15 @@ describe("getMoveAffectedEmbedElements", () => {{id: "moved", previousID: "previous"},), [embed]);});++ it("matches visible members that move with a folded heading", () => {+ const embed = asElement(new TestEmbedElement(["heading-child"]));++ assert.deepEqual(getMoveAffectedEmbedElements(+ [embed],+ {id: "heading", blockIDs: ["heading-child"]},+ ), [embed]);+ });});describe("shouldSyncMoveCopies", () => {diff --git a/app/src/protyle/wysiwyg/transactionEmbed.ts b/app/src/protyle/wysiwyg/transactionEmbed.tsindex d6fb5dd671..f884653d7f 100644--- a/app/src/protyle/wysiwyg/transactionEmbed.ts+++ b/app/src/protyle/wysiwyg/transactionEmbed.ts@@ -1,15 +1,23 @@export const getMoveAffectedEmbedElements = (embedElements: Iterable<Element>,- operation: Pick<IOperation, "id" | "parentID" | "previousID">,+ operation: Pick<IOperation, "id" | "blockIDs" | "parentID" | "previousID">,editingEmbedElement?: Element,) => {- const ids = [operation.id, operation.parentID, operation.previousID].filter(Boolean);- if (ids.length === 0) {+ const anchorIDs = [operation.id, operation.parentID, operation.previousID].filter(Boolean);+ const blockIDs = new Set(operation.blockIDs || []);+ if (anchorIDs.length === 0 && blockIDs.size === 0) {return [];}- const selector = ids.map(id => `[data-node-id="${id}"]`).join(",");- return Array.from(embedElements).filter(item =>- item !== editingEmbedElement && !!item.querySelector(selector));+ return Array.from(embedElements).filter(item => {+ if (item === editingEmbedElement) {+ return false;+ }+ if (anchorIDs.some(id => item.querySelector(`[data-node-id="${id}"]`))) {+ return true;+ }+ return blockIDs.size > 0 && Array.from(item.querySelectorAll("[data-node-id]"))+ .some(block => blockIDs.has(block.getAttribute("data-node-id")));+ });};export const shouldSyncMoveCopies = (isBacklink: boolean, isEmbedChildOperation: boolean) =>diff --git a/app/src/protyle/wysiwyg/transactionMove.test.ts b/app/src/protyle/wysiwyg/transactionMove.test.tsnew file mode 100644index 0000000000..8d71b02044--- /dev/null+++ b/app/src/protyle/wysiwyg/transactionMove.test.ts@@ -0,0 +1,59 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {getVisibleMoveElements} from "./transactionMove";++class TestMoveElement {+ nextElementSibling?: TestMoveElement;++ constructor(readonly id?: string) {+ }++ getAttribute(name: string) {+ return name === "data-node-id" ? this.id ?? null : null;+ }+}++const asElement = (element: TestMoveElement) => element as unknown as Element;++const linkElements = (...elements: TestMoveElement[]) => {+ elements.forEach((element, index) => {+ element.nextElementSibling = elements[index + 1];+ });+};++describe("getVisibleMoveElements", () => {+ it("collects the visible members of a stored move group in order", () => {+ const heading = new TestMoveElement("heading");+ const first = new TestMoveElement("first");+ const second = new TestMoveElement("second");+ const target = new TestMoveElement("target");+ linkElements(heading, first, second, target);++ assert.deepEqual(+ getVisibleMoveElements(asElement(heading), ["first", "second"]),+ [heading, first, second],+ );+ });++ it("allows folded descendants to be absent from the DOM", () => {+ const heading = new TestMoveElement("heading");+ const first = new TestMoveElement("first");+ const third = new TestMoveElement("third");+ const target = new TestMoveElement("target");+ linkElements(heading, first, third, target);++ assert.deepEqual(+ getVisibleMoveElements(asElement(heading), ["first", "hidden", "third"]),+ [heading, first, third],+ );+ });++ it("does not absorb destination blocks when all original children are hidden", () => {+ const heading = new TestMoveElement("heading");+ const target = new TestMoveElement("target");+ linkElements(heading, target);++ assert.deepEqual(getVisibleMoveElements(asElement(heading), ["hidden"]), [heading]);+ assert.deepEqual(getVisibleMoveElements(asElement(heading), []), [heading]);+ });+});diff --git a/app/src/protyle/wysiwyg/transactionMove.ts b/app/src/protyle/wysiwyg/transactionMove.tsnew file mode 100644index 0000000000..af849829c6--- /dev/null+++ b/app/src/protyle/wysiwyg/transactionMove.ts@@ -0,0 +1,37 @@+const getNextBlockElement = (element: Element) => {+ let nextElement = element.nextElementSibling;+ while (nextElement && !nextElement.getAttribute("data-node-id")) {+ nextElement = nextElement.nextElementSibling;+ }+ return nextElement;+};++export const getVisibleMoveElements = (sourceElement: Element, blockIDs?: string[]) => {+ const elements = [sourceElement];+ if (!blockIDs?.length) {+ return elements;+ }++ let blockIndex = 0;+ let nextElement = getNextBlockElement(sourceElement);+ while (nextElement) {+ const id = nextElement.getAttribute("data-node-id");+ if (!id) {+ break;+ }+ const matchedIndex = blockIDs.indexOf(id, blockIndex);+ if (matchedIndex < 0) {+ break;+ }+ elements.push(nextElement);+ blockIndex = matchedIndex + 1;+ if (blockIndex === blockIDs.length) {+ break;+ }+ nextElement = getNextBlockElement(nextElement);+ }+ return elements;+};++export const cloneMoveElements = (elements: Element[]) =>+ elements.map(item => item.cloneNode(true) as Element);diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex d25b5ff712..1c69420fa8 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -596,9 +596,9 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {// 生成文档历史 https://github.com/siyuan-note/siyuan/issues/14359generateOpTypeHistory(srcTree, HistoryOpUpdate)- var headingChildren []*ast.Node- if isMovingFoldHeading := ast.NodeHeading == srcNode.Type && treenode.IsSelfFolded(srcNode); isMovingFoldHeading {- headingChildren = treenode.HeadingChildren(srcNode)+ headingChildren, captureHeadingMoveGroup, moveGroupErr := tx.resolveHeadingMoveChildren(operation, srcNode)+ if nil != moveGroupErr {+ return moveGroupErr}srcParent := srcNode.Parent@@ -662,7 +662,7 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {return &TxErr{code: TxErrCodeSkipTx}}- if 0 < len(headingChildren) {+ if nil == operation.BlockIDs && 0 < len(headingChildren) {// 折叠标题再编辑形成外层列表(前面加上 * )时,前端给的 tx 序列会形成死循环,在这里解开// Nested lists cause hang after collapsing headings https://github.com/siyuan-note/siyuan/issues/15943lastChild := headingChildren[len(headingChildren)-1]@@ -671,6 +671,9 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {headingChildren = headingChildren[:len(headingChildren)-1]}}+ if captureHeadingMoveGroup {+ tx.storeHeadingMoveBlockIDs(operation, headingChildren)+ }tx.markListItemFoldCandidate(srcParent, srcTree)for i := len(headingChildren) - 1; -1 < i; i-- {@@ -729,6 +732,9 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {if isMovingParentIntoChild(srcNode, targetNode) {return &TxErr{code: TxErrCodeSkipTx}}+ if captureHeadingMoveGroup {+ tx.storeHeadingMoveBlockIDs(operation, headingChildren)+ }tx.markListItemFoldCandidate(srcParent, srcTree)processed := false@@ -787,6 +793,106 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {return}+const moveGroupIDContextKey = "moveGroupID"++func (tx *Transaction) resolveHeadingMoveChildren(operation *Operation, srcNode *ast.Node) (children []*ast.Node,+ capture bool, ret *TxErr) {+ if !tx.isReplay {+ // 移动集合由内核根据提交前的树生成,不能信任调用方传入的块 ID。+ operation.BlockIDs = nil+ }+ if tx.isReplay && nil != operation.BlockIDs {+ // 重放只移动首次执行保存的子块前缀,当前位置后来纳入的块仍留在原处。+ if ast.NodeHeading != srcNode.Type {+ return nil, false, invalidHeadingMoveGroupError(srcNode.ID)+ }+ if children, ok := headingMoveChildrenByBlockIDs(srcNode, operation.BlockIDs); ok {+ return children, false, nil+ }+ return nil, false, invalidHeadingMoveGroupError(srcNode.ID)+ }+ if ast.NodeHeading == srcNode.Type && treenode.IsSelfFolded(srcNode) {+ return treenode.HeadingChildren(srcNode), !tx.isReplay, nil+ }+ return nil, false, nil+}++func headingMoveChildrenByBlockIDs(heading *ast.Node, blockIDs []string) (ret []*ast.Node, ok bool) {+ if nil == blockIDs {+ return nil, false+ }+ if 0 == len(blockIDs) {+ return []*ast.Node{}, true+ }++ children := treenode.HeadingChildren(heading)+ blockIndex := 0+ for i, child := range children {+ ret = append(ret, child)+ if !child.IsBlock() || ast.NodeKramdownBlockIAL == child.Type {+ continue+ }+ if child.ID != blockIDs[blockIndex] {+ return nil, false+ }+ blockIndex+++ if blockIndex != len(blockIDs) {+ continue+ }+ for next := i + 1; next < len(children) && ast.NodeKramdownBlockIAL == children[next].Type; next++ {+ ret = append(ret, children[next])+ }+ return ret, true+ }+ return nil, false+}++func invalidHeadingMoveGroupError(id string) *TxErr {+ msg := "folded heading move group changed"+ logging.LogWarnf("%s [%s]", msg, id)+ return &TxErr{code: TxErrCodeReloadUI, msg: msg, id: id}+}++func (tx *Transaction) storeHeadingMoveBlockIDs(operation *Operation, headingChildren []*ast.Node) {+ blockIDs := make([]string, 0)+ for _, child := range headingChildren {+ if child.IsBlock() && ast.NodeKramdownBlockIAL != child.Type {+ blockIDs = append(blockIDs, child.ID)+ }+ }+ operation.BlockIDs = cloneOperationBlockIDs(blockIDs)++ moveGroupID, _ := operation.Context[moveGroupIDContextKey].(string)+ if "" != moveGroupID {+ for _, undoOperation := range tx.UndoOperations {+ undoMoveGroupID, _ := undoOperation.Context[moveGroupIDContextKey].(string)+ if moveGroupID == undoMoveGroupID {+ undoOperation.BlockIDs = cloneOperationBlockIDs(blockIDs)+ }+ }+ return+ }++ var candidates []*Operation+ for _, undoOperation := range tx.UndoOperations {+ if operation.ID == undoOperation.ID && ("move" == undoOperation.Action || "append" == undoOperation.Action) {+ candidates = append(candidates, undoOperation)+ }+ }+ if 1 == len(candidates) {+ candidates[0].BlockIDs = cloneOperationBlockIDs(blockIDs)+ }+}++func cloneOperationBlockIDs(blockIDs []string) []string {+ if nil == blockIDs {+ return nil+ }+ ret := make([]string, len(blockIDs))+ copy(ret, blockIDs)+ return ret+}+func isMovingFoldHeadingIntoSelf(targetNode *ast.Node, headingChildren []*ast.Node) bool {headingChildIDs := map[string]struct{}{}for _, headingChild := range headingChildren {@@ -1053,9 +1159,9 @@ func (tx *Transaction) doAppend(operation *Operation) (ret *TxErr) {}srcParent := srcNode.Parent- var headingChildren []*ast.Node- if isMovingFoldHeading := ast.NodeHeading == srcNode.Type && treenode.IsSelfFolded(srcNode); isMovingFoldHeading {- headingChildren = treenode.HeadingChildren(srcNode)+ headingChildren, captureHeadingMoveGroup, moveGroupErr := tx.resolveHeadingMoveChildren(operation, srcNode)+ if nil != moveGroupErr {+ return moveGroupErr}var srcEmptyList, targetNewList *ast.Nodeif ast.NodeListItem == srcNode.Type {@@ -1088,6 +1194,9 @@ func (tx *Transaction) doAppend(operation *Operation) (ret *TxErr) {util.PushMsg(Conf.Language(313), 5000)return &TxErr{code: TxErrCodeSkipTx}}+ if captureHeadingMoveGroup {+ tx.storeHeadingMoveBlockIDs(operation, headingChildren)+ }targetRoot := targetTree.Roottx.markListItemFoldCandidate(srcParent, srcTree)@@ -2199,7 +2308,7 @@ type Operation struct {PreviousID string `json:"previousID"`NextID string `json:"nextID"`RetData any `json:"retData"`- BlockIDs []string `json:"blockIDs"`+ BlockIDs []string `json:"blockIDs"` // move/append 时为随折叠标题移动的顶层块,闪卡操作时为目标块BlockID string `json:"blockID"`DeckID string `json:"deckID"` // 用于添加/删除闪卡diff --git a/kernel/model/transaction_fold_fts5_test.go b/kernel/model/transaction_fold_fts5_test.goindex 5a4003d563..15d4f2047e 100644--- a/kernel/model/transaction_fold_fts5_test.go+++ b/kernel/model/transaction_fold_fts5_test.go@@ -120,6 +120,219 @@ func TestCancelFoldedHeadingSuperBlockKeepsUndoBoundary(t *testing.T) {assertCancelledFoldedSuperBlock(t, fixture.sourceID, superBlockID, headingID, paragraphID, outsideID)}+func TestReplayFoldedHeadingMoveUsesOriginalChildren(t *testing.T) {+ const (+ anchorID = "20260819000000-anchor0"+ listID = "20260819000001-list001"+ itemID = "20260819000002-item001"+ itemBlockID = "20260819000003-itemblk"+ headingID = "20260819000004-heading"+ firstID = "20260819000005-first00"+ secondID = "20260819000006-second0"+ )+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ anchor := treenode.NewParagraph(anchorID)+ list := &ast.Node{Type: ast.NodeList, ID: listID, ListData: &ast.ListData{Typ: 1}}+ list.SetIALAttr("id", listID)+ item := &ast.Node{Type: ast.NodeListItem, ID: itemID, ListData: &ast.ListData{Typ: 1}}+ item.SetIALAttr("id", itemID)+ item.AppendChild(treenode.NewParagraph(itemBlockID))+ list.AppendChild(item)+ heading := newFoldMoveTestHeading(headingID, 2)+ writeFoldMoveTestTree(t, fixture.sourceID, anchor, list, heading, treenode.NewParagraph(firstID),+ treenode.NewParagraph(secondID))++ moveGroupID := "fold-heading-list"+ forward := &Transaction{+ DoOperations: []*Operation{{+ Action: "move",+ ID: headingID,+ PreviousID: anchorID,+ ParentID: fixture.sourceID,+ Context: map[string]any{moveGroupIDContextKey: moveGroupID},+ }},+ UndoOperations: []*Operation{{+ Action: "move",+ ID: headingID,+ PreviousID: listID,+ ParentID: fixture.sourceID,+ Context: map[string]any{moveGroupIDContextKey: moveGroupID},+ }},+ }+ if err := PerformTxSync(forward); nil != err {+ t.Fatalf("move folded heading before list failed: %s", err)+ }+ wantGroup := []string{firstID, secondID}+ if !slices.Equal(forward.DoOperations[0].BlockIDs, wantGroup) ||+ !slices.Equal(forward.UndoOperations[0].BlockIDs, wantGroup) {+ t.Fatalf("folded heading move group was not stored in both directions: do=%v undo=%v",+ forward.DoOperations[0].BlockIDs, forward.UndoOperations[0].BlockIDs)+ }+ assertFoldMoveState(t, fixture.sourceID, []string{anchorID, headingID, firstID, secondID, listID}, headingID, true)++ undo := &Transaction{DoOperations: cloneOperations(forward.UndoOperations)}+ undo.MarkReplay()+ if err := PerformTxSync(undo); nil != err {+ t.Fatalf("undo folded heading list move failed: %s", err)+ }+ assertFoldMoveState(t, fixture.sourceID, []string{anchorID, listID, headingID, firstID, secondID}, headingID, true)++ redo := &Transaction{DoOperations: cloneOperations(forward.DoOperations)}+ redo.MarkReplay()+ if err := PerformTxSync(redo); nil != err {+ t.Fatalf("redo folded heading list move failed: %s", err)+ }+ assertFoldMoveState(t, fixture.sourceID, []string{anchorID, headingID, firstID, secondID, listID}, headingID, true)+}++func TestReplayUnfoldedHeadingMoveUsesStoredChildren(t *testing.T) {+ const (+ paragraphID = "20260819000100-paragr0"+ headingID = "20260819000101-heading"+ childID = "20260819000102-child00"+ )+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ writeFoldMoveTestTree(t, fixture.sourceID, treenode.NewParagraph(paragraphID),+ newFoldMoveTestHeading(headingID, 2), treenode.NewParagraph(childID))++ moveGroupID := "fold-heading-paragraph"+ forward := &Transaction{+ DoOperations: []*Operation{+ {+ Action: "move",+ ID: headingID,+ ParentID: fixture.sourceID,+ Context: map[string]any{moveGroupIDContextKey: moveGroupID},+ },+ {Action: "unfoldHeading", ID: headingID},+ },+ UndoOperations: []*Operation{+ {+ Action: "move",+ ID: headingID,+ PreviousID: paragraphID,+ ParentID: fixture.sourceID,+ Context: map[string]any{moveGroupIDContextKey: moveGroupID},+ },+ {Action: "foldHeading", ID: headingID},+ },+ }+ if err := PerformTxSync(forward); nil != err {+ t.Fatalf("move and unfold heading failed: %s", err)+ }+ assertFoldMoveState(t, fixture.sourceID, []string{headingID, childID, paragraphID}, headingID, false)++ undo := &Transaction{DoOperations: cloneOperations(forward.UndoOperations)}+ undo.MarkReplay()+ if err := PerformTxSync(undo); nil != err {+ t.Fatalf("undo unfolded heading move failed: %s", err)+ }+ assertFoldMoveState(t, fixture.sourceID, []string{paragraphID, headingID, childID}, headingID, true)++ redo := &Transaction{DoOperations: cloneOperations(forward.DoOperations)}+ redo.MarkReplay()+ if err := PerformTxSync(redo); nil != err {+ t.Fatalf("redo unfolded heading move failed: %s", err)+ }+ assertFoldMoveState(t, fixture.sourceID, []string{headingID, childID, paragraphID}, headingID, false)+}++func TestReplayEmptyFoldedHeadingMoveGroup(t *testing.T) {+ const (+ anchorID = "20260819000200-anchor0"+ headingID = "20260819000201-heading"+ boundaryID = "20260819000202-boundry"+ )+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ writeFoldMoveTestTree(t, fixture.sourceID, treenode.NewParagraph(anchorID),+ newFoldMoveTestHeading(headingID, 2), newFoldMoveTestHeading(boundaryID, 2))++ moveGroupID := "empty-fold-heading"+ forward := &Transaction{+ DoOperations: []*Operation{{+ Action: "move",+ ID: headingID,+ ParentID: fixture.sourceID,+ Context: map[string]any{moveGroupIDContextKey: moveGroupID},+ }},+ UndoOperations: []*Operation{{+ Action: "move",+ ID: headingID,+ PreviousID: anchorID,+ ParentID: fixture.sourceID,+ Context: map[string]any{moveGroupIDContextKey: moveGroupID},+ }},+ }+ if err := PerformTxSync(forward); nil != err {+ t.Fatalf("move empty folded heading failed: %s", err)+ }+ if nil == forward.DoOperations[0].BlockIDs || 0 != len(forward.DoOperations[0].BlockIDs) ||+ nil == forward.UndoOperations[0].BlockIDs {+ t.Fatal("an empty folded heading move group should be stored as an explicit empty slice")+ }++ undo := &Transaction{DoOperations: cloneOperations(forward.UndoOperations)}+ undo.MarkReplay()+ if err := PerformTxSync(undo); nil != err {+ t.Fatalf("undo empty folded heading move failed: %s", err)+ }+ assertFoldMoveState(t, fixture.sourceID, []string{anchorID, headingID, boundaryID}, headingID, true)+}++func newFoldMoveTestHeading(id string, level int) *ast.Node {+ heading := &ast.Node{Type: ast.NodeHeading, ID: id, HeadingLevel: level}+ heading.SetIALAttr("id", id)+ heading.SetIALAttr("fold", "1")+ heading.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("Heading")})+ return heading+}++func writeFoldMoveTestTree(t *testing.T, rootID string, nodes ...*ast.Node) {+ t.Helper()+ tree, err := LoadTreeByBlockID(rootID)+ if nil != err {+ t.Fatalf("load folded heading move tree failed: %s", err)+ }+ for child := tree.Root.FirstChild; nil != child; {+ next := child.Next+ child.Unlink()+ child = next+ }+ for _, node := range nodes {+ tree.Root.AppendChild(node)+ }+ if _, err = filesys.WriteTree(tree); nil != err {+ t.Fatalf("write folded heading move tree failed: %s", err)+ }+ treenode.UpsertBlockTree(tree)+ sql.IndexTreeQueue(tree)+ sql.FlushQueue()+}++func assertFoldMoveState(t *testing.T, rootID string, wantIDs []string, headingID string, folded bool) {+ t.Helper()+ tree, err := LoadTreeByBlockID(rootID)+ if nil != err {+ t.Fatalf("load folded heading move state failed: %s", err)+ }+ var gotIDs []string+ for child := tree.Root.FirstChild; nil != child; child = child.Next {+ if child.IsBlock() && ast.NodeKramdownBlockIAL != child.Type {+ gotIDs = append(gotIDs, child.ID)+ }+ }+ if !slices.Equal(gotIDs, wantIDs) {+ t.Fatalf("unexpected top-level block order: got %v, want %v", gotIDs, wantIDs)+ }+ heading := treenode.GetNodeInTree(tree, headingID)+ if nil == heading || treenode.IsSelfFolded(heading) != folded {+ t.Fatalf("unexpected heading fold state: got %v, want %v", nil != heading && treenode.IsSelfFolded(heading), folded)+ }+}+func setupFoldTransactionDatabase(t *testing.T, fixture *fileOperationTestFixture) {t.Helper()Conf.Editor = conf.NewEditor()diff --git a/kernel/model/transaction_fold_test.go b/kernel/model/transaction_fold_test.goindex b92ee59789..34cd3ef447 100644--- a/kernel/model/transaction_fold_test.go+++ b/kernel/model/transaction_fold_test.go@@ -17,6 +17,7 @@package modelimport (+ "slices""testing""github.com/88250/lute/ast"@@ -24,6 +25,36 @@ import ("github.com/siyuan-note/siyuan/kernel/util")+func TestHeadingMoveChildrenByBlockIDs(t *testing.T) {+ document := &ast.Node{Type: ast.NodeDocument, ID: "document"}+ heading := &ast.Node{Type: ast.NodeHeading, ID: "heading", HeadingLevel: 2}+ headingIAL := &ast.Node{Type: ast.NodeKramdownBlockIAL}+ first := treenode.NewParagraph("20260819000300-first00")+ firstIAL := &ast.Node{Type: ast.NodeKramdownBlockIAL}+ second := treenode.NewParagraph("20260819000301-second0")+ secondIAL := &ast.Node{Type: ast.NodeKramdownBlockIAL}+ acquired := treenode.NewParagraph("20260819000302-acquire")+ for _, node := range []*ast.Node{heading, headingIAL, first, firstIAL, second, secondIAL, acquired} {+ document.AppendChild(node)+ }++ children, ok := headingMoveChildrenByBlockIDs(heading, []string{first.ID, second.ID})+ if !ok {+ t.Fatal("expected the stored heading move group to resolve")+ }+ if want := []*ast.Node{first, firstIAL, second, secondIAL}; !slices.Equal(children, want) {+ t.Fatalf("unexpected heading move children: got %v, want %v", children, want)+ }++ children, ok = headingMoveChildrenByBlockIDs(heading, []string{})+ if !ok || 0 != len(children) || nil == children {+ t.Fatal("an explicit empty move group should move only the heading")+ }+ if _, ok = headingMoveChildrenByBlockIDs(heading, []string{second.ID}); ok {+ t.Fatal("a stored move group must be a prefix of the current heading children")+ }+}+func TestMovingFoldHeadingIntoDescendantContainer(t *testing.T) {headingChild := &ast.Node{Type: ast.NodeSuperBlock, ID: "heading-child"}container := &ast.Node{Type: ast.NodeSuperBlock, ID: "container"}diff --git a/kernel/model/undolog.go b/kernel/model/undolog.goindex 7364d5ae47..e9bf658ece 100644--- a/kernel/model/undolog.go+++ b/kernel/model/undolog.go@@ -353,16 +353,22 @@ func removeEntryByID(stack []*UndoEntry, id string) []*UndoEntry {return stack}-// cloneOperations 深拷贝操作切片(值拷贝每个 Operation),使日志条目与后续事务解耦。-// performTx 的 doInsert0 等会原地改写 operation.ID/Action 等标量字段,若浅拷贝指针会导致-// 已记录的条目被改写、redo 重放时 ID 失效。值拷贝复制标量字段,Data(any) 共享引用(performTx 不改其内容)。+// cloneOperations 复制操作及重放期间可能改写的引用字段,使日志条目与后续事务解耦。+// Data(any) 共享引用,事务执行只会替换 Data 本身,不会修改其内部内容。func cloneOperations(ops []*Operation) []*Operation {if nil == ops {return nil}ret := make([]*Operation, len(ops))for i, op := range ops {- cloned := *op // 值拷贝标量字段(ID/Action/ParentID/PreviousID/NextID/AvID 等)+ cloned := *op+ cloned.BlockIDs = cloneOperationBlockIDs(op.BlockIDs)+ if nil != op.Context {+ cloned.Context = make(map[string]any, len(op.Context))+ for key, value := range op.Context {+ cloned.Context[key] = value+ }+ }ret[i] = &cloned}return ret@@ -461,7 +467,7 @@ func existingReplayBlockIDs(insertIndexes, deleteIndexes map[string]int) map[str// ResolveReplayDuplicateIds 在 undo/redo 重放事务前解决块 ID 冲突。// 场景:剪切块 X 后粘贴到别处(保留原 ID),再撤销剪切会 insert X,而 X 已存在于粘贴处,产生重复 ID。// 这里检查实际重放的 insert 操作;若其引入的 ID 在块树中已存在,且不会被前置 delete 清理,-// 则在当前重放操作的 ID、ParentID、PreviousID、NextID 与 Data 内联 ID 中统一替换为新 ID。+// 则在当前重放操作的 ID、ParentID、PreviousID、NextID、BlockIDs 与 Data 内联 ID 中统一替换为新 ID。func ResolveReplayDuplicateIds(tx *Transaction) {if nil == tx || !tx.isReplay {return@@ -509,6 +515,11 @@ func ResolveReplayDuplicateIds(tx *Transaction) {if newID, ok := replacements[op.NextID]; ok {op.NextID = newID}+ for i, blockID := range op.BlockIDs {+ if newID, ok := replacements[blockID]; ok {+ op.BlockIDs[i] = newID+ }+ }data, ok := op.Data.(string)if !ok {continuediff --git a/kernel/model/undolog_test.go b/kernel/model/undolog_test.goindex 720be7d415..3e7be26c99 100644--- a/kernel/model/undolog_test.go+++ b/kernel/model/undolog_test.go@@ -47,6 +47,25 @@ func TestReplaceReplayOperationID(t *testing.T) {}}+func TestCloneOperationsCopiesMoveMetadata(t *testing.T) {+ original := &Operation{+ Action: "move",+ ID: "heading",+ BlockIDs: []string{"child"},+ Context: map[string]any{moveGroupIDContextKey: "group"},+ }+ cloned := cloneOperations([]*Operation{original})[0]+ cloned.BlockIDs[0] = "changed"+ cloned.Context[moveGroupIDContextKey] = "changed"++ if "child" != original.BlockIDs[0] {+ t.Fatal("cloning operations should isolate move block IDs")+ }+ if "group" != original.Context[moveGroupIDContextKey] {+ t.Fatal("cloning operations should isolate move context")+ }+}+func TestReplayOperationBlockIndexes(t *testing.T) {containerID := "20260803120000-contain"childID := "20260803120001-childid"