Skip to content

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

:bug: Preserve mind map view and text selection during undo https://github.com/siyuan-note/siyuan/issues/20457

Danielfbcaa64bf13e
diff --git a/app/src/protyle/render/listMindmap/editor.test.ts b/app/src/protyle/render/listMindmap/editor.test.ts
index deccc600ef..58769f63dd 100644
--- a/app/src/protyle/render/listMindmap/editor.test.ts
+++ b/app/src/protyle/render/listMindmap/editor.test.ts
@@ -169,6 +169,8 @@ const browserCases = async (sourceCode: string, css: string, cleanupSource: stri
avRender: noop,
blockRender: noop,
highlightRender: noop,
+ getUndoFocusContext: (): undefined => undefined,
+ restoreFocusContext: () => false,
finishListMindmaps: () => state.finishNested(),
cleanListMindmapHTML: new Function(cleanupSource + "; return cleanListMindmapHTML;")(),
};
diff --git a/app/src/protyle/render/listMindmap/editor.ts b/app/src/protyle/render/listMindmap/editor.ts
index f247fe9cc1..c86aeb6f5f 100644
--- a/app/src/protyle/render/listMindmap/editor.ts
+++ b/app/src/protyle/render/listMindmap/editor.ts
@@ -21,18 +21,20 @@ import {highlightRender} from "../highlightRender";
import {cleanListMindmapHTML} from "./model";
import type {ListMindmapNode} from "./model";
import {finishListMindmaps} from "./index";
+import {getUndoFocusContext, restoreFocusContext} from "../../util/selection";
interface ListMindmapEditorOptions {
owner: IProtyle;
node: ListMindmapNode;
host: HTMLElement;
canEdit: () => boolean;
- onSave: (html: string) => Promise<boolean>;
+ onSave: (html: string, undoSelection?: Record<string, string>, redoSelection?: Record<string, string>) => Promise<boolean>;
onResize: () => void;
onAdd: (kind: "child" | "sibling") => Promise<void>;
onFinish: () => void;
- onUndo: (redo: boolean) => void;
+ onUndo: (redo: boolean, selection?: Record<string, string>) => void;
replaceFirstParagraph?: string;
+ selection?: Record<string, string>;
}
const nestedBranchType = (node: ListMindmapNode) =>
@@ -201,6 +203,33 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
// 菜单使用未缩放的容器定位,同时保持在原生全屏元素内可见。
overlays.forEach(element => overlayRoot.appendChild(element));
let lastHTML = comparableContent(fragment.getBlockHTML());
+ let undoSelection: Record<string, string>;
+ let lastSelection: Record<string, string>;
+ const captureSelection = () => {
+ const selection = getSelection();
+ if (!selection?.rangeCount) {
+ return;
+ }
+ const range = selection.getRangeAt(0);
+ const anchor = range.startContainer instanceof Element ? range.startContainer : range.startContainer.parentElement;
+ const end = range.endContainer instanceof Element ? range.endContainer : range.endContainer.parentElement;
+ if (anchor?.closest(".protyle-wysiwyg") !== fragment.wysiwyg ||
+ end?.closest(".protyle-wysiwyg") !== fragment.wysiwyg ||
+ anchor.closest(".protyle-wysiwyg__embed, .av") || end.closest(".protyle-wysiwyg__embed, .av")) {
+ return;
+ }
+ const context = getUndoFocusContext(fragment.wysiwyg, range, true);
+ if (context) {
+ lastSelection = {...context, backward: String(!range.collapsed && selection.anchorNode === range.endContainer &&
+ selection.anchorOffset === range.endOffset)};
+ return lastSelection;
+ }
+ };
+ const captureBeforeChange = () => {
+ if (comparableContent(fragment.getBlockHTML()) === lastHTML) {
+ undoSelection = captureSelection() || undoSelection;
+ }
+ };
const recover = () => {
if (recoveryShown) {
return;
@@ -249,11 +278,14 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
}
saving = true;
try {
- if (!await options.onSave(retainIndependentBlocks(html, node))) {
+ // 前后选区和同一批正文快照一起保存,不能在异步提交后读取下一批输入的选区。
+ const redoSelection = captureSelection() || lastSelection || undoSelection;
+ if (!await options.onSave(retainIndependentBlocks(html, node), undoSelection, redoSelection)) {
return false;
}
source = comparableContent(nodeContent(node));
lastHTML = version;
+ undoSelection = redoSelection;
changed = comparableContent(fragment.getBlockHTML()) !== version;
if (changed && !finishSession) {
saveTimer = window.setTimeout((): void => { void commit(); }, 350);
@@ -342,12 +374,15 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
}
return;
}
- if (await finish()) {
- options.onUndo(redo);
- }
+ options.onUndo(redo, captureSelection() || lastSelection);
};
setMobileToolbarUndo(fragment.protyle, owner, undo);
const signal = events.signal;
+ host.addEventListener("beforeinput", captureBeforeChange, {capture: true, signal});
+ host.addEventListener("compositionstart", captureBeforeChange, {capture: true, signal});
+ host.addEventListener("pointerdown", captureBeforeChange, {capture: true, signal});
+ host.addEventListener("keydown", captureBeforeChange, {capture: true, signal});
+ document.addEventListener("selectionchange", captureSelection, {signal});
host.addEventListener("beforeinput", event => {
const anchor = getSelection()?.anchorNode;
const element = anchor instanceof Element ? anchor : anchor?.parentElement;
@@ -359,6 +394,7 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
bindLiteCodeActions(host, fragment.protyle, {
signal,
canEdit: () => !finished && !closing && options.canEdit(),
+ beforeChange: captureBeforeChange,
onChange: () => {
changed = true;
void commit();
@@ -448,6 +484,9 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
document.addEventListener("pointerdown", event => {
if (!belongs(event.target as Node)) {
finish();
+ } else {
+ // 工具栏浮层位于节点 host 外,格式命令执行前仍需保存原文字选区。
+ captureBeforeChange();
}
}, {capture: true, signal});
window.addEventListener("blur", () => void commit(), {signal});
@@ -469,6 +508,7 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
range.selectNodeContents(editable);
selection.removeAllRanges();
selection.addRange(range);
+ captureBeforeChange();
if (options.replaceFirstParagraph && !document.execCommand("insertText", false, options.replaceFirstParagraph)) {
editable.textContent = options.replaceFirstParagraph;
range.selectNodeContents(editable);
@@ -477,6 +517,12 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
selection.addRange(range);
}
}
+ if (options.selection && restoreFocusContext(fragment.protyle, options.selection) &&
+ options.selection.backward === "true" && getSelection().rangeCount) {
+ const range = getSelection().getRangeAt(0);
+ getSelection().setBaseAndExtent(range.endContainer, range.endOffset, range.startContainer, range.startOffset);
+ }
+ undoSelection ||= captureSelection();
return {finish, destroy, pasteImages: (files: File[]) => {
if (finished || closing || !options.canEdit()) {
return;
diff --git a/app/src/protyle/render/listMindmap/editorHistory.test.ts b/app/src/protyle/render/listMindmap/editorHistory.test.ts
new file mode 100644
index 0000000000..2e4762e130
--- /dev/null
+++ b/app/src/protyle/render/listMindmap/editorHistory.test.ts
@@ -0,0 +1,121 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import test from "node:test";
+import {createSourceFile, isArrowFunction, isCallExpression, isVariableDeclaration, ScriptTarget, transpileModule} from "typescript";
+
+const source = createSourceFile("editor.ts", readFileSync("src/protyle/render/listMindmap/editor.ts", "utf8"),
+ ScriptTarget.ES2021, true);
+const declarations = new Map<string, string>();
+let pointerHandler: string;
+let keyboardCapture = false;
+const visit = (item: import("typescript").Node) => {
+ if (isVariableDeclaration(item) && ["save", "captureBeforeChange"].includes(item.name.getText(source))) {
+ declarations.set(item.name.getText(source), item.getText(source));
+ }
+ if (isCallExpression(item) && item.expression.getText(source) === "document.addEventListener" &&
+ item.arguments[0]?.getText(source) === '"pointerdown"' && isArrowFunction(item.arguments[1]) &&
+ item.arguments[1].getText(source).includes("!belongs")) {
+ pointerHandler = item.arguments[1].getText(source);
+ }
+ if (isCallExpression(item) && item.expression.getText(source) === "host.addEventListener" &&
+ item.arguments[0]?.getText(source) === '"keydown"' && item.arguments[1]?.getText(source) === "captureBeforeChange") {
+ keyboardCapture = item.arguments[2]?.getText(source).includes("capture: true");
+ }
+ item.forEachChild(visit);
+};
+visit(source);
+assert.equal(declarations.size, 2);
+assert.ok(pointerHandler);
+assert.equal(keyboardCapture, true);
+const compiled = transpileModule([...declarations.values()].map(value => `const ${value};`).join("\n"),
+ {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
+const pointerCode = transpileModule(`const pointerdown = ${pointerHandler};`,
+ {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
+
+const create = (initial: string, initialSelection: Record<string, string>) => {
+ const state = {html: initial, source: initial, selection: initialSelection, barrier: undefined as Promise<void> | undefined,
+ saves: [] as {html: string, undo: Record<string, string>, redo: Record<string, string>}[]};
+ const factory = new Function("state", "assert", `
+ let finished = false, closing = false, composing = false, saving = false, changed = false;
+ let saveTimer, lastHTML = state.html, source = state.source;
+ let undoSelection = state.selection, lastSelection = state.selection;
+ const clearTimeout = () => {}, window = {setTimeout: () => 1};
+ const comparableContent = value => value, cleanListMindmapHTML = value => value;
+ const retainIndependentBlocks = value => value, captureSelection = () => state.selection;
+ const node = {element: {isConnected: true}}, nodeContent = () => state.source;
+ const recover = () => assert.fail('Unexpected source conflict');
+ const fragment = {getBlockHTML: () => state.html, wysiwyg: {children: []},
+ protyle: {wysiwyg: {flushPendingInput: async () => {}}}};
+ const options = {canEdit: () => true, onSave: async (html, undo, redo) => {
+ state.saves.push({html, undo, redo});
+ await state.barrier;
+ state.source = html;
+ return true;
+ }};
+ const belongs = target => target === 'toolbar', finish = () => {};
+ ${compiled}
+ ${pointerCode}
+ return {save, captureBeforeChange, pointerdown, currentUndo: () => undoSelection};
+ `);
+ return {state, editor: factory(state, assert)};
+};
+
+test("mind map save binds both selection snapshots to their own content batch, including input during a save", async () => {
+ const before = {undoFocusId: "first", undoFocusEndId: "second", undoFocusStart: "3", undoFocusEnd: "1",
+ undoFocusIgnoreZWSP: "true", backward: "true"};
+ const after = {...before, undoFocusEndId: "first", undoFocusStart: "4", undoFocusEnd: "4", backward: "false"};
+ const next = {...after, undoFocusStart: "5", undoFocusEnd: "5"};
+ const {state, editor} = create("A😀BC\n中文", before);
+ editor.captureBeforeChange();
+ state.html = "A😀XC\n中文";
+ state.selection = after;
+ let release: () => void;
+ state.barrier = new Promise<void>(resolve => { release = resolve; });
+ const saving = editor.save(false);
+ await Promise.resolve();
+ assert.equal(state.saves.length, 1);
+ state.html = "A😀XYC\n中文";
+ state.selection = next;
+ release();
+ assert.equal(await saving, true);
+ assert.deepEqual(state.saves[0], {html: "A😀XC\n中文", undo: before, redo: after});
+ assert.equal(editor.currentUndo(), after, "the following batch starts at the prior committed selection");
+ editor.captureBeforeChange();
+ assert.equal(await editor.save(true), true);
+ assert.deepEqual(state.saves[1], {html: "A😀XYC\n中文", undo: after, redo: next});
+});
+
+test("unchanged content and an outside selection do not replace the last valid editing history", async () => {
+ const selection = {undoFocusId: "paragraph", undoFocusStart: "2", undoFocusEnd: "2"};
+ const {state, editor} = create("中文😀", selection);
+ state.selection = undefined;
+ editor.captureBeforeChange();
+ assert.equal(editor.currentUndo(), selection);
+ assert.equal(await editor.save(true), true);
+ assert.equal(state.saves.length, 0);
+ state.html = "中文😀x";
+ assert.equal(await editor.save(true), true);
+ assert.equal(state.saves[0].undo, selection);
+ assert.equal(state.saves[0].redo, selection);
+});
+
+test("floating toolbar captures the selected text before formatting, while undo keydown preserves a pending batch origin", async () => {
+ const caret = {undoFocusId: "paragraph", undoFocusStart: "0", undoFocusEnd: "0"};
+ const selected = {...caret, undoFocusStart: "2", undoFocusEnd: "4"};
+ const {state, editor} = create("ABCDE", caret);
+ state.selection = selected;
+ editor.pointerdown({target: "toolbar"});
+ assert.equal(editor.currentUndo(), selected, "document capture runs before the overlay formats its selected text");
+ state.html = "AB<strong>CD</strong>E";
+ state.selection = {...caret, undoFocusStart: "4", undoFocusEnd: "4"};
+ assert.equal(await editor.save(true), true);
+ assert.equal(state.saves[0].undo, selected);
+
+ const pending = create("", caret);
+ pending.editor.captureBeforeChange();
+ pending.state.html = "x";
+ pending.state.selection = {...caret, undoFocusStart: "1", undoFocusEnd: "1"};
+ pending.editor.captureBeforeChange(); // 实际 keydown capture 在 Ctrl+Z 处理器之前执行。
+ assert.equal(await pending.editor.save(true), true);
+ assert.equal(pending.state.saves[0].undo, caret, "undo keydown must not replace the pre-input selection with the current caret");
+});
diff --git a/app/src/protyle/render/listMindmap/focus.test.ts b/app/src/protyle/render/listMindmap/focus.test.ts
index c7b2318cf9..15a7d8612c 100644
--- a/app/src/protyle/render/listMindmap/focus.test.ts
+++ b/app/src/protyle/render/listMindmap/focus.test.ts
@@ -8,12 +8,12 @@ const source = createSourceFile("index.ts", readFileSync("src/protyle/render/lis
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", "change", "undo", "focusNode"].includes(item.name.getText(source)));
-assert.equal(methods.length, 4);
+const methods = controller.members.filter(item => item.name && ["add", "change", "undo", "focusNode", "edit"].includes(item.name.getText(source)));
+assert.equal(methods.length, 5);
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)")) {
+ item.initializer.getText(source).includes("this.undo(redo, id,")) {
editorUndo = item.initializer.getText(source);
}
item.forEachChild(visit);
@@ -57,17 +57,18 @@ test("undo from a node editor restores that node or its previous sibling", async
]);
const selected: string[] = [];
let removeNew = false;
- const owner = {undo: {undo: async () => {
+ const owner = {wysiwyg: {element: {isConnected: true}}, block: {rootID: "document"}, undo: {undo: async () => {
if (removeNew) {
nodes.delete("new");
}
}}};
const roots = new WeakMap();
- const context: any = {canEdit: () => true, roots};
+ const context: any = {canEdit: () => true, roots, cleanListMindmapHTML: (html: string) => html,
+ hasMindmapFocusOverlay: () => false};
runInNewContext(compiled, context);
const target = new context.Controller();
Object.assign(target, {
- owner, list: {dataset: {nodeId: "map"}}, model: {nodes, root},
+ owner, list: {dataset: {nodeId: "map"}, isConnected: true, outerHTML: "map"}, model: {nodes, root},
view: {getSelectedId: () => "root", focusNode: (id: string) => selected.push(id)},
});
roots.set(owner, {restoreFocus: (_listID: string, ids: string[]) => target.focusNode(ids)});
@@ -112,7 +113,7 @@ test("mind map transaction focus survives insertion, deletion and repeated undo/
selectedID = "root";
root.restoreFocus("map", [(redo ? operation.redo : operation.undo).undoFocusId]);
};
- const owner = {undo: {
+ const owner = {wysiwyg: {element: {isConnected: true}}, block: {rootID: "document"}, undo: {
undo: async () => {
const operation = operations.pop();
if (operation) {
@@ -131,6 +132,7 @@ test("mind map transaction focus survives insertion, deletion and repeated undo/
roots.set(owner, root);
const context: any = {
roots, canEdit: () => true, readListMindmap: getModel, cleanListMindmapHTML: (html: string) => html,
+ hasMindmapFocusOverlay: () => false,
getListMindmapSiblingIDs: () => new Map(), normalizeListMindmapSummaryMetadata: () => {},
updateTransaction: (_owner: unknown, _list: unknown, before: string, undo: FocusContext,
additional: {context: FocusContext}) => {
@@ -172,3 +174,62 @@ test("mind map transaction focus survives insertion, deletion and repeated undo/
await target.change(() => {});
assert.equal(operations.length, count, "unchanged content must not add a focus-only transaction");
});
+
+test("empty or canceled history restores the current text selection unless a newer interaction took over", async () => {
+ const selection = {undoFocusId: "body", undoFocusStart: "2", undoFocusEnd: "5"};
+ const opened: unknown[] = [];
+ const body = {getAttribute: () => "body", querySelectorAll: (): Element[] => []};
+ const node = {id: "item", contentBlocks: [body]};
+ const nodes = new Map([["item", node]]);
+ let release: () => void;
+ const owner = {block: {rootID: "document"}, wysiwyg: {element: {isConnected: true}},
+ undo: {undo: async () => {}}};
+ const roots = new WeakMap();
+ const context: any = {roots, canEdit: () => true, cleanListMindmapHTML: (html: string) => html,
+ hasMindmapFocusOverlay: () => false};
+ runInNewContext(compiled, context);
+ const target = Object.assign(new context.Controller(), {
+ owner, list: {dataset: {nodeId: "map"}, outerHTML: "same", isConnected: true}, model: {root: node, nodes},
+ view: {getSelectedId: () => "item", focusNode: () => {}, getContentHost: () => ({isConnected: true})},
+ edit: async (...args: unknown[]) => opened.push(args[4]),
+ });
+ const state = {focusRevision: 0, interactionRevision: 0,
+ restoreFocus: (_id: string, ids: string[], saved: unknown) => target.focusNode(ids, saved)};
+ roots.set(owner, state);
+ await target.undo(false, "item", selection);
+ assert.deepEqual(opened, [selection]);
+ owner.undo.undo = () => new Promise<void>(resolve => { release = resolve; });
+ const pending = target.undo(false, "item", selection);
+ state.interactionRevision++;
+ release();
+ await pending;
+ assert.equal(opened.length, 1, "late history completion must not steal focus after a click or new edit");
+ assert.equal(roots.get(owner).undoPending, false);
+});
+
+test("history reopening does not invalidate its own guard and stale editor cleanup cannot clear a newer editor", async () => {
+ const owner = {};
+ const roots = new WeakMap([[owner, {interactionRevision: 0}]]);
+ const options: any[] = [];
+ const editors: any[] = [];
+ const context: any = {roots, canEdit: () => true, openListMindmapEditor: (value: unknown) => {
+ options.push(value);
+ const editor = {finish: async () => true};
+ editors.push(editor);
+ return editor;
+ }};
+ runInNewContext(compiled, context);
+ const target = Object.assign(new context.Controller(), {
+ owner, editRequest: 0, list: {}, model: {nodes: new Map([["item", {id: "item"}]])},
+ view: {setEditing: () => {}, update: () => {}},
+ });
+ const saved = {undoFocusId: "body", undoFocusStart: "1", undoFocusEnd: "1"};
+ await target.edit("item", {isConnected: true}, undefined, undefined, saved,
+ () => roots.get(owner).interactionRevision === 0);
+ assert.equal(editors.length, 1);
+ assert.equal(options[0].selection, saved);
+ const newer = {finish: async () => true};
+ target.activeEditor = newer;
+ options[0].onFinish();
+ assert.equal(target.activeEditor, newer);
+});
diff --git a/app/src/protyle/render/listMindmap/fold.test.ts b/app/src/protyle/render/listMindmap/fold.test.ts
index 2307cadf4b..3e7df8b87e 100644
--- a/app/src/protyle/render/listMindmap/fold.test.ts
+++ b/app/src/protyle/render/listMindmap/fold.test.ts
@@ -141,7 +141,7 @@ test("batch folding saves a single undo snapshot and reads the source after fini
};
collect(root);
const snapshot = () => JSON.stringify([...nodes].map(([id, current]) => [id, current.collapsed]));
- const list = {isConnected: true, get outerHTML() { return snapshot(); }};
+ const list = {isConnected: true, dataset: {nodeId: "map-fold"}, get outerHTML() { return snapshot(); }};
const transactions: {before: string, after: string}[] = [];
let allowed = true;
const context: any = {
@@ -152,7 +152,10 @@ test("batch folding saves a single undo snapshot and reads the source after fini
getListMindmapFoldStates,
getListMindmapSiblingFoldStates,
cleanListMindmapHTML: (html: string) => html,
- updateTransaction: (_owner: unknown, _list: unknown, before: string) => {
+ updateTransaction: (_owner: unknown, _list: unknown, before: string, undoContext: Record<string, string>,
+ additional: {context: Record<string, string>}) => {
+ assert.equal(undoContext.mindmapSnapshotId, list.dataset.nodeId);
+ assert.equal(additional.context.mindmapSnapshotId, list.dataset.nodeId);
if (before !== snapshot()) {
transactions.push({before, after: snapshot()});
}
diff --git a/app/src/protyle/render/listMindmap/index.ts b/app/src/protyle/render/listMindmap/index.ts
index 54532c198a..94aa188a05 100644
--- a/app/src/protyle/render/listMindmap/index.ts
+++ b/app/src/protyle/render/listMindmap/index.ts
@@ -47,11 +47,23 @@ import {addListMindmapSummaryRanges, getListMindmapSiblingIDs, getListMindmapSum
getListMindmapSummarySnapshot} from "./summary";
import {isProtyleListItemFragment} from "../../runtimeCapabilities";
import {isFoldedRenderContent} from "../foldedContent";
+import {disposeCustomBlocksInElement} from "../../../plugin/customBlockRender";
+import {processRender} from "../../util/processCode";
+import {highlightRender} from "../highlightRender";
+import {avRender} from "../av/render";
+import {blockRender} from "../blockRender";
const roots = new WeakMap<IProtyle, {refresh: () => void, mountNew: (list: HTMLElement) => void,
- restoreFocus: (listID: string, candidateIDs: string[]) => void, focusRevision: number,
+ restoreFocus: (listID: string, candidateIDs: string[], selection?: Record<string, string>, source?: HTMLElement) => void, focusRevision: number,
+ interactionRevision?: number, focusGuard?: () => boolean, undoPending?: boolean,
finish: () => Promise<boolean>, destroy: () => void}>();
+const hasMindmapFocusOverlay = () => {
+ const active = document.activeElement;
+ return !!active?.closest(".b3-dialog, #commonMenu, #keyboardToolbar") &&
+ !active.closest('[data-type="undo"], [data-type="redo"]');
+};
+
export const finishListMindmaps = async (owner: IProtyle) => roots.get(owner)?.finish() ?? true;
export const mountNewListMindmap = (owner: IProtyle, list: HTMLElement) => roots.get(owner)?.mountNew(list);
@@ -560,7 +572,8 @@ class ListMindmapController {
return this.taskChanges;
}
- private async change(change: () => unknown, editing = false, focusID?: string) {
+ private async change(change: () => unknown, editing = false, focusID?: string,
+ selection?: {undo?: Record<string, string>, redo?: Record<string, string>}) {
if (this.disposed || !this.list.isConnected || !canEdit(this.owner, this.list)) {
return false;
}
@@ -589,8 +602,12 @@ class ListMindmapController {
// 将操作前后的节点分别记录在事务中,重做时可定位到重新插入的节点。
updateTransaction(this.owner, this.list, before, {
undoFocusId: selectedID, undoFocusStart: "0", undoFocusEnd: "0",
+ mindmapSnapshotId: this.list.dataset.nodeId,
+ ...(selection?.undo ? {undoFocusMindmapSelection: JSON.stringify(selection.undo)} : {}),
}, {doOperations: [], undoOperations: [], context: {
undoFocusId: nextID, undoFocusStart: "0", undoFocusEnd: "0",
+ mindmapSnapshotId: this.list.dataset.nodeId,
+ ...(selection?.redo ? {undoFocusMindmapSelection: JSON.stringify(selection.redo)} : {}),
}});
}
this.refresh();
@@ -629,10 +646,17 @@ class ListMindmapController {
}
}
- private async edit(id: string, host: HTMLElement, replaceFirstParagraph?: string, images?: File[]) {
+ private async edit(id: string, host: HTMLElement, replaceFirstParagraph?: string, images?: File[],
+ selection?: Record<string, string>, guard?: () => boolean) {
+ if (guard && !guard()) {
+ return;
+ }
+ if (!guard && roots.has(this.owner)) {
+ roots.get(this.owner).interactionRevision = (roots.get(this.owner).interactionRevision || 0) + 1;
+ }
const request = ++this.editRequest;
if (!canEdit(this.owner, this.list) || (this.activeEditor && !await this.activeEditor.finish()) ||
- request !== this.editRequest || this.disposed || !host?.isConnected) {
+ request !== this.editRequest || this.disposed || !host?.isConnected || guard && !guard()) {
return;
}
const node = this.model.nodes.get(id);
@@ -640,21 +664,25 @@ class ListMindmapController {
return;
}
this.view.setEditing(id);
- this.activeEditor = openListMindmapEditor({
- owner: this.owner, node, host, replaceFirstParagraph,
+ const editor = openListMindmapEditor({
+ owner: this.owner, node, host, replaceFirstParagraph, selection,
canEdit: () => !this.disposed && this.list.isConnected && canEdit(this.owner, this.list),
- onSave: html => this.change(() => replaceListMindmapContent(this.list, id, html), true),
+ onSave: (html, undo, redo) => this.change(() => replaceListMindmapContent(this.list, id, html), true, id, {undo, redo}),
onResize: () => this.view.refreshLayout(),
onAdd: kind => this.add(id, kind),
onFinish: () => {
+ if (this.activeEditor !== editor) {
+ return;
+ }
this.activeEditor = undefined;
this.view.setEditing(undefined);
if (!this.disposed) {
this.view.update(this.model);
}
},
- onUndo: redo => this.undo(redo, id),
+ onUndo: (redo, currentSelection) => this.undo(redo, id, currentSelection),
});
+ this.activeEditor = editor;
if (!this.activeEditor) {
this.view.setEditing(undefined);
this.view.update(this.model);
@@ -663,30 +691,116 @@ class ListMindmapController {
}
}
- private async undo(redo: boolean, editingID?: string) {
+ private async undo(redo: boolean, editingID?: string, selection?: Record<string, string>) {
+ const root = roots.get(this.owner);
+ if (root?.undoPending) {
+ return;
+ }
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;
+ const interactionRevision = root?.interactionRevision;
+ const editorRoot = this.owner.wysiwyg.element;
+ const documentID = this.owner.block.rootID;
+ const notebookID = this.owner.notebookId;
+ const guard = () => roots.get(this.owner) === root && editorRoot.isConnected &&
+ this.owner.block.rootID === documentID && this.owner.notebookId === notebookID &&
+ root?.interactionRevision === interactionRevision && !hasMindmapFocusOverlay();
+ if (root) {
+ root.undoPending = true;
+ root.focusGuard = guard;
}
- 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);
+ try {
+ if (!canEdit(this.owner, this.list) || (this.activeEditor && !await this.activeEditor.finish())) {
+ return;
+ }
+ const before = cleanListMindmapHTML(this.list.outerHTML);
+ if (editingID && guard()) {
+ this.view.focusNode(editingID);
+ }
+ const focusRevision = root?.focusRevision;
+ if (redo) {
+ await this.owner.undo.redo(this.owner);
+ } else {
+ await this.owner.undo.undo(this.owner);
+ }
+ if (root?.focusRevision === focusRevision && guard()) {
+ // 空栈或取消确认时恢复原编辑位置;结构回放仍只恢复节点选择。
+ const unchanged = this.list.isConnected && cleanListMindmapHTML(this.list.outerHTML) === before;
+ root?.restoreFocus(this.list.dataset.nodeId, candidateIDs, unchanged ? selection : undefined, this.list);
+ }
+ } finally {
+ if (root?.focusGuard === guard) {
+ root.focusGuard = undefined;
+ root.undoPending = false;
+ }
}
- if (root?.focusRevision === focusRevision) {
- root?.restoreFocus(this.list.dataset.nodeId, candidateIDs);
+ }
+
+ public focusNode(candidateIDs: string[], selection?: Record<string, string>, guard?: () => boolean) {
+ if (guard && !guard()) {
+ return;
+ }
+ const id = candidateIDs.find(id => this.model.nodes.has(id)) || this.model.root.id;
+ this.view.focusNode(id);
+ const node = this.model.nodes.get(id);
+ const content = selection && node && !node.virtual && this.view.getContentHost(id);
+ const ids = new Set(node?.contentBlocks?.flatMap(block => [block, ...Array.from(block.querySelectorAll("[data-node-id]"))])
+ .map(block => block.getAttribute("data-node-id")));
+ if (content && ids.has(selection.undoFocusId) && ids.has(selection.undoFocusEndId || selection.undoFocusId)) {
+ void this.edit(id, content, undefined, undefined, selection, guard);
}
}
- public focusNode(candidateIDs: string[]) {
- this.view.focusNode(candidateIDs.find(id => this.model.nodes.has(id)) || this.model.root.id);
+ public replay(html: string) {
+ if (this.disposed || !this.list.isConnected || this.activeEditor || !canEdit(this.owner, this.list) ||
+ this.list.dataset.type !== "NodeMindmap" && this.list.getAttribute(Constants.CUSTOM_SY_LIST_MINDMAP) !== "1") {
+ return false;
+ }
+ const template = this.list.ownerDocument.createElement("template");
+ template.innerHTML = cleanListMindmapHTML(normalizeHTMLAssetIFrameBlockDOM(html));
+ const next = template.content.firstElementChild as HTMLElement;
+ if (template.content.childElementCount !== 1 || next?.dataset.nodeId !== this.list.dataset.nodeId ||
+ next.dataset.type !== this.list.dataset.type || next.dataset.type !== "NodeMindmap" &&
+ next.getAttribute(Constants.CUSTOM_SY_LIST_MINDMAP) !== "1") {
+ return false;
+ }
+ try {
+ readListMindmap(next);
+ } catch (_error) {
+ return false;
+ }
+ Array.from(this.list.attributes).forEach(attribute => this.list.removeAttribute(attribute.name));
+ Array.from(next.attributes).forEach(attribute => this.list.setAttribute(attribute.name, attribute.value));
+ this.list.dataset.mindmapViewRendered = "true";
+ // 全屏时画布位于 body,原位置的标记也必须保留,才能正常退出全屏。
+ const retained = Array.from(this.list.childNodes).filter(child => child === this.host ||
+ child.nodeType === Node.COMMENT_NODE && child.nodeValue === "mindmap-view");
+ Array.from(this.list.childNodes).forEach(child => {
+ if (!retained.includes(child)) {
+ if (child instanceof Element) {
+ disposeCustomBlocksInElement(child);
+ }
+ child.remove();
+ }
+ });
+ const children = Array.from(next.childNodes);
+ children.forEach(child => this.list.insertBefore(child, retained[0] || null));
+ children.forEach(child => {
+ if (child instanceof Element) {
+ processRender(child);
+ highlightRender(child);
+ avRender(child, this.owner);
+ blockRender(this.owner, child);
+ }
+ });
+ // 即使序列化正文相同,源 Element 已替换,模型也必须重新绑定新节点。
+ this.snapshot = "";
+ this.refresh();
+ return true;
}
public async finish() {
@@ -762,7 +876,7 @@ export const initListMindmaps = (owner: IProtyle) => {
const placeholders = new Map<HTMLElement, HTMLElement>();
const failed = new WeakSet<HTMLElement>();
const newlyCreated = new WeakSet<HTMLElement>();
- let pendingFocus: {listID: string, candidateIDs: string[]};
+ let pendingFocus: {list: HTMLElement, candidateIDs: string[], selection?: Record<string, string>, guard?: () => boolean};
let frame = 0;
let disposed = false;
const clearPlaceholder = (list: HTMLElement) => {
@@ -828,8 +942,8 @@ export const initListMindmaps = (owner: IProtyle) => {
const instance = new ListMindmapController(owner, list);
instances.set(list, instance);
placeholders.delete(list);
- if (pendingFocus?.listID === list.dataset.nodeId) {
- instance.focusNode(pendingFocus.candidateIDs);
+ if (pendingFocus?.list === list) {
+ instance.focusNode(pendingFocus.candidateIDs, pendingFocus.selection, pendingFocus.guard);
pendingFocus = undefined;
}
} catch (error) {
@@ -879,21 +993,53 @@ export const initListMindmaps = (owner: IProtyle) => {
});
}
};
- const restoreFocus = (listID: string, candidateIDs: string[]) => {
- const list = getListMindmapElements(root).find(item => item.dataset.nodeId === listID);
+ const restoreFocus = (listID: string, candidateIDs: string[], selection?: Record<string, string>, source?: HTMLElement) => {
+ const state = roots.get(owner);
+ const revision = state?.interactionRevision;
+ const requestGuard = state?.focusGuard;
+ const guard = () => !disposed && roots.get(owner) === state && state?.interactionRevision === revision &&
+ !hasMindmapFocusOverlay() && (!requestGuard || requestGuard());
+ if (guard && !guard()) {
+ state.focusRevision++;
+ return;
+ }
+ const lists = getListMindmapElements(root);
+ const list = source && lists.includes(source) ? source : lists.find(item => item.dataset.nodeId === listID &&
+ !item.closest(".protyle-wysiwyg__embed"));
if (!list) {
return;
}
roots.get(owner).focusRevision++;
- pendingFocus = {listID, candidateIDs};
+ pendingFocus = {list, candidateIDs, selection, guard};
refresh();
const instance = instances.get(list);
if (instance) {
- instance.focusNode(candidateIDs);
+ instance.focusNode(candidateIDs, selection, guard);
pendingFocus = undefined;
}
};
- const unregister = registerListMindmapRoot(root, schedule, restoreFocus);
+ const unregister = registerListMindmapRoot(root, schedule, restoreFocus,
+ (source, html) => instances.get(source as HTMLElement)?.replay(html) ?? false);
+ const interactions = new AbortController();
+ const invalidateFocus = (event: Event) => {
+ if (event.target instanceof Element) {
+ if (event.target.closest(".b3-dialog")?.querySelector('[data-undo-confirmation="true"]') ||
+ event.target.closest("#keyboardToolbar") && event.target.closest('[data-type="undo"], [data-type="redo"]')) {
+ return;
+ }
+ }
+ if (event instanceof KeyboardEvent &&
+ (matchHotKey(window.siyuan.config.keymap.editor.general.undo, event) ||
+ matchHotKey(window.siyuan.config.keymap.editor.general.redo, event))) {
+ return;
+ }
+ const state = roots.get(owner);
+ if (state) {
+ state.interactionRevision = (state.interactionRevision || 0) + 1;
+ }
+ };
+ document.addEventListener("pointerdown", invalidateFocus, {capture: true, signal: interactions.signal});
+ document.addEventListener("keydown", invalidateFocus, {capture: true, signal: interactions.signal});
const observer = new MutationObserver(records => {
if (records.some(record => {
const element = record.target instanceof Element ? record.target : record.target.parentElement;
@@ -916,8 +1062,9 @@ export const initListMindmaps = (owner: IProtyle) => {
newlyCreated.add(list);
refresh();
}
- }, restoreFocus, focusRevision: 0, destroy: () => {
+ }, restoreFocus, focusRevision: 0, interactionRevision: 0, destroy: () => {
disposed = true;
+ interactions.abort();
unregister();
observer.disconnect();
cancelAnimationFrame(frame);
diff --git a/app/src/protyle/render/listMindmap/relation.test.ts b/app/src/protyle/render/listMindmap/relation.test.ts
index e32300c954..a8cf9c8215 100644
--- a/app/src/protyle/render/listMindmap/relation.test.ts
+++ b/app/src/protyle/render/listMindmap/relation.test.ts
@@ -30,7 +30,7 @@ test("manual route save and reset use one transaction and reject stale relation
const original = JSON.stringify(data);
const transactions: {before: string, after: string}[] = [];
const messages: string[] = [];
- const list = {isConnected: true, get outerHTML() { return JSON.stringify(data); }};
+ const list = {isConnected: true, dataset: {nodeId: "map-relations"}, get outerHTML() { return JSON.stringify(data); }};
const context: any = {
canEdit: () => true,
getListMindmapSiblingIDs: () => new Map(),
@@ -39,7 +39,12 @@ test("manual route save and reset use one transaction and reject stale relation
nodes: new Map(["a", "b", "c"].map(id => [id, {}]))}),
writeListMindmapMetadata: (_list: unknown, next: typeof data) => data = next,
cleanListMindmapHTML: (html: string) => html,
- updateTransaction: (_owner: unknown, _list: unknown, before: string) => transactions.push({before, after: list.outerHTML}),
+ updateTransaction: (_owner: unknown, _list: unknown, before: string, undoContext: Record<string, string>,
+ additional: {context: Record<string, string>}) => {
+ assert.equal(undoContext.mindmapSnapshotId, list.dataset.nodeId);
+ assert.equal(additional.context.mindmapSnapshotId, list.dataset.nodeId);
+ transactions.push({before, after: list.outerHTML});
+ },
showMessage: (message: string) => messages.push(message),
window: {siyuan: {languages: {listMindmapStale: "stale"}}}, console,
};
diff --git a/app/src/protyle/render/listMindmap/render.ts b/app/src/protyle/render/listMindmap/render.ts
index e9a4d58a42..bb02f1e62d 100644
--- a/app/src/protyle/render/listMindmap/render.ts
+++ b/app/src/protyle/render/listMindmap/render.ts
@@ -5,7 +5,8 @@ import {ListMindmapView} from "./view";
import {revealTabsForTarget} from "../tabsRender";
const editorRoots = new WeakMap<Element, {refresh: () => void,
- restoreFocus: (listID: string, candidateIDs: string[]) => void}>();
+ restoreFocus: (listID: string, candidateIDs: string[], selection?: Record<string, string>, source?: HTMLElement) => void,
+ replay?: (source: Element, html: string) => boolean}>();
const previews = new WeakMap<HTMLElement, ListMindmapView>();
const visibleViews = new WeakMap<HTMLElement, {view: ListMindmapView, host: HTMLElement}>();
@@ -70,13 +71,43 @@ export const resolveVisibleListMindmapBlock = (source: Element): {
};
export const registerListMindmapRoot = (root: Element, refresh: () => void,
- restoreFocus: (listID: string, candidateIDs: string[]) => void) => {
- editorRoots.set(root, {refresh, restoreFocus});
+ restoreFocus: (listID: string, candidateIDs: string[], selection?: Record<string, string>, source?: HTMLElement) => void,
+ replay?: (source: Element, html: string) => boolean) => {
+ editorRoots.set(root, {refresh, restoreFocus, replay});
return () => editorRoots.delete(root);
};
+export const readListMindmapSelection = (value: unknown): Record<string, string> | undefined => {
+ if (typeof value !== "string") {
+ return;
+ }
+ try {
+ const saved = JSON.parse(value);
+ if (!saved || typeof saved !== "object" || Array.isArray(saved) ||
+ !Object.values(saved).every(item => typeof item === "string") ||
+ !/^[\w-]+$/.test(saved.undoFocusId || "") ||
+ saved.undoFocusEndId !== undefined && !/^[\w-]+$/.test(saved.undoFocusEndId)) {
+ return;
+ }
+ for (const key of ["undoFocusStart", "undoFocusEnd", "undoFocusIndex", "undoFocusEndIndex", "undoFocusTableCell"]) {
+ if ((key === "undoFocusStart" || key === "undoFocusEnd" || saved[key] !== undefined) &&
+ (!/^\d+$/.test(saved[key]) || !Number.isSafeInteger(Number(saved[key])))) {
+ return;
+ }
+ }
+ for (const key of ["backward", "undoFocusStartAtEnd", "undoFocusIgnoreZWSP", "undoFocusCalloutTitle", "undoFocusCollapseToEnd"]) {
+ if (saved[key] !== undefined && !["true", "false"].includes(saved[key])) {
+ return;
+ }
+ }
+ return saved;
+ } catch (_error) {
+ // 不认识的选区仍退回节点选择,不影响正文回放。
+ }
+};
+
// 撤销回放会替换源块,节点焦点交给编辑器在脑图重新挂载后恢复。
-export const restoreListMindmapFocus = (root: Element, source: Element) => {
+export const restoreListMindmapFocus = (root: Element, source: Element, context?: IOperation["context"]) => {
const registered = editorRoots.get(root);
if (!registered || root.contains(source.closest(".mindmap-view"))) {
return false;
@@ -92,10 +123,16 @@ export const restoreListMindmapFocus = (root: Element, source: Element) => {
candidateIDs.push(id);
}
}
- registered.restoreFocus(list.dataset.nodeId, candidateIDs);
+ const selection = readListMindmapSelection(context?.undoFocusMindmapSelection);
+ registered.restoreFocus(list.dataset.nodeId, candidateIDs, selection, list);
return true;
};
+// 仅脑图控制器生成的完整源快照可就地回放;旧历史和局部块更新仍走完整源补齐。
+export const replayListMindmap = (root: Element, source: Element, operation: Extract<IOperation, {action: "update"}>) =>
+ operation.context?.mindmapSnapshotId === operation.id && source.getAttribute("data-node-id") === operation.id &&
+ typeof operation.data === "string" && !!editorRoots.get(root)?.replay?.(source, operation.data);
+
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));
diff --git a/app/src/protyle/render/listMindmap/replay.test.ts b/app/src/protyle/render/listMindmap/replay.test.ts
new file mode 100644
index 0000000000..e7a26664ce
--- /dev/null
+++ b/app/src/protyle/render/listMindmap/replay.test.ts
@@ -0,0 +1,238 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import test from "node:test";
+import {runInNewContext} from "node:vm";
+import {createSourceFile, isArrowFunction, isClassDeclaration, isVariableDeclaration, isVariableStatement, ScriptTarget, transpileModule} from "typescript";
+
+const compile = (source: string) => transpileModule(source, {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
+const indexSource = createSourceFile("index.ts", readFileSync("src/protyle/render/listMindmap/index.ts", "utf8"),
+ ScriptTarget.ES2021, true);
+const controller = indexSource.statements.find(item => isClassDeclaration(item) && item.name?.text === "ListMindmapController");
+assert.ok(controller && isClassDeclaration(controller));
+const replay = controller.members.find(item => item.name?.getText(indexSource) === "replay");
+const replaySource = compile(`class Controller { ${replay.getText(indexSource)} } globalThis.Controller = Controller;`);
+
+// 小型 DOM 替身验证对象身份和替换顺序;真实布局/选区另由 Electron 回归覆盖。
+class ElementFixture {
+ public nodeType = 1;
+ public nodeValue = "";
+ public childNodes: ElementFixture[] = [];
+ public parentElement?: ElementFixture;
+ public isConnected = true;
+ public ownerDocument: {createElement: () => unknown};
+ private attrs = new Map<string, string>();
+ constructor(id?: string, type = "NodeMindmap") {
+ if (id) {
+ this.setAttribute("data-node-id", id);
+ this.setAttribute("data-type", type);
+ }
+ }
+ get attributes() { return Array.from(this.attrs, ([name, value]) => ({name, value})); }
+ get dataset(): Record<string, string> {
+ const name = (key: string) => "data-" + key.replace(/[A-Z]/g, value => "-" + value.toLowerCase());
+ return new Proxy({}, {get: (_target, key: string) => this.getAttribute(name(key)),
+ set: (_target, key: string, value: string) => { this.setAttribute(name(key), value); return true; }});
+ }
+ getAttribute(name: string) { return this.attrs.get(name) ?? null; }
+ setAttribute(name: string, value: string) { this.attrs.set(name, value); }
+ removeAttribute(name: string) { this.attrs.delete(name); }
+ append(child: ElementFixture) { this.insertBefore(child, null); }
+ remove() {
+ if (this.parentElement) {
+ this.parentElement.childNodes.splice(this.parentElement.childNodes.indexOf(this), 1);
+ this.parentElement = undefined;
+ }
+ }
+ insertBefore(child: ElementFixture, before: ElementFixture | null) {
+ child.remove();
+ const index = before ? this.childNodes.indexOf(before) : this.childNodes.length;
+ assert.ok(index >= 0);
+ this.childNodes.splice(index, 0, child);
+ child.parentElement = this;
+ }
+}
+
+const fixture = () => {
+ const list = new ElementFixture("map");
+ const old = new ElementFixture("old", "NodeMindmapItem");
+ const host = new ElementFixture();
+ list.append(old);
+ list.append(host);
+ let next = new ElementFixture("map");
+ const heading = new ElementFixture("heading", "NodeHeading");
+ heading.setAttribute("fold", "1");
+ const hidden = new ElementFixture("hidden", "NodeParagraph");
+ next.append(heading);
+ next.append(hidden);
+ next.setAttribute("style", "height:420px");
+ const calls: [string, unknown][] = [];
+ list.ownerDocument = {createElement: () => ({
+ content: {get firstElementChild() { return next; }, childElementCount: 1},
+ set innerHTML(value: string) { calls.push(["parse", value]); },
+ })};
+ const context: any = {
+ Element: ElementFixture, Node: {COMMENT_NODE: 8}, Constants: {CUSTOM_SY_LIST_MINDMAP: "custom-sy-list-mindmap"},
+ canEdit: () => true, cleanListMindmapHTML: (html: string) => html,
+ normalizeHTMLAssetIFrameBlockDOM: (html: string) => { calls.push(["normalize", html]); return html; },
+ readListMindmap: (source: unknown) => { calls.push(["validate", source]); },
+ disposeCustomBlocksInElement: (source: unknown) => calls.push(["dispose", source]),
+ processRender: (source: unknown) => calls.push(["process", source]),
+ highlightRender: (source: unknown) => calls.push(["highlight", source]),
+ avRender: (source: unknown) => calls.push(["av", source]),
+ blockRender: (_owner: unknown, source: unknown) => calls.push(["embed", source]),
+ };
+ runInNewContext(replaySource, context);
+ const target = Object.assign(new context.Controller(), {list, host, owner: {}, refresh: () => calls.push(["refresh", list])});
+ return {target, list, host, old, heading, hidden, calls, setNext: (value: ElementFixture) => { next = value; }};
+};
+
+test("complete replay retains the list and canvas, restores folded source and renders only replacement source", () => {
+ const {target, list, host, old, heading, hidden, calls} = fixture();
+ assert.equal(target.replay("raw complete snapshot"), true);
+ assert.equal(target.list, list);
+ assert.equal(target.host, host);
+ assert.deepEqual(list.childNodes, [heading, hidden, host]);
+ assert.equal(list.dataset.mindmapViewRendered, "true");
+ assert.equal(list.getAttribute("style"), "height:420px");
+ assert.deepEqual(calls.filter(([kind]) => kind === "dispose"), [["dispose", old]]);
+ for (const kind of ["process", "highlight", "av", "embed"]) {
+ assert.deepEqual(calls.filter(([name]) => name === kind).map(([, node]) => node), [heading, hidden]);
+ }
+ assert.equal(calls.at(-1)[0], "refresh");
+});
+
+test("fullscreen replay preserves the exact return marker while the canvas is outside the list", () => {
+ const {target, list, host, heading, hidden} = fixture();
+ host.remove();
+ const marker = new ElementFixture();
+ marker.nodeType = 8;
+ marker.nodeValue = "mindmap-view";
+ list.append(marker);
+ assert.equal(target.replay("complete"), true);
+ assert.deepEqual(list.childNodes, [heading, hidden, marker]);
+ assert.equal(target.host, host);
+});
+
+test("equivalent snapshots still invalidate the model source cache after replacing its DOM", () => {
+ const {target, hidden} = fixture();
+ target.snapshot = "same serialized source";
+ let rebound = false;
+ target.refresh = () => {
+ assert.equal(target.snapshot, "");
+ assert.ok(target.list.childNodes.includes(hidden));
+ rebound = true;
+ };
+ assert.equal(target.replay("same serialized source"), true);
+ assert.equal(rebound, true);
+});
+
+test("replay falls back without mutation for another ID, type, inactive map or active editor", () => {
+ for (const state of ["id", "type", "editor", "disposed", "disconnected"]) {
+ const fixtureState = fixture();
+ const {target, list, old, host, calls} = fixtureState;
+ if (state === "id") { fixtureState.setNext(new ElementFixture("other")); }
+ if (state === "type") { fixtureState.setNext(new ElementFixture("map", "NodeList")); }
+ if (state === "editor") { target.activeEditor = {}; }
+ if (state === "disposed") { target.disposed = true; }
+ if (state === "disconnected") { list.isConnected = false; }
+ assert.equal(target.replay("snapshot"), false, state);
+ assert.deepEqual(list.childNodes, [old, host]);
+ assert.ok(!calls.some(([kind]) => kind === "dispose"));
+ }
+});
+
+const renderSource = createSourceFile("render.ts", readFileSync("src/protyle/render/listMindmap/render.ts", "utf8"),
+ ScriptTarget.ES2021, true);
+const names = ["editorRoots", "registerListMindmapRoot", "replayListMindmap", "readListMindmapSelection", "restoreListMindmapFocus"];
+const declarations = renderSource.statements.filter(item => isVariableStatement(item) &&
+ item.declarationList.declarations.some(declaration => names.includes(declaration.name.getText(renderSource))));
+const registry = new Function(compile(declarations.map(item => item.getText(renderSource)).join("\n").replace(/^export /gm, "")) +
+ "; return {registerListMindmapRoot, replayListMindmap, readListMindmapSelection};")();
+
+test("full snapshot permission is bound to each operation and registered source instance", () => {
+ const root = {};
+ const source = new ElementFixture("map");
+ const mirror = new ElementFixture("map");
+ const calls: unknown[] = [];
+ registry.registerListMindmapRoot(root, () => {}, () => {}, (element: unknown, html: string) => {
+ calls.push([element, html]);
+ return element === source;
+ });
+ const operation = {action: "update", id: "map", data: "complete", context: {mindmapSnapshotId: "map"}};
+ assert.equal(registry.replayListMindmap(root, source, operation), true);
+ assert.equal(registry.replayListMindmap(root, mirror, operation), false);
+ assert.equal(registry.replayListMindmap(root, source, {...operation, context: {}}), false);
+ assert.equal(registry.replayListMindmap(root, source, {...operation, id: "other"}), false);
+ assert.equal(calls.length, 2);
+});
+
+test("text selection validation preserves exact block offsets and rejects malformed context", () => {
+ const selection = {undoFocusId: "paragraph-1", undoFocusEndId: "paragraph-2", undoFocusStart: "2",
+ undoFocusEnd: "5", undoFocusIgnoreZWSP: "true", backward: "true"};
+ assert.deepEqual(registry.readListMindmapSelection(JSON.stringify(selection)), selection);
+ for (const value of [undefined, "{", "null", "[]", JSON.stringify({}),
+ JSON.stringify({...selection, undoFocusId: 'x"]'}), JSON.stringify({...selection, undoFocusStart: "-1"}),
+ JSON.stringify({...selection, undoFocusEnd: "1.5"}), JSON.stringify({...selection, backward: true}),
+ JSON.stringify({...selection, undoFocusEndIndex: "Infinity"})]) {
+ assert.equal(registry.readListMindmapSelection(value), undefined);
+ }
+});
+
+test("delayed global history focus targets the exact map instance and expires on a later interaction", () => {
+ let declaration: string;
+ const visit = (item: import("typescript").Node) => {
+ if (isVariableDeclaration(item) && item.name.getText(indexSource) === "restoreFocus" &&
+ item.initializer && isArrowFunction(item.initializer)) {
+ declaration = item.getText(indexSource);
+ }
+ item.forEachChild(visit);
+ };
+ visit(indexSource);
+ assert.ok(declaration);
+ const owner = {};
+ const state = {focusRevision: 0, interactionRevision: 0};
+ const root = {};
+ const mirror = {dataset: {nodeId: "map"}};
+ const source = {dataset: {nodeId: "map"}};
+ const roots = new WeakMap([[owner, state]]);
+ const dependencies = {owner, root, roots, disposed: false, getListMindmapElements: () => [mirror, source],
+ hasMindmapFocusOverlay: () => false, instances: new Map(), refresh: () => {}};
+ const api = new Function(...Object.keys(dependencies), `let pendingFocus;
+ ${compile(`const ${declaration};`)} return {restoreFocus, pending: () => pendingFocus};`)(...Object.values(dependencies));
+ api.restoreFocus("map", ["item"], undefined, source);
+ const pending = api.pending();
+ assert.equal(pending.list, source);
+ assert.equal(pending.guard(), true);
+ state.interactionRevision++;
+ assert.equal(pending.guard(), false, "global history also protects async mounting, without a controller undo guard");
+});
+
+test("transaction replay keeps block selection and runs before folded-source clipping or canvas disposal", () => {
+ const file = createSourceFile("transaction.ts", readFileSync("src/protyle/wysiwyg/transaction.ts", "utf8"), ScriptTarget.ES2021, true);
+ const declaration = file.statements.find(item => isVariableStatement(item) &&
+ item.declarationList.declarations.some(value => value.name.getText(file) === "updateBlock"));
+ assert.ok(declaration);
+ const calls: string[] = [];
+ const source = {parentElement: {}};
+ const saved = {};
+ const dependencies = {
+ getSelection: () => ({rangeCount: 0}), isInEmbedBlock: () => false,
+ captureBlockSelectionModeState: () => { calls.push("capture"); return saved; },
+ replayListMindmap: (_root: unknown, element: unknown, operation: {data: string}) => {
+ assert.equal(element, source);
+ assert.equal(operation.data, "full untrimmed source");
+ calls.push("replay"); return true;
+ },
+ restoreBlockSelectionModeState: (_root: unknown, element: unknown, value: unknown) => {
+ assert.equal(element, source); assert.equal(value, saved); calls.push("restore"); return source;
+ },
+ focusRestoredBlockSelectionMode: () => calls.push("focus"),
+ disposeCustomBlocksInElement: () => assert.fail("must not dispose the preserved canvas"),
+ getVisibleFoldHeadingHTML: () => assert.fail("complete source must not be clipped"),
+ };
+ const update = new Function(...Object.keys(dependencies), compile(declaration.getText(file)) + "; return updateBlock;")(
+ ...Object.values(dependencies));
+ update([source], {wysiwyg: {element: {}}}, {action: "update", id: "map", data: "full untrimmed source",
+ context: {mindmapSnapshotId: "map"}}, true);
+ assert.deepEqual(calls, ["capture", "replay", "restore", "focus"]);
+});
diff --git a/app/src/protyle/render/listMindmap/resizeTransaction.test.ts b/app/src/protyle/render/listMindmap/resizeTransaction.test.ts
index 6464267a38..4470b3b2ca 100644
--- a/app/src/protyle/render/listMindmap/resizeTransaction.test.ts
+++ b/app/src/protyle/render/listMindmap/resizeTransaction.test.ts
@@ -26,7 +26,7 @@ test("resizing uses one source update with both dimensions and retains the exact
}
globalThis.Controller = Controller;`, {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
let title = "Before editing";
- const list = {isConnected: true, parentElement: {classList: {contains: () => false}},
+ const list = {isConnected: true, dataset: {nodeId: "map-resize"}, parentElement: {classList: {contains: () => false}},
style: {width: "50%", height: "40vh", flex: ""},
get outerHTML() { return JSON.stringify({style: this.style, title}); }};
const transactions: {before: string, after: string}[] = [];
@@ -36,7 +36,12 @@ test("resizing uses one source update with both dimensions and retains the exact
getListMindmapSiblingIDs: () => new Map(), normalizeListMindmapSummaryMetadata: () => {},
cleanListMindmapHTML: (html: string) => html,
setBlockHeight: (block: typeof list, height: string) => block.style.height = height,
- updateTransaction: (_owner: unknown, _list: unknown, before: string) => transactions.push({before, after: list.outerHTML}),
+ updateTransaction: (_owner: unknown, _list: unknown, before: string, undoContext: Record<string, string>,
+ additional: {context: Record<string, string>}) => {
+ assert.equal(undoContext.mindmapSnapshotId, list.dataset.nodeId);
+ assert.equal(additional.context.mindmapSnapshotId, list.dataset.nodeId);
+ transactions.push({before, after: list.outerHTML});
+ },
showMessage: (message: string) => assert.fail(message), window: {siyuan: {languages: {listMindmapInvalid: "Invalid"}}}, console,
};
runInNewContext(compiled, context);
diff --git a/app/src/protyle/undo/globalUndo.ts b/app/src/protyle/undo/globalUndo.ts
index ab1d225ab2..4efe3b29a4 100644
--- a/app/src/protyle/undo/globalUndo.ts
+++ b/app/src/protyle/undo/globalUndo.ts
@@ -278,7 +278,7 @@ export const requestUndo = async (protyle: IProtyle, rootID?: string) => {
try {
confirmed = await new Promise<boolean>((resolve) => {
confirmDialog(`⚠️ ${window.siyuan.languages.undo}`,
- `${window.siyuan.languages.undoCrossDocConfirm}<div style="margin-top: 8px;">${names.map(n => `• ${n}`).join("<br>")}</div>`,
+ `<div data-undo-confirmation="true">${window.siyuan.languages.undoCrossDocConfirm}<div style="margin-top: 8px;">${names.map(n => `• ${n}`).join("<br>")}</div></div>`,
() => resolve(true),
() => resolve(false));
});
diff --git a/app/src/protyle/util/selection.ts b/app/src/protyle/util/selection.ts
index 392c571634..5a3ea585c6 100644
--- a/app/src/protyle/util/selection.ts
+++ b/app/src/protyle/util/selection.ts
@@ -667,7 +667,7 @@ 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)) {
+ if (startBlockElement === endBlockElement && restoreListMindmapFocus(protyle.wysiwyg.element, startBlockElement, context)) {
return true;
}
if (context.undoFocusTableCell !== undefined && startBlockElement.getAttribute("data-type") === "NodeTable") {
diff --git a/app/src/protyle/util/undoReplayFocus.test.ts b/app/src/protyle/util/undoReplayFocus.test.ts
index 9f4399cb9c..bae711ff67 100644
--- a/app/src/protyle/util/undoReplayFocus.test.ts
+++ b/app/src/protyle/util/undoReplayFocus.test.ts
@@ -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, registerListMindmapRoot};")(...Object.values(dependencies));
+ "return {TableCutControl, getUndoFocusContext, restoreFocusContext, restoreUndoFocus, focusByRange, focusByWbr, updateBlock, registerListMindmapRoot};")(...Object.values(dependencies));
const editor = document.createElement("div");
editor.className = "protyle-wysiwyg";
editor.contentEditable = "true";
@@ -230,6 +230,34 @@ const browserCases = async (source: string) => {
check.deepEqual(pendingFocus.pop(), {listID: "map", ids: ["text", "child", "map"]});
}
unregisterMindmap();
+ // 脑图保存的文本选区在新建节点编辑器内按原块身份恢复,包含中文、富文本和 UTF-16 emoji 偏移。
+ editor.innerHTML = '<div data-type="NodeMindmap" data-node-id="map"><div data-type="NodeMindmapItem" data-node-id="child">' +
+ paragraph("first", "A😀BC") + paragraph("second", '<span data-type="strong">中文</span>tail') + "</div></div>";
+ const map = editor.firstElementChild;
+ const item = map.firstElementChild;
+ const range = document.createRange();
+ range.setStart(item.firstElementChild.firstElementChild.firstChild, 3);
+ range.setEnd(item.lastElementChild.firstElementChild.firstChild.firstChild, 1);
+ getSelection().removeAllRanges();
+ getSelection().addRange(range);
+ const mindmapSaved = api.getUndoFocusContext(editor, range, true);
+ const fragmentRoot = document.createElement("div");
+ fragmentRoot.className = "protyle-wysiwyg";
+ document.body.append(fragmentRoot);
+ const unregisterText = api.registerListMindmapRoot(editor, noop,
+ (_id: string, ids: string[], selection: Record<string, string>, source: Element) => {
+ check.equal(source, map);
+ check.equal(ids[0], "child");
+ fragmentRoot.innerHTML = item.innerHTML;
+ check.equal(api.restoreFocusContext({wysiwyg: {element: fragmentRoot}}, selection), true);
+ });
+ check.equal(api.restoreUndoFocus(protyle, [{context: {undoFocusId: "child", undoFocusStart: "0", undoFocusEnd: "0",
+ undoFocusMindmapSelection: JSON.stringify(mindmapSaved)}}]), true);
+ check.equal(getSelection().toString(), "BC中");
+ check.equal(getSelection().getRangeAt(0).startOffset, 3);
+ check.ok(fragmentRoot.contains(getSelection().anchorNode));
+ unregisterText();
+ fragmentRoot.remove();
editor.remove();
return "Undo replay focus cases passed";
};
@@ -256,7 +284,7 @@ test("undo replay restores recorded carets across paragraphs, table cells and em
extract("tableCellRichValue.ts", ["TABLE_CELL_RICH_ATTRIBUTE"]) +
extract("selectionFocus.ts", ["getUndoFocusElement"]) +
extract("../render/listMindmap/render.ts", ["editorRoots", "registerListMindmapRoot",
- "restoreListMindmapFocus", "getListMindmapElements"]) +
+ "restoreListMindmapFocus", "getListMindmapElements", "readListMindmapSelection", "replayListMindmap"]) +
extract("../wysiwyg/getBlock.ts", ["getContenteditableElement", "isEndOfBlock", "hasNextSibling",
"isNotEditBlock", "isContainerBlock", "hasPreviousSibling"]) +
extract("../wysiwyg/transaction.ts", ["updateBlock"]) +
diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.ts
index cb91df7232..1da3663f47 100644
--- a/app/src/protyle/wysiwyg/transaction.ts
+++ b/app/src/protyle/wysiwyg/transaction.ts
@@ -92,6 +92,7 @@ import {getProtyleTransactionOwner} from "../runtimeCapabilities";
import {completeTabsListSource, convertTabsList, isTabsListConversion} from "./tabsList";
import {preserveTabTask} from "../util/tabsCopy";
import {waitForPendingTransactions} from "../util/transactionQueue";
+import {replayListMindmap} from "../render/listMindmap/render";
import {
invalidateTrackedRangesByOperations,
type ITrackedRangeInsertion,
@@ -782,6 +783,15 @@ const updateBlock = (updateElements: Element[], protyle: IProtyle, operation: Ex
if (!item.parentElement) {
return;
}
+ // 完整脑图快照保留画布实例;必须先于折叠正文裁剪和整个视图的销毁。
+ if (isUndo && operation.context?.mindmapSnapshotId === operation.id) {
+ const selectionModeState = captureBlockSelectionModeState(item);
+ if (replayListMindmap(protyle.wysiwyg.element, item, operation)) {
+ focusRestoredBlockSelectionMode(restoreBlockSelectionModeState(protyle.wysiwyg.element, item,
+ selectionModeState));
+ return;
+ }
+ }
let isRangeBlock = false;
if (range && item.contains(range.startContainer)) {
isRangeBlock = true;