Skip to content

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

:sparkles: Support undo and redo controls in mind maps https://github.com/siyuan-note/siyuan/issues/20854

Daniel260a24029889
diff --git a/app/src/assets/scss/protyle/_mindmap-view.scss b/app/src/assets/scss/protyle/_mindmap-view.scss
index 345c9daf0e..7f8acd7ff2 100644
--- a/app/src/assets/scss/protyle/_mindmap-view.scss
+++ b/app/src/assets/scss/protyle/_mindmap-view.scss
@@ -130,6 +130,18 @@
padding: 4px;
}
+ &--history &__toolbar-group {
+ gap: 3px;
+ }
+
+ &--history &__toolbar {
+ box-sizing: border-box;
+ }
+
+ &--history &__spacer {
+ display: none;
+ }
+
&__spacer {
flex: 1;
}
diff --git a/app/src/protyle/render/listMindmap/focus.test.ts b/app/src/protyle/render/listMindmap/focus.test.ts
index 39ad5f99a5..457303a959 100644
--- a/app/src/protyle/render/listMindmap/focus.test.ts
+++ b/app/src/protyle/render/listMindmap/focus.test.ts
@@ -8,8 +8,9 @@ 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", "edit"].includes(item.name.getText(source)));
-assert.equal(methods.length, 5);
+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);
let editorUndo = "";
const visit = (item: import("typescript").Node) => {
if (isPropertyAssignment(item) && item.name.getText(source) === "onUndo" &&
@@ -26,6 +27,38 @@ const compiled = transpileModule(`class Controller {
}
globalThis.Controller = Controller;`, {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
+test("canvas history follows embedded source documents, local stacks, busy state and subscription lifetime", () => {
+ const listeners = new Map<string, () => void>();
+ const states: unknown[] = [];
+ let editable = true;
+ let embedded = true;
+ const root = {undoPending: false};
+ const owner = {block: {rootID: "document"}, lite: false, undo: {undoStack: [] as unknown[], redoStack: [] as unknown[]}};
+ const context: any = {roots: new WeakMap([[owner, root]]), canEdit: () => editable,
+ getUndoStateSnapshot: (id: string) => ({canUndo: id === "source", canRedo: false, pending: false}),
+ hasUndoStateMirror: () => true,
+ subscribeUndoState: (id: string, listener: () => void) => {
+ listeners.set(id, listener); listener();
+ return () => listeners.delete(id);
+ }};
+ runInNewContext(compiled, context);
+ const target = Object.assign(new context.Controller(), {owner,
+ list: {closest: () => embedded ? {dataset: {rootId: "source"}} : null},
+ view: {setUndoState: (state: unknown) => states.push(JSON.parse(JSON.stringify(state)))}});
+ target.bindUndoState();
+ assert.deepEqual([...listeners.keys()], ["source"]);
+ assert.deepEqual(states.at(-1), {canUndo: true, canRedo: false, pending: false});
+ root.undoPending = true; listeners.get("source")();
+ assert.deepEqual(states.at(-1), {canUndo: true, canRedo: false, pending: true});
+ root.undoPending = false; embedded = false; target.bindUndoState();
+ assert.deepEqual([...listeners.keys()], ["document"]);
+ assert.deepEqual(states.at(-1), {canUndo: false, canRedo: false, pending: false});
+ owner.lite = true; owner.undo.redoStack.push({}); target.refreshUndoState();
+ assert.deepEqual(states.at(-1), {canUndo: false, canRedo: true, pending: false});
+ editable = false; target.bindUndoState();
+ assert.equal(listeners.size, 0);
+});
+
test("new mind map nodes become selected before editing", async () => {
const steps: string[] = [];
const item = {dataset: {nodeId: "new"}, classList: {replace: () => {}}};
diff --git a/app/src/protyle/render/listMindmap/history.test.ts b/app/src/protyle/render/listMindmap/history.test.ts
new file mode 100644
index 0000000000..47bbc30298
--- /dev/null
+++ b/app/src/protyle/render/listMindmap/history.test.ts
@@ -0,0 +1,136 @@
+import * as assert from "node:assert/strict";
+import {execFile} from "node:child_process";
+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";
+import {tmpdir} from "node:os";
+import * as path from "node:path";
+import {promisify} from "node:util";
+import test from "node:test";
+import {ScriptTarget, transpileModule} from "typescript";
+
+const browserCases = async (source: string, css: string) => {
+ const check = require("node:assert/strict");
+ const style = document.createElement("style"); style.textContent = css; document.head.append(style);
+ const api = new Function("Constants", "mathRender", "tabsRender", "destroyTabsRender", source +
+ ";return {ListMindmapView, readListMindmap};")(
+ {CUSTOM_SY_LIST_MINDMAP_DATA: "custom-sy-list-mindmap-data"}, () => {}, () => {}, () => {});
+ const lute = Lute.New(); lute.SetProtyleWYSIWYG(true);
+ const settle = async () => {
+ for (let i = 0; i < 3; i++) { await new Promise<void>(resolve => requestAnimationFrame(() => resolve())); }
+ };
+ for (const width of [240, 320, 700]) {
+ for (const scale of [1, .75]) {
+ document.body.className = width < 700 ? "body--android" : "body--windows";
+ const outer = document.createElement("div");
+ outer.style.cssText = `position:absolute;left:20px;top:20px;width:${width}px;height:360px;overflow:auto;` +
+ `transform:scale(${scale});transform-origin:top left`;
+ const host = document.createElement("div");
+ host.style.cssText = "--mindmap-view-height:1000px;--b3-border-color:#888";
+ outer.append(host); document.body.append(outer);
+ const holder = document.createElement("div"); holder.innerHTML = lute.Md2BlockDOM("- Root\n - Node\n");
+ const model = api.readListMindmap(holder.firstElementChild);
+ const original = holder.innerHTML;
+ let undo = 0;
+ let redo = 0;
+ let finishAllowed = true;
+ let release: () => void;
+ const view = new api.ListMindmapView({host, model, onExit() {}, onSettingsMenu() {}, onExpandLevelMenu() {},
+ finishEdit: () => finishAllowed,
+ onUndo: () => { undo++; return new Promise<void>(resolve => release = resolve); },
+ onRedo: () => { redo++; },
+ });
+ await settle();
+ view.setInteractionActive(true); view.clearSelection();
+ outer.scrollTop = 220; await settle();
+ const toolbar = host.querySelector<HTMLElement>(".mindmap-view__toolbar");
+ const button = (key: string) => toolbar.querySelector<HTMLButtonElement>(`[data-type="${key}"]`);
+ let stage = "initial";
+ const visible = () => {
+ const rect = toolbar.getBoundingClientRect();
+ const clip = view.fullscreenMarker ? {left: 0, top: 0, right: innerWidth, bottom: innerHeight} : outer.getBoundingClientRect();
+ check.equal(getComputedStyle(toolbar).visibility, "visible",
+ `${stage}: toolbar ${JSON.stringify(rect.toJSON())}, clip ${JSON.stringify(clip)}, style ${toolbar.style.cssText}`);
+ check.ok(rect.top >= clip.top - 1 && rect.bottom <= clip.bottom + 1);
+ for (const key of ["undo", "redo"]) {
+ const bounds = button(key).getBoundingClientRect();
+ check.ok(bounds.left >= clip.left - 1 && bounds.right <= clip.right + 1,
+ `${key} fits the ${width}px canvas at scale ${scale}`);
+ }
+ };
+ visible();
+ check.equal(button("undo").disabled, true); check.equal(button("redo").disabled, true);
+ view.setUndoState({canUndo: true, canRedo: false});
+ const bounds = button("undo").getBoundingClientRect();
+ await require("electron").ipcRenderer.invoke("mindmap-history-touch", [
+ {type: "touchStart", touchPoints: [{id: 1, x: (bounds.left + bounds.right) / 2, y: (bounds.top + bounds.bottom) / 2}]},
+ {type: "touchEnd", touchPoints: []},
+ ]);
+ await settle();
+ check.equal(undo, 1, "canvas undo works without a selected node or a text editor");
+ check.equal(button("undo").disabled, true); check.equal(button("redo").disabled, true);
+ button("undo").click(); await settle(); check.equal(undo, 1, "pending history cannot repeat");
+ check.ok(!document.activeElement.matches("input, textarea, [contenteditable='true']"), "undo does not focus text input");
+ check.equal(outer.scrollTop, 220, "history activation preserves document scroll position");
+ view.setUndoState({canUndo: false, canRedo: true}); release(); await settle();
+ check.equal(button("undo").disabled, true); check.equal(button("redo").disabled, false);
+ button("redo").focus();
+ check.equal(document.activeElement, button("redo"));
+ await require("electron").ipcRenderer.invoke("mindmap-history-key"); await settle();
+ check.equal(redo, 1, "the history control supports keyboard activation");
+ view.setUndoState({canUndo: true, canRedo: false}); finishAllowed = false;
+ button("undo").click(); await settle();
+ check.equal(undo, 1, "failed pending edits prevent history execution");
+ check.equal(button("undo").disabled, false, "canceled execution releases the local busy state");
+ stage = "short";
+ outer.style.height = "60px"; outer.dispatchEvent(new Event("scroll")); await settle(); visible();
+ outer.style.height = "360px"; outer.dispatchEvent(new Event("scroll")); await settle();
+ const scrollTop = outer.scrollTop;
+ stage = "fullscreen";
+ view.enterFullscreen(); await settle(); visible();
+ view.exitFullscreen(); await settle(); check.equal(outer.scrollTop, scrollTop); visible();
+ view.setReadOnly(true); await settle();
+ check.equal(button("undo"), null); check.equal(button("redo"), null);
+ view.setReadOnly(false); await settle(); visible();
+ check.equal(button("undo").disabled, false);
+ check.equal(holder.innerHTML, original, "history controls never write document metadata");
+ view.destroy(); outer.remove();
+ }
+ }
+ return "Mindmap history controls passed";
+};
+
+test("desktop and mobile canvas history stays visible and supports touch, keyboard, pending and read-only states", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY, timeout: 60000,
+}, async () => {
+ const source = ["../av/richTextValue.ts", "summary.ts", "connectors.ts", "appearance.ts", "model.ts", "fold.ts", "routing.ts", "pan.ts", "view.ts"]
+ .map(file => transpileModule(readFileSync(path.join(__dirname, file), "utf8")
+ .replace(/^import [\s\S]*?;\r?\n/gm, "").replace(/^export /gm, ""), {compilerOptions: {target: ScriptTarget.ES2021}}).outputText).join("\n");
+ const css = ["business/_block.scss", "business/_color.scss", "component/_svg.scss", "protyle/_mindmap-view.scss"]
+ .map(file => require("sass").compile(path.resolve(__dirname, "../../../assets/scss", file),
+ {logger: require("sass").Logger.silent}).css).join("\n");
+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-mindmap-history-"));
+ const script = path.join(temporary, "run.cjs");
+ const browserSource = transpileModule(`(${browserCases.toString()})`, {compilerOptions: {target: ScriptTarget.ES2021}})
+ .outputText.trim().replace(/^"use strict";\s*/, "").replace(/;$/, "");
+ writeFileSync(script, `const {app,BrowserWindow,ipcMain}=require("electron");
+app.setPath("userData",${JSON.stringify(path.join(temporary, "profile"))});app.commandLine.appendSwitch("disable-gpu");
+app.whenReady().then(async()=>{const win=new BrowserWindow({show:false,width:1000,height:800,
+webPreferences:{offscreen:true,nodeIntegration:true,contextIsolation:false}});
+ipcMain.handle("mindmap-history-touch",async(_event,events)=>{
+if(!win.webContents.debugger.isAttached())win.webContents.debugger.attach("1.3");
+await win.webContents.debugger.sendCommand("Emulation.setTouchEmulationEnabled",{enabled:true});
+try{for(const event of events){await win.webContents.debugger.sendCommand("Input.dispatchTouchEvent",event);await new Promise(resolve=>setTimeout(resolve,30));}}
+finally{await win.webContents.debugger.sendCommand("Emulation.setTouchEmulationEnabled",{enabled:false});}});
+ipcMain.handle("mindmap-history-key",()=>{win.webContents.sendInputEvent({type:"keyDown",keyCode:"Return"});win.webContents.sendInputEvent({type:"char",keyCode:"\\r"});win.webContents.sendInputEvent({type:"keyUp",keyCode:"Return"});});
+try{await win.loadURL("data:text/html,<html><body></body></html>");
+await win.webContents.executeJavaScript(require("fs").readFileSync(${JSON.stringify(path.resolve(__dirname, "../../../../stage/protyle/js/lute/lute.min.js"))},"utf8"));
+console.log(await win.webContents.executeJavaScript(${JSON.stringify(`const __name=value=>value;(${browserSource})(${JSON.stringify(source)},${JSON.stringify(css)})`)}));
+win.destroy();app.exit(0);}catch(error){console.error(error);win.destroy();app.exit(1);}});`, "utf8");
+ const env = {...process.env}; delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ const result = await promisify(execFile)(require("electron") as unknown as string, [script], {env, timeout: 55000, windowsHide: true});
+ assert.match(result.stdout, /Mindmap history controls passed/);
+ } finally {
+ assert.equal(path.dirname(path.resolve(temporary)), path.resolve(tmpdir()));
+ rmSync(temporary, {recursive: true, force: true});
+ }
+});
diff --git a/app/src/protyle/render/listMindmap/index.ts b/app/src/protyle/render/listMindmap/index.ts
index 28d3b09031..1bdd12e1ed 100644
--- a/app/src/protyle/render/listMindmap/index.ts
+++ b/app/src/protyle/render/listMindmap/index.ts
@@ -58,7 +58,7 @@ import {getListMindmapConnectorMenuItem} from "./connectorMenu";
import {getDefaultListMindmapConnectorStyle, setDefaultListMindmapConnectorStyle} from "./preferences";
import {assignListMindmapBranchColors, getListMindmapAppearanceMenu} from "./appearance";
import {getEmbedChildOperationContext} from "../../wysiwyg/getBlock";
-import {requestRedo, requestUndo} from "../../undo/globalUndo";
+import {getUndoStateSnapshot, hasUndoStateMirror, initMirror, requestRedo, requestUndo, subscribeUndoState} from "../../undo/globalUndo";
import {buildBlockDOMClipboardData} from "../../util/blockDOMClipboard";
import {buildWebClipboardHTML, getTextSiyuanFromTextHTML} from "../../util/clipboardData";
import {readClipboard, writeClipboardData} from "../../util/compatibility";
@@ -68,7 +68,7 @@ import {canCutMindmapBranches, copyMindmapBranches, pasteMindmapBranches, readMi
const roots = new WeakMap<IProtyle, {refresh: () => void, mountNew: (list: HTMLElement) => void,
restoreFocus: (listID: string, candidateIDs: string[], selection?: Record<string, string>, source?: HTMLElement) => void, focusRevision: number,
- interactionRevision?: number, focusGuard?: () => boolean, undoPending?: boolean,
+ interactionRevision?: number, focusGuard?: () => boolean, undoPending?: boolean, refreshUndoState?: () => void,
finish: () => Promise<boolean>, destroy: () => void}>();
const hasMindmapFocusOverlay = () => {
@@ -181,6 +181,8 @@ class ListMindmapController {
private taskChanges: Promise<void> = Promise.resolve();
private unregisterVisible?: () => void;
private resize: ReturnType<typeof bindListMindmapResize>;
+ private undoRootID?: string;
+ private unsubscribeUndoState?: () => void;
constructor(owner: IProtyle, list: HTMLElement) {
this.owner = owner;
@@ -582,6 +584,7 @@ class ListMindmapController {
metadata.summaries = metadata.summaries?.filter(item => item.id !== id) || [];
}),
});
+ this.bindUndoState();
list.dataset.mindmapViewRendered = "true";
this.resize = bindListMindmapResize({
block: list, host: this.host,
@@ -996,6 +999,7 @@ class ListMindmapController {
if (root) {
root.undoPending = true;
root.focusGuard = guard;
+ root.refreshUndoState?.();
}
try {
if (!canEdit(this.owner, this.list) || (this.activeEditor && !await this.activeEditor.finish())) {
@@ -1038,6 +1042,7 @@ class ListMindmapController {
if (root?.focusGuard === guard) {
root.focusGuard = undefined;
root.undoPending = false;
+ root.refreshUndoState?.();
}
}
}
@@ -1090,8 +1095,37 @@ class ListMindmapController {
return this.activeEditor ? this.activeEditor.finish() : true;
}
+ public refreshUndoState() {
+ if (this.disposed) {
+ return;
+ }
+ const state = getUndoStateSnapshot(this.undoRootID);
+ const undo = this.owner.undo;
+ if (this.owner.lite && undo && "undoStack" in undo && "redoStack" in undo &&
+ Array.isArray(undo.undoStack) && Array.isArray(undo.redoStack)) {
+ state.canUndo = undo.undoStack.length > 0;
+ state.canRedo = undo.redoStack.length > 0;
+ }
+ this.view.setUndoState({...state, pending: state.pending || !!roots.get(this.owner)?.undoPending});
+ }
+
+ private bindUndoState() {
+ const rootID = canEdit(this.owner, this.list) ?
+ this.list.closest<HTMLElement>(".protyle-wysiwyg__embed")?.dataset.rootId || this.owner.block.rootID : undefined;
+ if (rootID !== this.undoRootID) {
+ this.unsubscribeUndoState?.();
+ this.undoRootID = rootID;
+ this.unsubscribeUndoState = rootID ? subscribeUndoState(rootID, () => this.refreshUndoState()) : undefined;
+ if (rootID && !this.owner.lite && !hasUndoStateMirror(rootID)) {
+ void initMirror(rootID).catch(error => console.error(error));
+ }
+ }
+ this.refreshUndoState();
+ }
+
public refresh() {
this.view.setReadOnly(!canEdit(this.owner, this.list));
+ this.bindUndoState();
syncListMindmapHeight(this.list, this.host);
this.resize.refresh();
const snapshot = cleanListMindmapHTML(this.list.outerHTML);
@@ -1108,6 +1142,7 @@ class ListMindmapController {
return;
}
this.disposed = true;
+ this.unsubscribeUndoState?.();
const restoreFocus = this.host.contains(document.activeElement) && this.list.isConnected &&
this.list.dataset.type !== "NodeMindmap" && this.list.getAttribute(Constants.CUSTOM_SY_LIST_MINDMAP) !== "1";
this.activeEditor?.destroy();
@@ -1361,7 +1396,8 @@ export const initListMindmaps = (owner: IProtyle) => {
newlyCreated.add(list);
refresh();
}
- }, restoreFocus, focusRevision: 0, interactionRevision: 0, destroy: () => {
+ }, restoreFocus, refreshUndoState: () => instances.forEach(instance => instance.refreshUndoState()),
+ focusRevision: 0, interactionRevision: 0, destroy: () => {
disposed = true;
interactions.abort();
unregister();
diff --git a/app/src/protyle/render/listMindmap/model.test.ts b/app/src/protyle/render/listMindmap/model.test.ts
index e53f85bc56..becbceb0ba 100644
--- a/app/src/protyle/render/listMindmap/model.test.ts
+++ b/app/src/protyle/render/listMindmap/model.test.ts
@@ -389,6 +389,9 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
CUSTOM_SY_LIST_MINDMAP: "custom-sy-list-mindmap", CUSTOM_SY_LIST_MINDMAP_DATA: "custom-sy-list-mindmap-data"},
isProtyleListItemFragment: () => false, isHiddenTabContent: () => false,
isMobile: () => mobile, waitForPendingTransactions: async () => {},
+ getUndoStateSnapshot: () => ({canUndo: true, canRedo: true, pending: false}),
+ hasUndoStateMirror: () => true,
+ subscribeUndoState: (_rootID: string, listener: () => void) => { listener(); return () => {}; },
isEncryptedBox: () => false,
setStorageVal: () => check.fail("Embedded previews cannot persist viewport positions"),
fetchSyncPost: async () => ({code: 0, data: {dom: full}}),
@@ -1822,8 +1825,9 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
check.equal(view.getContentHost(alpha).firstElementChild, editorMarker);
view.setEditing();
view.update(api.readListMindmap(list));
- check.equal(host.querySelector('[aria-label="undo"]'), null);
- check.equal(host.querySelector('[aria-label="redo"]'), null);
+ check.equal(host.querySelector<HTMLButtonElement>('[aria-label="undo"]').disabled, true,
+ "the canvas exposes undo while an empty history keeps it disabled");
+ check.equal(host.querySelector<HTMLButtonElement>('[aria-label="redo"]').disabled, true);
check.equal(undo, 0);
check.equal(redo, 0);
finishAllowed = false;
diff --git a/app/src/protyle/render/listMindmap/view.ts b/app/src/protyle/render/listMindmap/view.ts
index 4a62311c34..b0d33298f7 100644
--- a/app/src/protyle/render/listMindmap/view.ts
+++ b/app/src/protyle/render/listMindmap/view.ts
@@ -70,8 +70,8 @@ export interface ListMindmapViewOptions {
onTabTaskMenu?: (id: string, itemId: string, anchor: HTMLElement) => void;
isTaskCycle?: (event: KeyboardEvent) => boolean;
isTaskCompletionToggle?: (event: KeyboardEvent) => boolean;
- onUndo?: () => void;
- onRedo?: () => void;
+ onUndo?: () => void | Promise<void>;
+ onRedo?: () => void | Promise<void>;
onNodeStyle?: (id: string, patch: Partial<ListMindmapNodeStyle>) => void;
onNodesStyle?: (ids: string[], patch: Partial<ListMindmapNodeStyle>) => void;
onNodeWidths?: (widths: {id: string, width: number}[], expected: string) => Promise<boolean>;
@@ -139,6 +139,8 @@ export class ListMindmapView {
widths: {id: string, width: number}[], baseWidth: number, slider: number, preview: boolean,
};
private widthPending = false;
+ private undoState = {canUndo: false, canRedo: false, pending: false};
+ private historyPending = false;
private inspectorFrame = 0;
private revealInspectorHost = false;
private readonly zoomLabel: HTMLSpanElement;
@@ -430,7 +432,7 @@ export class ListMindmapView {
this.disposers.push(() => target.removeEventListener(event, handler, options));
}
- private makeButton(key: string, icon: string, action: (event: MouseEvent) => void, className = "") {
+ private makeButton(key: string, icon: string, action: (event: MouseEvent) => void, className = "", finish = true) {
const button = createElement("button", "block__icon block__icon--show " + className);
button.type = "button";
button.setAttribute("aria-label", this.label(key));
@@ -440,7 +442,11 @@ export class ListMindmapView {
}
button.addEventListener("click", (event) => {
event.stopPropagation();
- this.finishThen(() => action(event));
+ if (finish) {
+ this.finishThen(() => action(event));
+ } else {
+ action(event);
+ }
});
return button;
}
@@ -548,6 +554,48 @@ export class ListMindmapView {
return this.locked;
}
+ public setUndoState(state: {canUndo: boolean, canRedo: boolean, pending?: boolean}) {
+ if (this.destroyed) {
+ return;
+ }
+ this.undoState = {...state, pending: !!state.pending};
+ this.updateUndoControls();
+ }
+
+ private updateUndoControls() {
+ for (const key of ["undo", "redo"] as const) {
+ const button = this.buttons.get(key);
+ if (button) {
+ button.disabled = this.readOnly || this.historyPending || this.undoState.pending ||
+ !(key === "undo" ? this.undoState.canUndo : this.undoState.canRedo);
+ }
+ }
+ }
+
+ private async runHistory(redo: boolean) {
+ if (this.readOnly || this.historyPending || this.buttons.get(redo ? "redo" : "undo")?.disabled) {
+ return;
+ }
+ this.historyPending = true;
+ this.updateUndoControls();
+ try {
+ this.closeInspectorPanel();
+ this.finishSummaryEdit?.(true);
+ this.finishRelationEdit?.(true);
+ const finished = await this.options.finishEdit?.();
+ if (finished !== false && !this.destroyed && !this.readOnly) {
+ await (redo ? this.options.onRedo?.() : this.options.onUndo?.());
+ }
+ } catch (error) {
+ console.error(error);
+ } finally {
+ this.historyPending = false;
+ if (!this.destroyed) {
+ this.updateUndoControls();
+ }
+ }
+ }
+
private activatePointer = (event: PointerEvent) => {
const target = event.target as Element;
if (this.pinching || target.closest(".mindmap-view") !== this.options.host ||
@@ -627,9 +675,13 @@ export class ListMindmapView {
}
private createToolbar() {
+ this.toolbar.style.top = this.toolbar.style.left = this.toolbar.style.right = this.toolbar.style.width =
+ this.toolbar.style.visibility = "";
+ const history = !this.readOnly && !!(this.options.onUndo || this.options.onRedo);
+ this.options.host.classList.toggle("mindmap-view--history", history);
const controls = createElement("div", "mindmap-view__toolbar-group");
- const add = (id: string, key: string, icon: string, action: () => void, nodeAction = false) => {
- const button = this.makeButton(key, icon, action);
+ const add = (id: string, key: string, icon: string, action: () => void, nodeAction = false, finish = true) => {
+ const button = this.makeButton(key, icon, action, "", finish);
this.buttons.set(id, button);
if (nodeAction) {
button.className = "color__square";
@@ -657,6 +709,15 @@ export class ListMindmapView {
add("fullscreen", "fullscreen", "iconFullscreen", () => this.toggleFullscreen());
};
this.toolbar.append(createElement("span", "mindmap-view__spacer fn__flex-1"), controls);
+ if (history) {
+ for (const [key, icon] of [["undo", "iconUndo"], ["redo", "iconRedo"]] as const) {
+ if (key === "undo" ? this.options.onUndo : this.options.onRedo) {
+ add(key, key, icon, () => void this.runHistory(key === "redo"), false, false);
+ this.buttons.get(key).dataset.type = key;
+ }
+ }
+ this.updateUndoControls();
+ }
this.levelSelect = undefined;
this.options.host.classList.toggle("mindmap-view--locked", this.locked);
add("lock", this.locked ? "listMindmapUnlock" : "listMindmapLock", this.locked ? "iconLock" : "iconUnlock", () => {
@@ -768,6 +829,7 @@ export class ListMindmapView {
this.levelSelect.parentElement.hidden = expand.hidden;
}
}
+ this.queueInspectorLayout();
}
private togglePanning(value = !this.panning) {
@@ -3654,7 +3716,8 @@ export class ListMindmapView {
}
private queueInspectorLayout(reveal = false) {
- if (this.destroyed || this.inspector.hidden && !reveal) {
+ const history = !this.readOnly && !!(this.options.onUndo || this.options.onRedo);
+ if (this.destroyed || this.inspector.hidden && !reveal && !history) {
return;
}
this.revealInspectorHost ||= reveal;
@@ -3665,7 +3728,11 @@ export class ListMindmapView {
this.inspectorFrame = 0;
const revealHost = this.revealInspectorHost;
this.revealInspectorHost = false;
- if (this.destroyed || this.inspector.hidden || this.readOnly) {
+ if (this.destroyed) {
+ return;
+ }
+ this.positionToolbar();
+ if (this.inspector.hidden || this.readOnly) {
return;
}
if (revealHost && !this.pointer && !this.pinching && !this.fullscreenMarker) {
@@ -3714,11 +3781,28 @@ export class ListMindmapView {
this.inspector.style.bottom = `${this.options.host.clientTop + this.options.host.clientHeight -
(visible.bottom - host.top) / scaleY + 8}px`;
// 可见条带放不下操作栏时保留选择,滚动回足够的空间后恢复显示。
+ const toolbarHeight = !this.readOnly && (this.options.onUndo || this.options.onRedo) ? this.toolbar.offsetHeight + 4 : 0;
this.inspector.style.visibility = width <= 0 ||
- (visible.bottom - visible.top) / scaleY < this.inspector.offsetHeight + 16 ? "hidden" : "";
+ (visible.bottom - visible.top) / scaleY < toolbarHeight + this.inspector.offsetHeight + 16 ? "hidden" : "";
this.positionInspectorPanel();
}
+ private positionToolbar() {
+ if (this.readOnly || !(this.options.onUndo || this.options.onRedo)) {
+ return;
+ }
+ const host = this.options.host.getBoundingClientRect();
+ const visible = this.getVisibleViewportBounds();
+ const scaleX = host.width / this.options.host.offsetWidth || 1;
+ const scaleY = host.height / this.options.host.offsetHeight || 1;
+ this.toolbar.style.left = `${(visible.left - host.left) / scaleX - this.options.host.clientLeft}px`;
+ this.toolbar.style.right = "auto";
+ this.toolbar.style.width = `${Math.max(0, (visible.right - visible.left) / scaleX)}px`;
+ this.toolbar.style.top = `${Math.max(0, (visible.top - host.top) / scaleY - this.options.host.clientTop)}px`;
+ this.toolbar.style.visibility = visible.right <= visible.left ||
+ (visible.bottom - visible.top) / scaleY < this.toolbar.offsetHeight + 8 ? "hidden" : "";
+ }
+
private positionInspectorPanel() {
if (this.destroyed || this.inspectorPopover.hidden || !this.inspectorPanel) {
return;
diff --git a/app/src/protyle/undo/globalUndo.test.ts b/app/src/protyle/undo/globalUndo.test.ts
new file mode 100644
index 0000000000..8a91f27365
--- /dev/null
+++ b/app/src/protyle/undo/globalUndo.test.ts
@@ -0,0 +1,89 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import test from "node:test";
+import {runInNewContext} from "node:vm";
+import {ScriptTarget, transpileModule} from "typescript";
+
+const compiled = transpileModule(readFileSync("src/protyle/undo/globalUndo.ts", "utf8")
+ .replace(/^import [\s\S]*?;\r?\n/gm, "").replace(/^export /gm, "") +
+ ";globalThis.api = {markMirror, getMirror, getUndoStateSnapshot, subscribeUndoState, syncMirrorFromBroadcast, initMirror, requestUndo, requestRedo};",
+{compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
+
+const load = (extra: Record<string, unknown> = {}) => {
+ const context: any = {console, Constants: {SIYUAN_APPID: "test"},
+ getMobileToolbarProtyle: (): undefined => undefined, getCurrentEditor: (): undefined => undefined,
+ getSelection: () => ({rangeCount: 0}), waitForPendingTransactions: async () => {}, ...extra};
+ runInNewContext(compiled, context);
+ return context.api as typeof import("./globalUndo");
+};
+const plain = (value: unknown) => JSON.parse(JSON.stringify(value));
+
+test("history subscriptions follow their document, include broadcasts and dispose independently", () => {
+ const api = load();
+ const first: unknown[] = [];
+ const second: unknown[] = [];
+ const stopFirst = api.subscribeUndoState("first", state => first.push(plain(state)));
+ const stopSecond = api.subscribeUndoState("second", state => second.push(plain(state)));
+ api.markMirror("first", {canUndo: true});
+ assert.deepEqual(first.at(-1), {canUndo: true, canRedo: false, pending: false});
+ assert.equal(second.length, 1);
+ api.syncMirrorFromBroadcast({second: {canUndo: false, canRedo: true}});
+ assert.deepEqual(second.at(-1), {canUndo: false, canRedo: true, pending: false});
+ stopFirst();
+ const replacement: unknown[] = [];
+ const stopReplacement = api.subscribeUndoState("first", state => replacement.push(plain(state)));
+ stopFirst();
+ api.markMirror("first", {canRedo: true});
+ assert.equal(first.length, 2);
+ assert.deepEqual(replacement.at(-1), {canUndo: true, canRedo: true, pending: false});
+ stopSecond(); stopReplacement();
+ api.markMirror("first", {canUndo: false});
+ assert.equal(replacement.length, 2);
+});
+
+test("initial history loads are shared and do not overwrite newer local or broadcast state", async () => {
+ let reply: (response: unknown) => void;
+ let finish: () => void;
+ let requests = 0;
+ const api = load({fetchPost: async (_url: string, _data: unknown, callback: (value: unknown) => void) => {
+ requests++; reply = callback; await new Promise<void>(resolve => finish = resolve);
+ }});
+ const states: unknown[] = [];
+ api.subscribeUndoState("doc", state => states.push(plain(state)));
+ const first = api.initMirror("doc");
+ const second = api.initMirror("doc");
+ assert.equal(first, second);
+ api.markMirror("doc", {canUndo: true, canRedo: false});
+ reply({data: {canUndo: false, canRedo: true}}); finish();
+ assert.equal(await first, true);
+ assert.equal(requests, 1);
+ assert.deepEqual(states.at(-1), {canUndo: true, canRedo: false, pending: false});
+});
+
+test("undo and redo publish pending state across documents and release it after completion or errors", async () => {
+ for (const redo of [false, true]) {
+ for (const fail of [false, true]) {
+ let release: () => void;
+ let requests = 0;
+ const api = load({waitForPendingTransactions: () => new Promise<void>(resolve => release = resolve),
+ fetchPost: async (url: string, _data: unknown, reply: (response: unknown) => void) => {
+ requests++;
+ if (fail) { throw new Error("request failed"); }
+ reply({data: url.endsWith("undoState") ? {canUndo: true, canRedo: true, peekMutatedRootIDs: []} :
+ {canUndo: redo, canRedo: !redo, undoOperations: [], doOperations: []}});
+ }});
+ const states: unknown[] = [];
+ api.subscribeUndoState("other", state => states.push(plain(state)));
+ const owner = {block: {rootID: "doc"}} as IProtyle;
+ const pending = (redo ? api.requestRedo : api.requestUndo)(owner, "doc");
+ assert.equal(api.getUndoStateSnapshot("doc").pending, true);
+ assert.deepEqual(states.at(-1), {canUndo: false, canRedo: false, pending: true});
+ await api.requestUndo(owner, "other");
+ assert.equal(requests, 0, "a second history command cannot start while the first is waiting");
+ release();
+ if (fail) { await assert.rejects(pending, /request failed/); } else { await pending; }
+ assert.equal(api.getUndoStateSnapshot("doc").pending, false);
+ assert.deepEqual(states.at(-1), {canUndo: false, canRedo: false, pending: false});
+ }
+ }
+});
diff --git a/app/src/protyle/undo/globalUndo.ts b/app/src/protyle/undo/globalUndo.ts
index 9c9095fecd..37e248d589 100644
--- a/app/src/protyle/undo/globalUndo.ts
+++ b/app/src/protyle/undo/globalUndo.ts
@@ -25,10 +25,49 @@ interface IUndoStateMirror {
const undoStateMirror = new Map<string, IUndoStateMirror>();
const undoStateInitializers = new Map<string, Promise<boolean>>();
let isUndoing = false; // 防重入:撤销/重做进行中忽略后续触发
+const undoStateListeners = new Map<string, Set<(state: ReturnType<typeof getUndoStateSnapshot>) => void>>();
+
+export const getUndoStateSnapshot = (rootID: string) => ({...getMirror(rootID), pending: isUndoing});
+
+const notifyUndoState = (rootID?: string) => {
+ const notify = (id: string) => {
+ const state = getUndoStateSnapshot(id);
+ undoStateListeners.get(id)?.forEach(listener => {
+ try {
+ listener(state);
+ } catch (error) {
+ console.error(error);
+ }
+ });
+ };
+ if (rootID) {
+ notify(rootID);
+ } else {
+ undoStateListeners.forEach((_listeners, id) => notify(id));
+ }
+};
+
+// 画布等不依赖文字选区的入口订阅同一份文档历史状态,销毁视图时解除订阅。
+export const subscribeUndoState = (rootID: string, listener: (state: ReturnType<typeof getUndoStateSnapshot>) => void) => {
+ let listeners = undoStateListeners.get(rootID);
+ if (!listeners) {
+ listeners = new Set();
+ undoStateListeners.set(rootID, listeners);
+ }
+ listeners.add(listener);
+ listener(getUndoStateSnapshot(rootID));
+ return () => {
+ listeners.delete(listener);
+ if (!listeners.size && undoStateListeners.get(rootID) === listeners) {
+ undoStateListeners.delete(rootID);
+ }
+ };
+};
export const markMirror = (rootID: string, state: Partial<IUndoStateMirror>) => {
const cur = undoStateMirror.get(rootID) || {canUndo: false, canRedo: false};
undoStateMirror.set(rootID, {...cur, ...state});
+ notifyUndoState(rootID);
};
export const getMirror = (rootID: string): IUndoStateMirror => {
@@ -77,7 +116,7 @@ export const syncMirrorFromBroadcast = (undoState: { [rootID: string]: { canUndo
return;
}
Object.entries(undoState).forEach(([rootID, state]) => {
- undoStateMirror.set(rootID, {canUndo: !!state.canUndo, canRedo: !!state.canRedo});
+ markMirror(rootID, {canUndo: !!state.canUndo, canRedo: !!state.canRedo});
});
};
@@ -90,10 +129,12 @@ export const initMirror = (rootID: string): Promise<boolean> => {
if (pending) {
return pending;
}
+ const before = undoStateMirror.get(rootID);
const initializer = fetchPost("/api/transactions/undoState", {rootID}, (response) => {
const data = response.data;
- if (data) {
- undoStateMirror.set(rootID, {canUndo: !!data.canUndo, canRedo: !!data.canRedo});
+ // 初始化返回前的本地事务或广播更新优先,避免旧快照覆盖刚产生的历史状态。
+ if (data && undoStateMirror.get(rootID) === before) {
+ markMirror(rootID, {canUndo: !!data.canUndo, canRedo: !!data.canRedo});
}
}).then(() => {
return undoStateMirror.has(rootID);
@@ -251,6 +292,7 @@ export const requestUndo = async (protyle: IProtyle, rootID?: string) => {
// 尽早置锁,阻止确认对话框期间触发新的撤销/重做(含 peek 与确认阶段)
isUndoing = true;
+ notifyUndoState();
try {
await waitForPendingTransactions(protyle);
@@ -330,6 +372,7 @@ export const requestUndo = async (protyle: IProtyle, rootID?: string) => {
}
} finally {
isUndoing = false;
+ notifyUndoState();
}
};
@@ -343,6 +386,7 @@ export const requestRedo = async (protyle: IProtyle, rootID?: string) => {
}
isUndoing = true;
+ notifyUndoState();
try {
await waitForPendingTransactions(protyle);
const state = await fetchUndoState(rootID);
@@ -388,5 +432,6 @@ export const requestRedo = async (protyle: IProtyle, rootID?: string) => {
}
} finally {
isUndoing = false;
+ notifyUndoState();
}
};