Skip to content

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

:sparkles: Improve document version comparison interactions https://github.com/siyuan-note/siyuan/issues/11601

Daniel1b866aa27e10
diff --git a/app/src/assets/scss/business/_history.scss b/app/src/assets/scss/business/_history.scss
index 9ea9466585..4e808b0495 100644
--- a/app/src/assets/scss/business/_history.scss
+++ b/app/src/assets/scss/business/_history.scss
@@ -135,6 +135,54 @@
}
&__compare {
+ &-legend {
+ display: flex;
+ align-items: center;
+ min-width: max-content;
+ margin-left: 8px;
+
+ .b3-chip {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ margin: 4px;
+ border: 0;
+ font-family: inherit;
+ }
+ }
+
+ &-filter {
+ > span {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background-color: var(--b3-theme-on-surface);
+ }
+
+ &--added > span {
+ background-color: var(--b3-theme-success);
+ }
+
+ &--removed > span {
+ background-color: var(--b3-theme-error);
+ }
+
+ &--modified > span {
+ background-color: var(--b3-theme-primary);
+ }
+ }
+
+ &-message {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ padding: 8px 16px;
+ color: var(--b3-theme-on-surface);
+ background-color: var(--b3-theme-surface);
+ border-bottom: 1px solid var(--b3-border-color);
+ }
+
&-scroll {
min-height: 0;
overflow-x: auto;
@@ -179,6 +227,16 @@
outline: 1px dashed var(--b3-theme-on-surface);
outline-offset: -1px;
}
+
+ .history__diff--filtered {
+ background-color: transparent !important;
+ box-shadow: none !important;
+ outline: 0 !important;
+
+ [data-history-diff="inline"] {
+ background-color: transparent !important;
+ }
+ }
}
&-label {
@@ -198,6 +256,10 @@
> textarea {
height: 100%;
}
+
+ > .fn__loading {
+ height: 100%;
+ }
}
}
diff --git a/app/src/history/diff.ts b/app/src/history/diff.ts
index 96dd69cdfb..6ad6ad463f 100644
--- a/app/src/history/diff.ts
+++ b/app/src/history/diff.ts
@@ -12,6 +12,7 @@ import {pathPosix} from "../util/pathName";
import {renderAssetsPreview} from "../asset/renderAssets";
import {resizeSide} from "./resizeSide";
import {confirmDialog} from "../dialog/confirmDialog";
+import {showDocVersionDiff} from "./docDiff";
type SnapshotDiffAggregate = "all" | "data" | "extension" | "other";
type SnapshotFileKind = "document" | "database" | "asset" | "plugin" | "widget" | "template" | "snippet" | "bazaar" | "workspaceData" | "other";
@@ -216,7 +217,7 @@ const genItem = (items: SnapshotDiffItem[], hasUndo = true) => {
let html = "";
items.forEach((item) => {
const compareID = item.compareFile ? ` data-id2="${item.compareFile.fileID}"` : "";
- html += `<li class="b3-list-item b3-list-item--hide-action history__diff-item"${compareID} data-created="${item.file.updated}" data-id="${item.file.fileID}" data-title="${escapeAttr(item.file.title)}">
+ html += `<li class="b3-list-item b3-list-item--hide-action history__diff-item"${compareID} data-created="${item.file.updated}" data-id="${item.file.fileID}" data-kind="${item.kind}" data-title="${escapeAttr(item.file.title)}">
<span class="history__diff-file">
<span class="history__diff-title">${escapeHtml(item.file.title)}</span>
<span class="history__diff-path" title="${escapeAttr(item.file.path)} ${item.file.hSize}">${escapeHtml(item.file.path)}</span>
@@ -282,6 +283,28 @@ const renderCompare = (app: App, element: HTMLElement) => {
if (!dialogContainerElement) {
return;
}
+ const id2 = element.getAttribute("data-id2");
+ if (element.dataset.kind === "document" && id2) {
+ const snapshots = Array.from(dialogContainerElement.querySelectorAll<HTMLElement>(".b3-dialog__header [data-snapshot]"));
+ if (snapshots.length === 2) {
+ const leftCreated = parseInt(snapshots[0].dataset.created);
+ const rightCreated = parseInt(snapshots[1].dataset.created);
+ showDocVersionDiff(app, {
+ type: "snapshot",
+ id: element.dataset.id,
+ snapshot: snapshots[0].dataset.snapshot,
+ label: `${window.siyuan.languages.dataSnapshot} ${snapshots[0].dataset.snapshot.substring(0, 7)} ${dayjs(leftCreated).format("YYYY-MM-DD HH:mm:ss")}`,
+ created: leftCreated,
+ }, {
+ type: "snapshot",
+ id: id2,
+ snapshot: snapshots[1].dataset.snapshot,
+ label: `${window.siyuan.languages.dataSnapshot} ${snapshots[1].dataset.snapshot.substring(0, 7)} ${dayjs(rightCreated).format("YYYY-MM-DD HH:mm:ss")}`,
+ created: rightCreated,
+ });
+ return;
+ }
+ }
const editorsElement = dialogContainerElement.querySelector('[data-type="editors"]');
const leftElement = editorsElement.firstElementChild;
const rightElement = editorsElement.lastElementChild;
@@ -347,7 +370,6 @@ const renderCompare = (app: App, element: HTMLElement) => {
titleElement.textContent = response.data.title;
leftElement.querySelector(".history__date").textContent = dayjs(response.data.updated).format("YYYY-MM-DD HH:mm");
});
- const id2 = element.getAttribute("data-id2");
if (id2) {
rightElement.classList.remove("fn__none");
fetchPost("/api/repo/openRepoSnapshotFile", {id: id2}, (response) => {
@@ -450,7 +472,8 @@ export const showDiff = (app: App, data: { id: string, time: string }[]) => {
event.stopPropagation();
break;
} else if (target.classList.contains("b3-list-item") && target.dataset.id) {
- if (target.classList.contains("b3-list-item--focus")) {
+ if (target.classList.contains("b3-list-item--focus") &&
+ !(target.dataset.kind === "document" && target.dataset.id2)) {
return;
}
dialog.element.querySelector(".history__side .b3-list-item--focus")?.classList.remove("b3-list-item--focus");
@@ -500,13 +523,13 @@ const genHTML = (left: string, right: string, dialog: Dialog, direct: string, fi
const headElement = dialog.element.querySelector(".b3-dialog__header");
headElement.innerHTML = `<div style="padding: 0;min-height: auto;" class="block__icons">
<span class="fn__flex-1"></span>
- <code class="fn__code${isPhone ? " fn__none" : ""}" data-snapshot="${left}">${left.substring(0, 7)}</code>
+ <code class="fn__code${isPhone ? " fn__none" : ""}" data-snapshot="${left}" data-created="${response.data.left.created}">${left.substring(0, 7)}</code>
${isPhone ? "" : '<span class="fn__space"></span>'}
${dayjs(response.data.left.created).format("YYYY-MM-DD HH:mm")}
<span class="fn__space"></span>
<span class="block__icon block__icon--show b3-tooltips b3-tooltips__s" aria-label="${window.siyuan.languages.switchDirect}" data-direct="${direct}"><svg><use xlink:href="#iconScrollHoriz"></use></svg></span>
<span class="fn__space"></span>
- <code class="fn__code${isPhone ? " fn__none" : ""}" data-snapshot="${right}">${right.substring(0, 7)}</code>
+ <code class="fn__code${isPhone ? " fn__none" : ""}" data-snapshot="${right}" data-created="${response.data.right.created}">${right.substring(0, 7)}</code>
${isPhone ? "" : '<span class="fn__space"></span>'}
${dayjs(response.data.right.created).format("YYYY-MM-DD HH:mm")}
<span class="fn__flex-1"></span>
diff --git a/app/src/history/doc.ts b/app/src/history/doc.ts
index 37f32dd975..6e7335cc41 100644
--- a/app/src/history/doc.ts
+++ b/app/src/history/doc.ts
@@ -154,6 +154,7 @@ export const openDocHistory = (options: {
type: "current" as const,
id: options.id,
label: window.siyuan.languages.currentVer,
+ created: Number.MAX_SAFE_INTEGER,
};
const selectedVersions: IDocVersionRef[] = [currentVersion];
const contentHTML = `<div class="fn__flex-column" style="height: 100%;">
@@ -353,11 +354,13 @@ export const openDocHistory = (options: {
event.preventDefault();
break;
} else if (type === "selectVersion" && repoFileElement) {
+ const created = parseInt(repoFileElement.getAttribute("data-created"));
toggleVersionSelection({
type: "snapshot",
id: repoFileElement.getAttribute("data-id"),
snapshot: repoFileElement.getAttribute("data-snapshot"),
- label: dayjs(parseInt(repoFileElement.getAttribute("data-created"))).format("YYYY-MM-DD HH:mm:ss"),
+ label: `${window.siyuan.languages.dataSnapshot} ${dayjs(created).format("YYYY-MM-DD HH:mm:ss")}`,
+ created,
});
event.stopPropagation();
event.preventDefault();
@@ -369,13 +372,15 @@ export const openDocHistory = (options: {
break;
} else if (type === "selectVersion" && !isLoading) {
const historyItemElement = target.parentElement;
+ const created = parseInt(historyItemElement.getAttribute("data-created")) * 1000;
getHistoryPath(historyItemElement, opElement.value, options.id, (item) => {
isLoading = false;
toggleVersionSelection({
type: "history",
id: historyItemElement.getAttribute("data-created"),
path: item.path,
- label: historyItemElement.querySelector(".b3-list-item__text").textContent.trim(),
+ label: `${window.siyuan.languages.fileHistory} ${historyItemElement.querySelector(".b3-list-item__text").textContent.trim()}`,
+ created,
});
});
event.stopPropagation();
diff --git a/app/src/history/docDiff.ts b/app/src/history/docDiff.ts
index 2546b7764b..c4329c62c5 100644
--- a/app/src/history/docDiff.ts
+++ b/app/src/history/docDiff.ts
@@ -4,16 +4,18 @@ import type {App} from "../index";
import {Protyle} from "../protyle";
import {disabledProtyle, onGet} from "../protyle/util/onGet";
import {escapeHtml} from "../util/escape";
-import {fetchPost} from "../util/fetch";
+import {fetchSyncPost} from "../util/fetch";
import {isMobile} from "../util/functions";
+import {
+ countDocVersionDifferences,
+ type DocVersionDiffFilter,
+ type IDocVersionDifference,
+ type IDocVersionRef,
+ matchesDocVersionDiffFilter,
+ orderDocVersionRefs,
+} from "./docDiffCore";
-export interface IDocVersionRef {
- type: "current" | "history" | "snapshot";
- id?: string;
- path?: string;
- snapshot?: string;
- label: string;
-}
+export type {IDocVersionRef} from "./docDiffCore";
interface IDocVersionContent {
id: string;
@@ -22,16 +24,13 @@ interface IDocVersionContent {
content: string;
}
-interface IDocVersionDifference {
- id: string;
- statuses: Array<"left-only" | "right-only" | "modified" | "moved">;
-}
-
interface IDocVersionDiff {
left: IDocVersionContent;
right: IDocVersionContent;
differences: IDocVersionDifference[];
large: boolean;
+ fallback: boolean;
+ message: string;
titleModified: boolean;
}
@@ -55,10 +54,56 @@ const toProtyleResponse = (content: IDocVersionContent) => {
} as IWebSocketData;
};
-export const showDocVersionDiff = (app: App, leftRef: IDocVersionRef, rightRef: IDocVersionRef) => {
+const getScrollAnchor = (element: HTMLElement) => {
+ const elementRect = element.getBoundingClientRect();
+ const blocks = Array.from(element.querySelectorAll<HTMLElement>(".protyle-wysiwyg [data-node-id]"));
+ let anchor: HTMLElement;
+ for (const block of blocks) {
+ const rect = block.getBoundingClientRect();
+ if (rect.top <= elementRect.top + 16) {
+ anchor = block;
+ } else if (!anchor) {
+ anchor = block;
+ break;
+ }
+ }
+ if (!anchor) {
+ return;
+ }
+ return {
+ id: anchor.dataset.nodeId,
+ offset: anchor.getBoundingClientRect().top - elementRect.top,
+ };
+};
+
+const syncDocVersionScroll = (source: HTMLElement, target: HTMLElement) => {
+ const anchor = getScrollAnchor(source);
+ const targetBlock = anchor?.id ?
+ target.querySelector<HTMLElement>(`[data-node-id="${CSS.escape(anchor.id)}"]`) : undefined;
+ if (targetBlock) {
+ const targetRect = target.getBoundingClientRect();
+ target.scrollTop += targetBlock.getBoundingClientRect().top - targetRect.top - anchor.offset;
+ return;
+ }
+
+ const sourceMax = source.scrollHeight - source.clientHeight;
+ const targetMax = target.scrollHeight - target.clientHeight;
+ target.scrollTop = sourceMax > 0 ? source.scrollTop / sourceMax * targetMax : 0;
+};
+
+export const showDocVersionDiff = (app: App, firstRef: IDocVersionRef, secondRef: IDocVersionRef) => {
+ let [leftRef, rightRef] = orderDocVersionRefs(firstRef, secondRef);
let editors: Protyle[] = [];
let diff: IDocVersionDiff;
let differenceIndex = -1;
+ let filter: DocVersionDiffFilter = "all";
+ let visibleDifferences: IDocVersionDifference[] = [];
+ let requestId = 0;
+ let isDestroyed = false;
+ let isSyncingScroll = false;
+ let removeScrollListeners = () => {
+ // 初次渲染前没有需要移除的监听器。
+ };
const dialog = new Dialog({
title: window.siyuan.languages.compare,
@@ -72,21 +117,23 @@ export const showDocVersionDiff = (app: App, leftRef: IDocVersionRef, rightRef:
<svg><use xlink:href="#iconDown"></use></svg>
</span>
<span class="history__diff-count ft__on-surface">0/0</span>
+ <div class="history__compare-legend fn__none"></div>
<span class="fn__flex-1"></span>
<span class="block__icon block__icon--show b3-tooltips b3-tooltips__w" data-type="diffSwap" aria-label="${window.siyuan.languages.switchDirect}">
<svg><use xlink:href="#iconScrollHoriz"></use></svg>
</span>
</div>
</div>
+ <div class="history__compare-message fn__none"></div>
<div class="history__compare-scroll fn__flex-1">
<div class="history__compare-editors fn__flex">
<div class="history__compare-panel fn__flex-column">
- <div class="history__compare-label ft__on-surface ft__ellipsis">${escapeHtml(leftRef.label)}</div>
+ <div class="history__compare-label ft__on-surface ft__ellipsis"></div>
<div class="protyle-title__input ft__center ft__breakword"></div>
<div class="history__compare-content fn__flex-1"></div>
</div>
<div class="history__compare-panel fn__flex-column">
- <div class="history__compare-label ft__on-surface ft__ellipsis">${escapeHtml(rightRef.label)}</div>
+ <div class="history__compare-label ft__on-surface ft__ellipsis"></div>
<div class="protyle-title__input ft__center ft__breakword"></div>
<div class="history__compare-content fn__flex-1"></div>
</div>
@@ -97,6 +144,9 @@ export const showDocVersionDiff = (app: App, leftRef: IDocVersionRef, rightRef:
height: isMobile() ? "100dvh" : "80vh",
containerClassName: "b3-dialog__container--theme",
destroyCallback() {
+ isDestroyed = true;
+ requestId++;
+ removeScrollListeners();
editors.forEach((editor) => editor.destroy());
editors = [];
}
@@ -106,70 +156,170 @@ export const showDocVersionDiff = (app: App, leftRef: IDocVersionRef, rightRef:
const rootElement = dialog.element.querySelector(".history__doc-compare") as HTMLElement;
const editorsElement = rootElement.querySelector(".history__compare-editors") as HTMLElement;
const countElement = rootElement.querySelector(".history__diff-count") as HTMLElement;
+ const legendElement = rootElement.querySelector(".history__compare-legend") as HTMLElement;
+ const messageElement = rootElement.querySelector(".history__compare-message") as HTMLElement;
+ const panels = Array.from(editorsElement.querySelectorAll<HTMLElement>(".history__compare-panel"));
+
+ const destroyEditors = () => {
+ removeScrollListeners();
+ removeScrollListeners = () => {
+ // 当前没有需要移除的监听器。
+ };
+ editors.forEach((editor) => editor.destroy());
+ editors = [];
+ };
+
const renderCount = () => {
- countElement.textContent = `${differenceIndex < 0 ? 0 : differenceIndex + 1}/${diff?.differences.length || 0}`;
+ countElement.textContent = `${differenceIndex < 0 ? 0 : differenceIndex + 1}/${visibleDifferences.length}`;
+ };
+
+ const setMessage = (message = "", retry = false) => {
+ if (!message) {
+ messageElement.classList.add("fn__none");
+ messageElement.innerHTML = "";
+ return;
+ }
+ messageElement.classList.remove("fn__none");
+ messageElement.innerHTML = `<span>${escapeHtml(message)}</span>${retry ?
+ `<button class="b3-button b3-button--outline" data-type="diffRetry">${window.siyuan.languages.retry}</button>` : ""}`;
+ };
+
+ const renderLoading = () => {
+ destroyEditors();
+ diff = undefined;
+ visibleDifferences = [];
+ differenceIndex = -1;
+ renderCount();
+ legendElement.classList.add("fn__none");
+ setMessage();
+ panels.forEach((panel, index) => {
+ panel.querySelector(".history__compare-label").textContent = index === 0 ? leftRef.label : rightRef.label;
+ panel.querySelector(".protyle-title__input").textContent = "";
+ panel.querySelector(".history__compare-content").innerHTML =
+ '<div class="fn__loading"><img style="height: 64px;width: 64px" src="/stage/loading-pure.svg"></div>';
+ });
+ };
+
+ const renderFilters = () => {
+ const counts = countDocVersionDifferences(diff.differences);
+ const items: {value: DocVersionDiffFilter, label: string, count: number}[] = [
+ {value: "all", label: window.siyuan.languages.all, count: counts.all},
+ {value: "added", label: window.siyuan.languages.addAttr, count: counts.added},
+ {value: "removed", label: window.siyuan.languages.remove, count: counts.removed},
+ {value: "modified", label: window.siyuan.languages.update, count: counts.modified},
+ ];
+ legendElement.innerHTML = items.map((item) => {
+ return `<button type="button" class="b3-chip b3-chip--middle b3-chip--pointer history__compare-filter history__compare-filter--${item.value}${filter === item.value ? " b3-chip--current" : ""}" data-type="diffFilter" data-value="${item.value}" aria-pressed="${filter === item.value}"><span></span>${item.label} ${item.count}</button>`;
+ }).join("");
+ legendElement.classList.remove("fn__none");
+ };
+
+ const applyFilter = () => {
+ if (!diff) {
+ return;
+ }
+ visibleDifferences = diff.differences.filter((item) => matchesDocVersionDiffFilter(item, filter));
+ differenceIndex = -1;
+ panels.forEach((panel) => {
+ panel.querySelectorAll(".history__diff--filtered").forEach((item) => {
+ item.classList.remove("history__diff--filtered");
+ });
+ });
+ diff.differences.forEach((item) => {
+ if (matchesDocVersionDiffFilter(item, filter)) {
+ return;
+ }
+ panels.forEach((panel) => {
+ const target = item.id === diff.left.rootID ?
+ panel.querySelector(".protyle-title__input") :
+ panel.querySelector(`[data-node-id="${CSS.escape(item.id)}"]`);
+ target?.classList.add("history__diff--filtered");
+ });
+ });
+ legendElement.querySelectorAll<HTMLElement>('[data-type="diffFilter"]').forEach((item) => {
+ const current = item.dataset.value === filter;
+ item.classList.toggle("b3-chip--current", current);
+ item.setAttribute("aria-pressed", current.toString());
+ });
+ renderCount();
};
+
const focusDifference = (step: number) => {
- if (!diff || diff.differences.length === 0) {
+ if (!diff || visibleDifferences.length === 0) {
return;
}
- differenceIndex = (differenceIndex + step + diff.differences.length) % diff.differences.length;
+ differenceIndex = (differenceIndex + step + visibleDifferences.length) % visibleDifferences.length;
rootElement.querySelectorAll(".history__diff--focus").forEach((item) => {
item.classList.remove("history__diff--focus");
});
- const id = diff.differences[differenceIndex].id;
- editorsElement.querySelectorAll(".history__compare-panel").forEach((panel) => {
- const block = panel.querySelector(`[data-node-id="${CSS.escape(id)}"]`);
- const target = block || (id === diff.left.rootID ? panel.querySelector(".protyle-title__input") : undefined);
- if (target) {
- target.classList.add("history__diff--focus");
- target.scrollIntoView({block: "center"});
+ const id = visibleDifferences[differenceIndex].id;
+ isSyncingScroll = true;
+ panels.forEach((panel, index) => {
+ const block = panel.querySelector<HTMLElement>(`[data-node-id="${CSS.escape(id)}"]`);
+ const target = block || (id === diff.left.rootID ?
+ panel.querySelector<HTMLElement>(".protyle-title__input") : undefined);
+ if (!target) {
+ return;
+ }
+ target.classList.add("history__diff--focus");
+ const scrollElement = editors[index]?.protyle.contentElement;
+ if (block && scrollElement) {
+ const scrollRect = scrollElement.getBoundingClientRect();
+ const blockRect = block.getBoundingClientRect();
+ scrollElement.scrollTop += blockRect.top - scrollRect.top - (scrollRect.height - blockRect.height) / 2;
}
});
+ requestAnimationFrame(() => {
+ isSyncingScroll = false;
+ });
renderCount();
};
- rootElement.addEventListener("click", (event) => {
- const target = (event.target as HTMLElement).closest("[data-type]") as HTMLElement;
- if (!target) {
+ const setupScrollSync = () => {
+ if (editors.length !== 2) {
return;
}
- if (target.dataset.type === "diffPrevious") {
- focusDifference(-1);
- } else if (target.dataset.type === "diffNext") {
- focusDifference(1);
- } else if (target.dataset.type === "diffSwap") {
- editorsElement.append(editorsElement.firstElementChild);
- }
- });
+ const left = editors[0].protyle.contentElement;
+ const right = editors[1].protyle.contentElement;
+ const sync = (source: HTMLElement, target: HTMLElement) => {
+ if (isSyncingScroll) {
+ return;
+ }
+ isSyncingScroll = true;
+ syncDocVersionScroll(source, target);
+ requestAnimationFrame(() => {
+ isSyncingScroll = false;
+ });
+ };
+ const syncLeft = () => sync(left, right);
+ const syncRight = () => sync(right, left);
+ left.addEventListener("scroll", syncLeft, {passive: true});
+ right.addEventListener("scroll", syncRight, {passive: true});
+ removeScrollListeners = () => {
+ left.removeEventListener("scroll", syncLeft);
+ right.removeEventListener("scroll", syncRight);
+ };
+ };
- fetchPost("/api/history/diffDocVersions", {
- left: {
- type: leftRef.type,
- id: leftRef.id || "",
- path: leftRef.path || "",
- },
- right: {
- type: rightRef.type,
- id: rightRef.id || "",
- path: rightRef.path || "",
- }
- }, (response) => {
- diff = response.data as IDocVersionDiff;
+ const renderDiff = () => {
const contents = [diff.left, diff.right];
const refs = [leftRef, rightRef];
- editorsElement.querySelectorAll(".history__compare-panel").forEach((panel, index) => {
- const titleElement = panel.querySelector(".protyle-title__input");
+ panels.forEach((panel, index) => {
+ panel.querySelector(".history__compare-label").textContent = refs[index].label;
+ const titleElement = panel.querySelector(".protyle-title__input") as HTMLElement;
titleElement.textContent = contents[index].title;
if (diff.titleModified) {
titleElement.setAttribute("data-history-diff", "modified");
+ } else {
+ titleElement.removeAttribute("data-history-diff");
}
const contentElement = panel.querySelector(".history__compare-content") as HTMLElement;
- if (diff.large) {
+ if (diff.large || diff.fallback) {
contentElement.innerHTML = '<textarea class="history__text fn__block" readonly></textarea>';
(contentElement.firstElementChild as HTMLTextAreaElement).value = contents[index].content;
return;
}
+ contentElement.innerHTML = "";
const editor = new Protyle(app, contentElement, {
blockId: "",
action: [Constants.CB_GET_HISTORY],
@@ -193,7 +343,81 @@ export const showDocVersionDiff = (app: App, leftRef: IDocVersionRef, rightRef:
action: [Constants.CB_GET_HISTORY, Constants.CB_GET_HTML],
});
});
- renderCount();
+ if (diff.large || diff.fallback) {
+ setMessage(diff.fallback ? diff.message : window.siyuan.languages._kernel[36]);
+ visibleDifferences = [];
+ differenceIndex = -1;
+ legendElement.classList.add("fn__none");
+ renderCount();
+ return;
+ }
+ setupScrollSync();
+ renderFilters();
+ applyFilter();
+ focusDifference(1);
+ };
+
+ const loadDiff = async () => {
+ const currentRequestId = ++requestId;
+ renderLoading();
+ try {
+ const response = await fetchSyncPost("/api/history/diffDocVersions", {
+ left: {
+ type: leftRef.type,
+ id: leftRef.id || "",
+ path: leftRef.path || "",
+ },
+ right: {
+ type: rightRef.type,
+ id: rightRef.id || "",
+ path: rightRef.path || "",
+ }
+ });
+ if (isDestroyed || currentRequestId !== requestId) {
+ return;
+ }
+ if (response.code !== 0 || !response.data) {
+ panels.forEach((panel) => {
+ panel.querySelector(".history__compare-content").innerHTML = "";
+ });
+ setMessage(response.msg || window.siyuan.languages.emptyContent, true);
+ return;
+ }
+ diff = response.data as IDocVersionDiff;
+ renderDiff();
+ } catch (error) {
+ if (isDestroyed || currentRequestId !== requestId) {
+ return;
+ }
+ panels.forEach((panel) => {
+ panel.querySelector(".history__compare-content").innerHTML = "";
+ });
+ setMessage(error instanceof Error ? error.message : String(error), true);
+ }
+ };
+
+ rootElement.addEventListener("click", (event) => {
+ const target = (event.target as HTMLElement).closest("[data-type]") as HTMLElement;
+ if (!target) {
+ return;
+ }
+ if (target.dataset.type === "diffPrevious") {
+ focusDifference(-1);
+ } else if (target.dataset.type === "diffNext") {
+ focusDifference(1);
+ } else if (target.dataset.type === "diffSwap") {
+ [leftRef, rightRef] = [rightRef, leftRef];
+ loadDiff();
+ } else if (target.dataset.type === "diffFilter") {
+ const nextFilter = target.dataset.value as DocVersionDiffFilter;
+ filter = filter === nextFilter ? "all" : nextFilter;
+ applyFilter();
+ focusDifference(1);
+ } else if (target.dataset.type === "diffRetry") {
+ loadDiff();
+ }
});
+
+ loadDiff();
(document.activeElement as HTMLElement)?.blur();
};
diff --git a/app/src/history/docDiffCore.test.ts b/app/src/history/docDiffCore.test.ts
new file mode 100644
index 0000000000..7b243b7187
--- /dev/null
+++ b/app/src/history/docDiffCore.test.ts
@@ -0,0 +1,53 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {
+ countDocVersionDifferences,
+ type IDocVersionDifference,
+ type IDocVersionRef,
+ matchesDocVersionDiffFilter,
+ orderDocVersionRefs,
+} from "./docDiffCore";
+
+const version = (label: string, created: number): IDocVersionRef => ({
+ type: "snapshot",
+ id: label,
+ label,
+ created,
+});
+
+describe("orderDocVersionRefs", () => {
+ it("orders the older version before the newer version", () => {
+ const older = version("older", 1);
+ const newer = version("newer", 2);
+
+ assert.deepEqual(orderDocVersionRefs(newer, older), [older, newer]);
+ assert.deepEqual(orderDocVersionRefs(older, newer), [older, newer]);
+ });
+});
+
+describe("document version difference filters", () => {
+ const differences: IDocVersionDifference[] = [
+ {id: "added", statuses: ["right-only"]},
+ {id: "removed", statuses: ["left-only"]},
+ {id: "modified", statuses: ["modified"]},
+ {id: "moved", statuses: ["moved"]},
+ {id: "modified-and-moved", statuses: ["modified", "moved"]},
+ ];
+
+ it("maps directional statuses to user-facing filters", () => {
+ assert.equal(matchesDocVersionDiffFilter(differences[0], "added"), true);
+ assert.equal(matchesDocVersionDiffFilter(differences[1], "removed"), true);
+ assert.equal(matchesDocVersionDiffFilter(differences[2], "modified"), true);
+ assert.equal(matchesDocVersionDiffFilter(differences[3], "modified"), true);
+ assert.equal(matchesDocVersionDiffFilter(differences[0], "removed"), false);
+ });
+
+ it("counts each filter without double-counting moved modifications", () => {
+ assert.deepEqual(countDocVersionDifferences(differences), {
+ all: 5,
+ added: 1,
+ removed: 1,
+ modified: 3,
+ });
+ });
+});
diff --git a/app/src/history/docDiffCore.ts b/app/src/history/docDiffCore.ts
new file mode 100644
index 0000000000..447097668d
--- /dev/null
+++ b/app/src/history/docDiffCore.ts
@@ -0,0 +1,45 @@
+export type DocVersionType = "current" | "history" | "snapshot";
+
+export interface IDocVersionRef {
+ type: DocVersionType;
+ id?: string;
+ path?: string;
+ snapshot?: string;
+ label: string;
+ created: number;
+}
+
+export type DocVersionDiffStatus = "left-only" | "right-only" | "modified" | "moved";
+export type DocVersionDiffFilter = "all" | "added" | "removed" | "modified";
+
+export interface IDocVersionDifference {
+ id: string;
+ statuses: DocVersionDiffStatus[];
+}
+
+export const orderDocVersionRefs = (left: IDocVersionRef, right: IDocVersionRef):
+ [IDocVersionRef, IDocVersionRef] => {
+ return left.created <= right.created ? [left, right] : [right, left];
+};
+
+export const matchesDocVersionDiffFilter = (difference: IDocVersionDifference, filter: DocVersionDiffFilter) => {
+ if (filter === "all") {
+ return true;
+ }
+ if (filter === "added") {
+ return difference.statuses.includes("right-only");
+ }
+ if (filter === "removed") {
+ return difference.statuses.includes("left-only");
+ }
+ return difference.statuses.includes("modified") || difference.statuses.includes("moved");
+};
+
+export const countDocVersionDifferences = (differences: IDocVersionDifference[]) => {
+ return {
+ all: differences.length,
+ added: differences.filter((item) => matchesDocVersionDiffFilter(item, "added")).length,
+ removed: differences.filter((item) => matchesDocVersionDiffFilter(item, "removed")).length,
+ modified: differences.filter((item) => matchesDocVersionDiffFilter(item, "modified")).length,
+ };
+};
diff --git a/kernel/model/history_diff.go b/kernel/model/history_diff.go
index d63e9e30c5..e0ddaa7853 100644
--- a/kernel/model/history_diff.go
+++ b/kernel/model/history_diff.go
@@ -54,6 +54,8 @@ type DocVersionDiffResult struct {
Right *DocVersionDiffContent `json:"right"`
Differences []*DocVersionDifference `json:"differences"`
Large bool `json:"large"`
+ Fallback bool `json:"fallback"`
+ Message string `json:"message"`
TitleModified bool `json:"titleModified"`
}
@@ -70,9 +72,12 @@ type DocVersionDifference struct {
}
type loadedDocVersion struct {
- tree *parse.Tree
- title string
- large bool
+ tree *parse.Tree
+ title string
+ rootID string
+ raw []byte
+ parseErr error
+ large bool
}
type docDiffBlock struct {
@@ -86,6 +91,7 @@ type docTextSegment struct {
start int
end int
storedRuns []string
+ signature string
}
// DiffDocVersions 比较同一文档的两个版本,并返回带临时差异标记的只读块 DOM。
@@ -101,7 +107,7 @@ func DiffDocVersions(leftRef, rightRef *DocVersionRef) (ret *DocVersionDiffResul
if err != nil {
return nil, err
}
- if left.tree.Root.ID != right.tree.Root.ID {
+ if "" != left.rootID && "" != right.rootID && left.rootID != right.rootID {
return nil, errors.New("document versions do not belong to the same document")
}
@@ -110,6 +116,14 @@ func DiffDocVersions(leftRef, rightRef *DocVersionRef) (ret *DocVersionDiffResul
Large: left.large || right.large,
TitleModified: left.title != right.title,
}
+ if nil == left.tree || nil == right.tree {
+ ret.Fallback = true
+ ret.Message = docVersionFallbackMessage(left, right)
+ ret.TitleModified = false
+ ret.Left = renderFallbackDocVersion(left)
+ ret.Right = renderFallbackDocVersion(right)
+ return
+ }
if ret.TitleModified {
ret.Differences = append(ret.Differences, &DocVersionDifference{
ID: left.tree.Root.ID,
@@ -193,6 +207,7 @@ func loadDocVersion(ref *DocVersionRef) (ret *loadedDocVersion, err error) {
ret = &loadedDocVersion{}
ret.tree, err = LoadTreeByBlockID(ref.ID)
if nil == err && nil != ret.tree {
+ ret.rootID = ret.tree.Root.ID
if info, statErr := os.Stat(filepath.Join(util.DataDir, ret.tree.Box, filepath.FromSlash(ret.tree.Path))); nil == statErr {
ret.large = 1024*1024 <= info.Size()
}
@@ -207,12 +222,18 @@ func loadDocVersion(ref *DocVersionRef) (ret *loadedDocVersion, err error) {
if err != nil {
return nil, err
}
- if nil == ret || nil == ret.tree || nil == ret.tree.Root {
+ if nil == ret || (nil == ret.tree && 0 == len(ret.raw)) || (nil != ret.tree && nil == ret.tree.Root) {
return nil, errors.New("document version is empty")
}
- if "" == ret.title {
+ if nil != ret.tree && "" == ret.rootID {
+ ret.rootID = ret.tree.Root.ID
+ }
+ if nil != ret.tree && "" == ret.title {
ret.title = ret.tree.Root.IALAttr("title")
}
+ if "" == ret.title {
+ ret.title = ret.rootID
+ }
return
}
@@ -253,10 +274,23 @@ func loadHistoryDocVersion(historyPath string) (ret *loadedDocVersion, err error
luteEngine := NewLute()
tree, err := dataparser.ParseJSONWithoutFix(data, luteEngine.ParseOptions)
+ rootID := strings.TrimSuffix(filepath.Base(absPath), filepath.Ext(absPath))
if err != nil {
- return nil, err
- }
- return &loadedDocVersion{tree: tree, title: tree.Root.IALAttr("title"), large: 1024*1024 <= len(data)}, nil
+ return &loadedDocVersion{
+ title: rootID,
+ rootID: rootID,
+ raw: data,
+ parseErr: err,
+ large: 1024*1024 <= len(data),
+ }, nil
+ }
+ return &loadedDocVersion{
+ tree: tree,
+ title: tree.Root.IALAttr("title"),
+ rootID: tree.Root.ID,
+ raw: data,
+ large: 1024*1024 <= len(data),
+ }, nil
}
func loadSnapshotDocVersion(fileID string) (ret *loadedDocVersion, err error) {
@@ -277,6 +311,16 @@ func loadSnapshotDocVersion(fileID string) (ret *loadedDocVersion, err error) {
if !strings.HasSuffix(strings.ToLower(file.Path), ".sy") {
return nil, errors.New("snapshot version is not a document")
}
+ repoPath := strings.TrimPrefix(file.Path, "/")
+ pathParts := strings.SplitN(repoPath, "/", 2)
+ if 0 < len(pathParts) && IsEncryptedBox(pathParts[0]) {
+ HoldBoxReadLock(pathParts[0])
+ _, unlockErr := GetDEKIfUnlocked(pathParts[0])
+ ReleaseBoxReadLock(pathParts[0])
+ if unlockErr != nil {
+ return nil, errors.New(Conf.Language(314))
+ }
+ }
data, err := repo.OpenFile(file)
if err != nil {
return nil, err
@@ -284,10 +328,23 @@ func loadSnapshotDocVersion(fileID string) (ret *loadedDocVersion, err error) {
data = decryptRepoDataIfNeeded(data, file.Path)
luteEngine := NewLute()
tree, err := dataparser.ParseJSONWithoutFix(data, luteEngine.ParseOptions)
+ rootID := strings.TrimSuffix(filepath.Base(file.Path), filepath.Ext(file.Path))
if err != nil {
- return nil, err
- }
- return &loadedDocVersion{tree: tree, title: tree.Root.IALAttr("title"), large: 1024*1024 <= len(data)}, nil
+ return &loadedDocVersion{
+ title: rootID,
+ rootID: rootID,
+ raw: data,
+ parseErr: err,
+ large: 1024*1024 <= len(data),
+ }, nil
+ }
+ return &loadedDocVersion{
+ tree: tree,
+ title: tree.Root.IALAttr("title"),
+ rootID: tree.Root.ID,
+ raw: data,
+ large: 1024*1024 <= len(data),
+ }, nil
}
func collectDocDiffBlocks(tree *parse.Tree) (blocks map[string]*docDiffBlock, children map[string][]string, order []string) {
@@ -448,7 +505,7 @@ func filterSharedDocBlockIDs(ids []string, other map[string]*docDiffBlock) (ret
func markDocInlineDiff(left, right *ast.Node) {
leftRunes, leftSegments, leftOK := collectDocTextSegments(left)
rightRunes, rightSegments, rightOK := collectDocTextSegments(right)
- if !leftOK || !rightOK || string(leftRunes) == string(rightRunes) {
+ if !leftOK || !rightOK {
return
}
matches, ok := lcsMatches(leftRunes, rightRunes, docDiffMaxLCSCells)
@@ -467,10 +524,28 @@ func markDocInlineDiff(left, right *ast.Node) {
leftChanged[match[0]] = false
rightChanged[match[1]] = false
}
+ leftSignatures := docTextSegmentSignatures(leftSegments, len(leftRunes))
+ rightSignatures := docTextSegmentSignatures(rightSegments, len(rightRunes))
+ for _, match := range matches {
+ if leftSignatures[match[0]] != rightSignatures[match[1]] {
+ leftChanged[match[0]] = true
+ rightChanged[match[1]] = true
+ }
+ }
applyDocTextDiff(leftSegments, leftChanged)
applyDocTextDiff(rightSegments, rightChanged)
}
+func docTextSegmentSignatures(segments []*docTextSegment, length int) (ret []string) {
+ ret = make([]string, length)
+ for _, segment := range segments {
+ for i := segment.start; i < segment.end; i++ {
+ ret[i] = segment.signature
+ }
+ }
+ return
+}
+
func collectDocTextSegments(block *ast.Node) (runes []rune, segments []*docTextSegment, ok bool) {
ok = true
ast.Walk(block, func(n *ast.Node, entering bool) ast.WalkStatus {
@@ -506,12 +581,28 @@ func collectDocTextSegments(block *ast.Node) (runes []rune, segments []*docTextS
start: start,
end: len(runes),
storedRuns: storedRuns,
+ signature: docTextNodeSignature(n),
})
return ast.WalkContinue
})
return
}
+func docTextNodeSignature(node *ast.Node) string {
+ if ast.NodeText == node.Type {
+ return node.Type.String()
+ }
+ return strings.Join([]string{
+ node.Type.String(),
+ node.TextMarkType,
+ node.TextMarkAHref,
+ node.TextMarkATitle,
+ node.TextMarkBlockRefID,
+ node.TextMarkFileAnnotationRefID,
+ node.TextMarkInlineMemoContent,
+ }, "|")
+}
+
func decodeDocTextMarkContent(node *ast.Node) (visible []rune, storedRuns []string) {
content := node.TextMarkTextContent
unescape := node.IsTextMarkType("code") || node.IsTextMarkType("tag") || node.IsTextMarkType("strong") ||
@@ -684,6 +775,27 @@ func prepareDocDiffTree(tree *parse.Tree) {
})
}
+func docVersionFallbackMessage(versions ...*loadedDocVersion) string {
+ for _, version := range versions {
+ if nil != version && nil != version.parseErr {
+ return version.parseErr.Error()
+ }
+ }
+ return ""
+}
+
+func renderFallbackDocVersion(version *loadedDocVersion) *DocVersionDiffContent {
+ if nil != version.tree {
+ return renderLargeDocVersion(version)
+ }
+ return &DocVersionDiffContent{
+ ID: version.rootID,
+ RootID: version.rootID,
+ Title: version.title,
+ Content: string(version.raw),
+ }
+}
+
func renderDocVersion(version *loadedDocVersion) *DocVersionDiffContent {
prepareDocDiffTree(version.tree)
luteEngine := NewLute()
diff --git a/kernel/model/history_diff_test.go b/kernel/model/history_diff_test.go
index c3695addb6..dc019f288a 100644
--- a/kernel/model/history_diff_test.go
+++ b/kernel/model/history_diff_test.go
@@ -80,6 +80,55 @@ func TestMarkDocInlineDiff(t *testing.T) {
}
}
+func TestMarkDocInlineFormatDiff(t *testing.T) {
+ left := &ast.Node{Type: ast.NodeParagraph, ID: "20260729000000-left01"}
+ left.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("same")})
+ right := &ast.Node{Type: ast.NodeParagraph, ID: "20260729000000-right1"}
+ right.AppendChild(&ast.Node{
+ Type: ast.NodeTextMark,
+ TextMarkType: "strong",
+ TextMarkTextContent: "same",
+ })
+
+ markDocInlineDiff(left, right)
+
+ if "inline" != left.FirstChild.IALAttr("data-history-diff") {
+ t.Fatal("expected changed formatting on the left to be marked")
+ }
+ if "inline" != right.FirstChild.IALAttr("data-history-diff") {
+ t.Fatal("expected changed formatting on the right to be marked")
+ }
+}
+
+func TestDocDiffBlockSignatureIgnoresDescendantsAndDisplayAttrs(t *testing.T) {
+ left := &ast.Node{
+ Type: ast.NodeBlockquote,
+ ID: "20260729000000-left01",
+ KramdownIAL: [][]string{
+ {"updated", "20260729000000"},
+ {"fold", "1"},
+ },
+ }
+ leftChild := &ast.Node{Type: ast.NodeParagraph, ID: "20260729000000-child1"}
+ leftChild.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("before")})
+ left.AppendChild(leftChild)
+
+ right := &ast.Node{
+ Type: ast.NodeBlockquote,
+ ID: "20260729000000-right1",
+ KramdownIAL: [][]string{
+ {"updated", "20260729000001"},
+ },
+ }
+ rightChild := &ast.Node{Type: ast.NodeParagraph, ID: "20260729000000-child1"}
+ rightChild.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("after")})
+ right.AppendChild(rightChild)
+
+ if docDiffBlockSignature(left) != docDiffBlockSignature(right) {
+ t.Fatal("expected descendant content and display attributes to be ignored")
+ }
+}
+
func TestDetectMovedDocBlocks(t *testing.T) {
left := map[string]*docDiffBlock{
"a": {parentID: "root"},