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: Restore the source selection when canceling new mind map nodes https://github.com/siyuan-note/siyuan/issues/21016
Daniele480eac64af6
diff --git a/app/src/protyle/render/listMindmap/focus.test.ts b/app/src/protyle/render/listMindmap/focus.test.tsindex b870897271..abaf686137 100644--- a/app/src/protyle/render/listMindmap/focus.test.ts+++ b/app/src/protyle/render/listMindmap/focus.test.ts@@ -9,8 +9,8 @@ const source = createSourceFile("index.ts", readFileSync("src/protyle/render/lisconst controller = source.statements.find(item => isClassDeclaration(item) && item.name?.text === "ListMindmapController");assert.ok(controller && isClassDeclaration(controller));const methods = controller.members.filter(item => item.name &&- ["add", "change", "undo", "focusNode", "edit", "refreshUndoState", "bindUndoState"].includes(item.name.getText(source)));-assert.equal(methods.length, 7);+ ["add", "deleteNode", "change", "undo", "focusNode", "edit", "refreshUndoState", "bindUndoState"].includes(item.name.getText(source)));+assert.equal(methods.length, 8);let editorUndo = "";const visit = (item: import("typescript").Node) => {if (isPropertyAssignment(item) && item.name.getText(source) === "onUndo" &&@@ -63,12 +63,13 @@ test("canvas history follows embedded source documents, local stacks, busy statetest("explicit mind map additions stay selected while clipboard additions still open the editor", async () => {const steps: string[] = [];- const item = {dataset: {nodeId: "new"}, classList: {replace: () => {}}};+ const item = {dataset: {nodeId: "new"}, classList: {replace: () => {}}, outerHTML: "new node"};const clipboard = {textPlain: "Pasted content"};const context: any = {canEdit: () => true,genListItemElement: () => item,addListMindmapNode: () => true,+ cleanListMindmapHTML: (html: string) => html,};runInNewContext(compiled, context);const target = new context.Controller();@@ -103,6 +104,60 @@ test("explicit mind map additions stay selected while clipboard additions stillassert.deepEqual(steps, [], "failed additions neither move focus nor open the editor");});+test("canceling new nodes restores their origin without overriding changed content, failed deletes or newer selection", async () => {+ for (const scenario of ["new", "changed", "replaced", "missing origin", "ordinary", "failed", "newer selection"]) {+ const original = {outerHTML: "new node"};+ const element = scenario === "replaced" ? {...original} : original;+ if (scenario === "changed") {+ element.outerHTML = "changed content";+ }+ const nodes = new Map([["new", {element}], ["origin", {}], ["other", {}]]);+ if (scenario === "missing origin") {+ nodes.delete("origin");+ }+ let selected: string = "new";+ let focusID: string;+ const origins = new WeakMap();+ if (scenario !== "ordinary") {+ origins.set(original, {id: "origin", html: "new node"});+ }+ const context: any = {cleanListMindmapHTML: (html: string) => html,+ deleteListMindmapNode: (_list: unknown, id: string) => scenario !== "failed" && nodes.delete(id)};+ runInNewContext(compiled, context);+ const target = Object.assign(new context.Controller(), {+ list: {contains: (node: unknown) => node === element}, model: {nodes}, newNodeOrigins: origins,+ view: {getSelectedId: () => selected, focusNode: (id: string) => { selected = id; }},+ change: async (action: () => boolean, _editing: boolean, nextID: string) => {+ focusID = nextID;+ const changed = action();+ if (changed) {+ selected = scenario === "newer selection" ? "other" : undefined;+ }+ return changed;+ },+ });+ assert.equal(await target.deleteNode("new"), scenario !== "failed", scenario);+ const special = ["new", "failed", "newer selection"].includes(scenario);+ assert.equal(focusID, special ? "origin" : undefined, `${scenario}: transaction uses the same destination`);+ assert.equal(selected, scenario === "new" ? "origin" : scenario === "failed" ? "new" :+ scenario === "newer selection" ? "other" : undefined, `${scenario}: focus follows the current interaction`);+ assert.equal(origins.has(element), scenario === "failed", `${scenario}: successful deletion clears creation state`);+ }+});++test("entering a new node editor permanently cancels its creation-origin shortcut", async () => {+ const element = {};+ const origins = new WeakMap([[element, {id: "origin", html: "new node"}]]);+ const context: any = {roots: new WeakMap(), canEdit: () => true, openListMindmapEditor: () => ({})};+ runInNewContext(compiled, context);+ const target = Object.assign(new context.Controller(), {+ owner: {}, list: {closest: (): null => null}, model: {nodes: new Map([["new", {element}]])},+ newNodeOrigins: origins, view: {setEditing: () => {}}, editRequest: 0,+ });+ await target.edit("new", {isConnected: true});+ assert.equal(origins.has(element), false, "even an editor closed without text changes counts as entering editing");+});+test("canvas undo and redo preserve the viewport throughout replay and release it on errors", async () => {const editor = {isConnected: true};let fail = false;diff --git a/app/src/protyle/render/listMindmap/index.ts b/app/src/protyle/render/listMindmap/index.tsindex 2b379a249e..1b746f1722 100644--- a/app/src/protyle/render/listMindmap/index.ts+++ b/app/src/protyle/render/listMindmap/index.ts@@ -177,6 +177,7 @@ class ListMindmapController {private model: ListMindmapModel;private snapshot = "";private activeEditor?: ReturnType<typeof openListMindmapEditor>;+ private newNodeOrigins?: WeakMap<HTMLElement, {id: string; html: string}>;private editRequest = 0;private disposed = false;private taskChanges: Promise<void> = Promise.resolve();@@ -489,7 +490,7 @@ class ListMindmapController {}),onMove: (id, target, placement) => this.change(() => moveListMindmapNode(list, id, target, placement)),onAdd: (id, kind) => this.add(id, kind),- onDelete: id => this.change(() => deleteListMindmapNode(list, id)),+ onDelete: id => this.deleteNode(id),onFold: id => this.change(() => {const node = this.model.nodes.get(id);if (node?.element && !node.virtual) {@@ -886,9 +887,31 @@ class ListMindmapController {if (content) {await this.edit(item.dataset.nodeId, content, undefined, clipboard);}+ } else {+ // 仅在当前源节点未编辑、未被回放替换时,记住取消新建应返回的位置。+ this.newNodeOrigins ||= new WeakMap();+ this.newNodeOrigins.set(item, {id, html: cleanListMindmapHTML(item.outerHTML)});}}+ private async deleteNode(id: string) {+ const element = this.model.nodes.get(id)?.element;+ const origin = element && this.list.contains(element) && this.newNodeOrigins?.get(element);+ const sourceID = origin && this.view.getSelectedId() === id && this.model.nodes.has(origin.id) &&+ cleanListMindmapHTML(element.outerHTML) === origin.html ? origin.id : undefined;+ const deleted = await this.change(() => deleteListMindmapNode(this.list, id), false, sourceID);+ if (deleted) {+ if (element) {+ this.newNodeOrigins?.delete(element);+ }+ if (sourceID && this.model.nodes.has(sourceID) && !this.model.nodes.has(id) &&+ (!this.view.getSelectedId() || this.view.getSelectedId() === id)) {+ this.view.focusNode(sourceID);+ }+ }+ return deleted;+ }+private async listInput(id: string, input: ListMindmapListInput, selection?: Record<string, string>) {const request = this.editRequest;const rootID = this.owner.block.rootID;@@ -950,6 +973,7 @@ class ListMindmapController {if (!node || node.virtual) {return;}+ this.newNodeOrigins?.delete(node.element);this.view.setEditing(id);const editor = openListMindmapEditor({owner: this.owner, node, host, replaceFirstParagraph, selection,diff --git a/app/src/protyle/render/listMindmap/model.test.ts b/app/src/protyle/render/listMindmap/model.test.tsindex 38a2be12af..f479cab8c3 100644--- a/app/src/protyle/render/listMindmap/model.test.ts+++ b/app/src/protyle/render/listMindmap/model.test.ts@@ -361,7 +361,7 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,for (const mobile of [false, true]) {const root = document.createElement("div");root.className = "protyle-wysiwyg";- root.innerHTML = lute.Md2BlockDOM("- Original\n - Folded child\n");+ root.innerHTML = lute.Md2BlockDOM("- Original\n - Folded child\n- Following\n");const original = root.firstElementChild as HTMLElement;api.retagMindmapBranch(original, true);original.firstElementChild.setAttribute("fold", "1");@@ -440,6 +440,7 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,copies.forEach(copy => controllers.push(new embedded.ListMindmapController(owner, copy)));const target = controllers[0];const itemID = copies[0].firstElementChild.getAttribute("data-node-id");+ const followingID = target.model.root.children[1].id;await target.view.options.onNodeStyle(itemID, {backgroundColor: "#ff0000"});check.equal(api.readListMindmap(copies[1]).metadata.nodes[itemID].backgroundColor, "#ff0000");check.equal(operations[0].undoOperations[0].context.undoFocusEmbedId, "first");@@ -474,16 +475,31 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,target.host.dispatchEvent(new KeyboardEvent("keydown", {key: "Delete", bubbles: true, cancelable: true}));await new Promise(resolve => setTimeout(resolve, 0));check.equal(target.model.nodes.has(siblingID), false);+ check.equal(target.view.getSelectedId(), itemID, "canceling a new sibling returns to its creation source instead of the following sibling");+ check.equal(operations.at(-1).doOperations[0].context.undoFocusId, itemID,+ "redo of the deletion also returns to the creation source");check.equal(editorOptions, undefined, "deleting a newly selected node never opens an editor");check.equal(target.model.nodes.has(addedID), true, "deleting the sibling preserves the previously added child");- // Double-click remains available on explicitly created children.await target.view.options.onAdd(itemID, "child");- const childID = target.view.getSelectedId();- target.view.getContentHost(childID).dispatchEvent(new MouseEvent("dblclick", {bubbles: true, cancelable: true}));+ const canceledChildID = target.view.getSelectedId();+ target.host.dispatchEvent(new KeyboardEvent("keydown", {key: "Backspace", bubbles: true, cancelable: true}));await new Promise(resolve => setTimeout(resolve, 0));- check.ok(editorOptions, "double-click opens the newly selected child editor");- check.equal(editorOptions.node.id, childID);+ check.equal(target.model.nodes.has(canceledChildID), false);+ check.equal(target.view.getSelectedId(), itemID, "canceling a new child returns to the parent even when sibling children remain");+ check.equal(operations.at(-1).doOperations[0].context.undoFocusId, itemID);+ // Entering editing ends the cancellation shortcut, even without changing the text.+ await target.view.options.onAdd(itemID, "sibling");+ const editedID = target.view.getSelectedId();+ target.view.getContentHost(editedID).dispatchEvent(new MouseEvent("dblclick", {bubbles: true, cancelable: true}));+ await new Promise(resolve => setTimeout(resolve, 0));+ check.ok(editorOptions, "double-click opens the newly selected sibling editor");+ check.equal(editorOptions.node.id, editedID);check.equal(editorOptions.replaceFirstParagraph, undefined);+ await target.finish();+ target.host.dispatchEvent(new KeyboardEvent("keydown", {key: "Delete", bubbles: true, cancelable: true}));+ await new Promise(resolve => setTimeout(resolve, 0));+ check.equal(target.view.getSelectedId(), followingID, "after entering editing, deletion keeps the normal next-sibling policy");+ check.equal(operations.at(-1).doOperations[0].context.undoFocusId, followingID);controllers.forEach(controller => controller.destroy());root.remove();}