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 mind map selection after undo https://github.com/siyuan-note/siyuan/issues/19835
Danieldfa1a0a782d3
diff --git a/app/src/protyle/render/listMindmap/focus.test.ts b/app/src/protyle/render/listMindmap/focus.test.tsnew file mode 100644index 0000000000..2817c5a13d--- /dev/null+++ b/app/src/protyle/render/listMindmap/focus.test.ts@@ -0,0 +1,80 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {createSourceFile, isClassDeclaration, isPropertyAssignment, ScriptTarget, transpileModule} from "typescript";++const source = createSourceFile("index.ts", readFileSync("src/protyle/render/listMindmap/index.ts", "utf8"),+ ScriptTarget.ES2021, true);+const 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", "undo", "focusNode"].includes(item.name.getText(source)));+assert.equal(methods.length, 3);+let editorUndo = "";+const visit = (item: import("typescript").Node) => {+ if (isPropertyAssignment(item) && item.name.getText(source) === "onUndo" &&+ item.initializer.getText(source).includes("this.undo(redo, id)")) {+ editorUndo = item.initializer.getText(source);+ }+ item.forEachChild(visit);+};+visit(controller);+assert.ok(editorUndo);+const compiled = transpileModule(`class Controller {+ ${methods.map(item => item.getText(source)).join("\n")}+ makeEditorUndo(id) { return ${editorUndo}; }+}+globalThis.Controller = Controller;`, {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;++test("new mind map nodes become selected before editing", async () => {+ const steps: string[] = [];+ const item = {dataset: {nodeId: "new"}, classList: {replace: () => {}}};+ const context: any = {+ canEdit: () => true,+ genListItemElement: () => item,+ addListMindmapNode: () => true,+ };+ runInNewContext(compiled, context);+ const target = new context.Controller();+ Object.assign(target, {+ owner: {}, list: {dataset: {type: "NodeMindmap"}, children: []},+ model: {nodes: new Map([["root", {id: "root"}]])},+ change: async (action: () => unknown) => action(),+ view: {focusNode: (id: string) => steps.push(`focus:${id}`),+ getContentHost: () => ({}),+ },+ edit: async (id: string) => { steps.push(`edit:${id}`); },+ });+ await target.add("root", "child");+ assert.deepEqual(steps, ["focus:new", "edit:new"]);+});++test("undo from a node editor restores that node or its previous sibling", async () => {+ const root = {id: "root", children: [{id: "existing"}, {id: "new"}]};+ const nodes = new Map<string, {id: string, parentId?: string, children?: {id: string}[]}>([+ ["root", root], ["existing", {id: "existing", parentId: "root"}],+ ["new", {id: "new", parentId: "root"}],+ ]);+ const selected: string[] = [];+ let removeNew = false;+ const owner = {undo: {undo: async () => {+ if (removeNew) {+ nodes.delete("new");+ }+ }}};+ const roots = new WeakMap();+ const context: any = {canEdit: () => true, roots};+ runInNewContext(compiled, context);+ const target = new context.Controller();+ Object.assign(target, {+ owner, list: {dataset: {nodeId: "map"}}, model: {nodes, root},+ view: {getSelectedId: () => "root", focusNode: (id: string) => selected.push(id)},+ });+ roots.set(owner, {restoreFocus: (_listID: string, ids: string[]) => target.focusNode(ids)});+ const onEditorUndo = target.makeEditorUndo("new");+ await onEditorUndo(false);+ assert.equal(selected.pop(), "new", "undoing node text keeps focus on the edited node");+ removeNew = true;+ await onEditorUndo(false);+ assert.equal(selected.pop(), "existing", "undoing node insertion focuses the previous sibling");+});diff --git a/app/src/protyle/render/listMindmap/index.ts b/app/src/protyle/render/listMindmap/index.tsindex 4eb867eab6..69cfb0bda9 100644--- a/app/src/protyle/render/listMindmap/index.ts+++ b/app/src/protyle/render/listMindmap/index.ts@@ -40,7 +40,7 @@ import {getListMindmapFoldStates} from "./fold";import {isMobile} from "../../../util/functions";const roots = new WeakMap<IProtyle, {refresh: () => void, mountNew: (list: HTMLElement) => void,- restoreFocus: (listID: string, selectedID: string | undefined, oldHost: HTMLElement) => void, destroy: () => void}>();+ restoreFocus: (listID: string, candidateIDs: string[]) => void, destroy: () => void}>();export const mountNewListMindmap = (owner: IProtyle, list: HTMLElement) => roots.get(owner)?.mountNew(list);@@ -451,6 +451,7 @@ class ListMindmapController {if (!await this.change(() => addListMindmapNode(this.list, id, kind === "child" ? "child" : "after", item))) {return;}+ this.view.focusNode(item.dataset.nodeId);const content = this.view.getContentHost(item.dataset.nodeId);if (content) {void this.edit(item.dataset.nodeId, content);@@ -481,7 +482,7 @@ class ListMindmapController {this.view.update(this.model);}},- onUndo: redo => this.undo(redo),+ onUndo: redo => this.undo(redo, id),});if (!this.activeEditor) {this.view.setEditing(undefined);@@ -489,9 +490,13 @@ class ListMindmapController {}}- private async undo(redo: boolean) {- const selectedID = this.view.getSelectedId();- const hadFocus = this.host.contains(document.activeElement);+ private async undo(redo: boolean, editingID?: string) {+ const selectedID = editingID || this.view.getSelectedId();+ const selected = selectedID ? this.model.nodes.get(selectedID) : undefined;+ const siblings = selected?.parentId ? this.model.nodes.get(selected.parentId)?.children || [] : [];+ const index = siblings.findIndex(node => node.id === selectedID);+ const candidateIDs = [selectedID, siblings[index - 1]?.id, siblings[index + 1]?.id,+ selected?.parentId].filter((id): id is string => !!id);if (!canEdit(this.owner, this.list) || (this.activeEditor && !await this.activeEditor.finish())) {return;}@@ -500,13 +505,11 @@ class ListMindmapController {} else {await this.owner.undo.undo(this.owner);}- if (hadFocus) {- roots.get(this.owner)?.restoreFocus(this.list.dataset.nodeId, selectedID, this.host);- }+ roots.get(this.owner)?.restoreFocus(this.list.dataset.nodeId, candidateIDs);}- public focusNode(id?: string) {- this.view.focusNode(id && this.model.nodes.has(id) ? id : this.model.root.id);+ public focusNode(candidateIDs: string[]) {+ this.view.focusNode(candidateIDs.find(id => this.model.nodes.has(id)) || this.model.root.id);}public refresh() {@@ -573,7 +576,7 @@ export const initListMindmaps = (owner: IProtyle) => {const instances = new Map<HTMLElement, ListMindmapController>();const loading = new WeakSet<HTMLElement>();const newlyCreated = new WeakSet<HTMLElement>();- let pendingFocus: {listID: string, selectedID?: string, oldHost: HTMLElement};+ let pendingFocus: {listID: string, candidateIDs: string[]};let frame = 0;let disposed = false;const refresh = () => {@@ -608,10 +611,7 @@ export const initListMindmaps = (owner: IProtyle) => {const instance = new ListMindmapController(owner, list);instances.set(list, instance);if (pendingFocus?.listID === list.dataset.nodeId) {- if (document.activeElement === document.body || pendingFocus.oldHost.contains(document.activeElement) ||- list.contains(document.activeElement)) {- instance.focusNode(pendingFocus.selectedID);- }+ instance.focusNode(pendingFocus.candidateIDs);pendingFocus = undefined;}} catch (error) {@@ -665,17 +665,16 @@ export const initListMindmaps = (owner: IProtyle) => {newlyCreated.add(list);refresh();}- }, restoreFocus: (listID, selectedID, oldHost) => {+ }, restoreFocus: (listID, candidateIDs) => {const list = getListMindmapElements(root).find(item => item.dataset.nodeId === listID);- if (!list || document.activeElement !== document.body && !oldHost.contains(document.activeElement) &&- !list.contains(document.activeElement)) {+ if (!list) {return;}- pendingFocus = {listID, selectedID, oldHost};+ pendingFocus = {listID, candidateIDs};refresh();const instance = instances.get(list);if (instance) {- instance.focusNode(selectedID);+ instance.focusNode(candidateIDs);pendingFocus = undefined;}}, destroy: () => {diff --git a/app/src/protyle/render/listMindmap/model.test.ts b/app/src/protyle/render/listMindmap/model.test.tsindex c3996d52c8..49335c1a4d 100644--- a/app/src/protyle/render/listMindmap/model.test.ts+++ b/app/src/protyle/render/listMindmap/model.test.ts@@ -174,7 +174,8 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,inputHost.contentEditable = "true";document.body.append(inputHost);const inputProtyle = {lute, wysiwyg: {element: inputHost, lastHTMLs: {}},- hint: {render: () => {}}, toolbar: {}, block: {parentID: "document"}} as unknown as IProtyle;+ hint: {render: () => {}}, toolbar: {}, block: {parentID: "document"},+ options: {typewriterMode: false}} as unknown as IProtyle;const caretOffset = (element: Element) => {const selection = getSelection();check.ok(selection.isCollapsed);