Skip to content

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

:art: Support cross-document undo https://github.com/siyuan-note/siyuan/issues/4866

Daniel03e3f7407010
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 263c67df45..772a268a7f 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,5 @@
{
+ "undoCrossDocConfirm": "سيؤثر هذا التراجع على المستندات التالية. هل تريد المتابعة؟",
"calcOperatorTemplate": "قالب",
"calcResultTemplate": "قالب",
"rollupTemplateTip": "مثال: .action{div (len (filter .values (gt . 0))) (len .values)}",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 7ee16c72a3..8d80413d0f 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,5 @@
{
+ "undoCrossDocConfirm": "Dieser Rückgängig-Vorgang wirkt sich auf die folgenden Dokumente aus. Fortfahren?",
"calcOperatorTemplate": "Vorlage",
"calcResultTemplate": "Vorlage",
"rollupTemplateTip": "Beispiel: .action{div (len (filter .values (gt . 0))) (len .values)}",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 4673d505df..773bf58e52 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,5 @@
{
+ "undoCrossDocConfirm": "This undo will affect the following documents. Continue?",
"calcOperatorTemplate": "Template",
"calcResultTemplate": "Template",
"rollupTemplateTip": ".action{div (len (filter .values (gt . 0))) (len .values)}",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 9bc59853b6..3ecd5ab6c2 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,5 @@
{
+ "undoCrossDocConfirm": "Este deshacer afectará a los siguientes documentos. ¿Continuar?",
"calcOperatorTemplate": "Plantilla",
"calcResultTemplate": "Plantilla",
"rollupTemplateTip": "Ejemplo: .action{div (len (filter .values (gt . 0))) (len .values)}",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 82c2e18c35..3163111ec1 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,5 @@
{
+ "undoCrossDocConfirm": "Cette annulation affectera les documents suivants. Continuer ?",
"calcOperatorTemplate": "Modèle",
"calcResultTemplate": "Modèle",
"rollupTemplateTip": "Exemple: .action{div (len (filter .values (gt . 0))) (len .values)}",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index db0ad85aff..c5e6b4996d 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,5 @@
{
+ "undoCrossDocConfirm": "ביטול זה ישפיע על המסמכים הבאים. להמשיך?",
"calcOperatorTemplate": "תבנית",
"calcResultTemplate": "תבנית",
"rollupTemplateTip": "דוגמה: .action{div (len (filter .values (gt . 0))) (len .values)}",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 15a819fca7..b2da64ff44 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,5 @@
{
+ "undoCrossDocConfirm": "यह पूर्ववत निम्नलिखित दस्तावेज़ों को प्रभावित करेगा। जारी रखें?",
"calcOperatorTemplate": "टेम्पलेट",
"calcResultTemplate": "टेम्पलेट",
"rollupTemplateTip": "उदाहरण: .action{div (len (filter .values (gt . 0))) (len .values)}",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 9f6b4e7485..c08ed4c204 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,5 @@
{
+ "undoCrossDocConfirm": "Pembatalan ini akan memengaruhi dokumen berikut. Lanjutkan?",
"calcOperatorTemplate": "Templat",
"calcResultTemplate": "Templat",
"rollupTemplateTip": "Contoh: .action{div (len (filter .values (gt . 0))) (len .values)}",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 21292d0636..c3c254aa3b 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,5 @@
{
+ "undoCrossDocConfirm": "Questo annullamento influenzerà i seguenti documenti. Continuare?",
"calcOperatorTemplate": "Modello",
"calcResultTemplate": "Modello",
"rollupTemplateTip": "Esempio: .action{div (len (filter .values (gt . 0))) (len .values)}",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index ab99af8074..fb8dc6e350 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,5 @@
{
+ "undoCrossDocConfirm": "この操作は以下のドキュメントに影響します。続行しますか?",
"calcOperatorTemplate": "テンプレート",
"calcResultTemplate": "テンプレート",
"rollupTemplateTip": "例: .action{div (len (filter .values (gt . 0))) (len .values)}",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 7faf3797e2..5fbda43e8d 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,5 @@
{
+ "undoCrossDocConfirm": "이 실행 취소는 다음 문서에 영향을 미칩니다. 계속하시겠습니까?",
"calcOperatorTemplate": "템플릿",
"calcResultTemplate": "템플릿",
"rollupTemplateTip": "예: .action{div (len (filter .values (gt . 0))) (len .values)}",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index ffc91cb7b4..3a98063c24 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,5 @@
{
+ "undoCrossDocConfirm": "Deze ongedaanmakerking beïnvloedt de volgende documenten. Doorgaan?",
"calcOperatorTemplate": "Sjabloon",
"calcResultTemplate": "Sjabloon",
"rollupTemplateTip": "Voorbeeld: .action{div (len (filter .values (gt . 0))) (len .values)}",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 9fe825f3b0..9d113d413d 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,5 @@
{
+ "undoCrossDocConfirm": "To cofnięcie wpłynie na następujące dokumenty. Kontynuować?",
"calcOperatorTemplate": "Szablon",
"calcResultTemplate": "Szablon",
"rollupTemplateTip": "Przykład: .action{div (len (filter .values (gt . 0))) (len .values)}",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index a0715e22b3..e1faacd985 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,5 @@
{
+ "undoCrossDocConfirm": "Este desfazer afetará os seguintes documentos. Continuar?",
"calcOperatorTemplate": "Modelo",
"calcResultTemplate": "Modelo",
"rollupTemplateTip": "Exemplo: .action{div (len (filter .values (gt . 0))) (len .values)}",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index d445d26972..3d11f7779f 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,5 @@
{
+ "undoCrossDocConfirm": "Эта отмена повлияет на следующие документы. Продолжить?",
"calcOperatorTemplate": "Шаблон",
"calcResultTemplate": "Шаблон",
"rollupTemplateTip": "Пример: .action{div (len (filter .values (gt . 0))) (len .values)}",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 33e554935e..5cf184f52e 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,5 @@
{
+ "undoCrossDocConfirm": "Táto akcia vrátenia späť ovplyvní nasledujúce dokumenty. Pokračovať?",
"calcOperatorTemplate": "Šablóna",
"calcResultTemplate": "Šablóna",
"rollupTemplateTip": "Príklad: .action{div (len (filter .values (gt . 0))) (len .values)}",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 722e10e01d..2d17a00f7a 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,5 @@
{
+ "undoCrossDocConfirm": "การยกเลิกนี้จะมีผลต่อเอกสารต่อไปนี้ ดำเนินการต่อหรือไม่",
"calcOperatorTemplate": "เทมเพลต",
"calcResultTemplate": "เทมเพลต",
"rollupTemplateTip": "ตัวอย่าง: .action{div (len (filter .values (gt . 0))) (len .values)}",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index c0f3827749..35b1a32806 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,5 @@
{
+ "undoCrossDocConfirm": "Bu geri alma aşağıdaki belgeleri etkileyecek. Devam edilsin mi?",
"calcOperatorTemplate": "Şablon",
"calcResultTemplate": "Şablon",
"rollupTemplateTip": "Örnek: .action{div (len (filter .values (gt . 0))) (len .values)}",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 0839019bda..acb2d7def2 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,5 @@
{
+ "undoCrossDocConfirm": "Це скасування вплине на наступні документи. Продовжити?",
"calcOperatorTemplate": "Шаблон",
"calcResultTemplate": "Шаблон",
"rollupTemplateTip": "Приклад: .action{div (len (filter .values (gt . 0))) (len .values)}",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 09db89c5b6..a57245759c 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,5 @@
{
+ "undoCrossDocConfirm": "本次撤销将影响以下文档,是否继续?",
"calcOperatorTemplate": "模板",
"calcResultTemplate": "模板",
"rollupTemplateTip": "示例:.action{div (len (filter .values (gt . 0))) (len .values)}",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 36c7b31be6..b0023e94e4 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,5 @@
{
+ "undoCrossDocConfirm": "本次撤銷將影響以下文件,是否繼續?",
"calcOperatorTemplate": "範本",
"calcResultTemplate": "範本",
"rollupTemplateTip": "範例:.action{div (len (filter .values (gt . 0))) (len .values)}",
diff --git a/app/src/mobile/editor.ts b/app/src/mobile/editor.ts
index c249184709..b4b314f765 100644
--- a/app/src/mobile/editor.ts
+++ b/app/src/mobile/editor.ts
@@ -13,6 +13,7 @@ import {pushBack} from "./util/MobileBackFoward";
import {setStorageVal} from "../protyle/util/compatibility";
import {showMessage} from "../dialog/message";
import {App} from "../index";
+import {initMirror} from "../protyle/undo/globalUndo";
import {getDocByScroll, saveScroll} from "../protyle/scroll/saveScroll";
export const getCurrentEditor = () => {
@@ -116,6 +117,10 @@ export const openMobileFileById = (app: App, id: string, action: TProtyleAction[
});
}
window.siyuan.mobile.editor.protyle.undo.clear();
+ // 切换文档后校准新文档的撤销镜像(语义 B:各文档栈隔离)
+ if (window.siyuan.mobile.editor.protyle.block?.rootID) {
+ initMirror(window.siyuan.mobile.editor.protyle.block.rootID);
+ }
} else {
fetchPost("/api/storage/updateRecentDocOpenTime", {rootID: data.data.rootID});
window.siyuan.mobile.editor = new Protyle(app, document.getElementById("editor"), protyleOptions);
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index 3bfc27773f..c02a89ec60 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -16,6 +16,7 @@ import {isInAndroid, isInEdge, isInHarmony} from "../../protyle/util/compatibili
import {tabCodeBlock} from "../../protyle/wysiwyg/codeBlock";
import {callMobileAppShowKeyboard, canInput, keyboardLockUntil} from "./mobileAppUtil";
import {isNotEditBlock} from "../../protyle/wysiwyg/getBlock";
+import {getMirror} from "../../protyle/undo/globalUndo";
let renderKeyboardToolbarTimeout: number;
let showUtil = false;
@@ -361,12 +362,14 @@ const renderKeyboardToolbar = () => {
const protyle = getCurrentEditor().protyle;
protyle.toolbar.range = range;
if (!dynamicElements[0].classList.contains("fn__none")) {
- if (protyle.undo.undoStack.length === 0) {
+ // 撤销权威栈在 kernel,本地按 rootID 读镜像设按钮态(零 fetch)
+ const undoState = protyle.block?.rootID ? getMirror(protyle.block.rootID) : {canUndo: false, canRedo: false};
+ if (!undoState.canUndo) {
dynamicElements[0].querySelector('[data-type="undo"]').setAttribute("disabled", "disabled");
} else {
dynamicElements[0].querySelector('[data-type="undo"]').removeAttribute("disabled");
}
- if (protyle.undo.redoStack.length === 0) {
+ if (!undoState.canRedo) {
dynamicElements[0].querySelector('[data-type="redo"]').setAttribute("disabled", "disabled");
} else {
dynamicElements[0].querySelector('[data-type="redo"]').removeAttribute("disabled");
diff --git a/app/src/protyle/index.ts b/app/src/protyle/index.ts
index d0a2f15fb7..4df0e5f036 100644
--- a/app/src/protyle/index.ts
+++ b/app/src/protyle/index.ts
@@ -24,6 +24,7 @@ import {
} from "./wysiwyg/transaction";
import {fetchPost} from "../util/fetch";
import {getDocDisplayName} from "../util/pathName";
+import {initMirror, refreshUndoButtons, syncMirrorFromBroadcast} from "./undo/globalUndo";
/// #if !MOBILE
import {updatePanelByEditor} from "../editor/util";
import {setPanelFocus} from "../layout/util";
@@ -300,6 +301,10 @@ export class Protyle {
}
private onTransaction(data: IWebSocketData) {
+ // 多窗口/多端:用广播附带的撤销状态同步本地镜像
+ if (data.context?.undoState) {
+ syncMirrorFromBroadcast(data.context.undoState);
+ }
if (!this.protyle.preview.element.classList.contains("fn__none") &&
data.context?.rootIDs?.includes(this.protyle.block.rootID)) {
this.protyle.preview.render(this.protyle);
@@ -362,10 +367,14 @@ export class Protyle {
}
} else {
// 不能使用 transaction,否则分屏后会重复添加
- this.protyle.undo.clear();
+ refreshUndoButtons(this.protyle);
this.reload(false);
}
}
+ // undo/redo 重放广播到达后,整批操作已应用,重置 lastHTMLs 防下次本地编辑算错逆操作
+ if (data.context?.isUndoReplay === true) {
+ this.protyle.wysiwyg.lastHTMLs = {};
+ }
}
private getDoc(mergedOptions: IProtyleOptions) {
@@ -390,6 +399,10 @@ export class Protyle {
}
private afterOnGet(mergedOptions: IProtyleOptions) {
+ // 文档加载完成后初始化撤销镜像(低频,不在 selectionchange 热路径)
+ if (this.protyle.block?.rootID) {
+ initMirror(this.protyle.block.rootID);
+ }
if (this.protyle.model) {
/// #if !MOBILE
if (mergedOptions.action?.includes(Constants.CB_GET_FOCUS) || mergedOptions.action?.includes(Constants.CB_GET_OPENNEW)) {
diff --git a/app/src/protyle/undo/globalUndo.ts b/app/src/protyle/undo/globalUndo.ts
new file mode 100644
index 0000000000..11a53d0017
--- /dev/null
+++ b/app/src/protyle/undo/globalUndo.ts
@@ -0,0 +1,271 @@
+import {Constants} from "../../constants";
+import {fetchPost} from "../../util/fetch";
+import {confirmDialog} from "../../dialog/confirmDialog";
+import {showMessage} from "../../dialog/message";
+/// #if !MOBILE
+import {getActiveTab} from "../../layout/tabUtil";
+/// #endif
+/// #if MOBILE
+import {getCurrentEditor} from "../../mobile/editor";
+/// #endif
+
+// 本地镜像:按 rootID 缓存 {canUndo, canRedo},按钮态零 fetch 读取。
+// 在编辑(add 落点)、撤销/重做响应、WS 广播(context.undoState)时更新。
+interface IUndoStateMirror {
+ canUndo: boolean;
+ canRedo: boolean;
+}
+
+const undoStateMirror = new Map<string, IUndoStateMirror>();
+let isUndoing = false; // 防重入:撤销/重做进行中忽略后续触发
+
+export const markMirror = (rootID: string, state: Partial<IUndoStateMirror>) => {
+ const cur = undoStateMirror.get(rootID) || {canUndo: false, canRedo: false};
+ undoStateMirror.set(rootID, {...cur, ...state});
+};
+
+export const getMirror = (rootID: string): IUndoStateMirror => {
+ return undoStateMirror.get(rootID) || {canUndo: false, canRedo: false};
+};
+
+// 从 WS 广播 context.undoState 批量更新镜像(多窗口/多端同步)
+export const syncMirrorFromBroadcast = (undoState: { [rootID: string]: { canUndo: boolean; canRedo: boolean } }) => {
+ if (!undoState) {
+ return;
+ }
+ Object.entries(undoState).forEach(([rootID, state]) => {
+ undoStateMirror.set(rootID, {canUndo: !!state.canUndo, canRedo: !!state.canRedo});
+ });
+};
+
+// 文档打开时主动初始化镜像(低频,不在 selectionchange 热路径)
+export const initMirror = (rootID: string) => {
+ if (!rootID) {
+ return;
+ }
+ fetchPost("/api/transactions/undoState", {rootID}, (response) => {
+ const data = response.data;
+ if (data) {
+ undoStateMirror.set(rootID, {canUndo: !!data.canUndo, canRedo: !!data.canRedo});
+ }
+ });
+};
+
+// 刷新指定 protyle 的撤销/重做按钮态(读镜像,零 fetch)
+export const refreshUndoButtons = (protyle: IProtyle) => {
+ if (!protyle.block?.rootID) {
+ return;
+ }
+ const state = getMirror(protyle.block.rootID);
+ if (protyle.breadcrumb) {
+ const parent = protyle.breadcrumb.element.parentElement;
+ const undoElement = parent.querySelector('[data-type="undo"]') as HTMLElement;
+ const redoElement = parent.querySelector('[data-type="redo"]') as HTMLElement;
+ if (undoElement) {
+ if (state.canUndo) {
+ undoElement.removeAttribute("disabled");
+ } else {
+ undoElement.setAttribute("disabled", "disabled");
+ }
+ }
+ if (redoElement) {
+ if (state.canRedo) {
+ redoElement.removeAttribute("disabled");
+ } else {
+ redoElement.setAttribute("disabled", "disabled");
+ }
+ }
+ }
+};
+
+export const getActiveProtyle = (): IProtyle => {
+ /// #if MOBILE
+ const editor = getCurrentEditor();
+ return editor?.protyle;
+ /// #else
+ const activeTab = getActiveTab();
+ const model = activeTab?.model;
+ if (model && (model as any).editor?.protyle) {
+ return (model as any).editor.protyle;
+ }
+ // 兜底:搜索/反链/自定义编辑器中聚焦的那个
+ /// #if !MOBILE
+ const allProtyle = (window as any).siyuan?.blockPanels || [];
+ for (const panel of allProtyle) {
+ if (panel.element && document.activeElement && panel.element.contains(document.activeElement)) {
+ return panel.editor?.protyle;
+ }
+ }
+ /// #endif
+ return undefined;
+ /// #endif
+};
+
+// 解析 rootID 列表为文档名,用于跨文档撤销确认提示
+const resolveRootNames = async (rootIDs: string[]): Promise<string[]> => {
+ const names: string[] = [];
+ for (const id of rootIDs) {
+ await new Promise<void>((resolve) => {
+ fetchPost("/api/filetree/getHPathByID", {id}, (response: IWebSocketData) => {
+ if (response.code === 0 && response.data) {
+ names.push(response.data as string);
+ } else {
+ names.push(id);
+ }
+ resolve();
+ });
+ });
+ }
+ return names;
+};
+
+const focusRootIDs = (rootIDs: string[], focusBlockId?: string) => {
+ // 只滚动发起窗口的焦点 protyle 到变更块;其它文档不强制重开(撤销物理结果在发起文档)
+ const protyle = getActiveProtyle();
+ if (protyle && rootIDs.includes(protyle.block?.rootID)) {
+ // 优先滚动到指定的变更块;未指定时滚到文档首块(兜底)
+ const targetId = focusBlockId || protyle.wysiwyg.element.querySelector("[data-node-id]")?.getAttribute("data-node-id");
+ if (targetId) {
+ const target = protyle.wysiwyg.element.querySelector(`[data-node-id="${targetId}"]`);
+ if (target) {
+ target.scrollIntoView({behavior: "smooth", block: "center"});
+ }
+ }
+ }
+};
+
+// 请求撤销:读镜像判可撤销 → 跨文档提示 → 调 kernel undo → 本地乐观应用 + 更新镜像
+export const requestUndo = async (protyle: IProtyle) => {
+ if (!protyle || isUndoing) {
+ return;
+ }
+ const rootID = protyle.block?.rootID;
+ if (!rootID) {
+ return;
+ }
+
+ const state = getMirror(rootID);
+ if (!state.canUndo) {
+ return; // 语义 B:栈空不做事
+ }
+
+ // 尽早置锁,阻止确认对话框期间触发新的撤销/重做(含 peek 与确认阶段)
+ isUndoing = true;
+
+ // 跨文档提示(标准①):先 peek 栈顶的 mutatedRootIDs
+ let peekMutatedRootIDs: string[] = [];
+ await new Promise<void>((resolve) => {
+ fetchPost("/api/transactions/undoState", {rootID}, (response) => {
+ if (response.data?.peekMutatedRootIDs) {
+ peekMutatedRootIDs = response.data.peekMutatedRootIDs;
+ }
+ resolve();
+ });
+ });
+
+ if (peekMutatedRootIDs.length > 1) {
+ const names = await resolveRootNames(peekMutatedRootIDs);
+ const confirmed = await new Promise<boolean>((resolve) => {
+ confirmDialog(`⚠️ ${window.siyuan.languages.undo}`,
+ `${window.siyuan.languages.undoCrossDocConfirm}<br>${names.join(" / ")}`,
+ () => resolve(true),
+ () => resolve(false));
+ });
+ if (!confirmed) {
+ isUndoing = false; // 拒绝,复位锁,栈与镜像不动
+ return;
+ }
+ }
+
+ fetchPost("/api/transactions/undo", {
+ rootID,
+ app: Constants.SIYUAN_APPID,
+ session: protyle.id,
+ }, (response) => {
+ isUndoing = false;
+ const data = response.data;
+ if (!data) {
+ return;
+ }
+ if (data.failed) {
+ // 撤销执行失败:kernel 已 Unpop 栈,镜像不动,提示用户
+ if (data.msg) {
+ showMessage(data.msg);
+ }
+ return;
+ }
+ if (!data.undoOperations || data.undoOperations.length === 0) {
+ // 栈空或无可撤销
+ markMirror(rootID, {canUndo: !!data.canUndo, canRedo: !!data.canRedo});
+ refreshUndoButtons(protyle);
+ return;
+ }
+ markMirror(rootID, {canUndo: !!data.canUndo, canRedo: !!data.canRedo});
+ const mutatedRootIDs: string[] = data.mutatedRootIDs || [];
+ if (mutatedRootIDs.length > 1) {
+ // 跨文档撤销:undoOperations 的锚点分散在多个文档,当前 protyle 无法本地乐观应用。
+ // 改为靠 kernel 广播(含发起方)刷新所有涉及文档的 DOM。
+ // 这里不调 renderLocal,避免在错误 protyle 上应用跨文档 move 导致前后端不一致。
+ refreshUndoButtons(protyle);
+ // 广播会到达当前窗口(/undo 对跨文档用 PushModeBroadcast),触发 onTransaction 刷新 DOM
+ } else {
+ // 单文档撤销:发起窗口本地乐观应用(isUndo=true,保光标/折叠/zoom)
+ protyle.undo.renderLocal(protyle, data.undoOperations, false);
+ refreshUndoButtons(protyle);
+ const focusBlockId = data.undoOperations?.find((op: IOperation) => op.action === "insert")?.id;
+ focusRootIDs(mutatedRootIDs, focusBlockId);
+ }
+ });
+};
+
+// 请求重做:对称,redo 不提示(其逆已在 undo 中确认)
+export const requestRedo = async (protyle: IProtyle) => {
+ if (!protyle || isUndoing) {
+ return;
+ }
+ const rootID = protyle.block?.rootID;
+ if (!rootID) {
+ return;
+ }
+
+ const state = getMirror(rootID);
+ if (!state.canRedo) {
+ return;
+ }
+
+ isUndoing = true;
+ fetchPost("/api/transactions/redo", {
+ rootID,
+ app: Constants.SIYUAN_APPID,
+ session: protyle.id,
+ }, (response) => {
+ isUndoing = false;
+ const data = response.data;
+ if (!data) {
+ return;
+ }
+ if (data.failed) {
+ // 重做执行失败:kernel 已回滚栈,镜像不动,提示用户
+ if (data.msg) {
+ showMessage(data.msg);
+ }
+ return;
+ }
+ if (!data.doOperations || data.doOperations.length === 0) {
+ markMirror(rootID, {canUndo: !!data.canUndo, canRedo: !!data.canRedo});
+ refreshUndoButtons(protyle);
+ return;
+ }
+ markMirror(rootID, {canUndo: !!data.canUndo, canRedo: !!data.canRedo});
+ const mutatedRootIDs: string[] = data.mutatedRootIDs || [];
+ if (mutatedRootIDs.length > 1) {
+ // 跨文档重做:锚点分散在多个文档,靠 kernel 广播(含发起方)刷新
+ refreshUndoButtons(protyle);
+ } else {
+ protyle.undo.renderLocal(protyle, data.doOperations, true);
+ refreshUndoButtons(protyle);
+ const focusBlockId = data.doOperations?.find((op: IOperation) => op.action === "insert")?.id;
+ focusRootIDs(mutatedRootIDs, focusBlockId);
+ }
+ });
+};
diff --git a/app/src/protyle/undo/index.ts b/app/src/protyle/undo/index.ts
index b9f735c73d..3d615e522d 100644
--- a/app/src/protyle/undo/index.ts
+++ b/app/src/protyle/undo/index.ts
@@ -1,142 +1,64 @@
-import {onTransaction, transaction} from "../wysiwyg/transaction";
+import {onTransaction} from "../wysiwyg/transaction";
import {preventScroll} from "../scroll/preventScroll";
import {Constants} from "../../constants";
import {hideElements} from "../ui/hideElements";
import {scrollCenter} from "../../util/highlightById";
import {matchHotKey} from "../util/hotKey";
import {ipcRenderer} from "electron";
+import {markMirror, refreshUndoButtons, requestRedo, requestUndo} from "./globalUndo";
-interface IOperations {
- doOperations: IOperation[],
- undoOperations: IOperation[]
-}
-
+// 撤销权威栈已下沉到 kernel(GlobalUndoLog),前端按 rootID 共享。
+// 本类仅保留发起窗口本地乐观应用的渲染逻辑(renderLocal,走 isUndo=true 分支,
+// 保住光标恢复/折叠/zoom 兜底),以及按钮态刷新。
export class Undo {
- private hasUndo = false;
- public redoStack: IOperations[];
- public undoStack: IOperations[];
-
- constructor() {
- this.redoStack = [];
- this.undoStack = [];
- }
-
public undo(protyle: IProtyle) {
if (protyle.disabled) {
return;
}
- if (this.undoStack.length === 0) {
- return;
- }
- const state = this.undoStack.pop();
- this.render(protyle, state, false);
- this.hasUndo = true;
- this.redoStack.push(state);
- if (protyle.breadcrumb) {
- const undoElement = protyle.breadcrumb.element.parentElement.querySelector('[data-type="undo"]');
- if (undoElement) {
- if (this.undoStack.length === 0) {
- undoElement.setAttribute("disabled", "true");
- }
- protyle.breadcrumb.element.parentElement.querySelector('[data-type="redo"]').removeAttribute("disabled");
- }
- }
+ // 转发到全局 Manager,由 kernel 弹栈 + 广播,发起窗口本地乐观应用
+ requestUndo(protyle);
}
public redo(protyle: IProtyle) {
if (protyle.disabled) {
return;
}
- if (this.redoStack.length === 0) {
- return;
- }
- const state = this.redoStack.pop();
- this.render(protyle, state, true);
- this.undoStack.push(state);
- if (protyle.breadcrumb) {
- const redoElement = protyle.breadcrumb.element.parentElement.querySelector('[data-type="redo"]');
- if (redoElement) {
- protyle.breadcrumb.element.parentElement.querySelector('[data-type="undo"]').removeAttribute("disabled");
- if (this.redoStack.length === 0) {
- redoElement.setAttribute("disabled", "true");
- }
- }
- }
+ requestRedo(protyle);
}
- private render(protyle: IProtyle, state: IOperations, redo: boolean) {
+ // renderLocal 仅在发起窗口本地应用操作(isUndo=true),不 POST 到 kernel
+ // (kernel 的 undo/redo 接口已执行事务并广播)。保留光标恢复/折叠/zoom/lastHTMLs 行为。
+ public renderLocal(protyle: IProtyle, operations: IOperation[], isRedo: boolean) {
hideElements(["hint", "gutter"], protyle);
protyle.wysiwyg.lastHTMLs = {};
- if (!redo) {
- for (let i = state.undoOperations.length - 1; i >= 0; i--) {
- if (state.undoOperations[i].action === "insert") {
- if (state.undoOperations[i].context) {
- state.undoOperations[i].context.setRange = "true";
- } else {
- state.undoOperations[i].context = {setRange: "true"};
- }
- break;
- }
- }
- onTransaction(protyle, state.undoOperations, true);
- transaction(protyle, state.undoOperations, undefined, {skipSync: true});
- } else {
- for (let i = state.doOperations.length - 1; i >= 0; i--) {
- if (state.doOperations[i].action === "insert") {
- if (state.doOperations[i].context) {
- state.doOperations[i].context.setRange = "true";
- } else {
- state.doOperations[i].context = {setRange: "true"};
- }
- break;
+ for (let i = operations.length - 1; i >= 0; i--) {
+ if (operations[i].action === "insert") {
+ if (operations[i].context) {
+ operations[i].context.setRange = "true";
+ } else {
+ operations[i].context = {setRange: "true"};
}
+ break;
}
- onTransaction(protyle, state.doOperations, true);
- transaction(protyle, state.doOperations, undefined, {skipSync: true});
}
+ onTransaction(protyle, operations, true);
document.querySelector(".av__panel")?.remove();
preventScroll(protyle);
scrollCenter(protyle);
}
- public replace(doOperations: IOperation[], protyle: IProtyle) {
- // undo 引发 replace 导致 stack 错误 https://github.com/siyuan-note/siyuan/issues/9178
- if (this.hasUndo && this.redoStack.length > 0) {
- this.undoStack.push(this.redoStack.pop());
- this.redoStack = [];
- this.hasUndo = false;
- if (protyle.breadcrumb) {
- const redoElement = protyle.breadcrumb.element.parentElement.querySelector('[data-type="redo"]');
- if (redoElement) {
- redoElement.setAttribute("disabled", "true");
- }
- }
- }
- if (this.undoStack.length > 0) {
- this.undoStack[this.undoStack.length - 1].doOperations = doOperations;
- }
- }
-
+ // add 降级为:不压栈(kernel 已在 commit 后 Record),仅置位本地镜像 + 刷新按钮态。
+ // 保留签名以兼容 transaction.ts 的调用点。
public add(doOperations: IOperation[], undoOperations: IOperation[], protyle: IProtyle) {
- this.undoStack.push({undoOperations, doOperations});
- if (this.undoStack.length > Constants.SIZE_UNDO) {
- this.undoStack.shift();
- }
- if (this.hasUndo) {
- this.redoStack = [];
- this.hasUndo = false;
- }
- if (protyle.breadcrumb) {
- const undoElement = protyle.breadcrumb.element.parentElement.querySelector('[data-type="undo"]');
- if (undoElement) {
- undoElement.removeAttribute("disabled");
- }
+ if (protyle.block?.rootID) {
+ markMirror(protyle.block.rootID, {canUndo: true});
}
+ refreshUndoButtons(protyle);
}
public clear() {
- this.undoStack = [];
- this.redoStack = [];
+ // kernel 全局栈不随前端编辑器销毁/重载而清空(跨窗口共享)。
+ // 本地仅刷新按钮态,镜像条目保留供重开校准。
}
}
diff --git a/app/src/protyle/util/editorCommonEvent.ts b/app/src/protyle/util/editorCommonEvent.ts
index 61b0603ffb..3f20ee0179 100644
--- a/app/src/protyle/util/editorCommonEvent.ts
+++ b/app/src/protyle/util/editorCommonEvent.ts
@@ -20,7 +20,8 @@ import {getAllEditor} from "../../layout/getAll";
import {updatePanelByEditor} from "../../editor/util";
/// #endif
import {blockRender} from "../render/blockRender";
-import {uploadLocalFiles} from "../upload";
+/// #else
+import {uploadFiles, uploadLocalFiles} from "../upload";
import {insertHTML} from "./insertHTML";
import {isBrowser} from "../../util/functions";
import {hideElements} from "../ui/hideElements";
@@ -30,8 +31,6 @@ import {zoomOut} from "../../menus/protyle";
/// #if !BROWSER
import {webUtils} from "electron";
import {dragUpload} from "../render/av/asset";
-/// #else
-import {uploadFiles} from "../upload";
/// #endif
import {addDragFill, getTypeByCellElement} from "../render/av/cell";
import {processClonePHElement} from "../render/util";
@@ -60,6 +59,34 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemen
let newListElement: Element;
let newListId: string;
const orderListElements: { [key: string]: Element } = {};
+ // 在 DOM 移动前显式捕获每个源块的位置,供 undoOperations 使用。
+ // 不能依赖循环内 getParentBlock(item)(移动后 item 的父已变),否则撤销会移到错误位置。
+ // 关键:对于文档顶层块,getParentBlock 返回 .protyle-wysiwyg 容器(无 data-node-id),
+ // 不能用目标 protyle 的 rootID(跨文档拖拽时这是错误的文档),必须用源 DOM 所属文档 rootID。
+ const sourcePositions = new Map<string, { previousID: string, parentID: string }>();
+ sourceElements.forEach(item => {
+ const id = item.getAttribute("data-node-id");
+ if (id) {
+ const parentBlock = getParentBlock(item);
+ let srcParentID = parentBlock?.getAttribute("data-node-id");
+ if (!srcParentID) {
+ // 顶层块:父是 .protyle-wysiwyg 容器(无 data-node-id)。
+ // 通过 getAllEditor 反查 item 所属的源 protyle,取其 block.rootID。
+ const sourceEditor = getAllEditor().find(editor =>
+ editor.protyle.wysiwyg.element === parentBlock);
+ srcParentID = sourceEditor?.protyle?.block?.rootID || "";
+ if (!srcParentID) {
+ // 兜底:找不到源编辑器时用目标 protyle 的 rootID(单文档场景正确,
+ // 跨文档场景下虽不精确但优于空值导致 loadTree 失败)
+ srcParentID = protyle.block.rootID;
+ }
+ }
+ sourcePositions.set(id, {
+ previousID: item.previousElementSibling?.getAttribute("data-node-id") || "",
+ parentID: srcParentID || "",
+ });
+ }
+ });
for (let index = sourceElements.length - 1; index >= 0; index--) {
const item = sourceElements[index];
const id = item.getAttribute("data-node-id");
@@ -98,11 +125,13 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemen
id: copyNewId,
});
} else {
+ // 用 DOM 移动前预捕获的源位置构造撤销操作,避免移动后 item 的父/兄弟已变导致撤销移到错误位置
+ const srcPos = sourcePositions.get(id) || {previousID: "", parentID};
undoOperations.push({
action: "move",
id,
- previousID: item.previousElementSibling?.getAttribute("data-node-id"),
- parentID,
+ previousID: srcPos.previousID,
+ parentID: srcPos.parentID,
});
}
if (!isSameDoc && !isCopy) {
@@ -202,8 +231,7 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemen
const otherSbData = await cancelSB(allEditor[i].protyle, topSourceParentElement);
doOperations.push(otherSbData.doOperations[0], otherSbData.doOperations[1]);
undoOperations.push(otherSbData.undoOperations[1], otherSbData.undoOperations[0]);
- // 需清空操作栈,否则撤销到移动出去的块的操作会抛异常
- allEditor[i].protyle.undo.clear();
+ // 全局撤销栈下跨文档移动为可逆条目,无需清空源编辑器历史
break;
}
}
@@ -224,8 +252,7 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemen
const otherSbData = await cancelSB(allEditor[i].protyle, oldSourceParentElement);
doOperations.push(otherSbData.doOperations[0], otherSbData.doOperations[1]);
undoOperations.push(otherSbData.undoOperations[1], otherSbData.undoOperations[0]);
- // 需清空操作栈,否则撤销到移动出去的块的操作会抛异常
- allEditor[i].protyle.undo.clear();
+ // 全局撤销栈下跨文档移动为可逆条目,无需清空源编辑器历史
break;
}
}
@@ -439,8 +466,8 @@ const dragSb = async (protyle: IProtyle, sourceElements: Element[], targetElemen
if (isSameDoc || isCopy) {
transaction(protyle, doOperations, undoOperations);
} else {
- // 跨文档或插入折叠标题下不支持撤销
- transaction(protyle, doOperations);
+ // 跨文档移动为可逆条目:全局撤销栈按 rootID 分栈联动,撤销时经 mutatedRootIDs 判定弹确认
+ transaction(protyle, doOperations, undoOperations);
}
if (document.contains(sourceElements[0])) {
focusBlock(sourceElements[0]);
@@ -518,8 +545,8 @@ const dragSame = async (protyle: IProtyle, sourceElements: Element[], targetElem
if (isSameDoc || isCopy) {
transaction(protyle, doOperations, undoOperations);
} else {
- // 跨文档或插入折叠标题下不支持撤销
- transaction(protyle, doOperations);
+ // 跨文档移动为可逆条目:全局撤销栈按 rootID 分栈联动,撤销时经 mutatedRootIDs 判定弹确认
+ transaction(protyle, doOperations, undoOperations);
}
if ((newSourceParentElement.length > 1 || hasFoldHeading) &&
newSourceParentElement[0].parentElement.classList.contains("sb") &&
diff --git a/kernel/api/router.go b/kernel/api/router.go
index 5daa374361..b9b2847deb 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -383,6 +383,10 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/template/renderSprig", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, renderSprig)
ginServer.Handle("POST", "/api/transactions", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, performTransactions)
+ ginServer.Handle("POST", "/api/transactions/undoState", model.CheckAuth, model.CheckReadonly, undoState)
+ ginServer.Handle("POST", "/api/transactions/undo", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, performUndo)
+ ginServer.Handle("POST", "/api/transactions/redo", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, performRedo)
+ ginServer.Handle("POST", "/api/transactions/clearHistory", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, clearHistory)
ginServer.Handle("POST", "/api/setting/setAccount", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setAccount)
ginServer.Handle("POST", "/api/setting/setEditor", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setEditor)
diff --git a/kernel/api/transaction.go b/kernel/api/transaction.go
index 2d1ed31cd0..ff02c246cd 100644
--- a/kernel/api/transaction.go
+++ b/kernel/api/transaction.go
@@ -73,6 +73,7 @@ func performTransactions(c *gin.Context) {
}
for _, transaction := range transactions {
transaction.Timestamp = timestamp
+ transaction.MarkFromAPI() // 标记来自 HTTP 入口,供全局撤销日志捕获判别
}
model.PerformTransactions(&transactions)
@@ -113,8 +114,244 @@ func pushTransactions(app, session string, transactions []*model.Transaction) {
rootIDs = append(rootIDs, tx.GetChangedRootIDs()...)
}
rootIDs = gulu.Str.RemoveDuplicatedElem(rootIDs)
+
+ for _, tx := range transactions {
+ tx.WaitForCommit()
+ }
+
+ // 附带每个 rootID 的撤销/重做可用状态,供前端本地镜像同步(多窗口/多端按钮态)
+ // 必须在 WaitForCommit 之后读取,确保 Record 已完成,状态含最新条目
+ undoStates := map[string]map[string]bool{}
+ for _, rootID := range rootIDs {
+ canUndo, canRedo, _ := model.GlobalUndoLog.State(rootID)
+ undoStates[rootID] = map[string]bool{
+ "canUndo": canUndo,
+ "canRedo": canRedo,
+ }
+ }
+ evt.Context = map[string]any{
+ "rootIDs": rootIDs,
+ "undoState": undoStates,
+ }
+
+ util.PushEvent(evt)
+}
+
+// undoState 查询指定文档的撤销/重做可用性及栈顶关联的 mutatedRootIDs。
+// 前端在打开文档时调用以初始化本地镜像。
+func undoState(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+
+ var rootID string
+ if !util.ParseJsonArgs(arg, ret,
+ util.BindJsonArg("rootID", &rootID, true, false),
+ ) {
+ return
+ }
+
+ canUndo, canRedo, peekMutatedRootIDs := model.GlobalUndoLog.State(rootID)
+ ret.Data = map[string]any{
+ "canUndo": canUndo,
+ "canRedo": canRedo,
+ "peekMutatedRootIDs": peekMutatedRootIDs,
+ }
+}
+
+// performUndo 撤销指定文档最近一次操作。
+// 弹出 rootID 撤销栈顶,同步执行其逆操作,广播给其它窗口/端。
+// 单文档撤销:发起窗口靠响应数据本地乐观应用,广播排除发起方(ExcludeSelf)。
+// 跨文档撤销:发起窗口无法本地乐观应用(锚点分散),广播含发起方(Broadcast)刷新其 DOM。
+// 逆操作失败时回滚栈状态(UndoRollback)并返回 data.failed=true,前端镜像不动。
+func performUndo(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+
+ var rootID, app, session string
+ if !util.ParseJsonArgs(arg, ret,
+ util.BindJsonArg("rootID", &rootID, true, false),
+ util.BindJsonArg("app", &app, false, false),
+ util.BindJsonArg("session", &session, false, false),
+ ) {
+ return
+ }
+
+ entry := model.GlobalUndoLog.Undo(rootID)
+ if nil == entry {
+ // 栈空,无可撤销
+ ret.Data = map[string]any{
+ "canUndo": false,
+ "canRedo": false,
+ }
+ return
+ }
+
+ tx := &model.Transaction{
+ Timestamp: time.Now().UnixMilli(),
+ DoOperations: entry.UndoOperationsForReplay(),
+ UndoOperations: entry.DoOperationsForReplay(),
+ }
+ tx.MarkReplay()
+
+ if err := model.PerformTxSync(tx); nil != err {
+ // 逆操作执行失败,回滚执行栈。返回 code=0 + data.failed=true(而非 code=-1),
+ // 否则前端 processMessage 拦截导致 fetchPost 回调不执行、isUndoing 永不复位。
+ model.GlobalUndoLog.UndoRollback(entry, rootID)
+ ret.Data = map[string]any{
+ "failed": true,
+ "msg": "undo failed: " + err.Error(),
+ }
+ return
+ }
+
+ // 成功:联动从其它关联栈移除该 entry
+ model.GlobalUndoLog.UndoCommit(entry, rootID)
+
+ crossDoc := len(entry.MutatedRootIDs()) > 1
+ pushUndoTransactions(app, session, []*model.Transaction{tx}, true, crossDoc)
+
+ canUndo, canRedo, _ := model.GlobalUndoLog.State(rootID)
+ ret.Data = map[string]any{
+ "doOperations": entry.DoOperationsForReplay(),
+ "undoOperations": entry.UndoOperationsForReplay(),
+ "mutatedRootIDs": entry.MutatedRootIDs(),
+ "canUndo": canUndo,
+ "canRedo": canRedo,
+ "isUndo": true,
+ }
+}
+
+// performRedo 重做指定文档最近一次撤销的操作。
+func performRedo(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+
+ var rootID, app, session string
+ if !util.ParseJsonArgs(arg, ret,
+ util.BindJsonArg("rootID", &rootID, true, false),
+ util.BindJsonArg("app", &app, false, false),
+ util.BindJsonArg("session", &session, false, false),
+ ) {
+ return
+ }
+
+ entry := model.GlobalUndoLog.Redo(rootID)
+ if nil == entry {
+ ret.Data = map[string]any{
+ "canUndo": false,
+ "canRedo": false,
+ }
+ return
+ }
+
+ tx := &model.Transaction{
+ Timestamp: time.Now().UnixMilli(),
+ DoOperations: entry.DoOperationsForReplay(),
+ UndoOperations: entry.UndoOperationsForReplay(),
+ }
+ tx.MarkReplay()
+
+ if err := model.PerformTxSync(tx); nil != err {
+ // 重做失败,回滚执行栈。返回 code=0 + data.failed=true(避免前端 isUndoing 死锁)。
+ model.GlobalUndoLog.RedoRollback(entry, rootID)
+ ret.Data = map[string]any{
+ "failed": true,
+ "msg": "redo failed: " + err.Error(),
+ }
+ return
+ }
+
+ // 成功:联动把 entry 重新挂到其它关联栈
+ model.GlobalUndoLog.RedoCommit(entry, rootID)
+
+ crossDoc := len(entry.MutatedRootIDs()) > 1
+ pushUndoTransactions(app, session, []*model.Transaction{tx}, true, crossDoc)
+
+ canUndo, canRedo, _ := model.GlobalUndoLog.State(rootID)
+ ret.Data = map[string]any{
+ "doOperations": entry.DoOperationsForReplay(),
+ "undoOperations": entry.UndoOperationsForReplay(),
+ "mutatedRootIDs": entry.MutatedRootIDs(),
+ "canUndo": canUndo,
+ "canRedo": canRedo,
+ "isUndo": false,
+ }
+}
+
+// clearHistory 清理撤销日志。rootID 非空时清该文档栈并联动移除其它栈相关条目;为空时清空全部。
+func clearHistory(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+
+ var rootID string
+ util.ParseJsonArgs(arg, ret,
+ util.BindJsonArg("rootID", &rootID, false, false),
+ )
+
+ model.GlobalUndoLog.Clear(rootID)
+}
+
+// pushUndoTransactions 广播 undo/redo 重放事务。
+// isReplay=true 时 context 标记 isUndoReplay(前端据此重置 lastHTMLs)。
+// includeSelf=true 时用 PushModeBroadcast(含发起方),用于跨文档撤销/重做——
+// 此时 undoOperations 锚点分散在多个文档,发起方无法本地乐观应用,需靠广播刷新自身 DOM;
+// includeSelf=false 时用 PushModeBroadcastExcludeSelf,发起方靠响应数据本地乐观应用。
+func pushUndoTransactions(app, session string, transactions []*model.Transaction, isReplay, includeSelf bool) {
+ pushMode := util.PushModeBroadcastExcludeSelf
+ if includeSelf {
+ pushMode = util.PushModeBroadcast
+ }
+ if !includeSelf && 0 < len(transactions) && 0 < len(transactions[0].DoOperations) {
+ action := transactions[0].DoOperations[0].Action
+ isAttrViewTx := strings.Contains(strings.ToLower(action), "attrview")
+ if isAttrViewTx && "setAttrViewName" != action {
+ pushMode = util.PushModeBroadcast
+ }
+ }
+
+ evt := util.NewCmdResult("transactions", 0, pushMode)
+ evt.AppId = app
+ evt.SessionId = session
+ evt.Data = transactions
+
+ var rootIDs []string
+ for _, tx := range transactions {
+ rootIDs = append(rootIDs, tx.GetChangedRootIDs()...)
+ }
+ rootIDs = gulu.Str.RemoveDuplicatedElem(rootIDs)
+
+ undoStates := map[string]map[string]bool{}
+ for _, rootID := range rootIDs {
+ canUndo, canRedo, _ := model.GlobalUndoLog.State(rootID)
+ undoStates[rootID] = map[string]bool{
+ "canUndo": canUndo,
+ "canRedo": canRedo,
+ }
+ }
evt.Context = map[string]any{
- "rootIDs": rootIDs,
+ "rootIDs": rootIDs,
+ "undoState": undoStates,
+ "isUndoReplay": isReplay,
}
for _, tx := range transactions {
diff --git a/kernel/model/transaction.go b/kernel/model/transaction.go
index 032ec978ca..566f167c23 100644
--- a/kernel/model/transaction.go
+++ b/kernel/model/transaction.go
@@ -61,6 +61,27 @@ func FlushTxQueue() {
}
}
+// PerformTxSync 同步执行单笔事务并返回错误,供 undo/redo 重放使用。
+// 与异步入队的 PerformTransactions 不同,这里直接持有 flushLock 串行执行 performTx,
+// 失败时返回原始错误(不转成推送消息),调用方据此回滚撤销栈状态。
+func PerformTxSync(tx *Transaction) (err error) {
+ defer logging.Recover()
+ // 初始化事务互斥锁(异步路径 PerformTransactions 在入队前初始化,同步路径这里补上)
+ if nil == tx.m {
+ tx.m = &sync.Mutex{}
+ }
+ flushLock.Lock()
+ isFlushing = true
+ defer func() {
+ isFlushing = false
+ flushLock.Unlock()
+ }()
+ if txErr := performTx(tx); nil != txErr {
+ return txErr
+ }
+ return
+}
+
var (
txQueue = make(chan *Transaction, 7)
flushLock = sync.Mutex{}
@@ -145,6 +166,19 @@ type TxErr struct {
id string
}
+// Error 实现 error 接口,供跨包(如 undo API)读取事务错误信息。
+func (e *TxErr) Error() string {
+ if "" != e.id {
+ return e.msg + " [" + e.id + "]"
+ }
+ return e.msg
+}
+
+// Code 返回事务错误码。
+func (e *TxErr) Code() int {
+ return e.code
+}
+
func performTx(tx *Transaction) (ret *TxErr) {
if 1 > len(tx.DoOperations) {
return
@@ -1833,6 +1867,9 @@ type Transaction struct {
isGlobalAssets bool // 是否属于全局资源
assetsDir string // 资源目录路径
+ fromAPI bool // 是否来自 /api/transactions HTTP 入口(用于撤销日志捕获判别)
+ isReplay bool // 是否为 undo/redo 重放构造的事务(重放不再进入撤销日志)
+
luteEngine *lute.Lute
m *sync.Mutex
state atomic.Int32 // 0: 初始化,1:未提交,:2: 已提交,3: 已回滚
@@ -1850,6 +1887,26 @@ func (tx *Transaction) GetChangedRootIDs() (ret []string) {
return
}
+// MarkFromAPI 标记事务来自 /api/transactions HTTP 入口,供全局撤销日志捕获判别。
+func (tx *Transaction) MarkFromAPI() {
+ tx.fromAPI = true
+}
+
+// MarkReplay 标记事务为 undo/redo 重放构造,重放不再进入撤销日志。
+func (tx *Transaction) MarkReplay() {
+ tx.isReplay = true
+}
+
+// GetMutatedRootIDs 返回真正被写盘修改结构的树 rootID,不含 refreshDynamicRefTexts 刷新的引用树。
+// 用于跨文档撤销判定:单文档编辑返回 1 个 rootID,跨文档移动返回多个,引用文本刷新不计入。
+func (tx *Transaction) GetMutatedRootIDs() (ret []string) {
+ for t := range tx.trees {
+ ret = append(ret, t)
+ }
+ ret = gulu.Str.RemoveDuplicatedElem(ret)
+ return
+}
+
func (tx *Transaction) WaitForCommit() {
for {
if 1 == tx.state.Load() {
@@ -1897,6 +1954,8 @@ func (tx *Transaction) commit() (err error) {
IncSync()
tx.state.Store(2)
+ // 已提交且 trees 稳定后记录到全局撤销日志(rollback 不记录)
+ GlobalUndoLog.Record(tx)
tx.m.Unlock()
return
}
diff --git a/kernel/model/undolog.go b/kernel/model/undolog.go
new file mode 100644
index 0000000000..c904b4d844
--- /dev/null
+++ b/kernel/model/undolog.go
@@ -0,0 +1,365 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "fmt"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/88250/gulu"
+)
+
+// UndoEntry 是撤销栈中的一条记录。跨文档操作(MutatedRootIDs 含多个 rootID)的 entry
+// 会以同一指针同时挂在这些 rootID 的栈上,撤销任一端时联动其它端移除引用。
+type UndoEntry struct {
+ id string
+ doOperations []*Operation
+ undoOperations []*Operation
+ timestamp int64
+ mutatedRootIDs []string // 真正被写盘修改的树 rootID,联动与跨文档判定用
+}
+
+// DoOperationsForReplay 返回正向操作副本,供 redo 重放构造事务。
+func (e *UndoEntry) DoOperationsForReplay() []*Operation {
+ return cloneOperations(e.doOperations)
+}
+
+// UndoOperationsForReplay 返回逆向操作副本,供 undo 重放构造事务。
+func (e *UndoEntry) UndoOperationsForReplay() []*Operation {
+ return cloneOperations(e.undoOperations)
+}
+
+// MutatedRootIDs 返回该条目影响的 rootID 列表副本。
+func (e *UndoEntry) MutatedRootIDs() []string {
+ if nil == e.mutatedRootIDs {
+ return nil
+ }
+ ret := make([]string, len(e.mutatedRootIDs))
+ copy(ret, e.mutatedRootIDs)
+ return ret
+}
+
+// undoStack 是单个 rootID 的撤销/重做栈。
+type undoStack struct {
+ undoStack []*UndoEntry
+ redoStack []*UndoEntry
+ hasUndo bool // 复现前端 hasUndo 状态机:undo 后置 true,add 时若 true 则清 redo
+}
+
+// UndoLog 是全局撤销日志,按 rootID 分栈,所有窗口/客户端共享同一权威。
+type UndoLog struct {
+ mu sync.Mutex
+ stacks map[string]*undoStack
+ max int
+}
+
+// GlobalUndoLog 全局撤销日志单例。内存态,重启清空。
+var GlobalUndoLog = newUndoLog(64)
+
+var undoEntrySeq uint64
+
+func newUndoLog(max int) *UndoLog {
+ return &UndoLog{
+ stacks: map[string]*undoStack{},
+ max: max,
+ }
+}
+
+func newUndoEntryID() string {
+ seq := atomic.AddUint64(&undoEntrySeq, 1)
+ return fmt.Sprintf("undo-%d-%d", time.Now().UnixNano(), seq)
+}
+
+// stack 返回 rootID 对应的栈,不存在则返回 nil。
+func (l *UndoLog) stack(rootID string) *undoStack {
+ return l.stacks[rootID]
+}
+
+// stackOrCreate 返回 rootID 对应的栈,不存在则新建。
+func (l *UndoLog) stackOrCreate(rootID string) *undoStack {
+ s := l.stacks[rootID]
+ if nil == s {
+ s = &undoStack{}
+ l.stacks[rootID] = s
+ }
+ return s
+}
+
+// Record 记录一笔已提交的编辑器事务。仅当事务来自 /api/transactions(fromAPI)、
+// 携带非空 UndoOperations、且非 undo/redo 重放(isReplay)时记录。
+func (l *UndoLog) Record(tx *Transaction) {
+ if !tx.fromAPI || 0 == len(tx.UndoOperations) || tx.isReplay {
+ return
+ }
+
+ rootIDs := tx.GetMutatedRootIDs()
+ if 0 == len(rootIDs) {
+ // 纯属性视图单元格编辑等不写 block tree 的事务不入栈
+ return
+ }
+
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ entry := &UndoEntry{
+ id: newUndoEntryID(),
+ doOperations: cloneOperations(tx.DoOperations),
+ undoOperations: cloneOperations(tx.UndoOperations),
+ timestamp: time.Now().UnixMilli(),
+ mutatedRootIDs: rootIDs,
+ }
+
+ for _, rootID := range rootIDs {
+ s := l.stackOrCreate(rootID)
+ s.undoStack = append(s.undoStack, entry)
+ if s.hasUndo {
+ s.redoStack = nil
+ s.hasUndo = false
+ }
+ if l.max < len(s.undoStack) {
+ s.undoStack = s.undoStack[len(s.undoStack)-l.max:]
+ }
+ }
+}
+
+// Peek 返回 rootID 撤销栈顶(不弹出),栈空返回 nil。
+func (l *UndoLog) Peek(rootID string) *UndoEntry {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ s := l.stack(rootID)
+ if nil == s || 0 == len(s.undoStack) {
+ return nil
+ }
+ return s.undoStack[len(s.undoStack)-1]
+}
+
+// Undo 弹出 rootID 撤销栈顶,压入执行栈重做栈,置 hasUndo。仅动执行栈,不做联动移除。
+// 成功执行逆操作后调 UndoCommit 完成联动;失败调 UndoRollback 精确回滚(因只动了执行栈)。
+// 返回弹出的 entry;栈空返回 nil。
+func (l *UndoLog) Undo(rootID string) *UndoEntry {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ s := l.stack(rootID)
+ if nil == s || 0 == len(s.undoStack) {
+ return nil
+ }
+
+ entry := s.undoStack[len(s.undoStack)-1]
+ s.undoStack = s.undoStack[:len(s.undoStack)-1]
+ // 只压入执行撤销的栈,符合语义 B:在 B 按 Ctrl+Y 不重做这条
+ s.redoStack = append(s.redoStack, entry)
+ if l.max < len(s.redoStack) {
+ s.redoStack = s.redoStack[len(s.redoStack)-l.max:]
+ }
+ s.hasUndo = true
+ return entry
+}
+
+// UndoCommit 在逆操作成功执行后,联动从其它关联栈移除该 entry(按 id 匹配)。
+func (l *UndoLog) UndoCommit(entry *UndoEntry, rootID string) {
+ if nil == entry {
+ return
+ }
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ for _, r := range entry.mutatedRootIDs {
+ if r == rootID {
+ continue
+ }
+ l.removeEntry(r, entry.id)
+ }
+}
+
+// UndoRollback 在逆操作执行失败时回滚执行栈:把 entry 从重做栈移回撤销栈顶,复位 hasUndo。
+// 因 Undo 只动了执行栈,此回滚精确无误。
+func (l *UndoLog) UndoRollback(entry *UndoEntry, rootID string) {
+ if nil == entry {
+ return
+ }
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ s := l.stack(rootID)
+ if nil == s {
+ return
+ }
+ // 从执行栈重做栈顶移除 entry(Undo 压入的)
+ if 0 < len(s.redoStack) && s.redoStack[len(s.redoStack)-1].id == entry.id {
+ s.redoStack = s.redoStack[:len(s.redoStack)-1]
+ }
+ // 推回执行栈撤销栈顶(恢复 Undo 弹出前的位置)
+ s.undoStack = append(s.undoStack, entry)
+ s.hasUndo = false
+}
+
+// Redo 弹出 rootID 重做栈顶,压回执行栈撤销栈。仅动执行栈,不做联动重挂。
+// 不改 hasUndo(复现前端 redo 的不对称)。成功后调 RedoCommit;失败调 RedoRollback。
+func (l *UndoLog) Redo(rootID string) *UndoEntry {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ s := l.stack(rootID)
+ if nil == s || 0 == len(s.redoStack) {
+ return nil
+ }
+
+ entry := s.redoStack[len(s.redoStack)-1]
+ s.redoStack = s.redoStack[:len(s.redoStack)-1]
+ s.undoStack = append(s.undoStack, entry)
+ return entry
+}
+
+// RedoCommit 在重做成功执行后,联动把 entry 重新挂到其它关联栈顶。
+func (l *UndoLog) RedoCommit(entry *UndoEntry, rootID string) {
+ if nil == entry {
+ return
+ }
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ for _, r := range entry.mutatedRootIDs {
+ if r == rootID {
+ continue
+ }
+ rs := l.stackOrCreate(r)
+ rs.undoStack = append(rs.undoStack, entry)
+ if l.max < len(rs.undoStack) {
+ rs.undoStack = rs.undoStack[len(rs.undoStack)-l.max:]
+ }
+ }
+}
+
+// RedoRollback 在重做执行失败时回滚执行栈:把 entry 从撤销栈移回重做栈顶。
+// 因 Redo 只动了执行栈,此回滚精确无误。
+func (l *UndoLog) RedoRollback(entry *UndoEntry, rootID string) {
+ if nil == entry {
+ return
+ }
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ s := l.stack(rootID)
+ if nil == s {
+ return
+ }
+ // 从执行栈撤销栈顶移除 entry(Redo 压入的)
+ if 0 < len(s.undoStack) && s.undoStack[len(s.undoStack)-1].id == entry.id {
+ s.undoStack = s.undoStack[:len(s.undoStack)-1]
+ }
+ // 推回执行栈重做栈顶
+ s.redoStack = append(s.redoStack, entry)
+ if l.max < len(s.redoStack) {
+ s.redoStack = s.redoStack[len(s.redoStack)-l.max:]
+ }
+}
+
+// State 返回 rootID 的撤销/重做可用性及栈顶关联的 mutatedRootIDs。
+func (l *UndoLog) State(rootID string) (canUndo, canRedo bool, peekMutatedRootIDs []string) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ s := l.stack(rootID)
+ if nil == s {
+ return
+ }
+ canUndo = 0 < len(s.undoStack)
+ canRedo = 0 < len(s.redoStack)
+ if canUndo {
+ top := s.undoStack[len(s.undoStack)-1]
+ peekMutatedRootIDs = append(peekMutatedRootIDs, top.mutatedRootIDs...)
+ peekMutatedRootIDs = gulu.Str.RemoveDuplicatedElem(peekMutatedRootIDs)
+ }
+ return
+}
+
+// Clear 清理撤销日志。rootID 非空时清该文档栈并联动移除其它栈中相关条目;为空时清空全部。
+func (l *UndoLog) Clear(rootID string) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ if "" == rootID {
+ l.stacks = map[string]*undoStack{}
+ return
+ }
+
+ s := l.stacks[rootID]
+ if nil == s {
+ return
+ }
+ // 收集该栈中所有跨文档条目的 id,联动从其它栈移除
+ linkedIDs := map[string]bool{}
+ for _, e := range s.undoStack {
+ for _, r := range e.mutatedRootIDs {
+ if r != rootID {
+ linkedIDs[e.id] = true
+ }
+ }
+ }
+ for _, e := range s.redoStack {
+ for _, r := range e.mutatedRootIDs {
+ if r != rootID {
+ linkedIDs[e.id] = true
+ }
+ }
+ }
+ delete(l.stacks, rootID)
+ for otherID, other := range l.stacks {
+ for id := range linkedIDs {
+ other.undoStack = removeEntryByID(other.undoStack, id)
+ other.redoStack = removeEntryByID(other.redoStack, id)
+ }
+ _ = otherID
+ }
+}
+
+// removeEntry 从 rootID 栈中按 id 移除一条 entry(撤销联动用)。
+func (l *UndoLog) removeEntry(rootID, id string) {
+ s := l.stacks[rootID]
+ if nil == s {
+ return
+ }
+ s.undoStack = removeEntryByID(s.undoStack, id)
+}
+
+func removeEntryByID(stack []*UndoEntry, id string) []*UndoEntry {
+ for i, e := range stack {
+ if e.id == id {
+ return append(stack[:i], stack[i+1:]...)
+ }
+ }
+ return stack
+}
+
+// cloneOperations 深拷贝操作切片(值拷贝每个 Operation),使日志条目与后续事务解耦。
+// performTx 的 doInsert0 等会原地改写 operation.ID/Action 等标量字段,若浅拷贝指针会导致
+// 已记录的条目被改写、redo 重放时 ID 失效。值拷贝复制标量字段,Data(any) 共享引用(performTx 不改其内容)。
+func cloneOperations(ops []*Operation) []*Operation {
+ if nil == ops {
+ return nil
+ }
+ ret := make([]*Operation, len(ops))
+ for i, op := range ops {
+ cloned := *op // 值拷贝标量字段(ID/Action/ParentID/PreviousID/NextID/AvID 等)
+ ret[i] = &cloned
+ }
+ return ret
+}