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 redo focus from transaction context https://github.com/siyuan-note/siyuan/issues/19835
Daniela5c5f0427378
diff --git a/app/src/protyle/render/listMindmap/focus.test.ts b/app/src/protyle/render/listMindmap/focus.test.tsindex 2817c5a13d..c7b2318cf9 100644--- a/app/src/protyle/render/listMindmap/focus.test.ts+++ b/app/src/protyle/render/listMindmap/focus.test.ts@@ -8,8 +8,8 @@ const source = createSourceFile("index.ts", readFileSync("src/protyle/render/lisScriptTarget.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);+const methods = controller.members.filter(item => item.name && ["add", "change", "undo", "focusNode"].includes(item.name.getText(source)));+assert.equal(methods.length, 4);let editorUndo = "";const visit = (item: import("typescript").Node) => {if (isPropertyAssignment(item) && item.name.getText(source) === "onUndo" &&@@ -78,3 +78,97 @@ test("undo from a node editor restores that node or its previous sibling", asyncawait onEditorUndo(false);assert.equal(selected.pop(), "existing", "undoing node insertion focuses the previous sibling");});++test("mind map transaction focus survives insertion, deletion and repeated undo/redo", async () => {+ type FocusContext = {undoFocusId: string, undoFocusStart: string, undoFocusEnd: string};+ type State = {id: string, children: string[]}[];+ type Operation = {before: string, after: string, undo: FocusContext, redo: FocusContext};+ const operations: Operation[] = [];+ const redoOperations: Operation[] = [];+ let state: State = [{id: "root", children: ["existing"]}, {id: "existing", children: []}];+ let selectedID = "existing";+ let target: any;+ const getModel = () => {+ const nodes = new Map(state.map(node => [node.id, {id: node.id, children: [], parentId: ""}]));+ state.forEach(node => {+ nodes.get(node.id).children = node.children.map(id => {+ const child = nodes.get(id);+ child.parentId = node.id;+ return child;+ });+ });+ return {nodes, root: nodes.get("root")};+ };+ const list = {isConnected: true, dataset: {nodeId: "map"}, get outerHTML() { return JSON.stringify(state); }};+ const roots = new WeakMap();+ const root = {focusRevision: 0, restoreFocus: (_listID: string, ids: string[]) => {+ root.focusRevision++;+ target.focusNode(ids);+ }};+ const replay = (operation: Operation, redo: boolean) => {+ state = JSON.parse(redo ? operation.after : operation.before);+ // 回放替换 DOM 后创建新的控制器,不能依赖旧控制器保存的选择。+ target = createController();+ selectedID = "root";+ root.restoreFocus("map", [(redo ? operation.redo : operation.undo).undoFocusId]);+ };+ const owner = {undo: {+ undo: async () => {+ const operation = operations.pop();+ if (operation) {+ redoOperations.push(operation);+ replay(operation, false);+ }+ },+ redo: async () => {+ const operation = redoOperations.pop();+ if (operation) {+ operations.push(operation);+ replay(operation, true);+ }+ },+ }};+ roots.set(owner, root);+ const context: any = {+ roots, canEdit: () => true, readListMindmap: getModel, cleanListMindmapHTML: (html: string) => html,+ getListMindmapSiblingIDs: () => new Map(), normalizeListMindmapSummaryMetadata: () => {},+ updateTransaction: (_owner: unknown, _list: unknown, before: string, undo: FocusContext,+ additional: {context: FocusContext}) => {+ operations.push({before, after: list.outerHTML, undo, redo: additional.context});+ redoOperations.length = 0;+ },+ showMessage: (message: string) => assert.fail(message),+ window: {siyuan: {languages: {listMindmapInvalid: "Mind map mutation failed"}}}, console,+ };+ runInNewContext(compiled, context);+ const createController = () => Object.assign(new context.Controller(), {+ owner, list, model: getModel(), refresh() { this.model = getModel(); },+ view: {getSelectedId: () => selectedID, focusNode: (id: string) => { selectedID = id; }},+ });+ target = createController();+ await target.change(() => {+ state[0].children.push("new");+ state.push({id: "new", children: []});+ }, false, "new");+ selectedID = "new";+ assert.equal(operations[0].undo.undoFocusId, "existing");+ assert.equal(operations[0].redo.undoFocusId, "new");+ for (let i = 0; i < 2; i++) {+ await target.undo(false);+ assert.equal(selectedID, "existing");+ await target.undo(true);+ assert.equal(selectedID, "new", "redo focus must not be overwritten by the selected sibling");+ }+ await target.change(() => {+ state[0].children = ["existing"];+ state = state.filter(node => node.id !== "new");+ });+ selectedID = "existing";+ await target.undo(false);+ assert.equal(selectedID, "new", "undoing deletion returns to the restored node");+ await target.undo(true);+ assert.equal(selectedID, "existing", "redoing deletion selects the surviving sibling");+ const count = operations.length;+ await target.change(() => {});+ assert.equal(operations.length, count, "unchanged content must not add a focus-only transaction");+});diff --git a/app/src/protyle/render/listMindmap/index.ts b/app/src/protyle/render/listMindmap/index.tsindex 23bf357ef5..60e66c55ec 100644--- a/app/src/protyle/render/listMindmap/index.ts+++ b/app/src/protyle/render/listMindmap/index.ts@@ -41,7 +41,7 @@ import {isMobile} from "../../../util/functions";import {getListMindmapSiblingIDs, getListMindmapSummaryRange} from "./summary";const roots = new WeakMap<IProtyle, {refresh: () => void, mountNew: (list: HTMLElement) => void,- restoreFocus: (listID: string, candidateIDs: string[]) => void, destroy: () => void}>();+ restoreFocus: (listID: string, candidateIDs: string[]) => void, focusRevision: number, destroy: () => void}>();export const mountNewListMindmap = (owner: IProtyle, list: HTMLElement) => roots.get(owner)?.mountNew(list);@@ -434,7 +434,7 @@ class ListMindmapController {return this.taskChanges;}- private async change(change: () => unknown, editing = false) {+ private async change(change: () => unknown, editing = false, focusID?: string) {if (this.disposed || !this.list.isConnected || !canEdit(this.owner, this.list)) {return false;}@@ -446,12 +446,27 @@ class ListMindmapController {}const before = cleanListMindmapHTML(this.list.outerHTML);try {- const previous = getListMindmapSiblingIDs(readListMindmap(this.list));+ const model = readListMindmap(this.list);+ const selectedID = this.view.getSelectedId() || model.root.id;+ const selected = model.nodes.get(selectedID);+ const siblings = selected?.parentId ? model.nodes.get(selected.parentId)?.children || [] : [];+ const index = siblings.findIndex(node => node.id === selectedID);+ const previous = getListMindmapSiblingIDs(model);if (change() === false) {return false;}normalizeListMindmapSummaryMetadata(this.list, previous);- updateTransaction(this.owner, this.list, before);+ if (cleanListMindmapHTML(this.list.outerHTML) !== before) {+ const next = readListMindmap(this.list);+ const nextID = [focusID, selectedID, siblings[index + 1]?.id, siblings[index - 1]?.id,+ selected?.parentId].find(id => next.nodes.has(id)) || next.root.id;+ // 将操作前后的节点分别记录在事务中,重做时可定位到重新插入的节点。+ updateTransaction(this.owner, this.list, before, {+ undoFocusId: selectedID, undoFocusStart: "0", undoFocusEnd: "0",+ }, {doOperations: [], undoOperations: [], context: {+ undoFocusId: nextID, undoFocusStart: "0", undoFocusEnd: "0",+ }});+ }this.refresh();return true;} catch (error) {@@ -477,7 +492,8 @@ class ListMindmapController {item.dataset.type = "NodeMindmapItem";item.classList.replace("li", "mindmap-item");}- if (!await this.change(() => addListMindmapNode(this.list, id, kind === "child" ? "child" : "after", item))) {+ if (!await this.change(() => addListMindmapNode(this.list, id, kind === "child" ? "child" : "after", item),+ false, item.dataset.nodeId)) {return;}this.view.focusNode(item.dataset.nodeId);@@ -529,12 +545,16 @@ class ListMindmapController {if (!canEdit(this.owner, this.list) || (this.activeEditor && !await this.activeEditor.finish())) {return;}+ const root = roots.get(this.owner);+ const focusRevision = root?.focusRevision;if (redo) {await this.owner.undo.redo(this.owner);} else {await this.owner.undo.undo(this.owner);}- roots.get(this.owner)?.restoreFocus(this.list.dataset.nodeId, candidateIDs);+ if (root?.focusRevision === focusRevision) {+ root?.restoreFocus(this.list.dataset.nodeId, candidateIDs);+ }}public focusNode(candidateIDs: string[]) {@@ -678,7 +698,21 @@ export const initListMindmaps = (owner: IProtyle) => {});}};- const unregister = registerListMindmapRoot(root, schedule);+ const restoreFocus = (listID: string, candidateIDs: string[]) => {+ const list = getListMindmapElements(root).find(item => item.dataset.nodeId === listID);+ if (!list) {+ return;+ }+ roots.get(owner).focusRevision++;+ pendingFocus = {listID, candidateIDs};+ refresh();+ const instance = instances.get(list);+ if (instance) {+ instance.focusNode(candidateIDs);+ pendingFocus = undefined;+ }+ };+ const unregister = registerListMindmapRoot(root, schedule, restoreFocus);const observer = new MutationObserver(records => {if (records.some(record => {const element = record.target instanceof Element ? record.target : record.target.parentElement;@@ -694,19 +728,7 @@ export const initListMindmaps = (owner: IProtyle) => {newlyCreated.add(list);refresh();}- }, restoreFocus: (listID, candidateIDs) => {- const list = getListMindmapElements(root).find(item => item.dataset.nodeId === listID);- if (!list) {- return;- }- pendingFocus = {listID, candidateIDs};- refresh();- const instance = instances.get(list);- if (instance) {- instance.focusNode(candidateIDs);- pendingFocus = undefined;- }- }, destroy: () => {+ }, restoreFocus, focusRevision: 0, destroy: () => {disposed = true;unregister();observer.disconnect();diff --git a/app/src/protyle/render/listMindmap/model.test.ts b/app/src/protyle/render/listMindmap/model.test.tsindex ec2e61c333..83f7ca5471 100644--- a/app/src/protyle/render/listMindmap/model.test.ts+++ b/app/src/protyle/render/listMindmap/model.test.ts@@ -2537,7 +2537,7 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,isTaskCompletionToggle: (event: KeyboardEvent) => event.ctrlKey && event.key === "k",onTaskToggle: (id: string, cycle: boolean) => controller.setTask(id,cycle ? taskAPI.nextTaskListStatus : taskAPI.nextTaskListMarker)});- const controller = Object.assign(new taskAPI.TaskController(), {owner, list: taskList, disposed: false,+ const controller = Object.assign(new taskAPI.TaskController(), {owner, list: taskList, view: taskView, disposed: false,taskChanges: Promise.resolve(), refresh: () => taskView.update(api.readListMindmap(taskList))});const taskNode = () => taskHost.querySelector<HTMLElement>(`[data-mindmap-id="${taskId}"]`);const taskButton = () => taskNode().querySelector<HTMLButtonElement>(".mindmap-view__task");@@ -2711,6 +2711,7 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,check.ok(anchor.classList.contains("tabs-task"));tabMenus++;}});+ tabController.view = tabView;const outerOptions = {readonly: () => false, task: () => check.fail("Outer editor claimed a preview task")};api.tabsRender(taskParent, outerOptions);const previewTask = (index = 1) => tabHost.querySelectorAll<HTMLElement>(".tabs-task")[index];diff --git a/app/src/protyle/render/listMindmap/render.ts b/app/src/protyle/render/listMindmap/render.tsindex 6034174a18..1f9a920f99 100644--- a/app/src/protyle/render/listMindmap/render.ts+++ b/app/src/protyle/render/listMindmap/render.ts@@ -4,7 +4,8 @@ import {readListMindmap} from "./model";import {ListMindmapView} from "./view";import {revealTabsForTarget} from "../tabsRender";-const editorRoots = new WeakMap<Element, () => void>();+const editorRoots = new WeakMap<Element, {refresh: () => void,+ restoreFocus: (listID: string, candidateIDs: string[]) => void}>();const previews = new WeakMap<HTMLElement, ListMindmapView>();const visibleViews = new WeakMap<HTMLElement, {view: ListMindmapView, host: HTMLElement}>();@@ -66,11 +67,33 @@ export const resolveVisibleListMindmapBlock = (source: Element): {return null;};-export const registerListMindmapRoot = (root: Element, refresh: () => void) => {- editorRoots.set(root, refresh);+export const registerListMindmapRoot = (root: Element, refresh: () => void,+ restoreFocus: (listID: string, candidateIDs: string[]) => void) => {+ editorRoots.set(root, {refresh, restoreFocus});return () => editorRoots.delete(root);};+// 撤销回放会替换源块,节点焦点交给编辑器在脑图重新挂载后恢复。+export const restoreListMindmapFocus = (root: Element, source: Element) => {+ const registered = editorRoots.get(root);+ if (!registered || source.closest(".mindmap-view")) {+ return false;+ }+ const list = getListMindmapElements(root).find(item => item.contains(source));+ if (!list) {+ return false;+ }+ const candidateIDs: string[] = [];+ for (let element = source; element && list.contains(element); element = element.parentElement) {+ const id = element.getAttribute("data-node-id");+ if (id) {+ candidateIDs.push(id);+ }+ }+ registered.restoreFocus(list.dataset.nodeId, candidateIDs);+ return true;+};+export const getListMindmapElements = (root: Element) => {const selector = `[data-type="NodeMindmap"], [data-type="NodeList"][${Constants.CUSTOM_SY_LIST_MINDMAP}="1"]`;const lists = Array.from(root.querySelectorAll<HTMLElement>(selector));@@ -84,7 +107,7 @@ export const getListMindmapElements = (root: Element) => {// 导出页面和只读预览共用节点布局,源列表始终保留在文档中。export const listMindmapRender = (root: Element, cdn?: string) => {const editor = root.closest(".protyle-wysiwyg");- const refresh = editor && editorRoots.get(editor);+ const refresh = editor && editorRoots.get(editor)?.refresh;if (refresh) {refresh();return;diff --git a/app/src/protyle/util/selection.ts b/app/src/protyle/util/selection.tsindex f3da4a6cef..7145058953 100644--- a/app/src/protyle/util/selection.ts+++ b/app/src/protyle/util/selection.ts@@ -30,6 +30,7 @@ import {stripSemanticMarkersFromRangeText} from "./inlineElementMarker";import {getSelectAllBlockAction, setBlockSelectionModeElement} from "../wysiwyg/blockSelection";+import {restoreListMindmapFocus} from "../render/listMindmap/render";const selectIsEditor = (editor: Element, range?: Range) => {if (!range) {@@ -718,6 +719,9 @@ export const restoreFocusContext = (protyle: IProtyle, context: Pick<IOperation[(!startEmbed || startEmbed.getAttribute("data-node-id") !== context.undoFocusEmbedId))) {return false;}+ if (startBlockElement === endBlockElement && restoreListMindmapFocus(protyle.wysiwyg.element, startBlockElement)) {+ return true;+ }if (context.undoFocusTableCell !== undefined && startBlockElement.getAttribute("data-type") === "NodeTable") {const index = Number(context.undoFocusTableCell);const cell = Number.isInteger(index) && index >= 0 ?diff --git a/app/src/protyle/util/undoReplayFocus.test.ts b/app/src/protyle/util/undoReplayFocus.test.tsindex d10d26d1b8..cafa3e0565 100644--- a/app/src/protyle/util/undoReplayFocus.test.ts+++ b/app/src/protyle/util/undoReplayFocus.test.ts@@ -33,7 +33,7 @@ const browserCases = async (source: string) => {const transactions: {before: string, after: string, undoContext: Record<string, string>,context: Record<string, string>}[] = [];const dependencies = {- Constants: {ZWSP: "\u200b"},+ Constants: {ZWSP: "\u200b", CUSTOM_SY_LIST_MINDMAP: "custom-sy-list-mindmap"},revealTabsForTarget: (): void => undefined,captureBlockSelectionModeState: noop,disposeCustomBlocksInElement: noop,@@ -67,7 +67,7 @@ const browserCases = async (source: string) => {};const api = new Function(...Object.keys(dependencies), source.replace('import("../render/tableCellRichEditor")',"loadRichCellEditor()") +- "return {TableCutControl, getUndoFocusContext, restoreUndoFocus, focusByRange, focusByWbr, updateBlock};")(...Object.values(dependencies));+ "return {TableCutControl, getUndoFocusContext, restoreUndoFocus, focusByRange, focusByWbr, updateBlock, registerListMindmapRoot};")(...Object.values(dependencies));const editor = document.createElement("div");editor.className = "protyle-wysiwyg";editor.contentEditable = "true";@@ -210,6 +210,26 @@ const browserCases = async (source: string) => {check.equal(highlightedCarets.length, 1);check.equal(highlightedCarets[0], editor.children[1]);assertCaret(editor.children[1].querySelector("[contenteditable]"), 2);+ const pendingFocus: {listID: string, ids: string[]}[] = [];+ const unregisterMindmap = api.registerListMindmapRoot(editor, noop, (listID: string, ids: string[]) => {+ pendingFocus.push({listID, ids});+ });+ for (const type of ["NodeMindmap", "NodeList"]) {+ editor.innerHTML = `<div data-node-id="map" data-type="${type}" custom-sy-list-mindmap="1">+ <div data-node-id="child" data-type="${type === "NodeMindmap" ? "NodeMindmapItem" : "NodeListItem"}">+ <div data-node-id="text" data-type="NodeParagraph"><div contenteditable="true">Child</div></div>+ </div></div>`;+ check.equal(api.restoreUndoFocus(protyle, [{context: {+ undoFocusId: "child", undoFocusStart: "0", undoFocusEnd: "0",+ }}]), true);+ check.deepEqual(pendingFocus.pop(), {listID: "map", ids: ["child", "map"]},+ "recorded node focus must reach the mind map before its view has mounted");+ check.equal(api.restoreUndoFocus(protyle, [{context: {+ undoFocusId: "text", undoFocusStart: "0", undoFocusEnd: "0",+ }}]), true);+ check.deepEqual(pendingFocus.pop(), {listID: "map", ids: ["text", "child", "map"]});+ }+ unregisterMindmap();editor.remove();return "Undo replay focus cases passed";};@@ -235,6 +255,8 @@ test("undo replay restores recorded carets across paragraphs, table cells and em"getSemanticMarkerPrefixLengthForNode"]) +extract("tableCellRichValue.ts", ["TABLE_CELL_RICH_ATTRIBUTE"]) +extract("selectionFocus.ts", ["getUndoFocusElement"]) ++ extract("../render/listMindmap/render.ts", ["editorRoots", "registerListMindmapRoot",+ "restoreListMindmapFocus", "getListMindmapElements"]) +extract("../wysiwyg/getBlock.ts", ["getContenteditableElement", "isEndOfBlock", "hasNextSibling","isNotEditBlock", "isContainerBlock", "hasPreviousSibling"]) +extract("../wysiwyg/transaction.ts", ["updateBlock"]) +