An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support comparing document versions https://github.com/siyuan-note/siyuan/issues/11601
Daniel4097f02af825
diff --git a/app/src/assets/scss/business/_history.scss b/app/src/assets/scss/business/_history.scssindex d2f389f25e..fa17bc08be 100644--- a/app/src/assets/scss/business/_history.scss+++ b/app/src/assets/scss/business/_history.scss@@ -116,4 +116,97 @@margin-top: 8px;}}++ &__doc-compare {+ height: 100%;+ min-height: 0;+ }++ &__compare {+ &-scroll {+ min-height: 0;+ overflow-x: auto;+ overflow-y: hidden;+ }++ &-editors {+ height: 100%;+ min-width: 720px;+ }++ &-panel {+ width: 50%;+ min-width: 360px;+ min-height: 0;+ background: var(--b3-theme-background);++ & + & {+ border-left: 1px solid var(--b3-border-color);+ }++ &:first-child {+ [data-history-diff~="only"],+ [data-history-diff="inline"] {+ background-color: color-mix(in srgb, var(--b3-theme-error) 18%, transparent);+ }+ }++ &:last-child {+ [data-history-diff~="only"],+ [data-history-diff="inline"] {+ background-color: color-mix(in srgb, var(--b3-theme-primary) 18%, transparent);+ }+ }++ [data-history-diff~="modified"] {+ box-shadow: 3px 0 0 var(--b3-theme-primary) inset;+ }++ [data-history-diff~="moved"] {+ outline: 1px dashed var(--b3-theme-on-surface);+ outline-offset: -1px;+ }+ }++ &-label {+ flex-shrink: 0;+ padding: 4px 8px;+ text-align: center;+ border-bottom: 1px solid var(--b3-border-color);+ }++ &-content {+ min-height: 0;++ > .protyle {+ height: 100%;+ }++ > textarea {+ height: 100%;+ }+ }+ }++ &__diff-count {+ min-width: 48px;+ padding: 0 4px;+ text-align: center;+ }++ &__diff--focus {+ animation: history-diff-focus 1.2s ease-out;+ }+}++@keyframes history-diff-focus {+ 0%,+ 40% {+ outline: 2px solid var(--b3-theme-primary);+ outline-offset: -2px;+ }++ 100% {+ outline-color: transparent;+ }}diff --git a/app/src/history/doc.ts b/app/src/history/doc.tsindex 4108f1ca11..5f8e5cecb1 100644--- a/app/src/history/doc.ts+++ b/app/src/history/doc.ts@@ -10,6 +10,7 @@ import type {App} from "../index";import {resizeSide} from "./resizeSide";import {escapeHtml} from "../util/escape";import {renderRepoFile, renderRepoFileList, rollbackRepoFile, saveRepoFile} from "./repoFile";+import {showDocVersionDiff, type IDocVersionRef} from "./docDiff";let historyEditor: Protyle;const repoHistoryEditors = new WeakMap<HTMLElement, Protyle>();@@ -52,6 +53,7 @@ const renderDoc = (element: HTMLElement, currentPage: number, id: string) => {pageInfoElement.textContent = window.siyuan.languages.pageCountAndHistoryCount.replace("${x}", response.data.pageCount).replace("${y}", response.data.totalCount);if (response.data.histories.length === 0) {listElement.innerHTML = `<li class="b3-list--empty">${window.siyuan.languages.emptyContent}</li>`;+ element.dispatchEvent(new CustomEvent("versionListRendered"));return;}let logsHTML = "";@@ -59,12 +61,16 @@ const renderDoc = (element: HTMLElement, currentPage: number, id: string) => {logsHTML += `<li class="b3-list-item b3-list-item--hide-action" data-created="${item}"><span class="b3-list-item__text">${dayjs(parseInt(item) * 1000).format("YYYY-MM-DD HH:mm:ss")}</span><span class="fn__space"></span>+ <span class="b3-list-item__action b3-tooltips b3-tooltips__w" data-type="selectVersion" aria-pressed="false" aria-label="${window.siyuan.languages.compare}">+ <svg><use xlink:href="#iconUncheck"></use></svg>+ </span><span class="b3-list-item__action b3-tooltips b3-tooltips__w" data-type="rollback" aria-label="${window.siyuan.languages.rollback}"><svg><use xlink:href="#iconUndo"></use></svg></span></li>`;});listElement.innerHTML = logsHTML;+ element.dispatchEvent(new CustomEvent("versionListRendered"));});};@@ -123,7 +129,8 @@ const renderRepo = async (element: HTMLElement, currentPage: number, id: string).replace("${x}", pageCount).replace("${y}", response.data.totalCount);pageInfoElement.classList.remove("fn__none");- renderRepoFileList(response.data.files, listElement, false);+ renderRepoFileList(response.data.files, listElement, false, true);+ element.dispatchEvent(new CustomEvent("versionListRendered"));};export const openDocHistory = (options: {@@ -132,6 +139,12 @@ export const openDocHistory = (options: {notebookId: string,pathString: string}) => {+ const currentVersion = {+ type: "current" as const,+ id: options.id,+ label: window.siyuan.languages.currentVer,+ };+ const selectedVersions: IDocVersionRef[] = [currentVersion];const contentHTML = `<div class="fn__flex-column" style="height: 100%;"><div class="layout-tab-bar fn__flex" ${isMobile() ? "" : 'style="border-radius: var(--b3-border-radius-b) var(--b3-border-radius-b) 0 0"'}><div data-type="doc" class="item item--full item--focus"><span class="fn__flex-1"></span><span class="item__text">${window.siyuan.languages.fileHistory}</span><span class="fn__flex-1"></span></div>@@ -156,6 +169,10 @@ export const openDocHistory = (options: {<option value="replace">${window.siyuan.languages.historyReplace}</option><option value="outline">${window.siyuan.languages.historyOutline}</option></select>+ <span class="fn__space"></span>+ <button class="b3-button b3-button--outline" data-type="selectCurrentVersion" aria-pressed="true"><svg><use xlink:href="#iconCheck"></use></svg>${window.siyuan.languages.currentVer}</button>+ <span class="fn__space"></span>+ <button class="b3-button b3-button--outline" data-type="compareVersions" disabled>${window.siyuan.languages.compare}</button></div></div><div class="fn__flex fn__flex-1 history__panel">@@ -180,6 +197,9 @@ export const openDocHistory = (options: {<span class="ft__on-surface fn__flex-shrink ft__selectnone fn__none">${window.siyuan.languages.pageCountAndSnapshotCount}</span><span class="fn__space"></span><div class="fn__flex-1"></div>+ <button class="b3-button b3-button--outline" data-type="selectCurrentVersion" aria-pressed="true"><svg><use xlink:href="#iconCheck"></use></svg>${window.siyuan.languages.currentVer}</button>+ <span class="fn__space"></span>+ <button class="b3-button b3-button--outline" data-type="compareVersions" disabled>${window.siyuan.languages.compare}</button></div></div><div class="fn__flex fn__flex-1 history__panel">@@ -209,8 +229,48 @@ export const openDocHistory = (options: {});dialog.element.setAttribute("data-key", Constants.DIALOG_HISTORYDOC);+ const versionKey = (version: IDocVersionRef) => `${version.type}:${version.id || version.path || ""}`;+ const syncVersionSelection = () => {+ const selectedKeys = new Set(selectedVersions.map(versionKey));+ dialog.element.querySelectorAll('[data-type="selectCurrentVersion"]').forEach((item) => {+ const selected = selectedKeys.has(versionKey(currentVersion));+ item.setAttribute("aria-pressed", selected.toString());+ item.querySelector("use").setAttribute("xlink:href", selected ? "#iconCheck" : "#iconUncheck");+ });+ dialog.element.querySelectorAll('[data-type="selectVersion"]').forEach((item) => {+ const row = item.closest(".b3-list-item");+ const type = row.getAttribute("data-type") === "searchFileItem" ? "snapshot" : "history";+ const id = type === "snapshot" ? row.getAttribute("data-id") : row.getAttribute("data-created");+ const selected = selectedKeys.has(`${type}:${id}`);+ item.setAttribute("aria-pressed", selected.toString());+ item.querySelector("use").setAttribute("xlink:href", selected ? "#iconCheck" : "#iconUncheck");+ });+ dialog.element.querySelectorAll('[data-type="compareVersions"]').forEach((item) => {+ if (selectedVersions.length === 2) {+ item.removeAttribute("disabled");+ } else {+ item.setAttribute("disabled", "disabled");+ }+ });+ };+ const toggleVersionSelection = (version: IDocVersionRef) => {+ const key = versionKey(version);+ const index = selectedVersions.findIndex((item) => versionKey(item) === key);+ if (index > -1) {+ selectedVersions.splice(index, 1);+ } else {+ if (selectedVersions.length === 2) {+ selectedVersions.shift();+ }+ selectedVersions.push(version);+ }+ syncVersionSelection();+ };+const fileElement = dialog.element.querySelector('#docHistoryContainer [data-type="doc"]') as HTMLElement;const repoElement = dialog.element.querySelector('#docHistoryContainer [data-type="repo"]') as HTMLElement;+ fileElement.addEventListener("versionListRendered", syncVersionSelection);+ repoElement.addEventListener("versionListRendered", syncVersionSelection);const opElement = fileElement.querySelector(".b3-select") as HTMLSelectElement;opElement.addEventListener("change", () => {renderDoc(fileElement, 1, options.id);@@ -283,17 +343,53 @@ export const openDocHistory = (options: {event.stopPropagation();event.preventDefault();break;+ } else if (type === "selectVersion" && repoFileElement) {+ 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"),+ });+ event.stopPropagation();+ event.preventDefault();+ break;} else if (type === "view" && repoFileElement) {previewRepoFile(repoFileElement);event.stopPropagation();event.preventDefault();break;+ } else if (type === "selectVersion" && !isLoading) {+ const historyItemElement = target.parentElement;+ 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(),+ });+ });+ event.stopPropagation();+ event.preventDefault();+ break;+ } else if (type === "selectCurrentVersion") {+ toggleVersionSelection(currentVersion);+ event.stopPropagation();+ event.preventDefault();+ break;+ } else if (type === "compareVersions" && target.getAttribute("disabled") !== "disabled" &&+ selectedVersions.length === 2) {+ showDocVersionDiff(options.app, selectedVersions[0], selectedVersions[1]);+ event.stopPropagation();+ event.preventDefault();+ break;} else if (type === "rollback" && !isLoading) {- getHistoryPath(target.parentElement, opElement.value, options.id, (item) => {+ const historyItemElement = target.parentElement;+ getHistoryPath(historyItemElement, opElement.value, options.id, (item) => {const dataPath = item.path;isLoading = false;const confirmTip = window.siyuan.languages.rollbackConfirm.replace("${name}", escapeHtml(item.title))- .replace("${time}", target.previousElementSibling.previousElementSibling.textContent.trim());+ .replace("${time}", historyItemElement.querySelector(".b3-list-item__text").textContent.trim());confirmDialog("⚠️ " + window.siyuan.languages.rollback, confirmTip, () => {fetchPost("/api/history/rollbackDocHistory", {historyPath: dataPathdiff --git a/app/src/history/docDiff.ts b/app/src/history/docDiff.tsnew file mode 100644index 0000000000..2546b7764b--- /dev/null+++ b/app/src/history/docDiff.ts@@ -0,0 +1,199 @@+import {Constants} from "../constants";+import {Dialog} from "../dialog";+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 {isMobile} from "../util/functions";++export interface IDocVersionRef {+ type: "current" | "history" | "snapshot";+ id?: string;+ path?: string;+ snapshot?: string;+ label: string;+}++interface IDocVersionContent {+ id: string;+ rootID: string;+ title: string;+ content: string;+}++interface IDocVersionDifference {+ id: string;+ statuses: Array<"left-only" | "right-only" | "modified" | "moved">;+}++interface IDocVersionDiff {+ left: IDocVersionContent;+ right: IDocVersionContent;+ differences: IDocVersionDifference[];+ large: boolean;+ titleModified: boolean;+}++const toProtyleResponse = (content: IDocVersionContent) => {+ return {+ code: 0,+ data: {+ ...content,+ box: "",+ path: "",+ parentID: "",+ parent2ID: "",+ mode: 0,+ blockCount: 0,+ scroll: {},+ type: "NodeDocument",+ eof: false,+ isBacklinkExpand: false,+ isSyncing: false,+ }+ } as IWebSocketData;+};++export const showDocVersionDiff = (app: App, leftRef: IDocVersionRef, rightRef: IDocVersionRef) => {+ let editors: Protyle[] = [];+ let diff: IDocVersionDiff;+ let differenceIndex = -1;++ const dialog = new Dialog({+ title: window.siyuan.languages.compare,+ content: `<div class="history__doc-compare fn__flex-column">+ <div class="history__action">+ <div class="block__icons">+ <span class="block__icon block__icon--show b3-tooltips b3-tooltips__e" data-type="diffPrevious" aria-label="${window.siyuan.languages.previousLabel}">+ <svg><use xlink:href="#iconUp"></use></svg>+ </span>+ <span class="block__icon block__icon--show b3-tooltips b3-tooltips__e" data-type="diffNext" aria-label="${window.siyuan.languages.nextLabel}">+ <svg><use xlink:href="#iconDown"></use></svg>+ </span>+ <span class="history__diff-count ft__on-surface">0/0</span>+ <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-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="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="protyle-title__input ft__center ft__breakword"></div>+ <div class="history__compare-content fn__flex-1"></div>+ </div>+ </div>+ </div>+</div>`,+ width: isMobile() ? "100vw" : "90vw",+ height: isMobile() ? "100dvh" : "80vh",+ containerClassName: "b3-dialog__container--theme",+ destroyCallback() {+ editors.forEach((editor) => editor.destroy());+ editors = [];+ }+ });+ dialog.element.setAttribute("data-key", Constants.DIALOG_HISTORYCOMPARE);++ 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 renderCount = () => {+ countElement.textContent = `${differenceIndex < 0 ? 0 : differenceIndex + 1}/${diff?.differences.length || 0}`;+ };+ const focusDifference = (step: number) => {+ if (!diff || diff.differences.length === 0) {+ return;+ }+ differenceIndex = (differenceIndex + step + diff.differences.length) % diff.differences.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"});+ }+ });+ renderCount();+ };++ 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") {+ editorsElement.append(editorsElement.firstElementChild);+ }+ });++ 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 contents = [diff.left, diff.right];+ const refs = [leftRef, rightRef];+ editorsElement.querySelectorAll(".history__compare-panel").forEach((panel, index) => {+ const titleElement = panel.querySelector(".protyle-title__input");+ titleElement.textContent = contents[index].title;+ if (diff.titleModified) {+ titleElement.setAttribute("data-history-diff", "modified");+ }+ const contentElement = panel.querySelector(".history__compare-content") as HTMLElement;+ if (diff.large) {+ contentElement.innerHTML = '<textarea class="history__text fn__block" readonly></textarea>';+ (contentElement.firstElementChild as HTMLTextAreaElement).value = contents[index].content;+ return;+ }+ const editor = new Protyle(app, contentElement, {+ blockId: "",+ action: [Constants.CB_GET_HISTORY],+ history: {+ created: refs[index].type === "history" ? refs[index].id || "" : "",+ snapshot: refs[index].snapshot || "",+ },+ render: {+ background: false,+ gutter: false,+ breadcrumb: false,+ breadcrumbDocName: false,+ },+ typewriterMode: false,+ });+ disabledProtyle(editor.protyle);+ editors.push(editor);+ onGet({+ data: toProtyleResponse(contents[index]),+ protyle: editor.protyle,+ action: [Constants.CB_GET_HISTORY, Constants.CB_GET_HTML],+ });+ });+ renderCount();+ });+ (document.activeElement as HTMLElement)?.blur();+};diff --git a/app/src/history/history.ts b/app/src/history/history.tsindex 7418bb1e24..662be47432 100644--- a/app/src/history/history.ts+++ b/app/src/history/history.ts@@ -17,6 +17,7 @@ import type {App} from "../index";import {resizeSide} from "./resizeSide";import {isSupportCSSHL, searchMarkRender} from "../protyle/render/searchMarkRender";import {renderRepoFile, renderRepoFileList, rollbackRepoFile, saveRepoFile} from "./repoFile";+import {openDocHistory} from "./doc";let historyEditor: Protyle;const repoHistoryEditors = new WeakMap<Element, Protyle>();@@ -686,6 +687,17 @@ const bindEvent = (app: App, element: Element, dialog?: Dialog) => {event.stopPropagation();event.preventDefault();break;+ } else if (target.classList.contains("b3-list-item__action") && type === "compare") {+ const itemElement = target.closest(".b3-list-item");+ openDocHistory({+ app,+ id: itemElement.getAttribute("data-id"),+ notebookId: itemElement.getAttribute("data-notebook-id"),+ pathString: itemElement.querySelector(".b3-list-item__text").textContent.trim(),+ });+ event.stopPropagation();+ event.preventDefault();+ break;} else if (target.classList.contains("b3-list-item__action") && type === "rollback" && !window.siyuan.config.readonly) {const liElement = target.closest(".b3-list-item");const dataType = target.parentElement.getAttribute("data-type") || liElement.getAttribute("data-type");@@ -704,8 +716,8 @@ const bindEvent = (app: App, element: Element, dialog?: Dialog) => {name = window.siyuan.languages.workspaceData;time = (isMobile() ? target.parentElement.parentElement : target.parentElement).querySelector("span[data-type='hCreated']").textContent.trim();} else {- name = target.previousElementSibling.previousElementSibling.textContent.trim();- time = dayjs(parseInt(target.parentElement.getAttribute("data-created")) * 1000).format("YYYY-MM-DD HH:mm:ss");+ name = liElement.querySelector(".b3-list-item__text").textContent.trim();+ time = dayjs(parseInt(liElement.getAttribute("data-created")) * 1000).format("YYYY-MM-DD HH:mm:ss");}confirmDialog("⚠️ " + window.siyuan.languages.rollback,window.siyuan.languages.rollbackConfirm.replace("${name}", name).replace("${time}", time),@@ -779,6 +791,7 @@ const bindEvent = (app: App, element: Element, dialog?: Dialog) => {let html = "";let ariaLabel = "";response.data.items.forEach((docItem: {+ id: string,title: string,path: string,op: string,@@ -807,10 +820,15 @@ const bindEvent = (app: App, element: Element, dialog?: Dialog) => {chipClass += "b3-chip--warning ";ariaLabel = window.siyuan.languages.historyOutline;}- html += `<li data-notebook-id="${docItem.notebook}" data-created="${created}" data-type="${typeElement.value === "4" ? "av" : (typeElement.value === "2" ? "assets" : "doc")}" data-path="${docItem.path}" class="b3-list-item b3-list-item--hide-action" style="padding-left: 22px">+ const itemType = typeElement.value === "4" ? "av" : (typeElement.value === "2" ? "assets" : "doc");+ const compareHTML = itemType === "doc" && docItem.op !== "delete" ? `<span class="b3-list-item__action ariaLabel" data-type="compare" data-position="6south" aria-label="${window.siyuan.languages.compare}">+ <svg><use xlink:href="#iconSplitLR"></use></svg>+ </span>` : "";+ html += `<li data-id="${docItem.id}" data-notebook-id="${docItem.notebook}" data-created="${created}" data-type="${itemType}" data-path="${docItem.path}" class="b3-list-item b3-list-item--hide-action" style="padding-left: 22px"><span class="${opElement.value === "all" ? "" : "fn__none"}${chipClass}ariaLabel" data-position="6south" aria-label="${ariaLabel}">${docItem.op.substring(0, 1).toUpperCase()}</span><span class="b3-list-item__text" title="${escapeAttr(docItem.title)}">${escapeHtml(docItem.title)}</span><span class="fn__space"></span>+ ${compareHTML}<span class="b3-list-item__action ariaLabel" data-type="rollback" data-position="6south" aria-label="${window.siyuan.languages.rollback}"><svg><use xlink:href="#iconUndo"></use></svg></span>diff --git a/app/src/history/repoFile.ts b/app/src/history/repoFile.tsindex 68e09bc9d9..119f809231 100644--- a/app/src/history/repoFile.ts+++ b/app/src/history/repoFile.ts@@ -21,7 +21,7 @@ interface IRepoFile {let repoFileRequestId = 0;-export const renderRepoFileList = (files: IRepoFile[], element: Element, showPath: boolean) => {+export const renderRepoFileList = (files: IRepoFile[], element: Element, showPath: boolean, showCompare = false) => {if (files.length === 0) {element.innerHTML = `<li class="b3-list--empty">${window.siyuan.languages.emptyContent}</li>`;return;@@ -30,6 +30,14 @@ export const renderRepoFileList = (files: IRepoFile[], element: Element, showPatlet html = "";files.forEach((item) => {const pathHTML = showPath && item.hPath ? `${escapeHtml(item.hPath)}<span class="fn__space"></span>` : "";+ const compareHTML = showCompare ? `<span class="b3-list-item__action" data-type="selectVersion" aria-pressed="false">+ <svg><use xlink:href="#iconUncheck"></use></svg>+ <span class="fn__space"></span>${window.siyuan.languages.compare}+ </span>+ <span class="fn__space"></span>` : "";+ const compareIconHTML = showCompare ? `<span class="b3-list-item__action b3-tooltips b3-tooltips__w" data-type="selectVersion" aria-pressed="false" aria-label="${window.siyuan.languages.compare}">+ <svg><use xlink:href="#iconUncheck"></use></svg>+ </span>` : "";/// #if MOBILEhtml += `<li class="b3-list-item" data-type="searchFileItem" data-id="${item.fileID}" data-snapshot="${item.indexID}" data-created="${item.updated}"><div class="fn__flex-1">@@ -41,6 +49,7 @@ export const renderRepoFileList = (files: IRepoFile[], element: Element, showPat</div><div class="fn__flex" style="height: 26px"><span class="fn__flex-1"></span>+ ${compareHTML}<span class="b3-list-item__action" data-type="saveAs"><svg><use xlink:href="#iconDownload"></use></svg><span class="fn__space"></span>${window.siyuan.languages.saveAs}@@ -63,6 +72,7 @@ export const renderRepoFileList = (files: IRepoFile[], element: Element, showPat${dayjs(item.updated).format("YYYY-MM-DD HH:mm:ss")}</div></div>+ ${compareIconHTML}<span class="b3-list-item__action b3-tooltips b3-tooltips__w" data-type="saveAs" aria-label="${window.siyuan.languages.saveAs}"><svg><use xlink:href="#iconDownload"></use></svg></span>diff --git a/kernel/api/history.go b/kernel/api/history.goindex 8c80185298..5558ffbea3 100644--- a/kernel/api/history.go+++ b/kernel/api/history.go@@ -176,6 +176,57 @@ func getDocHistoryContent(c *gin.Context) {}}+func diffDocVersions(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ arg, ok := util.JsonArg(c, ret)+ if !ok {+ return+ }++ leftArg, ok := arg["left"].(map[string]interface{})+ if !ok {+ ret.Code = -1+ ret.Msg = "left document version is required"+ return+ }+ rightArg, ok := arg["right"].(map[string]interface{})+ if !ok {+ ret.Code = -1+ ret.Msg = "right document version is required"+ return+ }+ left, ok := parseDocVersionRef(leftArg, ret)+ if !ok {+ return+ }+ right, ok := parseDocVersionRef(rightArg, ret)+ if !ok {+ return+ }++ diff, err := model.DiffDocVersions(left, right)+ if err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ ret.Data = diff+}++func parseDocVersionRef(arg map[string]interface{}, ret *gulu.Result) (ref *model.DocVersionRef, ok bool) {+ var typ, id, path string+ if !util.ParseJsonArgs(arg, ret,+ util.BindJsonArg("type", &typ, true, true),+ util.BindJsonArg("id", &id, false, false),+ util.BindJsonArg("path", &path, false, false),+ ) {+ return nil, false+ }+ return &model.DocVersionRef{Type: typ, ID: id, Path: path}, true+}+func rollbackDocHistory(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)diff --git a/kernel/api/router.go b/kernel/api/router.goindex 2e8464c522..c385b5cf1e 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -184,6 +184,7 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/history/rollbackNotebookHistory", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, rollbackNotebookHistory)ginServer.Handle("POST", "/api/history/rollbackAssetsHistory", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, rollbackAssetsHistory)ginServer.Handle("POST", "/api/history/getDocHistoryContent", model.CheckAuth, model.CheckAdminRole, getDocHistoryContent)+ ginServer.Handle("POST", "/api/history/diffDocVersions", model.CheckAuth, model.CheckAdminRole, diffDocVersions)ginServer.Handle("POST", "/api/history/rollbackDocHistory", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, rollbackDocHistory)ginServer.Handle("POST", "/api/history/clearWorkspaceHistory", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, clearWorkspaceHistory)ginServer.Handle("POST", "/api/history/reindexHistory", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, reindexHistory)@@ -296,7 +297,7 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/file/removeFile", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, removeFile)ginServer.Handle("POST", "/api/file/renameFile", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, renameFile)ginServer.Handle("POST", "/api/file/readDir", model.CheckAuth, model.CheckAdminRole, readDir)- ginServer.Handle("POST", "/api/file/getUniqueFilename", model.CheckAuth, getUniqueFilename)+ ginServer.Handle("POST", "/api/file/getUniqueFilename", model.CheckAuth, model.CheckAdminRole, getUniqueFilename)ginServer.Handle("POST", "/api/ref/refreshBacklink", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, refreshBacklink)ginServer.Handle("POST", "/api/ref/getBacklink", model.CheckAuth, getBacklink)diff --git a/kernel/model/history.go b/kernel/model/history.goindex aa045c5bea..be149e7dbc 100644--- a/kernel/model/history.go+++ b/kernel/model/history.go@@ -610,6 +610,7 @@ type History struct {}type HistoryItem struct {+ ID string `json:"id"`Title string `json:"title"`Path string `json:"path"`Op string `json:"op"`@@ -1281,6 +1282,7 @@ func fromSQLHistories(sqlHistories []*sql.History) (ret []*HistoryItem) {for _, sqlHistory := range sqlHistories {item := &HistoryItem{+ ID: sqlHistory.ID,Title: sqlHistory.Title,Path: filepath.ToSlash(strings.TrimPrefix(filepath.Join(util.HistoryDir, sqlHistory.Path), util.WorkspaceDir)),Op: sqlHistory.Op,diff --git a/kernel/model/history_diff.go b/kernel/model/history_diff.gonew file mode 100644index 0000000000..d63e9e30c5--- /dev/null+++ b/kernel/model/history_diff.go@@ -0,0 +1,710 @@+// 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 (+ "errors"+ "fmt"+ stdhtml "html"+ "os"+ "path/filepath"+ "sort"+ "strconv"+ "strings"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/88250/lute/render"+ "github.com/siyuan-note/dataparser"+ "github.com/siyuan-note/filelock"+ "github.com/siyuan-note/siyuan/kernel/util"+)++const (+ docVersionCurrent = "current"+ docVersionHistory = "history"+ docVersionSnapshot = "snapshot"++ docDiffMaxLCSCells = 2_000_000+ docDiffMaxBlocks = 10_000+)++type DocVersionRef struct {+ Type string `json:"type"`+ ID string `json:"id"`+ Path string `json:"path"`+}++type DocVersionDiffResult struct {+ Left *DocVersionDiffContent `json:"left"`+ Right *DocVersionDiffContent `json:"right"`+ Differences []*DocVersionDifference `json:"differences"`+ Large bool `json:"large"`+ TitleModified bool `json:"titleModified"`+}++type DocVersionDiffContent struct {+ ID string `json:"id"`+ RootID string `json:"rootID"`+ Title string `json:"title"`+ Content string `json:"content"`+}++type DocVersionDifference struct {+ ID string `json:"id"`+ Statuses []string `json:"statuses"`+}++type loadedDocVersion struct {+ tree *parse.Tree+ title string+ large bool+}++type docDiffBlock struct {+ node *ast.Node+ parentID string+ signature string+}++type docTextSegment struct {+ node *ast.Node+ start int+ end int+ storedRuns []string+}++// DiffDocVersions 比较同一文档的两个版本,并返回带临时差异标记的只读块 DOM。+func DiffDocVersions(leftRef, rightRef *DocVersionRef) (ret *DocVersionDiffResult, err error) {+ if (nil != leftRef && docVersionCurrent == leftRef.Type) || (nil != rightRef && docVersionCurrent == rightRef.Type) {+ FlushTxQueue()+ }+ left, err := loadDocVersion(leftRef)+ if err != nil {+ return nil, err+ }+ right, err := loadDocVersion(rightRef)+ if err != nil {+ return nil, err+ }+ if left.tree.Root.ID != right.tree.Root.ID {+ return nil, errors.New("document versions do not belong to the same document")+ }++ ret = &DocVersionDiffResult{+ Differences: []*DocVersionDifference{},+ Large: left.large || right.large,+ TitleModified: left.title != right.title,+ }+ if ret.TitleModified {+ ret.Differences = append(ret.Differences, &DocVersionDifference{+ ID: left.tree.Root.ID,+ Statuses: []string{"modified"},+ })+ }+ if ret.Large {+ ret.Left = renderLargeDocVersion(left)+ ret.Right = renderLargeDocVersion(right)+ return+ }++ leftBlocks, leftChildren, leftOrder := collectDocDiffBlocks(left.tree)+ rightBlocks, rightChildren, rightOrder := collectDocDiffBlocks(right.tree)+ if len(leftBlocks) > docDiffMaxBlocks || len(rightBlocks) > docDiffMaxBlocks {+ ret.Large = true+ ret.Left = renderLargeDocVersion(left)+ ret.Right = renderLargeDocVersion(right)+ return+ }++ moved := detectMovedDocBlocks(leftBlocks, rightBlocks, leftChildren, rightChildren)+ ids := make([]string, 0, len(leftBlocks)+len(rightBlocks))+ seen := map[string]bool{}+ for _, id := range rightOrder {+ ids = append(ids, id)+ seen[id] = true+ }+ for _, id := range leftOrder {+ if !seen[id] {+ ids = append(ids, id)+ }+ }++ for _, id := range ids {+ leftBlock, leftOK := leftBlocks[id]+ rightBlock, rightOK := rightBlocks[id]+ var statuses []string+ switch {+ case leftOK && !rightOK:+ statuses = append(statuses, "left-only")+ setDocDiffBlockAttrs(leftBlock.node, []string{"only"})+ case !leftOK && rightOK:+ statuses = append(statuses, "right-only")+ setDocDiffBlockAttrs(rightBlock.node, []string{"only"})+ default:+ modified := leftBlock.signature != rightBlock.signature+ if modified {+ statuses = append(statuses, "modified")+ }+ if moved[id] {+ statuses = append(statuses, "moved")+ }+ if 0 < len(statuses) {+ setDocDiffBlockAttrs(leftBlock.node, statuses)+ setDocDiffBlockAttrs(rightBlock.node, statuses)+ }+ if modified {+ markDocInlineDiff(leftBlock.node, rightBlock.node)+ }+ }+ if 0 < len(statuses) {+ ret.Differences = append(ret.Differences, &DocVersionDifference{ID: id, Statuses: statuses})+ }+ }++ ret.Left = renderDocVersion(left)+ ret.Right = renderDocVersion(right)+ return+}++func loadDocVersion(ref *DocVersionRef) (ret *loadedDocVersion, err error) {+ if nil == ref {+ return nil, errors.New("document version is required")+ }+ switch ref.Type {+ case docVersionCurrent:+ if !ast.IsNodeIDPattern(ref.ID) {+ return nil, errors.New("current document ID is invalid")+ }+ ret = &loadedDocVersion{}+ ret.tree, err = LoadTreeByBlockID(ref.ID)+ if nil == err && nil != ret.tree {+ 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()+ }+ }+ case docVersionHistory:+ ret, err = loadHistoryDocVersion(ref.Path)+ case docVersionSnapshot:+ ret, err = loadSnapshotDocVersion(ref.ID)+ default:+ return nil, fmt.Errorf("unsupported document version type [%s]", ref.Type)+ }+ if err != nil {+ return nil, err+ }+ if nil == ret || nil == ret.tree || nil == ret.tree.Root {+ return nil, errors.New("document version is empty")+ }+ if "" == ret.title {+ ret.title = ret.tree.Root.IALAttr("title")+ }+ return+}++func loadHistoryDocVersion(historyPath string) (ret *loadedDocVersion, err error) {+ absPath, err := validateHistoryPath(historyPath)+ if err != nil {+ return nil, err+ }+ if !strings.HasSuffix(strings.ToLower(absPath), ".sy") {+ return nil, errors.New("history version is not a document")+ }+ data, err := filelock.ReadFile(absPath)+ if err != nil {+ return nil, err+ }++ relPath, err := filepath.Rel(util.HistoryDir, absPath)+ if err != nil {+ return nil, err+ }+ parts := strings.SplitN(filepath.ToSlash(relPath), "/", 3)+ if len(parts) >= 2 && IsEncryptedBox(parts[1]) {+ HoldBoxReadLock(parts[1])+ defer ReleaseBoxReadLock(parts[1])+ dek, dekErr := GetDEKIfUnlocked(parts[1])+ if dekErr != nil {+ return nil, errors.New(Conf.Language(314))+ }+ filePath := ""+ if len(parts) >= 3 {+ filePath = parts[2]+ }+ data, err = DecryptFile(parts[1], filePath, dek, data)+ if err != nil {+ return nil, err+ }+ }++ luteEngine := NewLute()+ tree, err := dataparser.ParseJSONWithoutFix(data, luteEngine.ParseOptions)+ if err != nil {+ return nil, err+ }+ return &loadedDocVersion{tree: tree, title: tree.Root.IALAttr("title"), large: 1024*1024 <= len(data)}, nil+}++func loadSnapshotDocVersion(fileID string) (ret *loadedDocVersion, err error) {+ if "" == fileID {+ return nil, errors.New("snapshot file ID is required")+ }+ if 1 > len(Conf.Repo.Key) {+ return nil, errors.New(Conf.Language(26))+ }+ repo, err := newRepository()+ if err != nil {+ return nil, err+ }+ file, err := repo.GetFile(fileID)+ if err != nil {+ return nil, err+ }+ if !strings.HasSuffix(strings.ToLower(file.Path), ".sy") {+ return nil, errors.New("snapshot version is not a document")+ }+ data, err := repo.OpenFile(file)+ if err != nil {+ return nil, err+ }+ data = decryptRepoDataIfNeeded(data, file.Path)+ luteEngine := NewLute()+ tree, err := dataparser.ParseJSONWithoutFix(data, luteEngine.ParseOptions)+ if err != nil {+ return nil, err+ }+ return &loadedDocVersion{tree: tree, title: tree.Root.IALAttr("title"), large: 1024*1024 <= len(data)}, nil+}++func collectDocDiffBlocks(tree *parse.Tree) (blocks map[string]*docDiffBlock, children map[string][]string, order []string) {+ blocks = map[string]*docDiffBlock{}+ children = map[string][]string{}+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {+ if !entering || ast.NodeDocument == n.Type || !n.IsBlock() || "" == n.ID {+ return ast.WalkContinue+ }+ parentID := parentDocDiffBlockID(n)+ blocks[n.ID] = &docDiffBlock{+ node: n,+ parentID: parentID,+ signature: docDiffBlockSignature(n),+ }+ children[parentID] = append(children[parentID], n.ID)+ order = append(order, n.ID)+ return ast.WalkContinue+ })+ return+}++func parentDocDiffBlockID(node *ast.Node) string {+ for parent := node.Parent; nil != parent; parent = parent.Parent {+ if ast.NodeDocument != parent.Type && parent.IsBlock() && "" != parent.ID {+ return parent.ID+ }+ }+ return ""+}++func docDiffBlockSignature(block *ast.Node) string {+ var builder strings.Builder+ builder.WriteString(block.Type.String())+ builder.WriteByte('|')+ builder.WriteString(strconv.Itoa(block.HeadingLevel))+ builder.WriteByte('|')+ builder.WriteString(strconv.Itoa(int(block.TaskListItemMarker)))+ builder.WriteByte('|')+ builder.WriteString(block.CustomBlockInfo)+ builder.WriteByte('|')+ builder.Write(block.CodeBlockInfo)+ builder.WriteByte('|')+ builder.WriteString(block.AttributeViewID)+ builder.WriteByte(':')+ builder.WriteString(block.AttributeViewType)+ builder.WriteByte('|')+ builder.WriteString(block.CalloutType)+ builder.WriteByte(':')+ builder.WriteString(block.CalloutTitle)+ builder.WriteByte(':')+ builder.WriteString(block.CalloutIcon)+ builder.WriteByte(':')+ builder.WriteString(strconv.Itoa(block.CalloutIconType))+ builder.WriteByte('|')+ if nil != block.ListData {+ builder.WriteString(strconv.Itoa(block.ListData.Typ))+ builder.WriteByte(':')+ builder.WriteString(strconv.FormatBool(block.ListData.Tight))+ builder.WriteByte(':')+ builder.WriteString(strconv.Itoa(int(block.ListData.BulletChar)))+ builder.WriteByte(':')+ builder.WriteString(strconv.Itoa(block.ListData.Start))+ builder.WriteByte(':')+ builder.WriteString(strconv.Itoa(int(block.ListData.Delimiter)))+ }+ builder.WriteByte('|')+ for _, align := range block.TableAligns {+ builder.WriteString(strconv.Itoa(align))+ builder.WriteByte(',')+ }++ attrs := make([]string, 0, len(block.KramdownIAL))+ for _, attr := range block.KramdownIAL {+ if 2 > len(attr) || "id" == attr[0] || "updated" == attr[0] || "fold" == attr[0] || "heading-fold" == attr[0] {+ continue+ }+ attrs = append(attrs, attr[0]+"="+attr[1])+ }+ sort.Strings(attrs)+ builder.WriteString(strings.Join(attrs, ";"))++ ast.Walk(block, func(n *ast.Node, entering bool) ast.WalkStatus {+ if !entering {+ return ast.WalkContinue+ }+ if n != block && n.IsBlock() {+ return ast.WalkSkipChildren+ }+ builder.WriteByte('|')+ builder.WriteString(n.Type.String())+ builder.WriteByte(':')+ switch n.Type {+ case ast.NodeTextMark:+ builder.WriteString(n.TextMarkType)+ builder.WriteByte(':')+ builder.WriteString(n.TextMarkTextContent)+ builder.WriteByte(':')+ builder.WriteString(n.TextMarkInlineMathContent)+ builder.WriteByte(':')+ builder.WriteString(n.TextMarkAHref)+ builder.WriteByte(':')+ builder.WriteString(n.TextMarkATitle)+ builder.WriteByte(':')+ builder.WriteString(n.TextMarkBlockRefID)+ builder.WriteByte(':')+ builder.WriteString(n.TextMarkFileAnnotationRefID)+ builder.WriteByte(':')+ builder.WriteString(n.TextMarkInlineMemoContent)+ default:+ builder.Write(n.Tokens)+ }+ return ast.WalkContinue+ })+ return builder.String()+}++func detectMovedDocBlocks(left, right map[string]*docDiffBlock, leftChildren, rightChildren map[string][]string) map[string]bool {+ ret := map[string]bool{}+ for id, leftBlock := range left {+ if rightBlock, ok := right[id]; ok && leftBlock.parentID != rightBlock.parentID {+ ret[id] = true+ }+ }+ for parentID, leftIDs := range leftChildren {+ rightIDs := rightChildren[parentID]+ if 0 == len(rightIDs) {+ continue+ }+ leftShared := filterSharedDocBlockIDs(leftIDs, right)+ rightShared := filterSharedDocBlockIDs(rightIDs, left)+ matches, ok := lcsMatches(leftShared, rightShared, docDiffMaxLCSCells)+ if !ok {+ continue+ }+ stable := map[string]bool{}+ for _, match := range matches {+ stable[leftShared[match[0]]] = true+ }+ for _, id := range leftShared {+ if !stable[id] {+ ret[id] = true+ }+ }+ }+ return ret+}++func filterSharedDocBlockIDs(ids []string, other map[string]*docDiffBlock) (ret []string) {+ for _, id := range ids {+ if _, ok := other[id]; ok {+ ret = append(ret, id)+ }+ }+ return+}++func markDocInlineDiff(left, right *ast.Node) {+ leftRunes, leftSegments, leftOK := collectDocTextSegments(left)+ rightRunes, rightSegments, rightOK := collectDocTextSegments(right)+ if !leftOK || !rightOK || string(leftRunes) == string(rightRunes) {+ return+ }+ matches, ok := lcsMatches(leftRunes, rightRunes, docDiffMaxLCSCells)+ if !ok {+ return+ }+ leftChanged := make([]bool, len(leftRunes))+ rightChanged := make([]bool, len(rightRunes))+ for i := range leftChanged {+ leftChanged[i] = true+ }+ for i := range rightChanged {+ rightChanged[i] = true+ }+ for _, match := range matches {+ leftChanged[match[0]] = false+ rightChanged[match[1]] = false+ }+ applyDocTextDiff(leftSegments, leftChanged)+ applyDocTextDiff(rightSegments, rightChanged)+}++func collectDocTextSegments(block *ast.Node) (runes []rune, segments []*docTextSegment, ok bool) {+ ok = true+ ast.Walk(block, func(n *ast.Node, entering bool) ast.WalkStatus {+ if !entering {+ return ast.WalkContinue+ }+ if n != block && n.IsBlock() {+ return ast.WalkSkipChildren+ }+ var visible []rune+ var storedRuns []string+ switch n.Type {+ case ast.NodeText:+ visible = []rune(string(n.Tokens))+ for _, r := range visible {+ storedRuns = append(storedRuns, string(r))+ }+ case ast.NodeTextMark:+ if "" == n.TextMarkTextContent || n.IsTextMarkType("inline-math") {+ return ast.WalkContinue+ }+ visible, storedRuns = decodeDocTextMarkContent(n)+ default:+ return ast.WalkContinue+ }+ if 0 == len(visible) {+ return ast.WalkContinue+ }+ start := len(runes)+ runes = append(runes, visible...)+ segments = append(segments, &docTextSegment{+ node: n,+ start: start,+ end: len(runes),+ storedRuns: storedRuns,+ })+ return ast.WalkContinue+ })+ return+}++func decodeDocTextMarkContent(node *ast.Node) (visible []rune, storedRuns []string) {+ content := node.TextMarkTextContent+ unescape := node.IsTextMarkType("code") || node.IsTextMarkType("tag") || node.IsTextMarkType("strong") ||+ node.IsTextMarkType("em") || node.IsTextMarkType("a")+ if !unescape {+ visible = []rune(content)+ for _, r := range visible {+ storedRuns = append(storedRuns, string(r))+ }+ return+ }++ for 0 < len(content) {+ if '&' == content[0] {+ if semicolon := strings.IndexByte(content, ';'); 0 < semicolon && semicolon < 32 {+ raw := content[:semicolon+1]+ decoded := stdhtml.UnescapeString(raw)+ if decoded != raw {+ decodedRunes := []rune(decoded)+ visible = append(visible, decodedRunes...)+ storedRuns = append(storedRuns, raw)+ for i := 1; i < len(decodedRunes); i++ {+ storedRuns = append(storedRuns, "")+ }+ content = content[semicolon+1:]+ continue+ }+ }+ }+ r := []rune(content)[0]+ raw := string(r)+ visible = append(visible, r)+ storedRuns = append(storedRuns, raw)+ content = content[len(raw):]+ }+ return+}++func applyDocTextDiff(segments []*docTextSegment, changed []bool) {+ for _, segment := range segments {+ local := changed[segment.start:segment.end]+ for start := 0; start < len(segment.storedRuns); {+ end := start + 1+ for end < len(segment.storedRuns) && "" == segment.storedRuns[end] {+ end+++ }+ groupChanged := false+ for i := start; i < end; i++ {+ groupChanged = groupChanged || local[i]+ }+ if groupChanged {+ for i := start; i < end; i++ {+ local[i] = true+ }+ }+ start = end+ }+ hasChanged := false+ for _, value := range local {+ if value {+ hasChanged = true+ break+ }+ }+ if !hasChanged {+ continue+ }++ type textPart struct {+ changed bool+ content string+ }+ var parts []textPart+ for i, value := range local {+ raw := segment.storedRuns[i]+ if 0 == len(parts) || parts[len(parts)-1].changed != value {+ parts = append(parts, textPart{changed: value, content: raw})+ } else {+ parts[len(parts)-1].content += raw+ }+ }+ for _, part := range parts {+ if "" == part.content {+ continue+ }+ replacement := cloneDocTextNode(segment.node)+ if ast.NodeText == replacement.Type {+ if part.changed {+ replacement.Type = ast.NodeTextMark+ replacement.TextMarkTextContent = stdhtml.EscapeString(part.content)+ replacement.Tokens = nil+ replacement.SetIALAttr("data-history-diff", "inline")+ } else {+ replacement.Tokens = []byte(part.content)+ }+ } else {+ replacement.TextMarkTextContent = part.content+ if part.changed {+ replacement.SetIALAttr("data-history-diff", "inline")+ }+ }+ segment.node.InsertBefore(replacement)+ }+ segment.node.Unlink()+ }+}++func cloneDocTextNode(node *ast.Node) *ast.Node {+ ret := *node+ ret.Parent = nil+ ret.Previous = nil+ ret.Next = nil+ ret.FirstChild = nil+ ret.LastChild = nil+ ret.Children = nil+ ret.KramdownIAL = make([][]string, 0, len(node.KramdownIAL))+ for _, attr := range node.KramdownIAL {+ ret.KramdownIAL = append(ret.KramdownIAL, append([]string(nil), attr...))+ }+ ret.Tokens = append([]byte(nil), node.Tokens...)+ return &ret+}++func lcsMatches[T comparable](left, right []T, maxCells int) (matches [][2]int, ok bool) {+ if 0 == len(left) || 0 == len(right) {+ return [][2]int{}, true+ }+ if len(left) > maxCells/len(right) {+ return nil, false+ }+ width := len(right) + 1+ table := make([]int, (len(left)+1)*width)+ for i := len(left) - 1; 0 <= i; i-- {+ for j := len(right) - 1; 0 <= j; j-- {+ index := i*width + j+ if left[i] == right[j] {+ table[index] = table[(i+1)*width+j+1] + 1+ } else if table[(i+1)*width+j] >= table[i*width+j+1] {+ table[index] = table[(i+1)*width+j]+ } else {+ table[index] = table[i*width+j+1]+ }+ }+ }+ for i, j := 0, 0; i < len(left) && j < len(right); {+ if left[i] == right[j] {+ matches = append(matches, [2]int{i, j})+ i+++ j+++ } else if table[(i+1)*width+j] >= table[i*width+j+1] {+ i+++ } else {+ j+++ }+ }+ return matches, true+}++func setDocDiffBlockAttrs(node *ast.Node, statuses []string) {+ node.SetIALAttr("data-history-diff", strings.Join(statuses, " "))+}++func prepareDocDiffTree(tree *parse.Tree) {+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {+ if entering {+ n.RemoveIALAttr("heading-fold")+ n.RemoveIALAttr("fold")+ }+ return ast.WalkContinue+ })+}++func renderDocVersion(version *loadedDocVersion) *DocVersionDiffContent {+ prepareDocDiffTree(version.tree)+ luteEngine := NewLute()+ luteEngine.RenderOptions.ProtyleContenteditable = false+ return &DocVersionDiffContent{+ ID: version.tree.Root.ID,+ RootID: version.tree.Root.ID,+ Title: version.title,+ Content: luteEngine.Tree2BlockDOM(version.tree, luteEngine.RenderOptions, luteEngine.ParseOptions),+ }+}++func renderLargeDocVersion(version *loadedDocVersion) *DocVersionDiffContent {+ prepareDocDiffTree(version.tree)+ luteEngine := NewLute()+ luteEngine.RenderOptions.ProtyleContenteditable = false+ formatRenderer := render.NewFormatRenderer(version.tree, luteEngine.RenderOptions, luteEngine.ParseOptions)+ return &DocVersionDiffContent{+ ID: version.tree.Root.ID,+ RootID: version.tree.Root.ID,+ Title: version.title,+ Content: string(formatRenderer.Render()),+ }+}diff --git a/kernel/model/history_diff_test.go b/kernel/model/history_diff_test.gonew file mode 100644index 0000000000..c3695addb6--- /dev/null+++ b/kernel/model/history_diff_test.go@@ -0,0 +1,103 @@+// 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 (+ "strings"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestDocDiffLCSMatches(t *testing.T) {+ matches, ok := lcsMatches([]rune("abcde"), []rune("abXde"), docDiffMaxLCSCells)+ if !ok {+ t.Fatal("expected LCS calculation to succeed")+ }+ expected := [][2]int{{0, 0}, {1, 1}, {3, 3}, {4, 4}}+ if len(matches) != len(expected) {+ t.Fatalf("expected %d matches, got %d", len(expected), len(matches))+ }+ for i, match := range matches {+ if match != expected[i] {+ t.Fatalf("expected match %v, got %v", expected[i], match)+ }+ }+}++func TestDocDiffLCSBudget(t *testing.T) {+ if _, ok := lcsMatches(make([]rune, 2000), make([]rune, 2000), docDiffMaxLCSCells); ok {+ t.Fatal("expected LCS calculation to exceed its budget")+ }+}++func TestDecodeDocTextMarkContentPreservesEntities(t *testing.T) {+ node := &ast.Node{+ Type: ast.NodeTextMark,+ TextMarkType: "strong",+ TextMarkTextContent: "a<b",+ }+ visible, stored := decodeDocTextMarkContent(node)+ if "a<b" != string(visible) {+ t.Fatalf("expected visible text [a<b], got [%s]", string(visible))+ }+ if "a" != stored[0] || "<" != stored[1] || "b" != stored[2] {+ t.Fatalf("unexpected stored rune mapping: %v", stored)+ }+}++func TestMarkDocInlineDiff(t *testing.T) {+ left := &ast.Node{Type: ast.NodeParagraph, ID: "20260729000000-left01"}+ left.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("before")})+ right := &ast.Node{Type: ast.NodeParagraph, ID: "20260729000000-right1"}+ right.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("beXore")})++ markDocInlineDiff(left, right)++ if nil == left.FirstChild.Next || "inline" != left.FirstChild.Next.IALAttr("data-history-diff") {+ t.Fatal("expected changed text on the left to be marked")+ }+ if nil == right.FirstChild.Next || "inline" != right.FirstChild.Next.IALAttr("data-history-diff") {+ t.Fatal("expected changed text on the right to be marked")+ }+ if dom := util.NewLute().RenderNodeBlockDOM(left); !strings.Contains(dom, `data-history-diff="inline"`) {+ t.Fatalf("expected rendered block DOM to contain an inline diff marker, got [%s]", dom)+ }+}++func TestDetectMovedDocBlocks(t *testing.T) {+ left := map[string]*docDiffBlock{+ "a": {parentID: "root"},+ "b": {parentID: "root"},+ "c": {parentID: "root"},+ }+ right := map[string]*docDiffBlock{+ "a": {parentID: "root"},+ "b": {parentID: "root"},+ "c": {parentID: "root"},+ }+ moved := detectMovedDocBlocks(left, right,+ map[string][]string{"root": {"a", "b", "c"}},+ map[string][]string{"root": {"b", "a", "c"}})+ if !moved["a"] && !moved["b"] {+ t.Fatal("expected a reordered block to be marked as moved")+ }+ if moved["c"] {+ t.Fatal("expected the stable block to remain unmoved")+ }+}