Skip to content

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

:bug: Prevent stale tab selection persistence after undo https://github.com/siyuan-note/siyuan/issues/19580

Daniel4cb81f902581
diff --git a/app/src/protyle/wysiwyg/tabs.ts b/app/src/protyle/wysiwyg/tabs.ts
index 0d8eee81d5..698c7dd27f 100644
--- a/app/src/protyle/wysiwyg/tabs.ts
+++ b/app/src/protyle/wysiwyg/tabs.ts
@@ -223,9 +223,16 @@ export const initEditorTabs = (protyle: IProtyle) => {
}
tabs.setAttribute("tabs-active-id", id);
if (!protyle.lite) {
- queueTransaction(protyle, () => fetchPost("/api/attr/setBlockAttrs", {
- id: tabs.dataset.nodeId, attrs: {"tabs-active-id": id},
- }));
+ queueTransaction(protyle, async () => {
+ // 撤销及移动会替换容器或移除占位页签,排队保存时只提交仍有效的当前选择。
+ if (!tabs.isConnected || tabs.getAttribute("tabs-active-id") !== id ||
+ !getTabItems(tabs).some(item => item.dataset.nodeId === id)) {
+ return;
+ }
+ await fetchPost("/api/attr/setBlockAttrs", {
+ id: tabs.dataset.nodeId, attrs: {"tabs-active-id": id},
+ });
+ });
}
},
rename: item => renameTab(protyle, item),
diff --git a/app/src/protyle/wysiwyg/tabsPersistence.test.ts b/app/src/protyle/wysiwyg/tabsPersistence.test.ts
new file mode 100644
index 0000000000..ccad24a950
--- /dev/null
+++ b/app/src/protyle/wysiwyg/tabsPersistence.test.ts
@@ -0,0 +1,74 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {createSourceFile, isPropertyAssignment, Node, ScriptTarget, transpileModule} from "typescript";
+
+const source = createSourceFile("tabs.ts", readFileSync("src/protyle/wysiwyg/tabs.ts", "utf8"), ScriptTarget.ES2021, true);
+let select: string;
+const visit = (node: Node) => {
+ if (isPropertyAssignment(node) && node.name.getText(source) === "select") {
+ select = node.initializer.getText(source);
+ }
+ node.forEachChild(visit);
+};
+visit(source);
+assert.ok(select);
+const compiled = transpileModule(`(${select})(tabs, id);`, {
+ compilerOptions: {target: ScriptTarget.ES2021},
+}).outputText;
+
+const fixture = () => {
+ let active = "original";
+ let ids = ["original", "placeholder"];
+ const requests: unknown[] = [];
+ const tasks: (() => Promise<void>)[] = [];
+ const tabs = {
+ isConnected: true,
+ dataset: {nodeId: "tabs"},
+ getAttribute: () => active,
+ setAttribute: (_name: string, value: string) => { active = value; },
+ };
+ const selectTab = (id: string) => runInNewContext(compiled, {
+ tabs, id, protyle: {}, canEdit: () => true,
+ getTabItems: () => ids.map(nodeId => ({dataset: {nodeId}})),
+ queueTransaction: (_protyle: unknown, task: () => Promise<void>) => tasks.push(task),
+ fetchPost: async (_url: string, request: unknown) => { requests.push(request); },
+ });
+ return {tabs, requests, selectTab,
+ removePlaceholder: () => { ids = ["original"]; },
+ flush: async () => { for (const task of tasks) { await task(); } },
+ };
+};
+
+test("tab persistence ignores a placeholder removed during undo", async () => {
+ const f = fixture();
+ f.selectTab("placeholder");
+ f.removePlaceholder();
+ await f.flush();
+ assert.equal(f.requests.length, 0);
+});
+
+test("tab persistence ignores a replaced container", async () => {
+ const f = fixture();
+ f.selectTab("placeholder");
+ f.tabs.isConnected = false;
+ await f.flush();
+ assert.equal(f.requests.length, 0);
+});
+
+test("tab persistence only saves the latest selection", async () => {
+ const f = fixture();
+ f.selectTab("placeholder");
+ f.selectTab("original");
+ await f.flush();
+ assert.equal(f.requests.length, 1);
+ assert.equal(JSON.stringify(f.requests[0]), JSON.stringify({id: "tabs", attrs: {"tabs-active-id": "original"}}));
+});
+
+test("tab persistence saves a selection that remains valid", async () => {
+ const f = fixture();
+ f.selectTab("placeholder");
+ await f.flush();
+ assert.equal(f.requests.length, 1);
+});
diff --git a/app/tests/tabsDrag.test.js b/app/tests/tabsDrag.test.js
new file mode 100644
index 0000000000..875aafd9d4
--- /dev/null
+++ b/app/tests/tabsDrag.test.js
@@ -0,0 +1,178 @@
+const assert = require("node:assert/strict");
+const {readFileSync, mkdtempSync, rmSync} = require("node:fs");
+const path = require("node:path");
+const os = require("node:os");
+
+const sources = () => {
+ const ts = require("typescript");
+ const extract = (file, names) => {
+ const source = ts.createSourceFile(file, readFileSync(path.join(__dirname, "../src", file), "utf8"),
+ ts.ScriptTarget.Latest, true);
+ const statements = source.statements.filter(statement => ts.isVariableStatement(statement) &&
+ statement.declarationList.declarations.some(declaration => names.includes(declaration.name.getText(source))));
+ assert.equal(statements.length, names.length);
+ return ts.transpileModule(statements.map(statement => statement.getText(source)).join("\n")
+ .replace(/export const /g, "const "), {
+ compilerOptions: {target: ts.ScriptTarget.ES2021},
+ }).outputText;
+ };
+ return [
+ extract("protyle/util/editorCommonEvent.ts", ["getDragSourceParentID", "moveTo"]),
+ extract("protyle/wysiwyg/getBlock.ts", ["getParentBlock", "getPreviousBlockSibling", "getTopAloneElement"]),
+ extract("protyle/render/tabsRender.ts", ["getTabItems", "getTabTask"]),
+ extract("protyle/wysiwyg/tabsRemoval.ts", ["repairActiveTab"]),
+ extract("protyle/render/tabsState.ts", ["adjacentTabID"]),
+ ts.transpileModule(readFileSync(path.join(__dirname, "../src/protyle/render/tabsDrag.ts"), "utf8")
+ .replace(/export const /g, "const "), {compilerOptions: {target: ts.ScriptTarget.ES2021}}).outputText,
+ ].join("\n");
+};
+
+const cases = async (source) => {
+ const check = require("node:assert/strict");
+ const lute = window.Lute.New();
+ lute.SetTabs(true);
+ lute.SetKramdownIAL(true);
+ lute.SetProtyleWYSIWYG(true);
+ const genEmptyElement = (_wbr, _start, id) => {
+ const template = document.createElement("template");
+ template.innerHTML = lute.Md2BlockDOM("\u200b");
+ const paragraph = template.content.firstElementChild;
+ paragraph.dataset.nodeId = id;
+ return paragraph;
+ };
+ const root = document.createElement("div");
+ root.className = "protyle-wysiwyg";
+ document.body.append(root);
+ root.innerHTML = lute.Md2BlockDOM("::: tabs\n@tab Title\n\nBody\n:::\n\nTarget");
+ const tabs = root.querySelector(".tabs");
+ tabs.setAttribute("tabs-position", "left");
+ const item = tabs.querySelector(".tab-item");
+ const constants = {ZWSP: "\u200b", SIYUAN_DROP_BLOCK: "application/siyuan-block", SIYUAN_DROP_GUTTER: "application/siyuan-gutter"};
+ const protyle = {lute, wysiwyg: {element: root}, notebookId: "notebook", block: {rootID: "doc"}};
+ window.siyuan = {config: {system: {workspaceDir: "workspace"}}};
+ const {moveTo, bindTabsDrag, isDraggingTabs} = new Function("Constants", "genEmptyElement", "root", "protyle",
+ source + "; return {moveTo, bindTabsDrag, isDraggingTabs};")(
+ constants, genEmptyElement, root, protyle);
+ const list = document.createElement("div");
+ const button = document.createElement("button");
+ button.className = "tabs-tab";
+ button.dataset.tabId = item.dataset.nodeId;
+ list.append(button);
+ tabs.prepend(list);
+ let readonly = false;
+ bindTabsDrag(list, {tabs, readonly: () => readonly, render: () => {}, move: () => {}});
+ const transfer = new DataTransfer();
+ button.dispatchEvent(new DragEvent("dragstart", {bubbles: true, cancelable: true, dataTransfer: transfer}));
+ check.equal(isDraggingTabs(root), true);
+ check.equal(window.siyuan.dragElement, undefined);
+ check.equal(transfer.getData(constants.SIYUAN_DROP_BLOCK), "");
+ check.equal(transfer.types.some(value => value.startsWith(constants.SIYUAN_DROP_GUTTER)), false);
+ check.equal(transfer.getData("application/x-siyuan-tab"), item.dataset.nodeId);
+ button.dispatchEvent(new DragEvent("dragend", {bubbles: true}));
+ check.equal(isDraggingTabs(root), false);
+ check.equal(window.siyuan.dragElement, undefined);
+ readonly = true;
+ const rejected = new DragEvent("dragstart", {bubbles: true, cancelable: true, dataTransfer: new DataTransfer()});
+ button.dispatchEvent(rejected);
+ check.equal(rejected.defaultPrevented, true);
+ check.equal(isDraggingTabs(root), false);
+ readonly = false;
+ protyle.lite = true;
+ const liteTransfer = new DataTransfer();
+ button.dispatchEvent(new DragEvent("dragstart", {bubbles: true, cancelable: true, dataTransfer: liteTransfer}));
+ check.equal(liteTransfer.getData(constants.SIYUAN_DROP_BLOCK), "");
+ check.equal(window.siyuan.dragElement, undefined);
+ button.dispatchEvent(new DragEvent("dragend", {bubbles: true}));
+ protyle.lite = false;
+ list.remove();
+ const originalID = item.dataset.nodeId;
+ const originalHTML = root.innerHTML;
+ const result = await moveTo(protyle,
+ [item], root.lastElementChild, true, "afterend", false);
+ const stored = document.createElement("div");
+ stored.innerHTML = originalHTML;
+ const find = id => id === "doc" ? stored : stored.querySelector(`[data-node-id="${id}"]`);
+ const replay = operations => operations.forEach(operation => {
+ const node = find(operation.id);
+ if (operation.action === "setAttrs") {
+ const attrs = JSON.parse(operation.data);
+ if (attrs["tabs-active-id"]) {
+ check.ok(Array.from(node.children).some(child => child.dataset.nodeId === attrs["tabs-active-id"]),
+ JSON.stringify(operation));
+ }
+ Object.entries(attrs).forEach(([name, value]) => node.setAttribute(name, value));
+ } else if (operation.action === "delete") {
+ node?.remove();
+ } else if (operation.action === "update") {
+ node.outerHTML = lute.SpinBlockDOM(operation.data);
+ } else {
+ let moving = node;
+ if (operation.action === "insert") {
+ const template = document.createElement("template");
+ template.innerHTML = lute.SpinBlockDOM(operation.data);
+ moving = template.content.firstElementChild;
+ }
+ if (operation.previousID) {
+ find(operation.previousID).after(moving);
+ } else {
+ find(operation.parentID).prepend(moving);
+ }
+ }
+ });
+ replay(result.doOperations);
+ replay(result.undoOperations);
+ check.equal(find(originalID).parentElement.dataset.nodeId, tabs.dataset.nodeId);
+ check.equal(find(tabs.dataset.nodeId).getAttribute("tabs-position"), "left");
+ replay(result.doOperations);
+ replay(result.undoOperations);
+ root.remove();
+ return "Tabs drag cases passed";
+};
+
+const run = async () => {
+ const {app, BrowserWindow} = require("electron");
+ app.setPath("userData", process.argv[2]);
+ app.commandLine.appendSwitch("disable-gpu");
+ await app.whenReady();
+ const win = new BrowserWindow({show: false, webPreferences: {
+ nodeIntegration: true, contextIsolation: false, offscreen: true,
+ }});
+ let code = 0;
+ try {
+ await win.loadURL("data:text/html,<html><body></body></html>");
+ await win.webContents.executeJavaScript(readFileSync(path.join(__dirname,
+ "../stage/protyle/js/lute/lute.min.js"), "utf8"));
+ const result = await win.webContents.executeJavaScript(`(async () => { try {
+ return await (${cases.toString()})(${JSON.stringify(sources())});
+ } catch (error) { return error.stack; } })()`);
+ assert.equal(result, "Tabs drag cases passed");
+ console.log(result);
+ } catch (error) {
+ console.error(error);
+ code = 1;
+ } finally {
+ win.destroy();
+ app.exit(code);
+ }
+};
+
+if (process.versions.electron && process.type === "browser") {
+ run().catch(error => { console.error(error); require("electron").app.exit(1); });
+} else {
+ require("node:test").test("tab drag transactions preserve valid active IDs through undo and redo", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 45000,
+ }, async () => {
+ const profile = mkdtempSync(path.join(os.tmpdir(), "siyuan-tabs-drag-test-"));
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ const {stdout} = await require("node:util").promisify(require("node:child_process").execFile)(
+ require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 40000});
+ assert.match(stdout, /Tabs drag cases passed/);
+ } finally {
+ assert.ok(path.resolve(profile).startsWith(path.resolve(os.tmpdir()) + path.sep));
+ rmSync(profile, {recursive: true, force: true});
+ }
+ });
+}
diff --git a/kernel/model/transaction_tabs_fts5_test.go b/kernel/model/transaction_tabs_fts5_test.go
new file mode 100644
index 0000000000..2b15a52a77
--- /dev/null
+++ b/kernel/model/transaction_tabs_fts5_test.go
@@ -0,0 +1,76 @@
+//go:build fts5
+
+package model
+
+import (
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestTabItemDragUndoRedo(t *testing.T) {
+ fixture := setupStructureTransactionTest(t)
+ setupFoldTransactionDatabase(t, fixture)
+ tree, err := LoadTreeByBlockID(fixture.sourceID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ lute := util.NewLute()
+ parsed := lute.BlockDOM2Tree(lute.Md2BlockDOM("::: tabs\n@tab Title\n\nBody\n:::\n", false))
+ tabs := parsed.Root.FirstChild
+ tabs.SetIALAttr("tabs-position", "left")
+ item := tabs.FirstChild
+ tree.Root.AppendChild(tabs)
+ if _, err = filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(tree)
+ newTabs := &ast.Node{Type: ast.NodeTabs, ID: ast.NewNodeID()}
+ newTabs.SetIALAttr("id", newTabs.ID)
+ placeholder := &ast.Node{Type: ast.NodeTabItem, ID: ast.NewNodeID()}
+ placeholder.SetIALAttr("id", placeholder.ID)
+ placeholder.AppendChild(treenode.NewParagraph(""))
+ newTabs.AppendChild(placeholder)
+ restorePlaceholder := &ast.Node{Type: ast.NodeTabItem, ID: ast.NewNodeID()}
+ restorePlaceholder.SetIALAttr("id", restorePlaceholder.ID)
+ restorePlaceholder.AppendChild(treenode.NewParagraph(""))
+ item.Unlink()
+ tabs.AppendChild(restorePlaceholder)
+ paragraph := treenode.NewParagraph(tabs.ID)
+ forward := []*Operation{
+ {Action: "insert", ID: newTabs.ID, ParentID: tree.ID, Data: lute.RenderNodeBlockDOM(newTabs)},
+ {Action: "move", ID: item.ID, ParentID: newTabs.ID},
+ {Action: "delete", ID: placeholder.ID},
+ {Action: "update", ID: tabs.ID, Data: lute.RenderNodeBlockDOM(paragraph)},
+ }
+ undo := []*Operation{
+ {Action: "update", ID: tabs.ID, Data: lute.RenderNodeBlockDOM(tabs)},
+ {Action: "move", ID: item.ID, ParentID: tabs.ID},
+ {Action: "delete", ID: newTabs.ID},
+ {Action: "setAttrs", ID: tabs.ID, Data: `{"tabs-active-id":"` + item.ID + `"}`},
+ {Action: "delete", ID: restorePlaceholder.ID},
+ }
+ for i, operations := range [][]*Operation{forward, undo, forward, undo} {
+ if err = PerformTxSync(&Transaction{DoOperations: cloneOperations(operations), isReplay: i > 0}); err != nil {
+ t.Fatalf("step %d: %v", i, err)
+ }
+ current, loadErr := LoadTreeByBlockID(item.ID)
+ if loadErr != nil {
+ t.Fatal(loadErr)
+ }
+ moved := treenode.GetNodeInTree(current, item.ID)
+ wantParent := newTabs.ID
+ if i%2 == 1 {
+ wantParent = tabs.ID
+ if moved.Parent.IALAttr("tabs-position") != "left" {
+ t.Fatal("undo lost the vertical orientation")
+ }
+ }
+ if moved.Parent.ID != wantParent || moved.Parent.IALAttr("tabs-active-id") != item.ID {
+ t.Fatalf("step %d: parent=%s active=%s", i, moved.Parent.ID, moved.Parent.IALAttr("tabs-active-id"))
+ }
+ }
+}