Skip to content

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

:sparkles: Support viewing history of locked documents https://github.com/siyuan-note/siyuan/issues/20148

Daniel3b93b296fa61
diff --git a/app/src/history/doc.ts b/app/src/history/doc.ts
index 4a8dc0d38c..66fa33e0c4 100644
--- a/app/src/history/doc.ts
+++ b/app/src/history/doc.ts
@@ -27,7 +27,7 @@ const genCurrentVersionItem = () => `<li class="b3-list-item history__current-ve
</span>
</li>`;
-const renderDoc = (element: HTMLElement, currentPage: number, id: string) => {
+const renderDoc = (element: HTMLElement, currentPage: number, id: string, readonly: boolean) => {
getDocHistorySnapshots(element)?.reset();
const request = (Number(element.dataset.historyRequest) || 0) + 1;
element.dataset.historyRequest = String(request);
@@ -79,9 +79,9 @@ const renderDoc = (element: HTMLElement, currentPage: number, id: string) => {
logsHTML += `<li class="b3-list-item b3-list-item--hide-action" data-created="${item}">
<div class="fn__flex-1 fn__flex-column"><span class="b3-list-item__text">${dayjs(parseInt(item) * 1000).format("YYYY-MM-DD HH:mm:ss")}</span><span data-history-tags="${item}"></span></div>
<span class="fn__space"></span>
- <span class="b3-list-item__action b3-tooltips b3-tooltips__w" data-type="rollback" aria-label="${window.siyuan.languages.rollback}">
+ ${readonly ? "" : `<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>
+ </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>
@@ -93,7 +93,7 @@ const renderDoc = (element: HTMLElement, currentPage: number, id: string) => {
});
};
-const renderRepo = async (element: HTMLElement, currentPage: number, id: string) => {
+const renderRepo = async (element: HTMLElement, currentPage: number, id: string, readonly: boolean) => {
if (element.getAttribute("data-loading") === "true") {
return;
}
@@ -157,7 +157,7 @@ const renderRepo = async (element: HTMLElement, currentPage: number, id: string)
.replace("${x}", String(pageCount))
.replace("${y}", String(response.data.totalCount));
pageInfoElement.classList.remove("fn__none");
- renderRepoFileList(response.data.files, listElement, false, true);
+ renderRepoFileList(response.data.files, listElement, false, true, !readonly);
listElement.insertAdjacentHTML("afterbegin", genCurrentVersionItem());
getDocHistorySnapshots(element)?.setEntries(response.data.files.map(file => ({
created: file.fileID, historyPath: "", snapshots: file.snapshots || []
@@ -169,8 +169,10 @@ export const openDocHistory = (options: {
app: App,
id: string,
notebookId: string,
- pathString: string
+ pathString: string,
+ readonly?: boolean
}) => {
+ const readonly = options.readonly || window.siyuan.config.readonly;
let historyEditor: Protyle;
let isLoading = false;
const getHistoryPath = (target: Element, op: string, id: string, cb: (item: {path: string, title: string}) => void) => {
@@ -324,13 +326,13 @@ export const openDocHistory = (options: {
repoElement.addEventListener("versionListRendered", syncVersionSelection);
const opElement = fileElement.querySelector(".b3-select") as HTMLSelectElement;
opElement.addEventListener("change", () => {
- renderDoc(fileElement, 1, options.id);
+ renderDoc(fileElement, 1, options.id, readonly);
});
const docElement = fileElement.querySelector('.history__text[data-type="docPanel"]') as HTMLElement;
const mdElement = fileElement.querySelector('.history__text[data-type="mdPanel"]') as HTMLTextAreaElement;
const repoPreviewElement = repoElement.querySelector('[data-type="repoPanel"]') as HTMLElement;
const repoTitleElement = repoElement.querySelector(".protyle-title__input") as HTMLElement;
- renderDoc(fileElement, 1, options.id);
+ renderDoc(fileElement, 1, options.id, readonly);
historyEditor = new Protyle(options.app, docElement, {
blockId: "",
history: {
@@ -367,6 +369,11 @@ export const openDocHistory = (options: {
while (target && !target.isEqualNode(dialog.element)) {
const type = target.getAttribute("data-type");
const repoFileElement = target.closest('[data-type="searchFileItem"]');
+ if (type === "rollback" && (readonly || window.siyuan.config.readonly)) {
+ event.stopPropagation();
+ event.preventDefault();
+ return;
+ }
if (target.classList.contains("item")) {
target.parentElement.querySelector(".item--focus").classList.remove("item--focus");
Array.from(dialog.element.querySelector("#docHistoryContainer").children).forEach((item: HTMLElement) => {
@@ -376,7 +383,7 @@ export const openDocHistory = (options: {
target.classList.add("item--focus");
if (type === "repo" && item.getAttribute("data-init") !== "true" &&
item.getAttribute("data-loading") !== "true") {
- renderRepo(item, 1, options.id);
+ renderRepo(item, 1, options.id, readonly);
}
} else {
item.classList.add("fn__none");
@@ -506,7 +513,7 @@ export const openDocHistory = (options: {
break;
} else if ((type === "docprevious" || type === "docnext") && target.getAttribute("disabled") !== "disabled") {
const currentPage = parseInt(pageNumElement.textContent);
- renderDoc(fileElement, type === "docprevious" ? currentPage - 1 : currentPage + 1, options.id);
+ renderDoc(fileElement, type === "docprevious" ? currentPage - 1 : currentPage + 1, options.id, readonly);
event.stopPropagation();
event.preventDefault();
break;
@@ -523,14 +530,14 @@ export const openDocHistory = (options: {
showMessage(window.siyuan.languages.jumpToPage.replace("${x}", totalPage));
return;
}
- renderDoc(fileElement, Math.max(1, Math.min(parseInt(value), totalPage)), options.id);
+ renderDoc(fileElement, Math.max(1, Math.min(parseInt(value), totalPage)), options.id, readonly);
dialog.destroy();
},
});
} else if ((type === "snapshotprevious" || type === "snapshotnext") &&
target.getAttribute("disabled") !== "disabled") {
const currentPage = parseInt(repoElement.getAttribute("data-page") || "1");
- renderRepo(repoElement, type === "snapshotprevious" ? currentPage - 1 : currentPage + 1, options.id);
+ renderRepo(repoElement, type === "snapshotprevious" ? currentPage - 1 : currentPage + 1, options.id, readonly);
event.stopPropagation();
event.preventDefault();
break;
@@ -547,7 +554,7 @@ export const openDocHistory = (options: {
showMessage(window.siyuan.languages.jumpToPage.replace("${x}", totalPage));
return;
}
- renderRepo(repoElement, Math.max(1, Math.min(parseInt(value), totalPage)), options.id);
+ renderRepo(repoElement, Math.max(1, Math.min(parseInt(value), totalPage)), options.id, readonly);
dialog.destroy();
},
});
diff --git a/app/src/history/docReadonly.test.ts b/app/src/history/docReadonly.test.ts
new file mode 100644
index 0000000000..aaf4cb92d8
--- /dev/null
+++ b/app/src/history/docReadonly.test.ts
@@ -0,0 +1,204 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {resolve} from "node:path";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const {parse} = require("ifdef-loader/preprocessor");
+const noop = () => {};
+
+const loadModule = (path: string, mobile: boolean, dependencies: Record<string, unknown>, globals: object) => {
+ const source = parse(readFileSync(resolve("src", path), "utf8"), {MOBILE: mobile, BROWSER: true}, false, true, path);
+ const exports = {};
+ const code = transpileModule(source, {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText;
+ runInNewContext(code, {exports, require: (name: string) => dependencies[name] || {}, ...globals});
+ return exports;
+};
+
+for (const mobile of [false, true]) {
+ test(`locked document history remains accessible without exposing other history contexts (${mobile ? "mobile" : "desktop"})`, () => {
+ for (const mode of ["locked", "editable", "workspace", "publish", "history", "snapshot", "permanent"]) {
+ const items: IMenu[] = [];
+ const opened: Parameters<typeof import("./doc").openDocHistory>[0][] = [];
+ const keymaps = Object.fromEntries(["outline", "backlinks", "graphView", "attr", "spaceRepetition",
+ "quickMakeCard", "search", "addToDatabase"].map(key => [key, {custom: ""}]));
+ const menu = {element: {classList: {contains: () => true}, setAttribute: noop},
+ remove: noop, append: (item: IMenu) => items.push(item), popup: noop, fullscreen: noop};
+ const siyuan = {menus: {menu}, languages: {}, isPublish: mode === "publish",
+ config: {readonly: mode === "workspace", cloudRegion: 1, flashcard: {},
+ keymap: {general: keymaps, editor: {general: keymaps}}}};
+ const protyle = {app: {}, notebookId: "notebook", path: "/doc.sy", disabled: mode !== "editable",
+ block: {rootID: "doc", id: "doc"}, options: {history: {
+ created: mode === "history" ? "archive" : "", snapshot: mode === "snapshot" ? "archive" : ""}},
+ element: {getAttribute: () => mode === "permanent" ? "true" : null}} as unknown as IProtyle;
+ const module = loadModule("protyle/header/openTitleMenu.ts", mobile, {
+ "../../menus/Menu": {MenuItem: class {element: IMenu; constructor(item: IMenu) { this.element = item; }}},
+ "../../menus/commonMenuItem": {copySubMenu: (): IMenu[] => [], exportMd: () => ({}), movePathToMenu: () => ({})},
+ "../../util/fetch": {fetchPost: (_url: string, _body: unknown, callback: (response: unknown) => void) =>
+ callback({data: {name: "Document", ial: {id: "20231011123456", updated: "20231011123456"}}})},
+ "../../history/doc": {openDocHistory: (options: typeof opened[number]) => opened.push(options)},
+ "../../util/pathName": {isEncryptedBox: () => false},
+ "../../util/hostCapabilities": {getHostCapabilities: () => ({})},
+ "../util/hasClosest": {hasTopClosestByClassName: (): null => null},
+ "../util/compatibility": {updateHotkeyTip: () => ""},
+ "../../dialog/tooltip": {hideTooltip: noop},
+ "../../plugin/EventBus": {emitOpenMenu: noop},
+ "../../menus/block": {transferBlockRef: noop},
+ "../../constants": {Constants: {}},
+ "../../util/functions": {isMobile: () => mobile},
+ dayjs: () => ({format: () => "date"}),
+ }, {window: {siyuan}, getSelection: () => ({rangeCount: 0})}) as typeof import("../protyle/header/openTitleMenu");
+ module.openTitleMenu(protyle, {x: 0, y: 0}, "title");
+ const history = items.find(item => item.id === "fileHistory");
+ if (mode === "locked" || mode === "editable") {
+ assert.ok(history);
+ history.click(null, null);
+ assert.equal(opened[0].id, "doc");
+ assert.equal(opened[0].notebookId, "notebook");
+ assert.equal(opened[0].readonly, mode === "locked");
+ } else {
+ assert.equal(history, undefined, mode);
+ }
+ if (mode === "locked") {
+ assert.ok(!items.some(item => item.id === "delete" || item.id === "addToDatabase"));
+ }
+ }
+ });
+}
+
+class TestElement {
+ public dataset: Record<string, string> = {};
+ public innerHTML = "";
+ public textContent = "1";
+ public isConnected = true;
+ public parentElement: TestElement;
+ public nextElementSibling: TestElement;
+ public attributes = new Map<string, string>();
+ public listeners = new Map<string, (event: unknown) => void>();
+ public nodes = new Map<string, TestElement>();
+ public row = false;
+ public repoRow: TestElement;
+ public classList = {add: noop, remove: noop, contains: (name: string) => this.row && name === "b3-list-item"};
+
+ querySelector(selector: string): TestElement {
+ if (!this.nodes.has(selector)) {
+ this.nodes.set(selector, new TestElement());
+ }
+ return this.nodes.get(selector);
+ }
+
+ querySelectorAll(): TestElement[] { return []; }
+ getAttribute(name: string) { return this.attributes.get(name) ?? null; }
+ setAttribute(name: string, value: string) { this.attributes.set(name, value); }
+ removeAttribute(name: string) { this.attributes.delete(name); }
+ isEqualNode(element: TestElement) { return this === element; }
+ addEventListener(name: string, callback: (event: unknown) => void) { this.listeners.set(name, callback); }
+ dispatchEvent(event: Event) { this.listeners.get(event.type)?.(event); }
+ closest() { return this.repoRow; }
+}
+
+const createHistory = (mobile: boolean, readonly: boolean) => {
+ const root = new TestElement();
+ const file = root.querySelector('#docHistoryContainer [data-type="doc"]');
+ const next = file.querySelector('[data-type="docnext"]');
+ next.nextElementSibling = new TestElement();
+ next.nextElementSibling.nextElementSibling = new TestElement();
+ file.querySelector(".b3-select").setAttribute("value", "all");
+ const requests: {url: string, callback: (response: unknown) => void}[] = [];
+ let confirmations = 0;
+ let repoRollbacks = 0;
+ let comparisons = 0;
+ const snapshots = {reset: noop, load: noop, select: noop};
+ const module = loadModule("history/doc.ts", mobile, {
+ "../dialog": {Dialog: class {element = root;}},
+ "../dialog/confirmDialog": {confirmDialog: () => { confirmations++; }},
+ "../protyle": {Protyle: class {protyle = {options: {history: {}}};}},
+ "../protyle/util/onGet": {disabledProtyle: noop, onGet: noop},
+ "../util/fetch": {fetchPost: (url: string, _body: unknown, callback: (response: unknown) => void) =>
+ requests.push({url, callback})},
+ "../util/functions": {isMobile: () => mobile},
+ "../util/escape": {escapeHtml: String},
+ "../constants": {Constants: {LOCAL_HISTORY: "history"}},
+ "./docSnapshots": {getDocHistorySnapshots: () => snapshots, DocHistorySnapshots: class {select = noop;}},
+ "./docDiff": {showDocVersionDiff: () => { comparisons++; }},
+ "./repoFile": {rollbackRepoFile: () => { repoRollbacks++; }},
+ "./notebookDialogs": {trackNotebookHistoryDialog: noop},
+ "./resizeSide": {resizeSide: noop},
+ dayjs: () => ({format: () => "date"}),
+ }, {window: {siyuan: {config: {readonly: false}, storage: {history: {}}, languages: {
+ pageCountAndHistoryCount: "${x} ${y}", rollbackConfirm: "${name} ${time}"}}},
+ CustomEvent: class {constructor(public type: string) {}}}) as typeof import("./doc");
+ module.openDocHistory({app: {} as Parameters<typeof module.openDocHistory>[0]["app"],
+ id: "doc", notebookId: "notebook", pathString: "Document", readonly});
+ requests.shift().callback({data: {histories: ["1"], pageCount: 1, totalCount: 1}});
+ const click = (type: string, row = false) => {
+ const target = new TestElement();
+ target.row = row;
+ target.setAttribute("data-type", type);
+ target.setAttribute("data-created", "1");
+ target.parentElement = new TestElement();
+ target.parentElement.setAttribute("data-created", "1");
+ root.listeners.get("click")({target, stopPropagation: noop, preventDefault: noop});
+ return target;
+ };
+ return {file, requests, click, root, confirmations: () => confirmations,
+ repoRollbacks: () => repoRollbacks, comparisons: () => comparisons};
+};
+
+for (const mobile of [false, true]) {
+ test(`viewing locked history preserves preview and comparison while blocking both rollback paths (${mobile ? "mobile" : "desktop"})`, () => {
+ const view = createHistory(mobile, true);
+ const html = view.file.querySelector(".b3-list--background").innerHTML;
+ assert.ok(!html.includes('data-type="rollback"'));
+ assert.ok(html.includes('data-type="selectVersion"'));
+ view.click("rollback");
+ const target = new TestElement();
+ target.setAttribute("data-type", "rollback");
+ target.repoRow = new TestElement();
+ view.root.listeners.get("click")({target, stopPropagation: noop, preventDefault: noop});
+ assert.equal(view.requests.length, 0);
+ assert.equal(view.confirmations(), 0);
+ assert.equal(view.repoRollbacks(), 0);
+
+ view.click("", true);
+ const history = view.requests.shift();
+ assert.equal(history.url, "/api/history/getHistoryItems");
+ history.callback({data: {items: [{path: "history/doc.sy", title: "Document"}]}});
+ const preview = view.requests.shift();
+ assert.equal(preview.url, "/api/history/getDocHistoryContent");
+ preview.callback({data: {content: "Historical content", isLargeDoc: true}});
+ assert.equal((view.file.querySelector('.history__text[data-type="mdPanel"]') as TestElement & {value: string}).value,
+ "Historical content");
+ view.click("selectVersion");
+ view.requests.shift().callback({data: {items: [{path: "history/doc.sy", title: "Document"}]}});
+ view.click("compareVersions");
+ assert.equal(view.comparisons(), 1);
+ });
+}
+
+test("editable document history retains rollback", () => {
+ const view = createHistory(false, false);
+ assert.ok(view.file.querySelector(".b3-list--background").innerHTML.includes('data-type="rollback"'));
+ view.click("rollback");
+ view.requests.shift().callback({data: {items: [{path: "history/doc.sy", title: "Document"}]}});
+ assert.equal(view.confirmations(), 1);
+});
+
+test("snapshot file list permits viewing and comparison without rollback", () => {
+ const module = loadModule("history/repoFile.ts", false, {
+ "../util/escape": {escapeAttr: String, escapeHtml: String},
+ "../util/hostCapabilities": {getHostCapabilities: () => ({importExport: true})},
+ dayjs: () => ({format: () => "date"}),
+ }, {window: {siyuan: {languages: {}}}}) as typeof import("./repoFile");
+ const list = {innerHTML: ""} as HTMLElement;
+ const files = [{fileID: "file", indexID: "snapshot", title: "Document", hSize: "1KB", updated: 1}];
+ module.renderRepoFileList(files, list, false, true, false);
+ assert.ok(list.innerHTML.includes('data-type="searchFileItem"'));
+ assert.ok(list.innerHTML.includes('data-type="selectVersion"'));
+ assert.ok(!list.innerHTML.includes('data-type="rollback"'));
+ module.renderRepoFileList(files, list, false, true);
+ assert.ok(list.innerHTML.includes('data-type="rollback"'));
+});
diff --git a/app/src/history/repoFile.ts b/app/src/history/repoFile.ts
index daf7d7337f..c332c39312 100644
--- a/app/src/history/repoFile.ts
+++ b/app/src/history/repoFile.ts
@@ -22,7 +22,8 @@ interface IRepoFile {
let repoFileRequestId = 0;
-export const renderRepoFileList = (files: IRepoFile[], element: Element, showPath: boolean, showCompare = false) => {
+export const renderRepoFileList = (files: IRepoFile[], element: Element, showPath: boolean,
+ showCompare = false, allowRollback = true) => {
if (files.length === 0) {
element.innerHTML = `<li class="b3-list--empty">${window.siyuan.languages.emptyContent}</li>`;
return;
@@ -34,9 +35,9 @@ export const renderRepoFileList = (files: IRepoFile[], element: Element, showPat
html += `<li class="b3-list-item b3-list-item--hide-action" data-type="searchFileItem" data-id="${item.fileID}" data-snapshot="${item.indexID}" data-created="${item.updated}" data-title="${escapeAttr(escapeHtml(item.title))}">
<div class="fn__flex-1 fn__flex-column"><span class="b3-list-item__text">${dayjs(item.updated).format("YYYY-MM-DD HH:mm:ss")}</span><span data-history-tags="${escapeAttr(item.fileID)}"></span></div>
<span class="fn__space"></span>
- <span class="b3-list-item__action b3-tooltips b3-tooltips__w" data-type="rollback" aria-label="${window.siyuan.languages.rollback}">
+ ${allowRollback ? `<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>
+ </span>` : ""}
<span class="b3-list-item__action b3-tooltips b3-tooltips__w${getHostCapabilities().importExport ? "" : " fn__none"}" data-type="saveAs" aria-label="${window.siyuan.languages.saveAs}">
<svg><use xlink:href="#iconDownload"></use></svg>
</span>
@@ -63,10 +64,10 @@ export const renderRepoFileList = (files: IRepoFile[], element: Element, showPat
<span class="fn__space"></span>${window.siyuan.languages.saveAs}
</span>
<span class="fn__space"></span>
- <span class="b3-list-item__action" data-type="rollback">
+ ${allowRollback ? `<span class="b3-list-item__action" data-type="rollback">
<svg><use xlink:href="#iconUndo"></use></svg>
<span class="fn__space"></span> ${window.siyuan.languages.rollback}
- </span>
+ </span>` : ""}
</div>
</div>
</li>`;
@@ -83,9 +84,9 @@ export const renderRepoFileList = (files: IRepoFile[], element: Element, showPat
<span class="b3-list-item__action b3-tooltips b3-tooltips__w${getHostCapabilities().importExport ? "" : " fn__none"}" data-type="saveAs" aria-label="${window.siyuan.languages.saveAs}">
<svg><use xlink:href="#iconDownload"></use></svg>
</span>
- <span class="b3-list-item__action b3-tooltips b3-tooltips__w" data-type="rollback" aria-label="${window.siyuan.languages.rollback}">
+ ${allowRollback ? `<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>
+ </span>` : ""}
</li>`;
/// #endif
});
diff --git a/app/src/protyle/header/openTitleMenu.ts b/app/src/protyle/header/openTitleMenu.ts
index 9e2dcae949..dbc4cd64b8 100644
--- a/app/src/protyle/header/openTitleMenu.ts
+++ b/app/src/protyle/header/openTitleMenu.ts
@@ -343,7 +343,9 @@ export const openTitleMenu = (protyle: IProtyle, position: IPosition, from: stri
}).element);
}
/// #endif
- if (!protyle.disabled) {
+ if (!window.siyuan.config.readonly && !window.siyuan.isPublish &&
+ !protyle.options.history?.created && !protyle.options.history?.snapshot &&
+ protyle.element.getAttribute("disabled-forever") !== "true") {
window.siyuan.menus.menu.append(new MenuItem({
id: "fileHistory",
label: window.siyuan.languages.dataHistory,
@@ -353,7 +355,8 @@ export const openTitleMenu = (protyle: IProtyle, position: IPosition, from: stri
app: protyle.app,
id: protyle.block.rootID,
notebookId: protyle.notebookId,
- pathString: response.data.name
+ pathString: response.data.name,
+ readonly: protyle.disabled,
});
}
}).element);