Skip to content

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

:bug: Preserve folded headings when cancelling super blocks https://github.com/siyuan-note/siyuan/issues/18804

Danielfe77004ddd54
diff --git a/app/src/block/cancelSuperBlock.test.ts b/app/src/block/cancelSuperBlock.test.ts
new file mode 100644
index 0000000000..e846f82ec5
--- /dev/null
+++ b/app/src/block/cancelSuperBlock.test.ts
@@ -0,0 +1,80 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {buildCancelSuperBlockOperations} from "./cancelSuperBlock";
+
+describe("buildCancelSuperBlockOperations", () => {
+ it("moves every direct child with stable forward and undo anchors", () => {
+ const result = buildCancelSuperBlockOperations({
+ id: "super-block",
+ data: "<div></div>",
+ childIDs: ["heading", "paragraph"],
+ foldedHeadingIDs: [],
+ previousID: "before",
+ parentID: "document",
+ });
+
+ assert.deepEqual(result.doOperations, [{
+ action: "move",
+ id: "heading",
+ previousID: "before",
+ parentID: "document",
+ }, {
+ action: "move",
+ id: "paragraph",
+ previousID: "heading",
+ parentID: "document",
+ }, {
+ action: "delete",
+ id: "super-block",
+ }]);
+ assert.deepEqual(result.undoOperations, [{
+ action: "insert",
+ id: "super-block",
+ data: "<div></div>",
+ previousID: "before",
+ parentID: "document",
+ }, {
+ action: "move",
+ id: "heading",
+ previousID: undefined,
+ parentID: "super-block",
+ }, {
+ action: "move",
+ id: "paragraph",
+ previousID: "heading",
+ parentID: "super-block",
+ }]);
+ });
+
+ it("temporarily unfolds direct headings and restores nested folds from inside out", () => {
+ const result = buildCancelSuperBlockOperations({
+ id: "super-block",
+ data: "<div></div>",
+ childIDs: ["heading-1", "heading-2", "paragraph"],
+ foldedHeadingIDs: ["heading-1", "heading-2"],
+ parentID: "document",
+ });
+
+ assert.deepEqual(result.doOperations.map(operation => `${operation.action}:${operation.id}`), [
+ "unfoldHeading:heading-1",
+ "unfoldHeading:heading-2",
+ "move:heading-1",
+ "move:heading-2",
+ "move:paragraph",
+ "delete:super-block",
+ "foldHeading:heading-2",
+ "foldHeading:heading-1",
+ ]);
+ assert.deepEqual(result.undoOperations.map(operation => `${operation.action}:${operation.id}`), [
+ "unfoldHeading:heading-1",
+ "unfoldHeading:heading-2",
+ "insert:super-block",
+ "move:heading-1",
+ "move:heading-2",
+ "move:paragraph",
+ "foldHeading:heading-2",
+ "foldHeading:heading-1",
+ ]);
+ assert.equal(result.undoOperations.some(operation => operation.id === "outside"), false);
+ });
+});
diff --git a/app/src/block/cancelSuperBlock.ts b/app/src/block/cancelSuperBlock.ts
new file mode 100644
index 0000000000..a5d76c4708
--- /dev/null
+++ b/app/src/block/cancelSuperBlock.ts
@@ -0,0 +1,49 @@
+type TCancelSuperBlockOperationOptions = {
+ id: string,
+ data: string,
+ childIDs: string[],
+ foldedHeadingIDs: string[],
+ previousID?: string,
+ parentID?: string,
+};
+
+const genFoldOperations = (headingIDs: string[], action: "foldHeading" | "unfoldHeading") => {
+ return headingIDs.map(id => ({action, id}) as IOperation);
+};
+
+const genMoveOperations = (childIDs: string[], previousID: string | undefined, parentID: string | undefined) => {
+ return childIDs.map(id => {
+ const operation: IOperation = {
+ action: "move",
+ id,
+ previousID,
+ parentID,
+ };
+ previousID = id;
+ return operation;
+ });
+};
+
+export const buildCancelSuperBlockOperations = (options: TCancelSuperBlockOperationOptions) => {
+ const foldedHeadingIDs = options.foldedHeadingIDs;
+ const reversedFoldedHeadingIDs = [...foldedHeadingIDs].reverse();
+ const doOperations = [
+ ...genFoldOperations(foldedHeadingIDs, "unfoldHeading"),
+ ...genMoveOperations(options.childIDs, options.previousID, options.parentID),
+ {action: "delete", id: options.id} as IOperation,
+ ...genFoldOperations(reversedFoldedHeadingIDs, "foldHeading"),
+ ];
+ const undoOperations = [
+ ...genFoldOperations(foldedHeadingIDs, "unfoldHeading"),
+ {
+ action: "insert",
+ id: options.id,
+ data: options.data,
+ previousID: options.previousID,
+ parentID: options.parentID,
+ } as IOperation,
+ ...genMoveOperations(options.childIDs, undefined, options.id),
+ ...genFoldOperations(reversedFoldedHeadingIDs, "foldHeading"),
+ ];
+ return {doOperations, undoOperations};
+};
diff --git a/app/src/block/util.ts b/app/src/block/util.ts
index 46c03d18da..d3de9b557f 100644
--- a/app/src/block/util.ts
+++ b/app/src/block/util.ts
@@ -17,15 +17,31 @@ import {fetchPost, fetchSyncPost} from "../util/fetch";
import {openFileById} from "../editor/util";
import {openMobileFileById} from "../mobile/editor";
import {mathRender} from "../protyle/render/mathRender";
+import {buildCancelSuperBlockOperations} from "./cancelSuperBlock";
export const cancelSB = async (protyle: IProtyle, nodeElement: Element, range?: Range) => {
- const doOperations: IOperation[] = [];
- const undoOperations: IOperation[] = [];
let previousId = getPreviousBlockSibling(nodeElement)?.getAttribute("data-node-id");
nodeElement.classList.remove("protyle-wysiwyg--select");
nodeElement.removeAttribute("select-start");
nodeElement.removeAttribute("select-end");
const id = nodeElement.getAttribute("data-node-id");
+ const visibleChildElements = Array.from(nodeElement.children).filter(item => item.hasAttribute("data-node-id"));
+ let operationChildElements = visibleChildElements;
+ if (visibleChildElements.some(item => item.getAttribute("data-type") === "NodeHeading" &&
+ item.getAttribute("fold") === "1")) {
+ const response = await fetchSyncPost("/api/block/getBlockDOM", {
+ id,
+ notebook: protyle.notebookId,
+ });
+ const template = document.createElement("template");
+ template.innerHTML = response.data?.dom || "";
+ const fullSuperBlockElement = template.content.querySelector(`[data-node-id="${id}"]`);
+ if (!fullSuperBlockElement) {
+ return {doOperations: [], undoOperations: [], previousId};
+ }
+ operationChildElements = Array.from(fullSuperBlockElement.children).filter(item =>
+ item.hasAttribute("data-node-id"));
+ }
// 先清理拖拽手柄,避免手柄被克隆进撤销用的 SB 副本,导致恢复后残留多余手柄
nodeElement.querySelectorAll(".sb__resize").forEach(handle => handle.remove());
const sbElement = nodeElement.cloneNode() as HTMLElement;
@@ -44,46 +60,28 @@ export const cancelSB = async (protyle: IProtyle, nodeElement: Element, range?:
parentID = protyle.block.rootID;
}
}
- undoOperations.push({
- action: "insert",
+ const operationData = buildCancelSuperBlockOperations({
id,
data: sbElement.outerHTML,
+ childIDs: operationChildElements.map(item => item.getAttribute("data-node-id")),
+ foldedHeadingIDs: operationChildElements.filter(item =>
+ item.getAttribute("data-type") === "NodeHeading" && item.getAttribute("fold") === "1"
+ ).map(item => item.getAttribute("data-node-id")),
previousID: previousId,
parentID,
});
- Array.from(nodeElement.children).forEach((item, index) => {
- if (index === nodeElement.childElementCount - 1) {
- doOperations.push({
- action: "delete",
- id,
- });
- if (range) {
- getContenteditableElement(nodeElement)?.insertAdjacentHTML("afterbegin", "<wbr>");
- }
- nodeElement.lastElementChild.remove();
- nodeElement.replaceWith(...nodeElement.children);
- if (range) {
- focusByWbr(protyle.wysiwyg.element, range);
- }
- return;
- }
- doOperations.push({
- action: "move",
- id: item.getAttribute("data-node-id"),
- previousID: previousId,
- parentID,
- });
- undoOperations.push({
- action: "move",
- id: item.getAttribute("data-node-id"),
- previousID: getPreviousBlockSibling(item)?.getAttribute("data-node-id"),
- parentID: id
- });
- previousId = item.getAttribute("data-node-id");
- });
+ const focusId = visibleChildElements[visibleChildElements.length - 1]?.getAttribute("data-node-id") || previousId;
+ if (range) {
+ getContenteditableElement(nodeElement)?.insertAdjacentHTML("afterbegin", "<wbr>");
+ }
+ nodeElement.lastElementChild.remove();
+ nodeElement.replaceWith(...nodeElement.children);
+ if (range) {
+ focusByWbr(protyle.wysiwyg.element, range);
+ }
mathRender(protyle.wysiwyg.element);
// 超级块内嵌入块无面包屑,需重新渲染 https://github.com/siyuan-note/siyuan/issues/7574
- doOperations.forEach(item => {
+ operationData.doOperations.forEach(item => {
const element = protyle.wysiwyg.element.querySelector(`[data-node-id="${item.id}"]`);
if (element && element.getAttribute("data-type") === "NodeBlockQueryEmbed") {
element.removeAttribute("data-render");
@@ -91,7 +89,8 @@ export const cancelSB = async (protyle: IProtyle, nodeElement: Element, range?:
}
});
return {
- doOperations, undoOperations, previousId
+ ...operationData,
+ previousId: focusId
};
};
diff --git a/kernel/model/transaction_fold_fts5_test.go b/kernel/model/transaction_fold_fts5_test.go
new file mode 100644
index 0000000000..a7623a67a2
--- /dev/null
+++ b/kernel/model/transaction_fold_fts5_test.go
@@ -0,0 +1,212 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+//go:build fts5
+
+package model
+
+import (
+ "os"
+ "path/filepath"
+ "slices"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestCancelFoldedHeadingSuperBlockKeepsUndoBoundary(t *testing.T) {
+ const (
+ superBlockID = "20260817000000-sblock1"
+ headingID = "20260817000001-heading"
+ paragraphID = "20260817000002-para001"
+ outsideID = "20260817000003-outside"
+ )
+ fixture := setupStructureTransactionTest(t)
+ setupFoldTransactionDatabase(t, fixture)
+ tree, err := LoadTreeByBlockID(fixture.sourceID)
+ if nil != err {
+ t.Fatalf("load test tree failed: %s", err)
+ }
+ for child := tree.Root.FirstChild; nil != child; {
+ next := child.Next
+ child.Unlink()
+ child = next
+ }
+
+ superBlock := &ast.Node{Type: ast.NodeSuperBlock, ID: superBlockID}
+ superBlock.SetIALAttr("id", superBlockID)
+ superBlock.AppendChild(&ast.Node{Type: ast.NodeSuperBlockOpenMarker, Tokens: []byte("{{{")})
+ superBlock.AppendChild(&ast.Node{Type: ast.NodeSuperBlockLayoutMarker, Tokens: []byte("row")})
+ heading := &ast.Node{Type: ast.NodeHeading, ID: headingID, HeadingLevel: 1}
+ heading.SetIALAttr("id", headingID)
+ heading.SetIALAttr("fold", "1")
+ heading.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("Heading")})
+ paragraph := treenode.NewParagraph(paragraphID)
+ paragraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("Paragraph")})
+ superBlock.AppendChild(heading)
+ superBlock.AppendChild(paragraph)
+ superBlock.AppendChild(&ast.Node{Type: ast.NodeSuperBlockCloseMarker, Tokens: []byte("}}}")})
+ outside := treenode.NewParagraph(outsideID)
+ outside.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("Outside")})
+ tree.Root.AppendChild(superBlock)
+ tree.Root.AppendChild(outside)
+ if _, err = filesys.WriteTree(tree); nil != err {
+ t.Fatalf("write test tree failed: %s", err)
+ }
+ treenode.UpsertBlockTree(tree)
+
+ doOperations := []*Operation{
+ {Action: "unfoldHeading", ID: headingID},
+ {Action: "move", ID: headingID, ParentID: fixture.sourceID},
+ {Action: "move", ID: paragraphID, PreviousID: headingID, ParentID: fixture.sourceID},
+ {Action: "delete", ID: superBlockID},
+ {Action: "foldHeading", ID: headingID},
+ }
+ undoOperations := []*Operation{
+ {Action: "unfoldHeading", ID: headingID},
+ {
+ Action: "insert",
+ ID: superBlockID,
+ Data: `<div data-node-id="` + superBlockID + `" data-type="NodeSuperBlock" class="sb" ` +
+ `data-sb-layout="row"><div class="protyle-attr" contenteditable="false"></div></div>`,
+ ParentID: fixture.sourceID,
+ },
+ {Action: "move", ID: headingID, ParentID: superBlockID},
+ {Action: "move", ID: paragraphID, PreviousID: headingID, ParentID: superBlockID},
+ {Action: "foldHeading", ID: headingID},
+ }
+
+ if err = PerformTxSync(&Transaction{DoOperations: doOperations}); nil != err {
+ t.Fatalf("cancel folded heading super block failed: %s", err)
+ }
+ assertCancelledFoldedSuperBlock(t, fixture.sourceID, superBlockID, headingID, paragraphID, outsideID)
+
+ if err = PerformTxSync(&Transaction{DoOperations: undoOperations}); nil != err {
+ t.Fatalf("undo folded heading super block cancellation failed: %s", err)
+ }
+ assertRestoredFoldedSuperBlock(t, fixture.sourceID, superBlockID, headingID, paragraphID, outsideID)
+
+ if err = PerformTxSync(&Transaction{DoOperations: doOperations}); nil != err {
+ t.Fatalf("redo folded heading super block cancellation failed: %s", err)
+ }
+ assertCancelledFoldedSuperBlock(t, fixture.sourceID, superBlockID, headingID, paragraphID, outsideID)
+}
+
+func setupFoldTransactionDatabase(t *testing.T, fixture *fileOperationTestFixture) {
+ t.Helper()
+ Conf.Editor = conf.NewEditor()
+ Conf.Export = conf.NewExport()
+ originalTempDir := util.TempDir
+ originalQueueDir := util.QueueDir
+ originalConfDir := util.ConfDir
+ originalDBPath := util.DBPath
+ originalHistoryDBPath := util.HistoryDBPath
+ originalAssetContentDBPath := util.AssetContentDBPath
+ util.TempDir = t.TempDir()
+ util.QueueDir = filepath.Join(util.TempDir, "queue")
+ util.ConfDir = filepath.Join(util.TempDir, "conf")
+ util.DBPath = filepath.Join(util.TempDir, util.DBName)
+ util.HistoryDBPath = filepath.Join(util.TempDir, "history.db")
+ util.AssetContentDBPath = filepath.Join(util.TempDir, "asset_content.db")
+ for _, dir := range []string{util.QueueDir, util.ConfDir} {
+ if err := os.MkdirAll(dir, 0755); nil != err {
+ t.Fatalf("create test directory [%s] failed: %v", dir, err)
+ }
+ }
+ sql.InitDatabase(true)
+ sql.InitHistoryDatabase(true)
+ sql.InitAssetContentDatabase(true)
+ for _, path := range []string{fixture.sourcePath, fixture.targetPath} {
+ tree, err := filesys.LoadTree(fixture.box.ID, path, util.NewLute())
+ if nil != err {
+ t.Fatalf("reload fixture document [%s] failed: %v", path, err)
+ }
+ treenode.UpsertBlockTree(tree)
+ }
+ t.Cleanup(func() {
+ sql.CloseDatabase()
+ util.TempDir = originalTempDir
+ util.QueueDir = originalQueueDir
+ util.ConfDir = originalConfDir
+ util.DBPath = originalDBPath
+ util.HistoryDBPath = originalHistoryDBPath
+ util.AssetContentDBPath = originalAssetContentDBPath
+ })
+}
+
+func assertCancelledFoldedSuperBlock(t *testing.T, rootID, superBlockID, headingID, paragraphID, outsideID string) {
+ t.Helper()
+ tree, err := LoadTreeByBlockID(rootID)
+ if nil != err {
+ t.Fatalf("load cancelled tree failed: %s", err)
+ }
+ if nil != treenode.GetNodeInTree(tree, superBlockID) {
+ t.Fatal("cancelled super block should be removed")
+ }
+ heading := treenode.GetNodeInTree(tree, headingID)
+ paragraph := treenode.GetNodeInTree(tree, paragraphID)
+ outside := treenode.GetNodeInTree(tree, outsideID)
+ if heading.Parent != tree.Root || paragraph.Parent != tree.Root || outside.Parent != tree.Root {
+ t.Fatal("cancelled super block children and outside block should remain at the document root")
+ }
+ if !treenode.IsSelfFolded(heading) {
+ t.Fatal("cancelled heading should preserve its folded state")
+ }
+ if ids := contentBlockIDs(treenode.HeadingChildren(heading)); !slices.Equal(ids, []string{paragraphID, outsideID}) {
+ t.Fatalf("cancelled heading should use its new document scope, got %v", ids)
+ }
+}
+
+func assertRestoredFoldedSuperBlock(t *testing.T, rootID, superBlockID, headingID, paragraphID, outsideID string) {
+ t.Helper()
+ tree, err := LoadTreeByBlockID(rootID)
+ if nil != err {
+ t.Fatalf("load restored tree failed: %s", err)
+ }
+ superBlock := treenode.GetNodeInTree(tree, superBlockID)
+ heading := treenode.GetNodeInTree(tree, headingID)
+ paragraph := treenode.GetNodeInTree(tree, paragraphID)
+ outside := treenode.GetNodeInTree(tree, outsideID)
+ if nil == superBlock || heading.Parent != superBlock || paragraph.Parent != superBlock {
+ t.Fatal("undo should restore the original super block children")
+ }
+ if outside.Parent != tree.Root {
+ t.Fatal("undo should keep the outside block out of the super block")
+ }
+ if nil == superBlock.ChildByType(ast.NodeSuperBlockCloseMarker) {
+ t.Fatal("undo should restore the super block close marker")
+ }
+ if !treenode.IsSelfFolded(heading) {
+ t.Fatal("undo should restore the heading fold")
+ }
+ if ids := contentBlockIDs(treenode.HeadingChildren(heading)); !slices.Equal(ids, []string{paragraphID}) {
+ t.Fatalf("restored heading should stop at the super block boundary, got %v", ids)
+ }
+}
+
+func contentBlockIDs(nodes []*ast.Node) (ret []string) {
+ for _, node := range nodes {
+ if node.IsBlock() && ast.NodeKramdownBlockIAL != node.Type {
+ ret = append(ret, node.ID)
+ }
+ }
+ return
+}
diff --git a/kernel/treenode/fold_heading_stack_test.go b/kernel/treenode/fold_heading_stack_test.go
index 05c25a7325..7ab7697b08 100644
--- a/kernel/treenode/fold_heading_stack_test.go
+++ b/kernel/treenode/fold_heading_stack_test.go
@@ -148,6 +148,26 @@ func TestHeadingSiblingsKeepContainerBoundary(t *testing.T) {
assertHeadingIDs(t, HeadingSiblings(containerHeading), "container-heading", "container-heading-next")
}
+func TestHeadingChildrenKeepSuperBlockBoundary(t *testing.T) {
+ superBlock := &ast.Node{Type: ast.NodeSuperBlock, ID: "super-block"}
+ heading := &ast.Node{Type: ast.NodeHeading, HeadingLevel: 1, ID: "heading"}
+ paragraph := &ast.Node{Type: ast.NodeParagraph, ID: "paragraph"}
+ closeMarker := &ast.Node{Type: ast.NodeSuperBlockCloseMarker}
+ superBlock.AppendChild(&ast.Node{Type: ast.NodeSuperBlockOpenMarker})
+ superBlock.AppendChild(&ast.Node{Type: ast.NodeSuperBlockLayoutMarker})
+ superBlock.AppendChild(heading)
+ superBlock.AppendChild(paragraph)
+ superBlock.AppendChild(closeMarker)
+
+ children := HeadingChildren(heading)
+ if 1 != len(children) || paragraph != children[0] {
+ t.Fatalf("heading children should stop before the super block close marker, got %d nodes", len(children))
+ }
+ if superBlock != closeMarker.Parent {
+ t.Fatal("heading child lookup should keep the close marker in the super block")
+ }
+}
+
func assertHeadingIDs(t *testing.T, headings []*ast.Node, expected ...string) {
t.Helper()
if len(headings) != len(expected) {
diff --git a/kernel/treenode/heading.go b/kernel/treenode/heading.go
index ee7d68ddee..dd5412e875 100644
--- a/kernel/treenode/heading.go
+++ b/kernel/treenode/heading.go
@@ -221,6 +221,9 @@ func HeadingChildren(heading *ast.Node) (ret []*ast.Node) {
currentLevel := heading.HeadingLevel
for n := start; nil != n; n = n.Next {
+ if ast.NodeSuperBlockCloseMarker == n.Type {
+ break
+ }
if ast.NodeHeading == n.Type {
if currentLevel >= n.HeadingLevel {
break