An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
import {Constants} from "../../constants";
import {fetchPost} from "../../util/fetch";
import {confirmDialog} from "../../dialog/confirmDialog";
import {showMessage} from "../../dialog/message";
import {waitForPendingTransactions} from "../util/transactionQueue";
import {hasClosestByClassName} from "../util/hasClosest";
import {getUndoFocusTarget} from "../util/selectionFocus";
import {isKnownTransactionOperation} from "../util/transactionContract";
import type {APIPOSTRoutes} from "../../types/api";
import {isUndoViewportPreserved} from "./viewport";
/// #if !MOBILE
import {getActiveTab} from "../../layout/tabUtil";
/// #endif
/// #if MOBILE
import {getCurrentEditor} from "../../mobile/editor";
import {getMobileToolbarProtyle, getMobileToolbarUndo} from "../lite/mobileToolbar";
/// #endif
// 本地镜像:按 rootID 缓存 {canUndo, canRedo},按钮态零 fetch 读取。
// 在编辑(add 落点)、撤销/重做响应、WS 广播(context.undoState)时更新。
interface IUndoStateMirror {
canUndo: boolean;
canRedo: boolean;
}
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 => {
return undoStateMirror.get(rootID) || {canUndo: false, canRedo: false};
};
export const hasUndoStateMirror = (rootID: string) => undoStateMirror.has(rootID);
const getRangeRootID = (protyle: IProtyle, range?: Range) => {
if (!range?.startContainer?.isConnected || !protyle.wysiwyg.element.contains(range.startContainer)) {
return;
}
const embedElement = hasClosestByClassName(range.startContainer, "protyle-wysiwyg__embed");
if (embedElement) {
const rootID = embedElement.getAttribute("data-root-id");
if (rootID) {
return rootID;
}
}
return protyle.block?.rootID;
};
// 嵌入块是源文档在当前编辑器中的投影,撤销目标应由具体查询结果决定,外层查询块不绑定单一文档。
export const getUndoRootID = (protyle: IProtyle, range?: Range, fallbackRootID?: string) => {
if (!protyle) {
return fallbackRootID;
}
const rangeRootID = getRangeRootID(protyle, range);
if (rangeRootID) {
return rangeRootID;
}
const selection = getSelection();
if (selection.rangeCount > 0) {
const selectionRootID = getRangeRootID(protyle, selection.getRangeAt(0));
if (selectionRootID) {
return selectionRootID;
}
}
const toolbarRootID = getRangeRootID(protyle, protyle.toolbar?.range);
return toolbarRootID || fallbackRootID || protyle.block?.rootID;
};
// 从 WS 广播 context.undoState 批量更新镜像(多窗口/多端同步)
export const syncMirrorFromBroadcast = (undoState: { [rootID: string]: { canUndo: boolean; canRedo: boolean } }) => {
if (!undoState) {
return;
}
Object.entries(undoState).forEach(([rootID, state]) => {
markMirror(rootID, {canUndo: !!state.canUndo, canRedo: !!state.canRedo});
});
};
// 文档打开时主动初始化镜像(低频,不在 selectionchange 热路径)
export const initMirror = (rootID: string): Promise<boolean> => {
if (!rootID) {
return Promise.resolve(false);
}
const pending = undoStateInitializers.get(rootID);
if (pending) {
return pending;
}
const before = undoStateMirror.get(rootID);
const initializer = fetchPost("/api/transactions/undoState", {rootID}, (response) => {
const data = response.data;
// 初始化返回前的本地事务或广播更新优先,避免旧快照覆盖刚产生的历史状态。
if (data && undoStateMirror.get(rootID) === before) {
markMirror(rootID, {canUndo: !!data.canUndo, canRedo: !!data.canRedo});
}
}).then(() => {
return undoStateMirror.has(rootID);
}).finally(() => {
undoStateInitializers.delete(rootID);
});
undoStateInitializers.set(rootID, initializer);
return initializer;
};
const applyUndoButtons = (protyle: IProtyle, rootID: string) => {
const state = getMirror(rootID);
const applyState = (parent: ParentNode) => {
const undoElement = parent.querySelector('[data-type="undo"]') as HTMLElement;
const redoElement = parent.querySelector('[data-type="redo"]') as HTMLElement;
undoElement?.toggleAttribute("disabled", !state.canUndo);
redoElement?.toggleAttribute("disabled", !state.canRedo);
};
if (protyle.breadcrumb) {
applyState(protyle.breadcrumb.element.parentElement);
protyle.breadcrumb.refreshHistory?.(rootID);
}
/// #if MOBILE
const toolbarEditor = getMobileToolbarProtyle();
const undoOwner = toolbarEditor ? getMobileToolbarUndo(toolbarEditor)?.owner : getCurrentEditor()?.protyle;
if (undoOwner === protyle &&
getUndoRootID(protyle, protyle.toolbar?.range) === rootID) {
const keyboardToolbar = document.getElementById("keyboardToolbar");
if (keyboardToolbar) {
applyState(keyboardToolbar);
}
}
/// #endif
};
// 刷新指定 protyle 的撤销/重做按钮态;首次进入嵌入源文档时按需初始化其镜像。
export const refreshUndoButtons = (protyle: IProtyle, rootID = getUndoRootID(protyle)) => {
if (!rootID) {
return;
}
applyUndoButtons(protyle, rootID);
if (!hasUndoStateMirror(rootID)) {
initMirror(rootID).then((initialized) => {
if (initialized && getUndoRootID(protyle) === rootID) {
applyUndoButtons(protyle, rootID);
}
});
}
};
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).getCurrentProtyle) {
const range = getSelection().rangeCount > 0 ? getSelection().getRangeAt(0) : undefined;
return (model as any).getCurrentProtyle(range);
}
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) {
let name = id;
await fetchPost("/api/filetree/getHPathByID", {id}, (response: IWebSocketData) => {
if (response.code === 0 && response.data) {
name = response.data as string;
}
});
names.push(name);
}
return names;
};
const focusRootIDs = (rootIDs: string[], focusBlockId?: string) => {
// 只滚动发起窗口的焦点 protyle 到变更块;其他文档不强制重开(撤销物理结果在发起文档)
const protyle = getActiveProtyle();
if (protyle && !isUndoViewportPreserved(protyle.wysiwyg.element) &&
rootIDs.includes(protyle.block?.rootID) && focusBlockId) {
const targets = Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${focusBlockId}"]`));
const selection = getSelection();
const range = selection.rangeCount > 0 ? selection.getRangeAt(0) : undefined;
// 同 ID 块可能同时存在于嵌入块和源文档中,优先定位撤销后选区所在的副本。
const target = getUndoFocusTarget(targets, item =>
!!range && protyle.wysiwyg.element.contains(range.startContainer) && item.contains(range.startContainer)
);
if (target) {
const rect = target.getBoundingClientRect();
// 仅在变更块不在视口内时才滚动,避免打断用户当前的滚动位置
if (rect.bottom < 0 || rect.top > window.innerHeight) {
target.scrollIntoView({behavior: "smooth", block: "center"});
}
}
}
};
const fetchUndoState = async (rootID: string): Promise<{
canUndo: boolean;
canRedo: boolean;
peekMutatedRootIDs: string[];
} | undefined> => {
let state: {
canUndo: boolean;
canRedo: boolean;
peekMutatedRootIDs: string[];
};
await fetchPost("/api/transactions/undoState", {rootID}, (response) => {
if (response.data) {
state = {
canUndo: !!response.data?.canUndo,
canRedo: !!response.data?.canRedo,
peekMutatedRootIDs: response.data?.peekMutatedRootIDs || [],
};
}
});
return state;
};
const fetchUndoOperation = async (path: "/api/transactions/undo" | "/api/transactions/redo", data: {
rootID: string;
app: string;
session: string;
}) => {
let response: APIPOSTRoutes["/api/transactions/undo"]["response"] | undefined;
await fetchPost(path, data, (fetchResponse: APIPOSTRoutes["/api/transactions/undo"]["response"]) => {
response = fetchResponse;
});
return response;
};
// 请求撤销:读取 kernel 权威状态 → 跨文档提示 → 调 kernel undo → 本地乐观应用 + 更新镜像
export const requestUndo = async (protyle: IProtyle, rootID?: string) => {
if (!protyle || isUndoing) {
return;
}
if (!rootID) {
return;
}
// 尽早置锁,阻止确认对话框期间触发新的撤销/重做(含 peek 与确认阶段)
isUndoing = true;
notifyUndoState();
try {
await waitForPendingTransactions(protyle);
// 等待输入事务提交后读取权威状态,避免本地镜像尚未更新时吞掉立即撤销。
const state = await fetchUndoState(rootID);
if (!state) {
return;
}
markMirror(rootID, {canUndo: state.canUndo, canRedo: state.canRedo});
if (!state.canUndo) {
refreshUndoButtons(protyle, rootID);
return;
}
if (state.peekMutatedRootIDs.length > 1) {
const names = await resolveRootNames(state.peekMutatedRootIDs);
// 确认期间拦截当前编辑器的键盘输入(遮罩只挡鼠标点击,不挡键盘冒泡)
const blockInput = (e: Event) => {
e.stopImmediatePropagation();
e.preventDefault();
};
protyle.wysiwyg.element.addEventListener("keydown", blockInput, true);
protyle.wysiwyg.element.addEventListener("beforeinput", blockInput, true);
let confirmed = false;
try {
confirmed = await new Promise<boolean>((resolve) => {
confirmDialog(`⚠️ ${window.siyuan.languages.undo}`,
`<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));
});
} finally {
protyle.wysiwyg.element.removeEventListener("keydown", blockInput, true);
protyle.wysiwyg.element.removeEventListener("beforeinput", blockInput, true);
}
if (!confirmed) {
return;
}
}
const response = await fetchUndoOperation("/api/transactions/undo", {
rootID,
app: Constants.SIYUAN_APPID,
session: protyle.id,
});
const data = response?.data;
if (!data || "closeTimeout" in data) {
return;
}
if ("failed" in data) {
// 撤销执行失败:kernel 已 Unpop 栈,镜像不动,提示用户
if (data.msg) {
showMessage(data.msg);
}
return;
}
if (!("undoOperations" in data) || !data.undoOperations || data.undoOperations.length === 0) {
// 栈空或无可撤销
markMirror(rootID, {canUndo: !!data.canUndo, canRedo: !!data.canRedo});
refreshUndoButtons(protyle, rootID);
return;
}
markMirror(rootID, {canUndo: !!data.canUndo, canRedo: !!data.canRedo});
const mutatedRootIDs: string[] = data.mutatedRootIDs || [];
if (mutatedRootIDs.length > 1) {
// 跨文档撤销:doOperations 的锚点分散在多个文档,当前 protyle 无法本地乐观应用。
// 改为靠 kernel 广播(含发起方)刷新所有涉及文档的 DOM。
// 这里不调 renderLocal,避免在错误 protyle 上应用跨文档 move 导致前后端不一致。
refreshUndoButtons(protyle, rootID);
// 广播会到达当前窗口(/undo 对跨文档用 PushModeBroadcast),触发 onTransaction 刷新 DOM
} else {
// 单文档撤销:发起窗口本地乐观应用 doOperations(kernel 实际执行的操作,如 insert 恢复块)
protyle.undo.renderLocal(protyle, data.doOperations?.filter(isKnownTransactionOperation));
refreshUndoButtons(protyle, rootID);
const focusBlockId = data.doOperations?.find(op => op?.id)?.id;
focusRootIDs(mutatedRootIDs, focusBlockId);
}
} finally {
isUndoing = false;
notifyUndoState();
}
};
// 请求重做:对称,redo 不提示(其逆已在 undo 中确认)
export const requestRedo = async (protyle: IProtyle, rootID?: string) => {
if (!protyle || isUndoing) {
return;
}
if (!rootID) {
return;
}
isUndoing = true;
notifyUndoState();
try {
await waitForPendingTransactions(protyle);
const state = await fetchUndoState(rootID);
if (!state) {
return;
}
markMirror(rootID, {canUndo: state.canUndo, canRedo: state.canRedo});
if (!state.canRedo) {
refreshUndoButtons(protyle, rootID);
return;
}
const response = await fetchUndoOperation("/api/transactions/redo", {
rootID,
app: Constants.SIYUAN_APPID,
session: protyle.id,
});
const data = response?.data;
if (!data || "closeTimeout" in data) {
return;
}
if ("failed" in data) {
// 重做执行失败:kernel 已回滚栈,镜像不动,提示用户
if (data.msg) {
showMessage(data.msg);
}
return;
}
if (!("doOperations" in data) || !data.doOperations || data.doOperations.length === 0) {
markMirror(rootID, {canUndo: !!data.canUndo, canRedo: !!data.canRedo});
refreshUndoButtons(protyle, rootID);
return;
}
markMirror(rootID, {canUndo: !!data.canUndo, canRedo: !!data.canRedo});
const mutatedRootIDs: string[] = data.mutatedRootIDs || [];
if (mutatedRootIDs.length > 1) {
// 跨文档重做:锚点分散在多个文档,靠 kernel 广播(含发起方)刷新
refreshUndoButtons(protyle, rootID);
} else {
protyle.undo.renderLocal(protyle, data.doOperations.filter(isKnownTransactionOperation));
refreshUndoButtons(protyle, rootID);
const focusBlockId = data.doOperations?.find(op => op?.id)?.id;
focusRootIDs(mutatedRootIDs, focusBlockId);
}
} finally {
isUndoing = false;
notifyUndoState();
}
};