An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Improve backlink folding state persistence https://github.com/siyuan-note/siyuan/issues/17438
Daniel34d90deae0f3
diff --git a/app/src/layout/dock/Backlink.ts b/app/src/layout/dock/Backlink.tsindex 67248d1d9f..d5fcf636ea 100644--- a/app/src/layout/dock/Backlink.ts+++ b/app/src/layout/dock/Backlink.ts@@ -37,6 +37,18 @@ import {type TBacklinkDailyNoteFilter} from "./backlinkSourceFilter";import {escapeHtml} from "../../util/escape";+import {ViewStateService} from "../../util/viewState";+import {+ applyViewFoldStates,+ invalidateViewFoldRequests,+ registerViewFoldContext,+ unregisterViewFoldContext,+} from "../../protyle/util/viewFold";+import {+ captureBacklinkReadingAnchor,+ type IBacklinkReadingAnchor,+ restoreBacklinkReadingAnchor,+} from "./backlinkReadingAnchor";interface IBacklinkItemRecord {revision: string,@@ -66,12 +78,33 @@ interface IBacklinkListResponse {mk: string}-interface IBacklinkScrollAnchor {- rootID: string,- isMention: boolean,- offset: number,- scrollElement: HTMLElement,-}+const getBacklinkOccurrenceBreadcrumb = (element: Element) => {+ const wysiwygElement = element.closest(".protyle-wysiwyg");+ if (!wysiwygElement) {+ return;+ }+ let topLevelElement = element;+ while (topLevelElement.parentElement && topLevelElement.parentElement !== wysiwygElement) {+ topLevelElement = topLevelElement.parentElement;+ }+ if (topLevelElement.parentElement !== wysiwygElement) {+ return;+ }+ let currentElement: Element | null = topLevelElement;+ while (currentElement) {+ if (currentElement.classList.contains("protyle-breadcrumb__bar") &&+ currentElement.hasAttribute("data-backlink-id")) {+ return currentElement;+ }+ currentElement = currentElement.previousElementSibling;+ }+};++const getBacklinkOccurrenceID = (element: Element) =>+ getBacklinkOccurrenceBreadcrumb(element)?.getAttribute("data-backlink-id") || "";++const getBacklinkOccurrenceRevision = (element: Element) =>+ getBacklinkOccurrenceBreadcrumb(element)?.getAttribute("data-backlink-revision") || "";export class Backlink extends Model {public element: HTMLElement;@@ -108,6 +141,7 @@ export class Backlink extends Model {private itemRecords = [new Map<string, IBacklinkItemRecord>(), new Map<string, IBacklinkItemRecord>()];private listRevision = "";private listQueryKey = "";+ private renderedQueryKey = "";private indexChangeVersion = 0;private pendingRootIDs = new Set<string>();private pendingFull = false;@@ -117,6 +151,18 @@ export class Backlink extends Model {private empty = false;private emptyChange?: (empty: boolean) => void;private sourceFilter = createBacklinkSourceFilter();+ private viewState?: ViewStateService;+ private viewStateReady: Promise<void> = Promise.resolve();+ private viewStateLoaded = false;+ private viewStateGeneration = 0;+ private viewStateSearchQueued = false;+ private viewStateSearchInit = false;+ private viewStateSearchRefreshAll = false;+ private readingAnchorTimers: [number?, number?] = [];+ private restoringReadingAnchors: [boolean, boolean] = [false, false];+ private readingAnchorScrollEpochs: [number, number] = [0, 0];+ private readingAnchorRenderGeneration = 0;+ private ownerScrollListener?: () => void;constructor(options: {app: App,@@ -332,7 +378,7 @@ export class Backlink extends Model {},blockExtHTML: `<span class="b3-list-item__action b3-tooltips b3-tooltips__nw" aria-label="${window.siyuan.languages.more}"><svg><use xlink:href="#iconMore"></use></svg></span>`});- this.tree.element.addEventListener("scroll", () => {+ this.tree.element.addEventListener("scroll", (event) => {this.tree.element.querySelectorAll(".protyle-gutters").forEach(item => {item.classList.add("fn__none");item.innerHTML = "";@@ -340,8 +386,11 @@ export class Backlink extends Model {this.tree.element.querySelectorAll(".protyle-wysiwyg--hl").forEach((hlItem) => {hlItem.classList.remove("protyle-wysiwyg--hl");});+ if (event.isTrusted) {+ this.handleReadingAnchorScroll(false);+ }});- this.mTree.element.addEventListener("scroll", () => {+ this.mTree.element.addEventListener("scroll", (event) => {this.mTree.element.querySelectorAll(".protyle-gutters").forEach(item => {item.classList.add("fn__none");item.innerHTML = "";@@ -349,11 +398,24 @@ export class Backlink extends Model {this.mTree.element.querySelectorAll(".protyle-wysiwyg--hl").forEach((hlItem) => {hlItem.classList.remove("protyle-wysiwyg--hl");});+ if (event.isTrusted) {+ this.handleReadingAnchorScroll(true);+ }});+ if (this.type === "bottom") {+ this.ownerScrollListener = () => {+ this.handleReadingAnchorScroll(false);+ };+ this.ownerProtyle.contentElement.addEventListener("scroll", this.ownerScrollListener);+ }// 为了快捷键的 dispatchthis.element.querySelector('[data-type="collapse"]').addEventListener("click", () => {this.cancelContextRequests(this.tree.element, false);this.hideEditorGutters(this.tree.element);+ this.invalidateHeadingRequests(this.tree.element);+ this.getDocumentItemElements(this.tree).forEach(item => {+ this.setDocumentExpanded(false, item.getAttribute("data-node-id"), false);+ });this.tree.element.querySelectorAll(".protyle").forEach(item => {item.classList.add("fn__none");});@@ -387,6 +449,10 @@ export class Backlink extends Model {case "mCollapse":this.cancelContextRequests(this.mTree.element, true);this.hideEditorGutters(this.mTree.element);+ this.invalidateHeadingRequests(this.mTree.element);+ this.getDocumentItemElements(this.mTree).forEach(item => {+ this.setDocumentExpanded(true, item.getAttribute("data-node-id"), false);+ });this.mTree.element.querySelectorAll(".protyle").forEach(item => {item.classList.add("fn__none");});@@ -443,10 +509,65 @@ export class Backlink extends Model {}});+ this.setViewStateHost(this.blockId);this.showBottomLoading();this.searchBacklinks(true);}+ private setViewStateHost(blockID: string) {+ this.clearReadingAnchorTimers();+ const previousReady = this.viewStateReady;+ const previous = this.viewState;+ const generation = ++this.viewStateGeneration;+ this.viewState = undefined;+ this.viewStateLoaded = !blockID;+ const createService = async () => {+ await previousReady;+ if (previous) {+ try {+ await previous.destroy();+ } catch (error) {+ console.error(error);+ }+ }+ if (generation !== this.viewStateGeneration || !blockID) {+ return;+ }+ const service = new ViewStateService({+ scope: "backlink",+ surface: this.type,+ hostID: blockID,+ });+ this.viewState = service;+ await service.ready;+ };+ this.viewStateReady = createService().catch(error => {+ console.error(error);+ }).then(() => {+ if (generation === this.viewStateGeneration) {+ this.viewStateLoaded = true;+ }+ });+ }++ private getDocumentStateField(isMention: boolean, documentID: string) {+ return `item:${isMention ? "backmention" : "backlink"}:${encodeURIComponent(documentID)}`;+ }++ private getSectionStateField(isMention: boolean) {+ return `section:${isMention ? "backmention" : "backlink"}`;+ }++ private setDocumentExpanded(isMention: boolean, documentID: string, expanded: boolean) {+ if (documentID && this.viewState) {+ this.viewState.set(this.getDocumentStateField(isMention, documentID), expanded);+ }+ }++ private setSectionFolded(isMention: boolean, folded: boolean) {+ this.viewState?.set(this.getSectionStateField(isMention), folded);+ }+private handelCallback() {if (this.type === "local") {fetchPost("/api/block/checkBlockExist", {id: this.blockId}, existResponse => {@@ -481,6 +602,10 @@ export class Backlink extends Model {}private setLayout(element: HTMLElement) {+ const backlinkWasFolded = this.tree.element.classList.contains("fn__none");+ const backmentionWasFolded = this.mTree.element.style.height === "0px";+ this.savePendingReadingAnchor(false);+ this.savePendingReadingAnchor(true);if (this.mTree.element.style.flex) {if (this.mTree.element.style.height === "0px") {this.tree.element.classList.remove("fn__none");@@ -506,22 +631,44 @@ export class Backlink extends Model {element.querySelector("use").setAttribute("xlink:href", "#iconDown");}}+ this.setSectionFolded(false, this.tree.element.classList.contains("fn__none"));+ this.setSectionFolded(true, this.mTree.element.style.height === "0px");+ const viewFoldPromises = this.syncViewFoldVisibility();+ const restoreBacklink = backlinkWasFolded && !this.tree.element.classList.contains("fn__none");+ const restoreBackmention = backmentionWasFolded && this.mTree.element.style.height !== "0px";this.tree.element.dispatchEvent(new CustomEvent("scroll"));this.mTree.element.dispatchEvent(new CustomEvent("scroll"));+ if (restoreBacklink) {+ this.restorePersistedReadingAnchorAfter(false, viewFoldPromises[0]);+ }+ if (restoreBackmention) {+ this.restorePersistedReadingAnchorAfter(true, viewFoldPromises[1]);+ }}private setDockSectionLayout(listElement: HTMLElement) {const isMention = listElement === this.mTree.element;const backlinkFolded = this.tree.element.classList.contains("fn__none");const backmentionFolded = this.mTree.element.style.height === "0px";+ const nextBacklinkFolded = isMention ? backlinkFolded : !backlinkFolded;+ const nextBackmentionFolded = isMention ? !backmentionFolded : backmentionFolded;+ if (isMention ? nextBackmentionFolded : nextBacklinkFolded) {+ this.savePendingReadingAnchor(isMention);+ }this.applyDockLayout(- isMention ? backlinkFolded : !backlinkFolded,- isMention ? !backmentionFolded : backmentionFolded,+ nextBacklinkFolded,+ nextBackmentionFolded,this.status[this.blockId]?.backlinkMStatus ?? 1,);- this.saveStatus();+ this.setSectionFolded(isMention, isMention ? nextBackmentionFolded : nextBacklinkFolded);+ const viewFoldPromises = this.syncViewFoldVisibility();+ const restoreAnchor = isMention ? !nextBackmentionFolded : !nextBacklinkFolded;+ this.saveStatus(false);this.tree.element.dispatchEvent(new CustomEvent("scroll"));this.mTree.element.dispatchEvent(new CustomEvent("scroll"));+ if (restoreAnchor) {+ this.restorePersistedReadingAnchorAfter(isMention, viewFoldPromises[isMention ? 1 : 0]);+ }}private setBottomLayout(element: HTMLElement, listElement: HTMLElement) {@@ -529,9 +676,13 @@ export class Backlink extends Model {return;}const folded = !listElement.classList.contains("fn__none");+ if (folded) {+ this.savePendingReadingAnchor(listElement === this.mTree.element);+ }if (folded) {this.cancelContextRequests(listElement, listElement === this.mTree.element);this.hideEditorGutters(listElement);+ this.invalidateHeadingRequests(listElement);listElement.dataset.heightFolding = "true";collapseHeight(listElement, () => {delete listElement.dataset.heightFolding;@@ -540,14 +691,22 @@ export class Backlink extends Model {} else {delete listElement.dataset.heightFolding;listElement.classList.remove("fn__none");- expandHeight(listElement);+ const viewFoldPromise = this.resumeViewFoldStates(listElement);+ const expandPromise = new Promise<void>(resolve => {+ expandHeight(listElement, resolve);+ });+ this.restorePersistedReadingAnchorAfter(+ listElement === this.mTree.element,+ Promise.all([viewFoldPromise, expandPromise]).then(() => undefined),+ );}if (folded) {listElement.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");}element.setAttribute("aria-label", folded ? window.siyuan.languages.expand : window.siyuan.languages.collapse);element.querySelector("use").setAttribute("xlink:href", folded ? "#iconRight" : "#iconDown");- this.saveStatus();+ this.setSectionFolded(listElement === this.mTree.element, folded);+ this.saveStatus(false);}private setFocus() {@@ -733,7 +892,7 @@ export class Backlink extends Model {window.siyuan.menus.menu.popup({x: event.clientX, y: event.clientY});}- private toggleItem(liElement: HTMLElement, isMention: boolean) {+ private toggleItem(liElement: HTMLElement, isMention: boolean, persist = true) {const svgElement = liElement.firstElementChild?.firstElementChild;if (!svgElement || svgElement.getAttribute("disabled")) {return;@@ -748,8 +907,10 @@ export class Backlink extends Model {}if (editor && this.type === "bottom") {hideElements(["gutter"], editor.protyle);+ invalidateViewFoldRequests(editor.protyle);editor.protyle.element.classList.add("fn__none");} else if (editor) {+ unregisterViewFoldContext(editor.protyle);editor.destroy();this.editors.splice(this.editors.indexOf(editor), 1);editor.protyle.element.remove();@@ -758,13 +919,20 @@ export class Backlink extends Model {record.contextRevision = "";}}+ if (persist) {+ this.setDocumentExpanded(isMention, docId, false);+ }this.updateBottomBacklinkSpacing();} else if (editor && !record?.contextDirty) {editor.protyle.element.classList.remove("fn__none");svgElement.classList.add("b3-list-item__arrow--open");+ void applyViewFoldStates(editor.protyle);+ if (persist) {+ this.setDocumentExpanded(isMention, docId, true);+ }this.updateBottomBacklinkSpacing();} else {- this.loadContext(liElement, isMention, true);+ this.loadContext(liElement, isMention, true, persist);}}@@ -794,7 +962,7 @@ export class Backlink extends Model {});}- private loadContext(liElement: HTMLElement, isMention: boolean, expand: boolean) {+ private loadContext(liElement: HTMLElement, isMention: boolean, expand: boolean, persist = false) {const index = isMention ? 1 : 0;const docId = liElement.getAttribute("data-node-id");const record = this.itemRecords[index].get(docId);@@ -805,6 +973,7 @@ export class Backlink extends Model {svgElement.setAttribute("disabled", "disabled");const keyword = isMention ? this.inputsElement[1].value : this.inputsElement[0].value;const blockId = this.blockId;+ const viewStateGeneration = this.viewStateGeneration;const contextRequestVersion = this.contextRequestVersions[index];const requestGeneration = ++record.requestGeneration;const param: IObject = {@@ -821,7 +990,8 @@ export class Backlink extends Model {param.knownRevision = record.contextRevision;}fetchPost(isMention ? "/api/ref/getBackmentionDoc" : "/api/ref/getBacklinkDoc", param, (response) => {- if (this.destroyed || blockId !== this.blockId || !liElement.isConnected ||+ if (this.destroyed || blockId !== this.blockId || viewStateGeneration !== this.viewStateGeneration ||+ !liElement.isConnected ||contextRequestVersion !== this.contextRequestVersions[index] ||requestGeneration !== record.requestGeneration) {return;@@ -836,11 +1006,30 @@ export class Backlink extends Model {if (!response.data.unchanged) {const backlinkData = isMention ? response.data.backmentions : response.data.backlinks;if (record.editor) {- const scrollAnchor = this.captureScrollAnchor(this.type === "bottom" ? undefined : (isMention ? this.mTree : this.tree));- record.editor.protyle.options.backlinkData = backlinkData;- renderBacklink(record.editor.protyle, backlinkData);- searchMarkRender(record.editor.protyle, response.data.keywords);- this.restoreScrollAnchor(scrollAnchor);+ const editor = record.editor;+ const scrollAnchor = this.captureReadingAnchor(isMention);+ const scrollEpoch = this.getReadingAnchorScrollEpoch(isMention);+ const anchorQueryKey = this.renderedQueryKey;+ editor.protyle.options.backlinkData = backlinkData;+ void renderBacklink(editor.protyle, backlinkData).then(() => {+ window.requestAnimationFrame(() => {+ if (this.destroyed || blockId !== this.blockId ||+ viewStateGeneration !== this.viewStateGeneration ||+ contextRequestVersion !== this.contextRequestVersions[index] ||+ requestGeneration !== record.requestGeneration || record.editor !== editor ||+ !editor.protyle.element.isConnected || editor.protyle.element.classList.contains("fn__none") ||+ scrollEpoch !== this.getReadingAnchorScrollEpoch(isMention) ||+ anchorQueryKey !== this.renderedQueryKey || anchorQueryKey !== this.listQueryKey) {+ return;+ }+ if (scrollAnchor) {+ this.restoreReadingAnchor(scrollAnchor);+ } else {+ this.restorePersistedReadingAnchor(isMention, docId);+ }+ });+ });+ searchMarkRender(editor.protyle, response.data.keywords);} else {const editorElement = document.createElement("div");editorElement.style.minHeight = "auto";@@ -873,11 +1062,39 @@ export class Backlink extends Model {searchMarkRender(editor.protyle, response.data.keywords);this.editors.push(editor);record.editor = editor;+ const service = this.viewState;+ const scrollEpoch = this.getReadingAnchorScrollEpoch(isMention);+ const anchorQueryKey = this.renderedQueryKey;+ if (service) {+ void registerViewFoldContext(editor.protyle, {+ store: service,+ pane: isMention ? "backmention" : "backlink",+ rootID: docId,+ getOccurrenceID: getBacklinkOccurrenceID,+ getOccurrenceRevision: getBacklinkOccurrenceRevision,+ }).then(() => {+ window.requestAnimationFrame(() => {+ if (this.destroyed || blockId !== this.blockId ||+ viewStateGeneration !== this.viewStateGeneration || service !== this.viewState ||+ contextRequestVersion !== this.contextRequestVersions[index] ||+ requestGeneration !== record.requestGeneration || record.editor !== editor ||+ !editor.protyle.element.isConnected || editor.protyle.element.classList.contains("fn__none") ||+ scrollEpoch !== this.getReadingAnchorScrollEpoch(isMention) ||+ anchorQueryKey !== this.renderedQueryKey || anchorQueryKey !== this.listQueryKey) {+ return;+ }+ this.restorePersistedReadingAnchor(isMention, docId);+ });+ });+ }}}if (expand) {record.editor?.protyle.element.classList.remove("fn__none");svgElement.classList.add("b3-list-item__arrow--open");+ if (persist) {+ this.setDocumentExpanded(isMention, docId, true);+ }}this.updateBottomBacklinkSpacing();}).finally(() => {@@ -895,6 +1112,37 @@ export class Backlink extends Model {});}+ private invalidateHeadingRequests(element: Element) {+ this.editors.forEach(editor => {+ if (editor.protyle.element === element || element.contains(editor.protyle.element)) {+ invalidateViewFoldRequests(editor.protyle);+ }+ });+ }++ private resumeViewFoldStates(element: Element) {+ const promises: Promise<void>[] = [];+ this.editors.forEach(editor => {+ if ((editor.protyle.element === element || element.contains(editor.protyle.element)) &&+ !editor.protyle.element.classList.contains("fn__none")) {+ promises.push(applyViewFoldStates(editor.protyle));+ }+ });+ return Promise.all(promises).then(() => undefined);+ }++ private syncViewFoldVisibility() {+ const promises: [Promise<void>, Promise<void>] = [Promise.resolve(), Promise.resolve()];+ [this.tree.element, this.mTree.element].forEach((element, index) => {+ if (element.classList.contains("fn__none") || element.style.height === "0px") {+ this.invalidateHeadingRequests(element);+ } else {+ promises[index] = this.resumeViewFoldStates(element);+ }+ });+ return promises;+ }+private cancelContextRequests(element: Element, isMention: boolean) {this.contextRequestVersions[isMention ? 1 : 0]++;element.querySelectorAll(".b3-list-item__arrow[disabled]").forEach(item => {@@ -904,6 +1152,7 @@ export class Backlink extends Model {private destroyItemRecord(record: IBacklinkItemRecord) {if (record.editor) {+ unregisterViewFoldContext(record.editor.protyle);record.editor.destroy();const editorIndex = this.editors.indexOf(record.editor);if (editorIndex > -1) {@@ -1014,36 +1263,220 @@ export class Backlink extends Model {return changed;}- private captureScrollAnchor(tree?: Tree): IBacklinkScrollAnchor | undefined {- const scrollElement = this.type === "bottom" ? this.ownerProtyle.contentElement : tree.element;- const scopeElement = tree?.element || this.element;- const scrollRect = scrollElement.getBoundingClientRect();- const itemElements = Array.from(- scopeElement.querySelectorAll(".b3-list > .backlinkList__item[data-node-id]")- ) as HTMLElement[];- const anchorElement = itemElements.find(item => item.getBoundingClientRect().bottom >= scrollRect.top);- if (!anchorElement) {- return;+ private getReadingAnchorField(isMention: boolean) {+ if (this.type === "bottom") {+ return "anchor:bottom";}- return {- rootID: anchorElement.getAttribute("data-node-id"),- isMention: this.mTree.element.contains(anchorElement),- offset: anchorElement.getBoundingClientRect().top - scrollRect.top,+ return `anchor:${isMention ? "backmention" : "backlink"}`;+ }++ private getReadingAnchorIndex(isMention: boolean) {+ return this.type === "bottom" ? 0 : (isMention ? 1 : 0);+ }++ private getReadingAnchorScrollEpoch(isMention: boolean) {+ return this.readingAnchorScrollEpochs[this.getReadingAnchorIndex(isMention)];+ }++ private isRestoringReadingAnchor(isMention: boolean) {+ return this.restoringReadingAnchors[this.getReadingAnchorIndex(isMention)];+ }++ private isReadingAnchorPaneVisible(isMention: boolean) {+ const listElement = isMention ? this.mTree.element : this.tree.element;+ return !listElement.classList.contains("fn__none") && listElement.dataset.heightFolding !== "true" &&+ (this.type === "bottom" || !isMention || listElement.style.height !== "0px");+ }++ private isBottomReadingAnchorViewportActive() {+ if (this.type !== "bottom" || !this.ownerProtyle || this.element.classList.contains("fn__none") ||+ this.element.getClientRects().length === 0) {+ return this.type !== "bottom";+ }+ const ownerRect = this.ownerProtyle.contentElement.getBoundingClientRect();+ const panelRect = this.element.getBoundingClientRect();+ return panelRect.bottom > ownerRect.top && panelRect.top < ownerRect.bottom;+ }++ private capturePaneReadingAnchor(isMention: boolean): IBacklinkReadingAnchor | undefined {+ const tree = isMention ? this.mTree : this.tree;+ const pane = isMention ? "backmention" : "backlink";+ const scrollElement = this.getScrollElement(tree);+ const anchor = captureBacklinkReadingAnchor({+ scopeElement: tree.element,scrollElement,- };+ pane,+ queryKey: this.renderedQueryKey,+ });+ const scrollRect = scrollElement.getBoundingClientRect();+ const scopeRect = tree.element.getBoundingClientRect();+ const viewportTop = Math.max(scrollRect.top, scopeRect.top);+ const viewportBottom = Math.min(scrollRect.bottom, scopeRect.bottom);+ const titleElements = Array.from(tree.element.querySelectorAll(+ ":scope > .b3-list > .backlinkList__item > .b3-list-item[data-node-id]"+ )) as HTMLElement[];+ const titleElement = titleElements.filter(item => {+ const rect = item.getBoundingClientRect();+ return rect.bottom > viewportTop && rect.top < viewportBottom;+ }).sort((left, right) => {+ const leftOffset = left.getBoundingClientRect().top - scrollRect.top;+ const rightOffset = right.getBoundingClientRect().top - scrollRect.top;+ if (leftOffset <= 0 && rightOffset > 0) {+ return -1;+ }+ if (rightOffset <= 0 && leftOffset > 0) {+ return 1;+ }+ return leftOffset <= 0 ? rightOffset - leftOffset : leftOffset - rightOffset;+ })[0];+ const titleAnchor = titleElement ? {+ pane,+ rootID: titleElement.getAttribute("data-node-id") || "",+ occurrenceID: "",+ blockID: "",+ offset: titleElement.getBoundingClientRect().top - scrollRect.top,+ queryKey: this.renderedQueryKey,+ } satisfies IBacklinkReadingAnchor : undefined;+ const anchors = [anchor, titleAnchor].filter((item): item is IBacklinkReadingAnchor => Boolean(item));+ const crossingAnchor = anchors.filter(item => item.offset <= 0)+ .sort((left, right) => right.offset - left.offset)[0];+ return crossingAnchor || anchors.filter(item => item.offset > 0)+ .sort((left, right) => left.offset - right.offset)[0];+ }++ private captureReadingAnchor(isMention: boolean) {+ if (this.type !== "bottom") {+ return this.capturePaneReadingAnchor(isMention);+ }+ const anchors = [this.capturePaneReadingAnchor(false), this.capturePaneReadingAnchor(true)]+ .filter((item): item is IBacklinkReadingAnchor => Boolean(item));+ const crossingAnchor = anchors.filter(anchor => anchor.offset <= 0)+ .sort((left, right) => right.offset - left.offset)[0];+ return crossingAnchor || anchors.filter(anchor => anchor.offset > 0)+ .sort((left, right) => left.offset - right.offset)[0];}- private restoreScrollAnchor(anchor?: IBacklinkScrollAnchor) {+ private restoreReadingAnchor(anchor?: IBacklinkReadingAnchor) {if (!anchor) {return;}- const tree = anchor.isMention ? this.mTree : this.tree;- const anchorElement = tree.element.querySelector(`.backlinkList__item[data-node-id="${anchor.rootID}"]`);- if (!anchorElement) {+ const isMention = anchor.pane === "backmention";+ if (!this.isReadingAnchorPaneVisible(isMention)) {return;}- const offset = anchorElement.getBoundingClientRect().top - anchor.scrollElement.getBoundingClientRect().top;- anchor.scrollElement.scrollTop += offset - anchor.offset;+ const tree = isMention ? this.mTree : this.tree;+ const index = this.getReadingAnchorIndex(isMention);+ this.restoringReadingAnchors[index] = true;+ const restored = restoreBacklinkReadingAnchor({+ anchor,+ scopeElement: tree.element,+ scrollElement: this.getScrollElement(tree),+ pane: anchor.pane,+ queryKey: this.listQueryKey,+ });+ if (!restored) {+ this.restoringReadingAnchors[index] = false;+ return;+ }+ window.requestAnimationFrame(() => {+ this.restoringReadingAnchors[index] = false;+ });+ }++ private restorePersistedReadingAnchor(isMention: boolean, loadedRootID?: string) {+ if (this.type === "bottom" && !this.isBottomReadingAnchorViewportActive()) {+ return;+ }+ const anchor = this.viewState?.get<IBacklinkReadingAnchor>(this.getReadingAnchorField(isMention));+ if (loadedRootID && (anchor?.rootID !== loadedRootID ||+ anchor.pane !== (isMention ? "backmention" : "backlink"))) {+ return;+ }+ this.restoreReadingAnchor(anchor);+ }++ private restorePersistedReadingAnchorAfter(isMention: boolean, promise: Promise<void>) {+ const generation = this.viewStateGeneration;+ const service = this.viewState;+ const blockID = this.blockId;+ const queryKey = this.renderedQueryKey;+ const scrollEpoch = this.getReadingAnchorScrollEpoch(isMention);+ void promise.then(() => {+ if (this.destroyed || generation !== this.viewStateGeneration || service !== this.viewState ||+ blockID !== this.blockId || queryKey !== this.renderedQueryKey || queryKey !== this.listQueryKey ||+ scrollEpoch !== this.getReadingAnchorScrollEpoch(isMention)) {+ return;+ }+ this.restorePersistedReadingAnchor(isMention);+ });+ }++ private clearReadingAnchorTimers() {+ this.readingAnchorTimers.forEach(timer => {+ if (timer) {+ window.clearTimeout(timer);+ }+ });+ this.readingAnchorTimers = [];+ this.restoringReadingAnchors = [false, false];+ this.readingAnchorScrollEpochs[0]++;+ this.readingAnchorScrollEpochs[1]++;+ this.readingAnchorRenderGeneration++;+ }++ private handleReadingAnchorScroll(isMention: boolean) {+ if (this.isRestoringReadingAnchor(isMention)) {+ return;+ }+ this.readingAnchorScrollEpochs[this.getReadingAnchorIndex(isMention)]++;+ this.scheduleReadingAnchorSave(isMention);+ }++ private scheduleReadingAnchorSave(isMention: boolean) {+ if (this.isRestoringReadingAnchor(isMention) || !this.viewState || !this.renderedQueryKey ||+ this.renderedQueryKey !== this.listQueryKey) {+ return;+ }+ const index = this.getReadingAnchorIndex(isMention);+ if (this.readingAnchorTimers[index]) {+ window.clearTimeout(this.readingAnchorTimers[index]);+ }+ const generation = this.viewStateGeneration;+ const service = this.viewState;+ const queryKey = this.renderedQueryKey;+ this.readingAnchorTimers[index] = window.setTimeout(() => {+ this.readingAnchorTimers[index] = undefined;+ if (this.destroyed || generation !== this.viewStateGeneration || service !== this.viewState ||+ queryKey !== this.renderedQueryKey || queryKey !== this.listQueryKey) {+ return;+ }+ this.saveReadingAnchor(isMention, service, queryKey);+ }, 400);+ }++ private savePendingReadingAnchor(isMention: boolean) {+ const index = this.getReadingAnchorIndex(isMention);+ if (this.readingAnchorTimers[index]) {+ window.clearTimeout(this.readingAnchorTimers[index]);+ this.readingAnchorTimers[index] = undefined;+ }+ this.saveReadingAnchor(isMention);+ }++ private saveReadingAnchor(isMention: boolean, service = this.viewState, queryKey = this.renderedQueryKey) {+ if (!service || service !== this.viewState || !queryKey || queryKey !== this.renderedQueryKey ||+ queryKey !== this.listQueryKey) {+ return;+ }+ const anchor = this.captureReadingAnchor(isMention);+ if (!anchor || anchor.queryKey !== queryKey) {+ if (this.type === "bottom" && !this.isBottomReadingAnchorViewportActive() &&+ service.has(this.getReadingAnchorField(isMention))) {+ service.remove(this.getReadingAnchorField(isMention));+ }+ return;+ }+ service.set(this.getReadingAnchorField(isMention), anchor);}private refreshExpandedContexts(rootIDs: Set<string>, full: boolean) {@@ -1057,7 +1490,7 @@ export class Backlink extends Model {return;}if (full || rootIDs.has(rootID)) {- this.loadContext(record.headerElement, index === 1, true);+ this.loadContext(record.headerElement, index === 1, true, false);}});});@@ -1101,11 +1534,15 @@ export class Backlink extends Model {delete this.mTree.element.dataset.heightFolding;this.cancelContextRequests(this.tree.element, false);this.cancelContextRequests(this.mTree.element, true);- this.editors.forEach(item => item.destroy());+ this.editors.forEach(item => {+ unregisterViewFoldContext(item.protyle);+ item.destroy();+ });this.editors = [];this.itemRecords.forEach(records => records.clear());this.listRevision = "";this.listQueryKey = "";+ this.renderedQueryKey = "";if (resetLists) {this.tree.updateData(null);this.mTree.updateData(null);@@ -1126,6 +1563,7 @@ export class Backlink extends Model {this.notebookId = "";this.blockId = blockId;this.rootId = rootId;+ this.setViewStateHost(blockId);this.setRequesting(false);this.showBottomLoading();}@@ -1145,6 +1583,7 @@ export class Backlink extends Model {this.blockId = blockId;this.rootId = rootId;this.notebookId = notebookId || "";+ this.setViewStateHost(blockId);const status = this.status[blockId];this.tree.element.previousElementSibling.querySelector('[data-type="sort"]').setAttribute("data-sort",@@ -1233,6 +1672,25 @@ export class Backlink extends Model {if (!this.blockId) {return;}+ if (!this.viewStateLoaded) {+ this.viewStateSearchInit = this.viewStateSearchInit || init;+ this.viewStateSearchRefreshAll = this.viewStateSearchRefreshAll || refreshAllContexts;+ if (!this.viewStateSearchQueued) {+ this.viewStateSearchQueued = true;+ void this.viewStateReady.then(() => {+ this.viewStateSearchQueued = false;+ if (this.destroyed) {+ return;+ }+ const queuedInit = this.viewStateSearchInit;+ const queuedRefreshAll = this.viewStateSearchRefreshAll;+ this.viewStateSearchInit = false;+ this.viewStateSearchRefreshAll = false;+ this.searchBacklinks(queuedInit, queuedRefreshAll);+ });+ }+ return;+ }if (this.requesting) {this.searchQueued = true;return;@@ -1332,7 +1790,13 @@ export class Backlink extends Model {});}- public saveStatus() {+ public saveStatus(includeReadingAnchor = true) {+ if (includeReadingAnchor) {+ this.saveReadingAnchor(false);+ if (this.type !== "bottom") {+ this.saveReadingAnchor(true);+ }+ }this.status[this.blockId] = {sort: parseInt(this.tree.element.previousElementSibling.querySelector('[data-type="sort"]').getAttribute("data-sort")),mSort: parseInt(this.mTree.element.previousElementSibling.querySelector('[data-type="mSort"]').getAttribute("data-sort")),@@ -1390,13 +1854,30 @@ export class Backlink extends Model {this.notebookId = data.box;this.inputsElement[0].value = data.k;this.inputsElement[1].value = data.mk;- const backlinkAnchor = this.captureScrollAnchor(this.type === "bottom" ? undefined : this.tree);- const mentionAnchor = this.type === "bottom" ? undefined : this.captureScrollAnchor(this.mTree);+ const runtimeAnchorRenderGeneration = ++this.readingAnchorRenderGeneration;+ const runtimeAnchors = (this.type === "bottom" ? [false] : [false, true]).map(isMention => ({+ anchor: this.captureReadingAnchor(isMention),+ isMention,+ scrollEpoch: this.getReadingAnchorScrollEpoch(isMention),+ }));+ const runtimeAnchorBlockID = this.blockId;+ const runtimeAnchorQueryKey = this.renderedQueryKey;const backlinkChanged = this.reconcileList(this.tree, data.backlinks, false);const backmentionChanged = this.reconcileList(this.mTree, data.backmentions, true);+ this.renderedQueryKey = this.listQueryKey;if (backlinkChanged || backmentionChanged) {- this.restoreScrollAnchor(backlinkAnchor);- this.restoreScrollAnchor(mentionAnchor);+ window.requestAnimationFrame(() => {+ if (this.destroyed || runtimeAnchorBlockID !== this.blockId ||+ runtimeAnchorRenderGeneration !== this.readingAnchorRenderGeneration ||+ runtimeAnchorQueryKey !== this.renderedQueryKey || runtimeAnchorQueryKey !== this.listQueryKey) {+ return;+ }+ runtimeAnchors.forEach(({anchor, isMention, scrollEpoch}) => {+ if (scrollEpoch === this.getReadingAnchorScrollEpoch(isMention)) {+ this.restoreReadingAnchor(anchor);+ }+ });+ });}const bottomVisibility = this.type === "bottom" ?getBottomBacklinkVisibility(data.linkRefsCount, data.mentionsCount, data.k, data.mk) : undefined;@@ -1446,17 +1927,43 @@ export class Backlink extends Model {};}+ const persistedBacklinkFolded = this.viewState?.get<boolean>(this.getSectionStateField(false));+ const persistedBackmentionFolded = this.viewState?.get<boolean>(this.getSectionStateField(true));+ if (typeof persistedBacklinkFolded === "boolean") {+ this.status[this.blockId].backlinkFolded = persistedBacklinkFolded;+ }+ if (typeof persistedBackmentionFolded === "boolean") {+ this.status[this.blockId].backmentionFolded = persistedBackmentionFolded;+ }++ const applyDocumentState = (items: IBlockTree[], isMention: boolean, openIDs: string[]) => {+ items.forEach(item => {+ const expanded = this.viewState?.get<boolean>(this.getDocumentStateField(isMention, item.id));+ if (typeof expanded !== "boolean") {+ return;+ }+ const index = openIDs.indexOf(item.id);+ if (expanded && index === -1) {+ openIDs.push(item.id);+ } else if (!expanded && index > -1) {+ openIDs.splice(index, 1);+ }+ });+ };+ applyDocumentState(data.backlinks, false, this.status[this.blockId].backlinkOpenIds);+ applyDocumentState(data.backmentions, true, this.status[this.blockId].backlinkMOpenIds);+// restore statusthis.status[this.blockId].backlinkOpenIds.forEach(item => {const liElement = this.tree.element.querySelector(`.b3-list-item[data-node-id="${item}"]`) as HTMLElement;if (liElement && !liElement.querySelector(".b3-list-item__arrow--open")) {- this.toggleItem(liElement, false);+ this.toggleItem(liElement, false, false);}});this.status[this.blockId].backlinkMOpenIds.forEach(item => {const liElement = this.mTree.element.querySelector(`.b3-list-item[data-node-id="${item}"]`) as HTMLElement;if (liElement && !liElement.querySelector(".b3-list-item__arrow--open")) {- this.toggleItem(liElement, true);+ this.toggleItem(liElement, true, false);}});if (this.type === "bottom") {@@ -1482,9 +1989,33 @@ export class Backlink extends Model {}if (init) {+ const generation = this.viewStateGeneration;+ const service = this.viewState;+ const blockID = this.blockId;+ const queryKey = this.renderedQueryKey;+ const panes = this.type === "bottom" ? [false] : [false, true];+ const scrollEpochs = panes.map(isMention => this.getReadingAnchorScrollEpoch(isMention));setTimeout(() => {- this.tree.element.scrollTop = this.status[this.blockId].scrollTop;- this.mTree.element.scrollTop = this.status[this.blockId].mScrollTop;+ if (this.destroyed || generation !== this.viewStateGeneration || service !== this.viewState ||+ blockID !== this.blockId || queryKey !== this.renderedQueryKey || queryKey !== this.listQueryKey) {+ return;+ }+ panes.forEach((isMention, index) => {+ if (scrollEpochs[index] !== this.getReadingAnchorScrollEpoch(isMention)) {+ return;+ }+ const anchor = this.viewState?.get<IBacklinkReadingAnchor>(this.getReadingAnchorField(isMention));+ const targetIsMention = this.type === "bottom" && anchor ?+ anchor.pane === "backmention" : isMention;+ if (!this.isReadingAnchorPaneVisible(targetIsMention)) {+ return;+ }+ if (!anchor && this.type !== "bottom") {+ (isMention ? this.mTree : this.tree).element.scrollTop = isMention ?+ this.status[this.blockId].mScrollTop : this.status[this.blockId].scrollTop;+ }+ this.restorePersistedReadingAnchor(isMention);+ });}, Constants.TIMEOUT_LOAD);}}@@ -1592,7 +2123,12 @@ export class Backlink extends Model {}public destroy() {+ if (this.blockId && !this.showingLoading) {+ this.saveStatus();+ }this.destroyed = true;+ this.viewStateGeneration++;+ this.clearReadingAnchorTimers();cancelHeightAnimation(this.tree.element);cancelHeightAnimation(this.mTree.element);delete this.tree.element.dataset.heightFolding;@@ -1600,12 +2136,19 @@ export class Backlink extends Model {if (this.ownerFocusoutListener) {this.ownerProtyle.element.removeEventListener("focusout", this.ownerFocusoutListener);}+ if (this.ownerScrollListener) {+ this.ownerProtyle.contentElement.removeEventListener("scroll", this.ownerScrollListener);+ }if (this.panelFocusoutListener) {this.element.removeEventListener("focusout", this.panelFocusoutListener);}this.visibilityObserver?.disconnect();- this.editors.forEach(item => item.destroy());+ this.editors.forEach(item => {+ unregisterViewFoldContext(item.protyle);+ item.destroy();+ });this.editors = [];+ void this.viewState?.destroy().catch(error => console.error(error));if (this.ws) {this.ws.onclose = null;this.ws.close();diff --git a/app/src/layout/dock/backlinkReadingAnchor.test.ts b/app/src/layout/dock/backlinkReadingAnchor.test.tsnew file mode 100644index 0000000000..573faf8c41--- /dev/null+++ b/app/src/layout/dock/backlinkReadingAnchor.test.ts@@ -0,0 +1,350 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {+ captureBacklinkReadingAnchor,+ type IBacklinkReadingAnchor,+ restoreBacklinkReadingAnchor,+ selectBacklinkReadingAnchorCandidate+} from "./backlinkReadingAnchor";++interface IRect {+ top: number,+ bottom: number,+}++class FakeElement {+ public parentElement: FakeElement | null = null;+ public scrollTop = 0;+ private readonly attributes = new Map<string, string>();+ private readonly classNames = new Set<string>();+ private readonly childElements: FakeElement[] = [];+ private rect: IRect;++ constructor(rect: IRect, classNames = "") {+ this.rect = rect;+ classNames.split(" ").filter(Boolean).forEach(item => this.classNames.add(item));+ }++ public append(...elements: FakeElement[]) {+ elements.forEach(element => {+ element.parentElement = this;+ this.childElements.push(element);+ });+ return this;+ }++ public setAttribute(name: string, value: string) {+ this.attributes.set(name, value);+ return this;+ }++ public setRect(rect: IRect) {+ this.rect = rect;+ }++ public getAttribute(name: string) {+ return this.attributes.get(name) || null;+ }++ public hasAttribute(name: string) {+ return this.attributes.has(name);+ }++ public get children() {+ return this.childElements as unknown as HTMLCollection;+ }++ public get previousElementSibling() {+ if (!this.parentElement) {+ return null;+ }+ const index = this.parentElement.childElements.indexOf(this);+ return index > 0 ? this.parentElement.childElements[index - 1] : null;+ }++ public get nextElementSibling() {+ if (!this.parentElement) {+ return null;+ }+ const index = this.parentElement.childElements.indexOf(this);+ return index > -1 && index < this.parentElement.childElements.length - 1 ?+ this.parentElement.childElements[index + 1] : null;+ }++ public matches(selector: string) {+ const classNames = Array.from(selector.matchAll(/\.([\w-]+)/g), item => item[1]);+ const attributes = Array.from(selector.matchAll(/\[([\w-]+)\]/g), item => item[1]);+ return classNames.every(item => this.classNames.has(item)) &&+ attributes.every(item => this.hasAttribute(item));+ }++ public closest(selector: string): FakeElement | null {+ if (this.matches(selector)) {+ return this;+ }+ return this.parentElement?.closest(selector) || null;+ }++ public querySelectorAll(selector: string) {+ const descendants: FakeElement[] = [];+ const visit = (element: FakeElement) => {+ element.childElements.forEach(child => {+ descendants.push(child);+ visit(child);+ });+ };+ visit(this);+ const selectorParts = selector.split(" ");+ if (selectorParts.length === 1) {+ return descendants.filter(item => item.matches(selector));+ }+ const targetSelector = selectorParts[selectorParts.length - 1];+ const ancestorSelector = selectorParts.slice(0, -1).join(" ");+ return descendants.filter(item => item.matches(targetSelector) && Boolean(item.closest(ancestorSelector)));+ }++ public getBoundingClientRect() {+ return {+ top: this.rect.top,+ bottom: this.rect.bottom,+ height: this.rect.bottom - this.rect.top,+ } as DOMRect;+ }+}++const asHTMLElement = (element: FakeElement) => element as unknown as HTMLElement;++const createBlock = (id: string, rect: IRect, type = "NodeParagraph") => {+ return new FakeElement(rect)+ .setAttribute("data-node-id", id)+ .setAttribute("data-type", type);+};++const createFixture = () => {+ const scrollElement = new FakeElement({top: 0, bottom: 200});+ const scopeElement = new FakeElement({top: -100, bottom: 400});+ const documentElement = new FakeElement({top: -80, bottom: 350}, "backlinkList__item")+ .setAttribute("data-node-id", "root-a");+ const titleElement = new FakeElement({top: -80, bottom: -50}, "b3-list-item")+ .setAttribute("data-node-id", "root-a");+ const wysiwygElement = new FakeElement({top: -50, bottom: 350}, "protyle-wysiwyg");+ const breadcrumbElement = new FakeElement({top: -50, bottom: -30}, "protyle-breadcrumb__bar")+ .setAttribute("data-backlink-id", "occurrence-a");+ const parentBlock = createBlock("parent", {top: -20, bottom: 120}, "NodeList");+ const activeBlock = createBlock("active", {top: -5, bottom: 35});+ const nextBlock = createBlock("next", {top: 40, bottom: 80});+ parentBlock.append(activeBlock);+ wysiwygElement.append(breadcrumbElement, parentBlock, nextBlock);+ documentElement.append(titleElement, wysiwygElement);+ scopeElement.append(documentElement);+ return {+ scrollElement,+ scopeElement,+ documentElement,+ titleElement,+ wysiwygElement,+ breadcrumbElement,+ parentBlock,+ activeBlock,+ nextBlock,+ };+};++const captureFixture = (fixture: ReturnType<typeof createFixture>) => captureBacklinkReadingAnchor({+ scopeElement: asHTMLElement(fixture.scopeElement),+ scrollElement: asHTMLElement(fixture.scrollElement),+ pane: "backlink",+ queryKey: "query-a",+});++const restoreFixture = (+ fixture: ReturnType<typeof createFixture>,+ anchor: IBacklinkReadingAnchor,+ pane: "backlink" | "backmention" = "backlink",+ queryKey = "query-a",+) => restoreBacklinkReadingAnchor({+ anchor,+ scopeElement: asHTMLElement(fixture.scopeElement),+ scrollElement: asHTMLElement(fixture.scrollElement),+ pane,+ queryKey,+});++describe("selectBacklinkReadingAnchorCandidate", () => {+ it("selects the deepest and smallest block crossing the viewport top", () => {+ const parent = {id: "parent", top: -20, bottom: 120, height: 140, depth: 2, order: 0};+ const child = {id: "child", top: -5, bottom: 35, height: 40, depth: 4, order: 1};+ const below = {id: "below", top: 10, bottom: 30, height: 20, depth: 5, order: 2};++ assert.equal(selectBacklinkReadingAnchorCandidate([parent, below, child], 0, 100), child);+ });++ it("selects the nearest visible block below the viewport top", () => {+ const first = {id: "first", top: 20, bottom: 80, height: 60, depth: 2, order: 0};+ const precise = {id: "precise", top: 20, bottom: 50, height: 30, depth: 3, order: 1};+ const outside = {id: "outside", top: 120, bottom: 150, height: 30, depth: 5, order: 2};++ assert.equal(selectBacklinkReadingAnchorCandidate([outside, first, precise], 0, 100), precise);+ });+});++describe("captureBacklinkReadingAnchor", () => {+ it("captures an occurrence-scoped nested block with neighboring candidates", () => {+ const fixture = createFixture();++ assert.deepEqual(captureFixture(fixture), {+ pane: "backlink",+ rootID: "root-a",+ occurrenceID: "occurrence-a",+ blockID: "active",+ offset: -5,+ previousBlockID: "parent",+ nextBlockID: "next",+ queryKey: "query-a",+ });+ });++ it("uses the explicit owner viewport when the scope starts lower in it", () => {+ const fixture = createFixture();+ fixture.scopeElement.setRect({top: 80, bottom: 400});+ fixture.parentBlock.setRect({top: 85, bottom: 150});+ fixture.activeBlock.setRect({top: 85, bottom: 110});+ fixture.nextBlock.setRect({top: 120, bottom: 150});++ assert.equal(captureFixture(fixture)?.offset, 85);+ });++ it("captures a document-only anchor before its backlink blocks are hydrated", () => {+ const fixture = createFixture();+ fixture.titleElement.setRect({top: 20, bottom: 50});+ fixture.parentBlock.setRect({top: 0, bottom: 0});+ fixture.activeBlock.setRect({top: 0, bottom: 0});+ fixture.nextBlock.setRect({top: 0, bottom: 0});++ assert.deepEqual(captureFixture(fixture), {+ pane: "backlink",+ rootID: "root-a",+ occurrenceID: "",+ blockID: "",+ offset: 20,+ queryKey: "query-a",+ });+ });+});++describe("restoreBacklinkReadingAnchor", () => {+ it("restores the exact block at the captured visual offset", () => {+ const fixture = createFixture();+ const anchor = captureFixture(fixture);+ fixture.activeBlock.setRect({top: 25, bottom: 65});++ assert.equal(restoreFixture(fixture, anchor), "block");+ assert.equal(fixture.scrollElement.scrollTop, 30);+ });++ it("falls back to the next block before the previous block", () => {+ const fixture = createFixture();+ const anchor = captureFixture(fixture);+ fixture.activeBlock.setAttribute("data-node-id", "replacement");++ assert.equal(restoreFixture(fixture, anchor), "next");+ assert.equal(fixture.scrollElement.scrollTop, 45);+ });++ it("skips hidden exact and neighboring block targets", () => {+ const hiddenExactFixture = createFixture();+ const hiddenExactAnchor = captureFixture(hiddenExactFixture);+ hiddenExactFixture.activeBlock.setRect({top: 0, bottom: 0});+ assert.equal(restoreFixture(hiddenExactFixture, hiddenExactAnchor), "next");++ const hiddenNextFixture = createFixture();+ const hiddenNextAnchor = captureFixture(hiddenNextFixture);+ hiddenNextFixture.activeBlock.setAttribute("data-node-id", "replacement");+ hiddenNextFixture.nextBlock.setRect({top: 0, bottom: 0});+ assert.equal(restoreFixture(hiddenNextFixture, hiddenNextAnchor), "previous");++ const hiddenPreviousFixture = createFixture();+ const hiddenPreviousAnchor = captureFixture(hiddenPreviousFixture);+ hiddenPreviousFixture.activeBlock.setAttribute("data-node-id", "replacement");+ hiddenPreviousFixture.nextBlock.setAttribute("data-node-id", "replacement-next");+ hiddenPreviousFixture.parentBlock.setRect({top: 0, bottom: 0});+ assert.equal(restoreFixture(hiddenPreviousFixture, hiddenPreviousAnchor), "occurrence");+ });++ it("falls back through the previous block and occurrence breadcrumb", () => {+ const previousFixture = createFixture();+ const previousAnchor = captureFixture(previousFixture);+ previousFixture.activeBlock.setAttribute("data-node-id", "replacement");+ previousFixture.nextBlock.setAttribute("data-node-id", "replacement-next");+ assert.equal(restoreFixture(previousFixture, previousAnchor), "previous");++ const occurrenceFixture = createFixture();+ const occurrenceAnchor = captureFixture(occurrenceFixture);+ occurrenceFixture.activeBlock.setAttribute("data-node-id", "replacement");+ occurrenceFixture.nextBlock.setAttribute("data-node-id", "replacement-next");+ occurrenceFixture.parentBlock.setAttribute("data-node-id", "replacement-parent");+ assert.equal(restoreFixture(occurrenceFixture, occurrenceAnchor), "occurrence");+ });++ it("does not restore a matching block ID from another occurrence", () => {+ const fixture = createFixture();+ const anchor = captureFixture(fixture);+ fixture.activeBlock.setAttribute("data-node-id", "replacement");+ fixture.nextBlock.setAttribute("data-node-id", "replacement-next");+ fixture.parentBlock.setAttribute("data-node-id", "replacement-parent");+ fixture.wysiwygElement.append(+ new FakeElement({top: 200, bottom: 220}, "protyle-breadcrumb__bar")+ .setAttribute("data-backlink-id", "occurrence-b"),+ createBlock("active", {top: 220, bottom: 260}),+ );++ assert.equal(restoreFixture(fixture, anchor), "occurrence");+ });++ it("falls back to the document title when the occurrence no longer exists", () => {+ const fixture = createFixture();+ const anchor = captureFixture(fixture);+ fixture.breadcrumbElement.setAttribute("data-backlink-id", "replacement-occurrence");++ assert.equal(restoreFixture(fixture, anchor), "document");+ });++ it("restores a document-only anchor to its title", () => {+ const fixture = createFixture();+ fixture.titleElement.setRect({top: 20, bottom: 50});+ fixture.parentBlock.setRect({top: 0, bottom: 0});+ fixture.activeBlock.setRect({top: 0, bottom: 0});+ fixture.nextBlock.setRect({top: 0, bottom: 0});+ const anchor = captureFixture(fixture);+ fixture.titleElement.setRect({top: 70, bottom: 100});++ assert.equal(restoreFixture(fixture, anchor), "document");+ assert.equal(fixture.scrollElement.scrollTop, 50);+ });++ it("does not restore while the section or selected fallback target is hidden", () => {+ const hiddenSectionFixture = createFixture();+ const hiddenSectionAnchor = captureFixture(hiddenSectionFixture);+ hiddenSectionFixture.scopeElement.setRect({top: 0, bottom: 0});+ assert.equal(restoreFixture(hiddenSectionFixture, hiddenSectionAnchor), undefined);+ assert.equal(hiddenSectionFixture.scrollElement.scrollTop, 0);++ const hiddenTargetFixture = createFixture();+ const hiddenTargetAnchor = captureFixture(hiddenTargetFixture);+ hiddenTargetFixture.activeBlock.setAttribute("data-node-id", "replacement");+ hiddenTargetFixture.nextBlock.setAttribute("data-node-id", "replacement-next");+ hiddenTargetFixture.parentBlock.setAttribute("data-node-id", "replacement-parent");+ hiddenTargetFixture.breadcrumbElement.setRect({top: 0, bottom: 0});+ assert.equal(restoreFixture(hiddenTargetFixture, hiddenTargetAnchor), undefined);+ assert.equal(hiddenTargetFixture.scrollElement.scrollTop, 0);+ });++ it("rejects anchors from another pane or query", () => {+ const fixture = createFixture();+ const anchor = captureFixture(fixture);++ assert.equal(restoreFixture(fixture, anchor, "backmention"), undefined);+ assert.equal(restoreFixture(fixture, anchor, "backlink", "query-b"), undefined);+ assert.equal(fixture.scrollElement.scrollTop, 0);+ });+});diff --git a/app/src/layout/dock/backlinkReadingAnchor.ts b/app/src/layout/dock/backlinkReadingAnchor.tsnew file mode 100644index 0000000000..200e6bd428--- /dev/null+++ b/app/src/layout/dock/backlinkReadingAnchor.ts@@ -0,0 +1,307 @@+export type TBacklinkReadingPane = "backlink" | "backmention";++export interface IBacklinkReadingAnchor {+ pane: TBacklinkReadingPane,+ rootID: string,+ occurrenceID: string,+ blockID: string,+ offset: number,+ previousBlockID?: string,+ nextBlockID?: string,+ queryKey: string,+}++export interface ICaptureBacklinkReadingAnchorOptions {+ scopeElement: HTMLElement,+ scrollElement: HTMLElement,+ pane: TBacklinkReadingPane,+ queryKey: string,+}++export interface IRestoreBacklinkReadingAnchorOptions extends ICaptureBacklinkReadingAnchorOptions {+ anchor: IBacklinkReadingAnchor,+}++export interface IBacklinkReadingAnchorCandidate {+ top: number,+ bottom: number,+ height: number,+ depth: number,+ order: number,+}++export type TBacklinkReadingAnchorRestoreTarget = "block" | "next" | "previous" | "occurrence" | "document";++interface IBacklinkDOMAnchorCandidate extends IBacklinkReadingAnchorCandidate {+ element: HTMLElement,+ rootID: string,+ occurrenceID: string,+}++interface IBacklinkOccurrence {+ breadcrumbElement: HTMLElement,+ wysiwygElement: HTMLElement,+}++const BLOCK_SELECTOR = "[data-node-id][data-type]";+const BREADCRUMB_SELECTOR = ".protyle-breadcrumb__bar[data-backlink-id]";+const DOCUMENT_SELECTOR = ".backlinkList__item[data-node-id]";++const getAttribute = (element: Element, name: string) => element.getAttribute(name) || "";++const getElementDepth = (element: HTMLElement, ancestor: HTMLElement) => {+ let depth = 0;+ let current: HTMLElement | null = element;+ while (current && current !== ancestor) {+ depth++;+ current = current.parentElement;+ }+ return depth;+};++const getOccurrence = (element: HTMLElement): IBacklinkOccurrence | undefined => {+ const wysiwygElement = element.closest(".protyle-wysiwyg") as HTMLElement;+ if (!wysiwygElement) {+ return;+ }+ let topLevelElement = element;+ while (topLevelElement.parentElement && topLevelElement.parentElement !== wysiwygElement) {+ topLevelElement = topLevelElement.parentElement;+ }+ if (topLevelElement.parentElement !== wysiwygElement) {+ return;+ }+ let siblingElement = topLevelElement.previousElementSibling as HTMLElement;+ while (siblingElement) {+ if (siblingElement.matches(BREADCRUMB_SELECTOR)) {+ return {+ breadcrumbElement: siblingElement,+ wysiwygElement,+ };+ }+ siblingElement = siblingElement.previousElementSibling as HTMLElement;+ }+};++const getOccurrenceBlocks = (occurrence: IBacklinkOccurrence) => {+ const blocks: HTMLElement[] = [];+ let siblingElement = occurrence.breadcrumbElement.nextElementSibling as HTMLElement;+ while (siblingElement && !siblingElement.matches(BREADCRUMB_SELECTOR)) {+ if (siblingElement.matches(BLOCK_SELECTOR)) {+ blocks.push(siblingElement);+ }+ blocks.push(...Array.from(siblingElement.querySelectorAll(BLOCK_SELECTOR)).filter(item =>+ item.closest(".protyle-wysiwyg") === occurrence.wysiwygElement+ ) as HTMLElement[]);+ siblingElement = siblingElement.nextElementSibling as HTMLElement;+ }+ return blocks;+};++const compareCandidatePrecision = <T extends IBacklinkReadingAnchorCandidate>(left: T, right: T) => {+ if (left.depth !== right.depth) {+ return right.depth - left.depth;+ }+ if (left.height !== right.height) {+ return left.height - right.height;+ }+ return left.order - right.order;+};++export const selectBacklinkReadingAnchorCandidate = <T extends IBacklinkReadingAnchorCandidate>(+ candidates: T[],+ viewportTop: number,+ viewportBottom: number,+) => {+ const visibleCandidates = candidates.filter(item => item.bottom > viewportTop && item.top < viewportBottom);+ const crossingCandidates = visibleCandidates.filter(item => item.top <= viewportTop && item.bottom >= viewportTop);+ if (crossingCandidates.length > 0) {+ return [...crossingCandidates].sort(compareCandidatePrecision)[0];+ }+ return [...visibleCandidates].sort((left, right) => {+ if (left.top !== right.top) {+ return left.top - right.top;+ }+ return compareCandidatePrecision(left, right);+ })[0];+};++const collectDOMCandidates = (scopeElement: HTMLElement) => {+ const candidates: IBacklinkDOMAnchorCandidate[] = [];+ const elements = Array.from(scopeElement.querySelectorAll(`.protyle-wysiwyg ${BLOCK_SELECTOR}`)) as HTMLElement[];+ elements.forEach((element, order) => {+ const occurrence = getOccurrence(element);+ const documentElement = element.closest(DOCUMENT_SELECTOR) as HTMLElement;+ const rootID = documentElement && getAttribute(documentElement, "data-node-id");+ const occurrenceID = occurrence && getAttribute(occurrence.breadcrumbElement, "data-backlink-id");+ const blockID = getAttribute(element, "data-node-id");+ if (!occurrence || !rootID || !occurrenceID || !blockID) {+ return;+ }+ const rect = element.getBoundingClientRect();+ if (rect.bottom <= rect.top) {+ return;+ }+ candidates.push({+ element,+ rootID,+ occurrenceID,+ top: rect.top,+ bottom: rect.bottom,+ height: rect.height,+ depth: getElementDepth(element, occurrence.wysiwygElement),+ order,+ });+ });+ return candidates;+};++const collectDocumentCandidates = (scopeElement: HTMLElement) => {+ return (Array.from(scopeElement.querySelectorAll(+ `${DOCUMENT_SELECTOR} > .b3-list-item[data-node-id]`+ )) as HTMLElement[]).map((element, order) => {+ const rect = element.getBoundingClientRect();+ return {+ element,+ top: rect.top,+ bottom: rect.bottom,+ height: rect.height,+ depth: 0,+ order,+ };+ }).filter(item => item.bottom > item.top);+};++export const captureBacklinkReadingAnchor = (options: ICaptureBacklinkReadingAnchorOptions) => {+ const scrollRect = options.scrollElement.getBoundingClientRect();+ const scopeRect = options.scopeElement.getBoundingClientRect();+ const viewportTop = Math.max(scrollRect.top, scopeRect.top);+ const viewportBottom = Math.min(scrollRect.bottom, scopeRect.bottom);+ if (viewportBottom <= viewportTop) {+ return;+ }+ const candidate = selectBacklinkReadingAnchorCandidate(+ collectDOMCandidates(options.scopeElement),+ viewportTop,+ viewportBottom,+ );+ if (!candidate) {+ const documentCandidate = selectBacklinkReadingAnchorCandidate(+ collectDocumentCandidates(options.scopeElement),+ viewportTop,+ viewportBottom,+ );+ if (!documentCandidate) {+ return;+ }+ return {+ pane: options.pane,+ rootID: getAttribute(documentCandidate.element, "data-node-id"),+ occurrenceID: "",+ blockID: "",+ offset: documentCandidate.top - scrollRect.top,+ queryKey: options.queryKey,+ } satisfies IBacklinkReadingAnchor;+ }+ const occurrence = getOccurrence(candidate.element);+ if (!occurrence) {+ return;+ }+ const blocks = getOccurrenceBlocks(occurrence);+ const blockIndex = blocks.indexOf(candidate.element);+ const previousBlockID = blockIndex > 0 ? getAttribute(blocks[blockIndex - 1], "data-node-id") : undefined;+ const nextBlockID = blockIndex > -1 && blockIndex < blocks.length - 1 ?+ getAttribute(blocks[blockIndex + 1], "data-node-id") : undefined;+ return {+ pane: options.pane,+ rootID: candidate.rootID,+ occurrenceID: candidate.occurrenceID,+ blockID: getAttribute(candidate.element, "data-node-id"),+ offset: candidate.top - scrollRect.top,+ previousBlockID: previousBlockID || undefined,+ nextBlockID: nextBlockID || undefined,+ queryKey: options.queryKey,+ } satisfies IBacklinkReadingAnchor;+};++const findElementByAttribute = (elements: Element[], name: string, value: string) => {+ return elements.find(item => item.getAttribute(name) === value) as HTMLElement;+};++const isVisibleAnchorElement = (element?: HTMLElement) => {+ if (!element || element.closest(".fn__none")) {+ return false;+ }+ const rect = element.getBoundingClientRect();+ return rect.bottom > rect.top;+};++const findDocumentElement = (scopeElement: HTMLElement, rootID: string) => {+ return findElementByAttribute(+ Array.from(scopeElement.querySelectorAll(DOCUMENT_SELECTOR)),+ "data-node-id",+ rootID,+ );+};++const findDocumentTitleElement = (documentElement: HTMLElement) => {+ return Array.from(documentElement.children).find(item => item.matches(".b3-list-item[data-node-id]")) as HTMLElement;+};++export const restoreBacklinkReadingAnchor = (options: IRestoreBacklinkReadingAnchorOptions) => {+ const {anchor} = options;+ if (anchor.pane !== options.pane || anchor.queryKey !== options.queryKey) {+ return;+ }+ if (!isVisibleAnchorElement(options.scopeElement)) {+ return;+ }+ const documentElement = findDocumentElement(options.scopeElement, anchor.rootID);+ if (!documentElement) {+ return;+ }+ const breadcrumbElement = findElementByAttribute(+ Array.from(documentElement.querySelectorAll(BREADCRUMB_SELECTOR)),+ "data-backlink-id",+ anchor.occurrenceID,+ );+ let targetElement: HTMLElement;+ let target: TBacklinkReadingAnchorRestoreTarget;+ if (breadcrumbElement) {+ const occurrence = {+ breadcrumbElement,+ wysiwygElement: breadcrumbElement.parentElement,+ } as IBacklinkOccurrence;+ const blocks = getOccurrenceBlocks(occurrence);+ const blockCandidates: Array<[string, TBacklinkReadingAnchorRestoreTarget]> = [+ [anchor.blockID, "block"],+ [anchor.nextBlockID, "next"],+ [anchor.previousBlockID, "previous"],+ ];+ for (const [blockID, candidateTarget] of blockCandidates) {+ if (!blockID) {+ continue;+ }+ const candidateElement = findElementByAttribute(blocks, "data-node-id", blockID);+ if (isVisibleAnchorElement(candidateElement)) {+ targetElement = candidateElement;+ target = candidateTarget;+ break;+ }+ }+ if (!targetElement) {+ targetElement = breadcrumbElement;+ target = "occurrence";+ }+ } else {+ targetElement = findDocumentTitleElement(documentElement);+ target = "document";+ }+ if (!isVisibleAnchorElement(targetElement)) {+ return;+ }+ const scrollRect = options.scrollElement.getBoundingClientRect();+ const targetRect = targetElement.getBoundingClientRect();+ options.scrollElement.scrollTop += targetRect.top - scrollRect.top - anchor.offset;+ return target;+};diff --git a/app/src/menus/protyle.ts b/app/src/menus/protyle.tsindex b8c386f3f9..48e3a58bd8 100644--- a/app/src/menus/protyle.ts+++ b/app/src/menus/protyle.ts@@ -9,6 +9,7 @@ import {import {MenuItem} from "./Menu";import {getTableCellVerticalAlignmentMenus, setTableCellStyle} from "../protyle/util/tableControl";import {focusBlock, focusByRange, focusByWbr, getEditorRange, selectAll,} from "../protyle/util/selection";+import {getViewFoldOccurrenceID, hasViewFoldContext, setViewFoldTransient} from "../protyle/util/viewFold";import {deleteColumn,deleteRow,@@ -2691,6 +2692,21 @@ export const setFoldById = (data: {Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${data.id}"]`)).find((item: Element) => {if (!isInEmbedBlock(item)) {const operations = setFold(protyle, item, true, false, true, true);+ if (hasViewFoldContext(protyle)) {+ const occurrenceID = getViewFoldOccurrenceID(protyle, item);+ void setViewFoldTransient(protyle, item, false, undefined, true).then(() => {+ const focusElement = Array.from(protyle.wysiwyg.element.querySelectorAll(+ `[data-node-id="${data.currentNodeID}"]`+ )).find(element => getViewFoldOccurrenceID(protyle, element) === occurrenceID);+ if (focusElement) {+ focusBlock(focusElement);+ }+ }).catch(error => console.error(error));+ return true;+ }+ if (operations.doOperations.length === 0) {+ return true;+ }operations.doOperations[0].context = {focusId: data.currentNodeID,};diff --git a/app/src/protyle/gutter/button.test.ts b/app/src/protyle/gutter/button.test.tsindex ead8bfb4d9..ba6430f202 100644--- a/app/src/protyle/gutter/button.test.ts+++ b/app/src/protyle/gutter/button.test.ts@@ -29,6 +29,15 @@ describe("genGutterBlockButtonHTML", () => {assert.match(html, /data-embed-id="20260817120001-embed"/);assert.doesNotMatch(html, /draggable="true"/);});++ it("keeps repeated view occurrences distinct", () => {+ const html = genGutterBlockButtonHTML({+ ...baseOptions,+ viewOccurrenceID: "fragment/second",+ });++ assert.match(html, /data-view-occurrence-id="fragment%2Fsecond"/);+ });});describe("canShowGutterInsert", () => {diff --git a/app/src/protyle/gutter/button.ts b/app/src/protyle/gutter/button.tsindex 67a3d73cd2..16ebce5224 100644--- a/app/src/protyle/gutter/button.ts+++ b/app/src/protyle/gutter/button.ts@@ -5,14 +5,17 @@ export interface IGutterBlockButtonOptions {nodeID: string;icon: string;embedID?: string;+ viewOccurrenceID?: string;popoverHTML?: string;draggable: boolean;}export const genGutterBlockButtonHTML = (options: IGutterBlockButtonOptions) => {const embedHTML = options.embedID ? ` data-embed-id="${options.embedID}"` : "";+ const viewOccurrenceHTML = options.viewOccurrenceID ?+ ` data-view-occurrence-id="${encodeURIComponent(options.viewOccurrenceID)}"` : "";return `<button class="ariaLabel" data-delay="500" data-position="parentW" aria-label="${options.ariaLabel}"-data-type="${options.type}" data-subtype="${options.subtype}" data-node-id="${options.nodeID}"${embedHTML}>+data-type="${options.type}" data-subtype="${options.subtype}" data-node-id="${options.nodeID}"${embedHTML}${viewOccurrenceHTML}><svg><use xlink:href="#${options.icon}"></use></svg><span ${options.popoverHTML || ""} ${options.draggable ? 'draggable="true"' : ""}></span></button>`;diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.tsindex 703f3f2a6a..7f0cbe8ab3 100644--- a/app/src/protyle/gutter/index.ts+++ b/app/src/protyle/gutter/index.ts@@ -111,6 +111,7 @@ import {applyHeadingLevelUpdates, getHeadingLevelUpdateOperations} from "../utilimport {getBacklinkGutterContentTop, getFixedGutterPosition, getGutterMarginHeight} from "./layout";import {closeSubElement} from "../toolbar/subElementLifecycle";import {canShowGutterInsert, genGutterBlockButtonHTML} from "./button";+import {getViewFoldOccurrenceID, hasViewFoldContext, setViewFold} from "../util/viewFold";// 块类型 data-type 到本地化名称键的映射,用于块标提示中的 ${x}const BLOCK_TYPE_LANG_KEYS: { [key: string]: string } = {@@ -401,33 +402,46 @@ export class Gutter {}}});- const doOperations: IOperation[] = [];- const undoOperations: IOperation[] = [];- Array.from(foldElement.children).forEach((ulElement) => {- if (ulElement.classList.contains("list")) {- Array.from(ulElement.children).forEach((listItemElement) => {- if (listItemElement.classList.contains("li")) {- if (hasFold) {- listItemElement.removeAttribute("fold");- } else if (listItemElement.childElementCount > 3) {- listItemElement.setAttribute("fold", "1");+ if (hasViewFoldContext(protyle)) {+ Array.from(foldElement.children).forEach(ulElement => {+ if (ulElement.classList.contains("list")) {+ Array.from(ulElement.children).forEach(listItemElement => {+ if (listItemElement.classList.contains("li") &&+ (hasFold || listItemElement.childElementCount > 3)) {+ setViewFold(protyle, listItemElement, !hasFold);}- const listId = listItemElement.getAttribute("data-node-id");- doOperations.push({- action: "setAttrs",- id: listId,- data: JSON.stringify({fold: hasFold ? "" : "1"})- });- undoOperations.push({- action: "setAttrs",- id: listId,- data: JSON.stringify({fold: hasFold ? "1" : ""})- });- }- });- }- });- transaction(protyle, doOperations, undoOperations);+ });+ }+ });+ } else {+ const doOperations: IOperation[] = [];+ const undoOperations: IOperation[] = [];+ Array.from(foldElement.children).forEach((ulElement) => {+ if (ulElement.classList.contains("list")) {+ Array.from(ulElement.children).forEach((listItemElement) => {+ if (listItemElement.classList.contains("li")) {+ if (hasFold) {+ listItemElement.removeAttribute("fold");+ } else if (listItemElement.childElementCount > 3) {+ listItemElement.setAttribute("fold", "1");+ }+ const listId = listItemElement.getAttribute("data-node-id");+ doOperations.push({+ action: "setAttrs",+ id: listId,+ data: JSON.stringify({fold: hasFold ? "" : "1"})+ });+ undoOperations.push({+ action: "setAttrs",+ id: listId,+ data: JSON.stringify({fold: hasFold ? "1" : ""})+ });+ }+ });+ }+ });+ transaction(protyle, doOperations, undoOperations);+ }buttonElement.removeAttribute("disabled");} else {foldStatus = setFold(protyle, foldElement).fold;@@ -570,29 +584,38 @@ export class Gutter {if (arrowElement) {arrowElement.style.transform = hasFold ? "rotate(90deg)" : "";}- const doOperations: IOperation[] = [];- const undoOperations: IOperation[] = [];- Array.from(foldElement.parentElement.children).find((listItemElement) => {- if (listItemElement.classList.contains("li")) {- if (hasFold) {- listItemElement.removeAttribute("fold");- } else if (listItemElement.childElementCount > 3) {- listItemElement.setAttribute("fold", "1");+ if (hasViewFoldContext(protyle)) {+ Array.from(foldElement.parentElement.children).forEach(listItemElement => {+ if (listItemElement.classList.contains("li") &&+ (hasFold || listItemElement.childElementCount > 3)) {+ setViewFold(protyle, listItemElement, !hasFold);}- const listId = listItemElement.getAttribute("data-node-id");- doOperations.push({- action: "setAttrs",- id: listId,- data: JSON.stringify({fold: hasFold ? "" : "1"})- });- undoOperations.push({- action: "setAttrs",- id: listId,- data: JSON.stringify({fold: hasFold ? "1" : ""})- });- }- });- transaction(protyle, doOperations, undoOperations);+ });+ } else {+ const doOperations: IOperation[] = [];+ const undoOperations: IOperation[] = [];+ Array.from(foldElement.parentElement.children).find((listItemElement) => {+ if (listItemElement.classList.contains("li")) {+ if (hasFold) {+ listItemElement.removeAttribute("fold");+ } else if (listItemElement.childElementCount > 3) {+ listItemElement.setAttribute("fold", "1");+ }+ const listId = listItemElement.getAttribute("data-node-id");+ doOperations.push({+ action: "setAttrs",+ id: listId,+ data: JSON.stringify({fold: hasFold ? "" : "1"})+ });+ undoOperations.push({+ action: "setAttrs",+ id: listId,+ data: JSON.stringify({fold: hasFold ? "1" : ""})+ });+ }+ });+ transaction(protyle, doOperations, undoOperations);+ }} else {const hasFold = setFold(protyle, foldElement).fold;const foldArrowElement = buttonElement.parentElement.querySelector("[data-type='fold'] > svg") as HTMLElement;@@ -1482,10 +1505,14 @@ export class Gutter {return;}const embedID = (element as HTMLElement).dataset.embedId;+ const viewOccurrenceID = (element as HTMLElement).dataset.viewOccurrenceId;return Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${id}"]`)).find(item => {if (!this.isMatchNode(item)) {return false;}+ if (viewOccurrenceID && encodeURIComponent(getViewFoldOccurrenceID(protyle, item)) !== viewOccurrenceID) {+ return false;+ }const embedElement = isInEmbedBlock(item, false);if (embedID) {return embedElement && embedElement.getAttribute("data-node-id") === embedID &&@@ -3579,6 +3606,8 @@ export class Gutter {if (protyle.options.backlinkData) {popoverHTML = `class="popover__block" data-id="${dataNodeId}"`;}+ const viewOccurrenceID = hasViewFoldContext(protyle) ?+ getViewFoldOccurrenceID(protyle, nodeElement) : "";const buttonHTML = type ? genGutterBlockButtonHTML({ariaLabel: gutterTip,type,@@ -3586,6 +3615,7 @@ export class Gutter {nodeID: dataNodeId,icon: getIconByType(type, nodeElement.getAttribute("data-subtype")),embedID,+ viewOccurrenceID,popoverHTML,draggable: !protyle.disabled && !embedContext,}) : "";@@ -3596,7 +3626,7 @@ export class Gutter {if (type === "NodeListItem" && nodeElement.childElementCount > 3 || type === "NodeHeading") {const fold = nodeElement.getAttribute("fold");foldHTML = `<button class="ariaLabel" data-delay="500" data-position="parentW" aria-label="${window.siyuan.languages.fold}"-data-type="fold" style="cursor:inherit;"><svg style="width: 10px;${fold && fold === "1" ? "" : "transform:rotate(90deg)"}"><use xlink:href="#iconPlay"></use></svg></button>`;+data-type="fold"${viewOccurrenceID ? ` data-view-occurrence-id="${encodeURIComponent(viewOccurrenceID)}"` : ""} style="cursor:inherit;"><svg style="width: 10px;${fold && fold === "1" ? "" : "transform:rotate(90deg)"}"><use xlink:href="#iconPlay"></use></svg></button>`;}if (type === "NodeListItem" || type === "NodeList") {listItem = nodeElement;@@ -3658,6 +3688,8 @@ data-type="fold" style="cursor:inherit;"><svg style="width: 10px;${fold && foldsubtype: embedElement.getAttribute("data-subtype"),nodeID: embedElement.getAttribute("data-node-id"),icon: getIconByType(type, embedElement.getAttribute("data-subtype")),+ viewOccurrenceID: hasViewFoldContext(protyle) ?+ getViewFoldOccurrenceID(protyle, embedElement) : "",popoverHTML: protyle.options.backlinkData ?`class="popover__block" data-id="${embedElement.getAttribute("data-node-id")}"` : "",draggable: !protyle.disabled,diff --git a/app/src/protyle/index.ts b/app/src/protyle/index.tsindex a114cad038..2bdec16827 100644--- a/app/src/protyle/index.ts+++ b/app/src/protyle/index.ts@@ -52,6 +52,7 @@ import {renderAVAttribute} from "./render/av/blockAttr";import {setFoldById, zoomOut} from "../menus/protyle";import {setEditMode} from "./util/setEditMode";import {waitForPendingTransactions} from "./util/transactionQueue";+import {applyViewFoldStates, invalidateViewFoldRequests} from "./util/viewFold";export class Protyle {@@ -361,10 +362,12 @@ export class Protyle {const hadContent = this.protyle.wysiwyg.element.childElementCount > 0;let needCreateAction = "";let hasDeleteOp = false;+ let skippedBacklinkStructure = false;const operations: IOperation[] = [];data.data[0].doOperations.find((item: IOperation) => {if (this.protyle.options.backlinkData && ["delete", "move"].includes(item.action)) {// 反链上下文只展示源文档的一部分,结构操作等待索引提交后按内容版本增量同步。+ skippedBacklinkStructure = true;return true;} else {if (item.action === "delete") {@@ -379,6 +382,9 @@ export class Protyle {});if (operations.length > 0) {onTransaction(this.protyle, operations, false);+ } else if (skippedBacklinkStructure) {+ invalidateViewFoldRequests(this.protyle);+ void applyViewFoldStates(this.protyle);}// 聚焦块被分屏另一侧的删除操作连带删除时(容器块删除会级联删除其所有子孙块,如列表/超级块/引述等),当前页签的聚焦块已成为孤儿但仍显示,需退出聚焦// Improve editor state synchronization when deleting blocks https://github.com/siyuan-note/siyuan/issues/17742diff --git a/app/src/protyle/util/blockFold.ts b/app/src/protyle/util/blockFold.tsindex a353fd0b4a..d0442f76b4 100644--- a/app/src/protyle/util/blockFold.ts+++ b/app/src/protyle/util/blockFold.ts@@ -8,6 +8,13 @@ import {clearSelect} from "./clear";import {removeFoldHeading} from "./heading";import {getSbChildBlockCount, getTopAloneElement} from "../wysiwyg/getBlock";import {fetchSyncPost} from "../../util/fetch";+import {+ getViewFoldOccurrenceID,+ hasViewFoldContext,+ setViewFold,+ setViewFoldState,+ setViewFoldTransient,+} from "./viewFold";const applyFoldState = (protyle: IProtyle, nodeElement: Element, folded: boolean) => {if (!folded) {@@ -36,26 +43,78 @@ const applyFoldState = (protyle: IProtyle, nodeElement: Element, folded: boolean}};+const getEmptyFoldResult = () => ({+ fold: -1,+ doOperations: [] as IOperation[],+ undoOperations: [] as IOperation[],+ ready: Promise.resolve(),+});+export const setFold = (protyle: IProtyle, nodeElement: Element, isOpen?: boolean,- isRemove?: boolean, addLoading = true, getOperations = false) => {+ isRemove?: boolean, addLoading = true, getOperations = false,+ persistViewState = !getOperations) => {if (nodeElement.getAttribute("data-type") === "NodeListItem" && nodeElement.childElementCount < 4 &&// 该情况需要强制展开 https://github.com/siyuan-note/siyuan/issues/12327!isOpen) {// 没有子列表或多个块的列表项不进行折叠- return {fold: -1};+ return getEmptyFoldResult();}if (nodeElement.getAttribute("data-type") === "NodeThematicBreak") {- return {fold: -1};+ return getEmptyFoldResult();}const hasFold = nodeElement.getAttribute("fold") === "1";+ if (hasViewFoldContext(protyle)) {+ if ((hasFold && typeof isOpen === "boolean" && !isOpen) ||+ (!hasFold && typeof isOpen === "boolean" && isOpen)) {+ return getEmptyFoldResult();+ }+ const folded = !hasFold;+ const ready = persistViewState ?+ (setViewFold(protyle, nodeElement, folded), Promise.resolve()) :+ setViewFoldTransient(protyle, nodeElement, folded, undefined, false);+ preventScroll(protyle);+ if (!getOperations) {+ return {fold: folded ? 1 : 0, undoOperations: [], doOperations: [], ready};+ }+ const id = nodeElement.getAttribute("data-node-id");+ if (nodeElement.getAttribute("data-type") === "NodeHeading") {+ return {+ fold: folded ? 1 : 0,+ doOperations: [{+ action: folded ? "foldHeading" : "unfoldHeading",+ id,+ data: !folded && isRemove ? "remove" : undefined,+ }] as IOperation[],+ undoOperations: [{+ action: folded ? "unfoldHeading" : "foldHeading",+ id,+ }] as IOperation[],+ ready,+ };+ }+ return {+ fold: folded ? 1 : 0,+ doOperations: [{+ action: "setAttrs",+ id,+ data: JSON.stringify({fold: folded ? "1" : ""}),+ }] as IOperation[],+ undoOperations: [{+ action: "setAttrs",+ id,+ data: JSON.stringify({fold: folded ? "" : "1"}),+ }] as IOperation[],+ ready,+ };+ }if (hasFold) {if (typeof isOpen === "boolean" && !isOpen) {- return {fold: -1};+ return getEmptyFoldResult();}applyFoldState(protyle, nodeElement, false);} else {if (typeof isOpen === "boolean" && isOpen) {- return {fold: -1};+ return getEmptyFoldResult();}applyFoldState(protyle, nodeElement, true);}@@ -103,11 +162,40 @@ export const setFold = (protyle: IProtyle, nodeElement: Element, isOpen?: boolea}// 折叠后,防止滚动条滚动后调用 get 请求 https://github.com/siyuan-note/siyuan/issues/2248preventScroll(protyle);- return {fold: !hasFold ? 1 : 0, undoOperations, doOperations};+ return {fold: !hasFold ? 1 : 0, undoOperations, doOperations, ready: Promise.resolve()};};const headingFoldingProtyles = new WeakSet<IProtyle>();+const getViewHeadingGroup = (protyle: IProtyle, nodeElement: Element, scope: "children" | "siblings") => {+ if (scope === "children" && nodeElement.getAttribute("fold") === "1") {+ return [nodeElement];+ }+ const occurrenceID = getViewFoldOccurrenceID(protyle, nodeElement);+ const level = Number(nodeElement.getAttribute("data-subtype")?.substring(1));+ const headings = Array.from(protyle.wysiwyg.element.querySelectorAll('[data-type="NodeHeading"]')).filter(item => {+ return getViewFoldOccurrenceID(protyle, item) === occurrenceID;+ });+ if (scope === "siblings") {+ return headings.filter(item => Number(item.getAttribute("data-subtype")?.substring(1)) === level);+ }+ const startIndex = headings.indexOf(nodeElement);+ const children: Element[] = [];+ let directLevel = 7;+ for (let index = startIndex + 1; index < headings.length; index++) {+ const current = headings[index];+ const currentLevel = Number(current.getAttribute("data-subtype")?.substring(1));+ if (currentLevel <= level) {+ break;+ }+ if (currentLevel <= directLevel) {+ directLevel = currentLevel;+ children.push(current);+ }+ }+ return children;+};+export const foldHeadingGroup = async (protyle: IProtyle, nodeElement: Element,scope: "children" | "siblings") => {if (headingFoldingProtyles.has(protyle) || nodeElement.getAttribute("data-type") !== "NodeHeading") {@@ -116,6 +204,16 @@ export const foldHeadingGroup = async (protyle: IProtyle, nodeElement: Element,headingFoldingProtyles.add(protyle);try {+ if (hasViewFoldContext(protyle)) {+ const headings = getViewHeadingGroup(protyle, nodeElement, scope);+ const foldAll = headings.some(item => item.getAttribute("fold") !== "1");+ headings.slice().reverse().forEach(item => {+ if ((item.getAttribute("fold") === "1") !== foldAll) {+ setViewFold(protyle, item, foldAll);+ }+ });+ return;+ }const id = nodeElement.getAttribute("data-node-id");const response = await fetchSyncPost("/api/block/getHeadingFoldTransaction", {id, scope});const doOperations = response.data?.doOperations as IOperation[];@@ -159,26 +257,30 @@ const isFoldable = (el: Element) => {};const foldBlocksRecursively0 = async (protyle: IProtyle, nodeElements: Element[]) => {- const candidates = new Map<string, {element: Element, order: number}>();+ const viewContext = hasViewFoldContext(protyle);+ const candidates = new Map<string, {element: Element, order: number, occurrenceID: string}>();let order = 0;- const addCandidate = (element: Element) => {+ const addCandidate = (element: Element, occurrenceID = getViewFoldOccurrenceID(protyle, element)) => {if (!isFoldable(element) ||(element.getAttribute("data-type") === "NodeHeading" &&element.parentElement?.getAttribute("data-type") === "NodeListItem")) {return;}const id = element.getAttribute("data-node-id");- if (!id || candidates.has(id)) {+ const key = viewContext ? `${encodeURIComponent(occurrenceID)}:${id}` : id;+ if (!id || candidates.has(key)) {return;}- candidates.set(id, {element, order});+ candidates.set(key, {element, order, occurrenceID});order++;};- const addScope = (scope: ParentNode) => {+ const addScope = (scope: ParentNode, occurrenceID?: string) => {if (scope instanceof Element) {- addCandidate(scope);+ addCandidate(scope, occurrenceID);}- scope.querySelectorAll("[data-type='NodeHeading'], .li, .bq, .sb, .callout").forEach(addCandidate);+ scope.querySelectorAll("[data-type='NodeHeading'], .li, .bq, .sb, .callout").forEach(element => {+ addCandidate(element, occurrenceID);+ });};const scopes = await Promise.all(nodeElements.map(async (element) => {@@ -196,39 +298,72 @@ const foldBlocksRecursively0 = async (protyle: IProtyle, nodeElements: Element[]});fullHTML = response.data.dom;}- return {element, fullHTML};+ return {element, fullHTML, occurrenceID: getViewFoldOccurrenceID(protyle, element)};}));- scopes.forEach(({element, fullHTML}) => {+ scopes.forEach(({element, fullHTML, occurrenceID}) => {if (fullHTML) {const template = document.createElement("template");template.innerHTML = fullHTML;- addScope(template.content);+ addScope(template.content, occurrenceID);} else {- addScope(element);+ addScope(element, occurrenceID);}});- const elementsToFold = Array.from(candidates.values()).sort((a, b) => a.order - b.order).map((candidate) => {- return protyle.wysiwyg.element.querySelector(`[data-node-id="${candidate.element.getAttribute("data-node-id")}"]`) ||- candidate.element;+ const foldCandidates = Array.from(candidates.values()).sort((a, b) => a.order - b.order).map((candidate) => {+ const id = candidate.element.getAttribute("data-node-id");+ if (viewContext) {+ const connectedElement = Array.from(protyle.wysiwyg.element.querySelectorAll(+ `[data-node-id="${id}"]`+ )).find(element => {+ return getViewFoldOccurrenceID(protyle, element) === candidate.occurrenceID;+ });+ return {...candidate, element: connectedElement || candidate.element};+ }+ return {+ ...candidate,+ element: protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`) || candidate.element,+ };});- if (elementsToFold.length === 0) {+ if (foldCandidates.length === 0) {return;}// 任一候选块未折叠时执行全部折叠;全部已折叠时执行全部展开。- let isFoldAll = elementsToFold.some(item => item.getAttribute("fold") !== "1");+ let isFoldAll = foldCandidates.some(item => item.element.getAttribute("fold") !== "1");// 单个入口已折叠时以展开入口为准,后代状态不影响操作方向。if (isFoldAll && nodeElements.length === 1 && nodeElements[0].getAttribute("fold") === "1") {isFoldAll = false;}// 内层状态需要先写入内核,外层标题最后展开时返回的 DOM 才能包含后代块的最终折叠状态。- const elementsToProcess = Array.from(elementsToFold).reverse();- const scrollElement = (isFoldAll ? elementsToProcess : elementsToFold).find(element => element.isConnected);+ const candidatesToProcess = Array.from(foldCandidates).reverse();+ const scrollElement = (isFoldAll ? candidatesToProcess : foldCandidates)+ .find(candidate => candidate.element.isConnected)?.element;++ if (hasViewFoldContext(protyle)) {+ candidatesToProcess.forEach(candidate => {+ const element = candidate.element;+ if (element.isConnected) {+ setViewFold(protyle, element, isFoldAll);+ } else {+ setViewFoldState(+ protyle,+ candidate.occurrenceID,+ element.getAttribute("data-node-id"),+ isFoldAll,+ );+ }+ });+ preventScroll(protyle);+ if (scrollElement) {+ scrollCenter(protyle, scrollElement);+ }+ return;+ }const doOperations: IOperation[] = [];const undoOperations: IOperation[] = [];- elementsToProcess.forEach(element => {+ candidatesToProcess.forEach(({element}) => {const hasFold = element.getAttribute("fold") === "1";if ((isFoldAll && hasFold) || (!isFoldAll && !hasFold)) {return;diff --git a/app/src/protyle/util/clear.ts b/app/src/protyle/util/clear.tsindex f7764b8476..b7e2476b81 100644--- a/app/src/protyle/util/clear.ts+++ b/app/src/protyle/util/clear.ts@@ -13,7 +13,27 @@ const getAVElements = (element: Element) => {return elements;};+const clearViewState = (element: Element) => {+ const attributes = ["data-view-fold-source", "data-view-fold-hidden-source", "data-view-fold",+ "data-view-fold-default", "data-view-fold-hidden", "data-view-heading-owner", "data-view-heading-loaded"];+ const elements = [element, ...Array.from(element.querySelectorAll(attributes.map(attribute => {+ return `[${attribute}]`;+ }).join(", ")))];+ elements.forEach(item => {+ const sourceFold = item.getAttribute("data-view-fold-source");+ if (sourceFold !== null) {+ item.toggleAttribute("fold", sourceFold === "1");+ }+ const sourceHidden = item.getAttribute("data-view-fold-hidden-source");+ if (sourceHidden !== null) {+ item.classList.toggle("fn__none", sourceHidden === "1");+ }+ attributes.forEach(attribute => item.removeAttribute(attribute));+ });+};+export const clearBlockElement = (element: Element, keepRefcount = false) => {+ clearViewState(element);element.classList.remove("protyle-wysiwyg--select", "protyle-wysiwyg--hl");element.removeAttribute(Constants.CUSTOM_RIFF_DECKS);if (!keepRefcount) {diff --git a/app/src/protyle/util/editorCommonEvent.ts b/app/src/protyle/util/editorCommonEvent.tsindex 93e2579ba9..e3b80d5e2f 100644--- a/app/src/protyle/util/editorCommonEvent.ts+++ b/app/src/protyle/util/editorCommonEvent.ts@@ -887,7 +887,7 @@ const dragSame = async (protyle: IProtyle, sourceElements: Element[], targetElem}unfoldHeadingElements.forEach(item => {const foldData = setFold(protyle, item, true, false, false, true);- if (!foldData.doOperations) {+ if (!foldData.doOperations?.length) {return;}foldData.doOperations[0].context = {diff --git a/app/src/protyle/util/insertHTML.ts b/app/src/protyle/util/insertHTML.tsindex c0b3cc0834..5243285470 100644--- a/app/src/protyle/util/insertHTML.ts+++ b/app/src/protyle/util/insertHTML.ts@@ -1494,9 +1494,11 @@ export const insertHTML = (html: string, protyle: IProtyle, isBlock = false,const childrenIDs: string[] = response.data;const previousId = (childrenIDs && childrenIDs.length > 0) ? childrenIDs[childrenIDs.length - 1] : blockElement.getAttribute("data-node-id");foldData = setFold(protyle, blockElement, true, false, false, true);- foldData.doOperations[0].context = {- focusId: lastElement?.getAttribute("data-node-id"),- };+ if (foldData.doOperations.length > 0) {+ foldData.doOperations[0].context = {+ focusId: lastElement?.getAttribute("data-node-id"),+ };+ }doOperation.forEach(item => {if (item.action === "insert") {item.previousID = previousId;diff --git a/app/src/protyle/util/viewFold.ts b/app/src/protyle/util/viewFold.tsnew file mode 100644index 0000000000..400beacc59--- /dev/null+++ b/app/src/protyle/util/viewFold.ts@@ -0,0 +1,570 @@+import {fetchSyncPost} from "../../util/fetch";+import {processRender} from "./processCode";+import {highlightRender} from "../render/highlightRender";+import {avRender} from "../render/av/render";+import {blockRender} from "../render/blockRender";+import {disabledProtyle} from "./onGet";+import {+ clearViewFoldDefaultsForOccurrence,+ clearViewFoldOccurrenceRuntimeState,+} from "./viewFoldRuntimeState";++const VIEW_FOLD_SOURCE = "data-view-fold-source";+const VIEW_FOLD_VALUE = "data-view-fold";+const VIEW_FOLD_DEFAULT = "data-view-fold-default";+const VIEW_FOLD_HIDDEN = "data-view-fold-hidden";+const VIEW_FOLD_HIDDEN_SOURCE = "data-view-fold-hidden-source";+const VIEW_HEADING_OWNER = "data-view-heading-owner";+const VIEW_HEADING_LOADED = "data-view-heading-loaded";++export interface IViewFoldStateStore {+ get<T>(key: string): T | undefined,+ set<T>(key: string, value: T): void,+ remove(key: string): void,+}++export interface IViewFoldContext {+ store: IViewFoldStateStore,+ pane: string,+ rootID: string,+ generation?: number,+ defaults?: Map<string, boolean>,+ transient?: Map<string, boolean>,+ getOccurrenceID?: (element: Element) => string,+ getOccurrenceRevision?: (element: Element) => string,+}++const viewFoldContexts = new WeakMap<IProtyle, IViewFoldContext>();+const headingRequestVersions = new WeakMap<Element, number>();+interface IHeadingChildrenRequest {+ context: IViewFoldContext,+ contextGeneration: number,+ occurrenceID: string,+ revision: string,+ stateKey: string,+ requestVersion: number,+ promise: Promise<void>,+}+const headingChildrenRequests = new WeakMap<Element, IHeadingChildrenRequest>();++const encodeKeyPart = (value: string) => encodeURIComponent(value || "");++export const getViewFoldOccurrenceID = (protyle: IProtyle, element: Element) => {+ return viewFoldContexts.get(protyle)?.getOccurrenceID?.(element) || "";+};++const getViewFoldStateKeyByIdentity = (context: IViewFoldContext, occurrenceID: string, blockID: string) => {+ if (!blockID) {+ return "";+ }+ return [+ "fold",+ encodeKeyPart(context.pane),+ encodeKeyPart(context.rootID),+ encodeKeyPart(occurrenceID),+ encodeKeyPart(blockID),+ ].join(":");+};++export const getViewFoldStateKey = (protyle: IProtyle, element: Element) => {+ const context = viewFoldContexts.get(protyle);+ const blockID = element.getAttribute("data-node-id");+ if (!context || !blockID) {+ return "";+ }+ return getViewFoldStateKeyByIdentity(context, getViewFoldOccurrenceID(protyle, element), blockID);+};++const getSourceFold = (element: Element) => {+ const source = element.getAttribute(VIEW_FOLD_SOURCE);+ return source === null ? element.getAttribute("fold") === "1" : source === "1";+};++const getHeadingLevel = (element: Element) => {+ const subtype = element.getAttribute("data-subtype") || "";+ return /^h[1-6]$/.test(subtype) ? Number(subtype.substring(1)) : 0;+};++const getHeadingChildren = (heading: Element) => {+ const level = getHeadingLevel(heading);+ const children: Element[] = [];+ let current = heading.nextElementSibling;+ while (current && !current.classList.contains("protyle-breadcrumb__bar")) {+ const currentLevel = getHeadingLevel(current);+ if (currentLevel > 0 && currentLevel <= level) {+ break;+ }+ children.push(current);+ current = current.nextElementSibling;+ }+ return children;+};++const setHeadingChildrenHidden = (heading: Element, hidden: boolean, token: string) => {+ getHeadingChildren(heading).forEach(child => {+ const tokens = new Set((child.getAttribute(VIEW_FOLD_HIDDEN) || "").split(" ").filter(Boolean));+ if (hidden) {+ if (!child.hasAttribute(VIEW_FOLD_HIDDEN_SOURCE)) {+ child.setAttribute(VIEW_FOLD_HIDDEN_SOURCE, child.classList.contains("fn__none") ? "1" : "0");+ }+ tokens.add(token);+ child.classList.add("fn__none");+ } else {+ tokens.delete(token);+ if (tokens.size === 0) {+ if (child.getAttribute(VIEW_FOLD_HIDDEN_SOURCE) !== "1") {+ child.classList.remove("fn__none");+ }+ child.removeAttribute(VIEW_FOLD_HIDDEN_SOURCE);+ }+ }+ if (tokens.size === 0) {+ child.removeAttribute(VIEW_FOLD_HIDDEN);+ } else {+ child.setAttribute(VIEW_FOLD_HIDDEN, Array.from(tokens).join(" "));+ }+ });+};++const getHeadingToken = (protyle: IProtyle, heading: Element) => {+ return encodeKeyPart(getViewFoldStateKey(protyle, heading) || heading.getAttribute("data-node-id"));+};++const renderHeadingChildren = (protyle: IProtyle, heading: Element, children: Element[]) => {+ if (children.length === 0) {+ return;+ }+ const token = getHeadingToken(protyle, heading);+ const fragment = document.createDocumentFragment();+ children.forEach(child => {+ child.removeAttribute("parent-heading");+ child.setAttribute(VIEW_HEADING_OWNER, token);+ fragment.appendChild(child);+ });+ heading.after(fragment);+ children.forEach(child => {+ processRender(child);+ highlightRender(child);+ avRender(child, protyle);+ blockRender(protyle, child);+ });+ if (protyle.disabled) {+ disabledProtyle(protyle);+ }+};++const ensureHeadingChildren = async (protyle: IProtyle, heading: Element, stateKey: string, force = false) => {+ if (getHeadingChildren(heading).length > 0 || heading.getAttribute(VIEW_HEADING_LOADED) === "1" ||+ (!force && getSourceFold(heading) === false)) {+ return;+ }+ const context = viewFoldContexts.get(protyle);+ if (!context) {+ return;+ }+ const contextGeneration = context.generation || 0;+ const occurrenceID = getViewFoldOccurrenceID(protyle, heading);+ const revision = context.getOccurrenceRevision?.(heading) || "";+ const currentRequestVersion = headingRequestVersions.get(heading) || 0;+ const inFlight = headingChildrenRequests.get(heading);+ if (inFlight?.context === context && inFlight.occurrenceID === occurrenceID && inFlight.revision === revision &&+ inFlight.stateKey === stateKey && inFlight.requestVersion === currentRequestVersion) {+ await inFlight.promise;+ if (headingChildrenRequests.get(heading) === inFlight) {+ headingChildrenRequests.delete(heading);+ }+ if (inFlight.contextGeneration === contextGeneration) {+ return;+ }+ if (viewFoldContexts.get(protyle) === context && heading.isConnected &&+ getViewFoldStateKey(protyle, heading) === stateKey && heading.getAttribute(VIEW_FOLD_VALUE) === "0") {+ await ensureHeadingChildren(protyle, heading, stateKey, force);+ }+ return;+ }++ const requestVersion = currentRequestVersion + 1;+ headingRequestVersions.set(heading, requestVersion);+ const promise = (async () => {+ let response: IWebSocketData;+ try {+ response = await fetchSyncPost("/api/block/getHeadingChildrenDOM", {+ id: heading.getAttribute("data-node-id"),+ removeFoldAttr: false,+ });+ } catch (error) {+ console.error(error);+ return;+ }+ if (viewFoldContexts.get(protyle) !== context || context.generation !== contextGeneration ||+ !heading.isConnected || headingRequestVersions.get(heading) !== requestVersion ||+ getViewFoldOccurrenceID(protyle, heading) !== occurrenceID ||+ getViewFoldStateKey(protyle, heading) !== stateKey ||+ (context.getOccurrenceRevision?.(heading) || "") !== revision ||+ heading.getAttribute(VIEW_FOLD_VALUE) !== "0") {+ return;+ }+ if (response.code !== 0 || typeof response.data !== "string") {+ return;+ }+ const template = document.createElement("template");+ template.innerHTML = response.data;+ const elements = Array.from(template.content.children);+ if (!elements[0] || elements[0].getAttribute("data-node-id") !== heading.getAttribute("data-node-id")) {+ return;+ }+ heading.setAttribute(VIEW_HEADING_LOADED, "1");+ if (getHeadingChildren(heading).length > 0) {+ return;+ }+ const children = elements.slice(1);+ renderHeadingChildren(protyle, heading, children);+ const foldedHeadings: Element[] = [];+ children.forEach(element => {+ if (element.getAttribute("data-type") === "NodeHeading" && element.getAttribute("fold") === "1") {+ foldedHeadings.push(element);+ }+ element.querySelectorAll('[data-type="NodeHeading"][fold="1"]').forEach(item => foldedHeadings.push(item));+ });+ foldedHeadings.reverse().forEach(item => applyFold(protyle, item, true, true));+ await Promise.all([heading, ...children].map(element => applyViewFoldStates(protyle, element)));+ })();+ const request: IHeadingChildrenRequest = {+ context,+ contextGeneration,+ occurrenceID,+ revision,+ stateKey,+ requestVersion,+ promise,+ };+ headingChildrenRequests.set(heading, request);+ try {+ await promise;+ } finally {+ if (headingChildrenRequests.get(heading) === request) {+ headingChildrenRequests.delete(heading);+ }+ }+};++const applyFold = (protyle: IProtyle, element: Element, folded: boolean, sourceFold?: boolean) => {+ const source = sourceFold ?? getSourceFold(element);+ const previousFold = element.getAttribute(VIEW_FOLD_VALUE);+ const foldValue = folded ? "1" : "0";+ element.setAttribute(VIEW_FOLD_SOURCE, source ? "1" : "0");+ element.setAttribute(VIEW_FOLD_VALUE, foldValue);+ if (folded) {+ element.setAttribute("fold", "1");+ } else {+ element.removeAttribute("fold");+ }+ if (element.getAttribute("data-type") === "NodeHeading") {+ const token = getHeadingToken(protyle, element);+ setHeadingChildrenHidden(element, folded, token);+ if (previousFold !== foldValue) {+ headingRequestVersions.set(element, (headingRequestVersions.get(element) || 0) + 1);+ }+ }+};++export const markViewFoldDefault = (element: Element, folded: boolean) => {+ if (!element.hasAttribute(VIEW_FOLD_SOURCE)) {+ element.setAttribute(VIEW_FOLD_SOURCE, element.getAttribute("fold") === "1" ? "1" : "0");+ }+ element.setAttribute(VIEW_FOLD_DEFAULT, folded ? "1" : "0");+ element.setAttribute(VIEW_FOLD_VALUE, folded ? "1" : "0");+ element.toggleAttribute("fold", folded);+ if (folded) {+ element.setAttribute("fold", "1");+ }+};++export const hasViewFoldContext = (protyle: IProtyle) => viewFoldContexts.has(protyle);++export const registerViewFoldContext = (protyle: IProtyle, context: IViewFoldContext) => {+ viewFoldContexts.set(protyle, {+ ...context,+ generation: (viewFoldContexts.get(protyle)?.generation || 0) + 1,+ defaults: new Map<string, boolean>(),+ transient: new Map<string, boolean>(),+ });+ return applyViewFoldStates(protyle);+};++export const clearViewFoldDefaults = (protyle: IProtyle, occurrenceID: string) => {+ const context = viewFoldContexts.get(protyle);+ if (!context || !occurrenceID) {+ return;+ }+ clearViewFoldDefaultsForOccurrence(context, {+ pane: context.pane,+ rootID: context.rootID,+ occurrenceID,+ });+};++export const clearViewFoldOccurrenceState = (protyle: IProtyle, occurrenceID: string) => {+ const context = viewFoldContexts.get(protyle);+ if (!context || !occurrenceID) {+ return;+ }+ clearViewFoldOccurrenceRuntimeState(context, {+ pane: context.pane,+ rootID: context.rootID,+ occurrenceID,+ });+};++export const invalidateViewFoldRequests = (protyle: IProtyle) => {+ const context = viewFoldContexts.get(protyle);+ if (context) {+ context.generation = (context.generation || 0) + 1;+ }+};++export const unregisterViewFoldContext = (protyle: IProtyle) => {+ viewFoldContexts.delete(protyle);+};++export const setViewFoldState = (protyle: IProtyle, occurrenceID: string, blockID: string, folded: boolean) => {+ const context = viewFoldContexts.get(protyle);+ if (!context) {+ return false;+ }+ const stateKey = getViewFoldStateKeyByIdentity(context, occurrenceID, blockID);+ if (!stateKey) {+ return false;+ }+ context.store.set(stateKey, folded);+ context.transient?.delete(stateKey);+ return true;+};++export const setViewFold = (protyle: IProtyle, element: Element, folded: boolean, sourceFold?: boolean) => {+ const stateKey = getViewFoldStateKey(protyle, element);+ if (!stateKey || !setViewFoldState(protyle, getViewFoldOccurrenceID(protyle, element),+ element.getAttribute("data-node-id"), folded)) {+ return false;+ }+ applyFold(protyle, element, folded, sourceFold);+ if (!folded && element.getAttribute("data-type") === "NodeHeading") {+ void ensureHeadingChildren(protyle, element, stateKey, true).catch(error => console.error(error));+ }+ return true;+};++export const setViewFoldTransient = async (protyle: IProtyle, element: Element, folded: boolean,+ sourceFold?: boolean, loadHeadingChildren = true) => {+ const stateKey = getViewFoldStateKey(protyle, element);+ if (!viewFoldContexts.has(protyle) || !stateKey) {+ return;+ }+ viewFoldContexts.get(protyle)?.transient?.set(stateKey, folded);+ applyFold(protyle, element, folded, sourceFold);+ if (loadHeadingChildren && !folded && element.getAttribute("data-type") === "NodeHeading") {+ await ensureHeadingChildren(protyle, element, stateKey, true);+ }+};++export const applyViewFoldStates = async (protyle: IProtyle, scope?: ParentNode) => {+ const context = viewFoldContexts.get(protyle);+ if (!context) {+ return;+ }+ const root = scope || protyle.wysiwyg.element;+ const elements: Element[] = [];+ if (root instanceof Element && root.hasAttribute("data-node-id")) {+ elements.push(root);+ }+ root.querySelectorAll("[data-node-id][data-type]").forEach(element => elements.push(element));+ const headings: Promise<void>[] = [];+ elements.forEach(element => {+ const stateKey = getViewFoldStateKey(protyle, element);+ if (!stateKey) {+ return;+ }+ const transient = context.transient?.get(stateKey);+ const override = context.store.get<boolean>(stateKey);+ const defaultAttribute = element.getAttribute(VIEW_FOLD_DEFAULT);+ if (defaultAttribute !== null) {+ context.defaults?.set(stateKey, defaultAttribute === "1");+ }+ const defaultFold = defaultAttribute === null ? context.defaults?.get(stateKey) : defaultAttribute === "1";+ if (typeof transient !== "boolean" && typeof override !== "boolean" && typeof defaultFold !== "boolean") {+ return;+ }+ const folded = typeof transient === "boolean" ? transient :+ (typeof override === "boolean" ? override : defaultFold);+ applyFold(protyle, element, folded);+ if (!folded && element.getAttribute("data-type") === "NodeHeading") {+ headings.push(ensureHeadingChildren(protyle, element, stateKey, true));+ }+ });+ await Promise.all(headings);+};++const restoreViewFoldElement = (element: Element) => {+ const source = element.getAttribute(VIEW_FOLD_SOURCE);+ if (source !== null) {+ if (source === "1") {+ element.setAttribute("fold", "1");+ } else {+ element.removeAttribute("fold");+ }+ }+ const hiddenSource = element.getAttribute(VIEW_FOLD_HIDDEN_SOURCE);+ if (hiddenSource !== null) {+ element.classList.toggle("fn__none", hiddenSource === "1");+ }+ [VIEW_FOLD_SOURCE, VIEW_FOLD_VALUE, VIEW_FOLD_DEFAULT, VIEW_FOLD_HIDDEN,+ VIEW_FOLD_HIDDEN_SOURCE, VIEW_HEADING_OWNER, VIEW_HEADING_LOADED].forEach(attribute => element.removeAttribute(attribute));+};++export const sanitizeViewFoldHTML = (html: string) => {+ if (!html || !html.includes("data-view-")) {+ return html;+ }+ const template = document.createElement("template");+ template.innerHTML = html;+ template.content.querySelectorAll(`[${VIEW_FOLD_SOURCE}], [${VIEW_FOLD_HIDDEN_SOURCE}], [${VIEW_FOLD_DEFAULT}], ` ++ `[${VIEW_HEADING_OWNER}], [${VIEW_HEADING_LOADED}]`).forEach(restoreViewFoldElement);+ return template.innerHTML;+};++const stripFoldAttribute = (operation: IOperation) => {+ if (operation.action === "setAttrs" && typeof operation.data === "string") {+ try {+ const attrs = JSON.parse(operation.data);+ if (!Object.prototype.hasOwnProperty.call(attrs, "fold")) {+ return operation;+ }+ delete attrs.fold;+ if (Object.keys(attrs).length === 0) {+ return undefined;+ }+ return {...operation, data: JSON.stringify(attrs)};+ } catch (error) {+ console.error(error);+ return operation;+ }+ }+ if (operation.action === "updateAttrs" && typeof operation.data === "object" && operation.data !== null) {+ const data = operation.data as {+ old?: Record<string, string>,+ new?: Record<string, string>,+ [key: string]: unknown,+ };+ const oldAttrs = {...data.old};+ const newAttrs = {...data.new};+ if (!Object.prototype.hasOwnProperty.call(oldAttrs, "fold") &&+ !Object.prototype.hasOwnProperty.call(newAttrs, "fold")) {+ return operation;+ }+ delete oldAttrs.fold;+ delete newAttrs.fold;+ const otherKeys = Object.keys(data).filter(key => key !== "old" && key !== "new");+ if (Object.keys(oldAttrs).length === 0 && Object.keys(newAttrs).length === 0 && otherKeys.length === 0) {+ return undefined;+ }+ return {...operation, data: {...data, old: oldAttrs, new: newAttrs}};+ }+ return operation;+};++const sanitizeOperations = (operations: IOperation[] = []) => operations.flatMap(operation => {+ if (operation.action === "foldHeading" || operation.action === "unfoldHeading") {+ return [];+ }+ const stripped = stripFoldAttribute(operation);+ if (!stripped) {+ return [];+ }+ if (["update", "insert", "append"].includes(stripped.action) && typeof stripped.data === "string") {+ return [{...stripped, data: sanitizeViewFoldHTML(stripped.data)}];+ }+ return [stripped];+});++const sanitizeOperationHTML = (operations: IOperation[] = []) => operations.map(operation => {+ if (["update", "insert", "append"].includes(operation.action) && typeof operation.data === "string") {+ return {...operation, data: sanitizeViewFoldHTML(operation.data)};+ }+ return operation;+});++const getFoldValue = (operation: IOperation) => {+ if (operation.action === "foldHeading") {+ return true;+ }+ if (operation.action === "unfoldHeading") {+ return false;+ }+ if (operation.action === "setAttrs" && typeof operation.data === "string") {+ try {+ const attrs = JSON.parse(operation.data);+ return Object.prototype.hasOwnProperty.call(attrs, "fold") ? attrs.fold === "1" : undefined;+ } catch (error) {+ console.error(error);+ }+ }+ if (operation.action === "updateAttrs" && typeof operation.data === "object" && operation.data !== null) {+ const data = operation.data as {old?: Record<string, string>, new?: Record<string, string>};+ if (Object.prototype.hasOwnProperty.call(data.old || {}, "fold") ||+ Object.prototype.hasOwnProperty.call(data.new || {}, "fold")) {+ return data.new?.fold === "1";+ }+ }+ return undefined;+};++export const prepareViewFoldTransaction = (protyle: IProtyle, doOperations: IOperation[], undoOperations?: IOperation[]) => {+ if (!hasViewFoldContext(protyle)) {+ return {+ doOperations: sanitizeOperationHTML(doOperations),+ undoOperations: undoOperations ? sanitizeOperationHTML(undoOperations) : undefined,+ };+ }+ return {+ doOperations: sanitizeOperations(doOperations),+ undoOperations: undoOperations ? sanitizeOperations(undoOperations) : undefined,+ };+};++export const handleViewFoldSourceOperation = (protyle: IProtyle, operation: IOperation) => {+ if (!hasViewFoldContext(protyle) || !operation.id) {+ return false;+ }+ const sourceFold = getFoldValue(operation);+ if (typeof sourceFold !== "boolean") {+ return false;+ }+ protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach(element => {+ const stateKey = getViewFoldStateKey(protyle, element);+ const context = viewFoldContexts.get(protyle);+ const transient = stateKey ? context?.transient?.get(stateKey) : undefined;+ const override = stateKey ? context?.store.get<boolean>(stateKey) : undefined;+ const defaultAttribute = element.getAttribute(VIEW_FOLD_DEFAULT);+ if (defaultAttribute !== null && stateKey) {+ context?.defaults?.set(stateKey, defaultAttribute === "1");+ }+ const defaultFold = defaultAttribute === null && stateKey ? context?.defaults?.get(stateKey) :+ defaultAttribute === "1";+ const effective = typeof transient === "boolean" ? transient :+ (typeof override === "boolean" ? override :+ (typeof defaultFold === "boolean" ? defaultFold : sourceFold));+ applyFold(protyle, element, effective, sourceFold);+ if (!effective && element.getAttribute("data-type") === "NodeHeading") {+ const key = getViewFoldStateKey(protyle, element);+ if (key) {+ void ensureHeadingChildren(protyle, element, key, true);+ }+ }+ });+ const stripped = stripFoldAttribute(operation);+ if (stripped) {+ operation.data = stripped.data;+ return operation.action === "foldHeading" || operation.action === "unfoldHeading";+ }+ return true;+};diff --git a/app/src/protyle/util/viewFoldRuntimeState.test.ts b/app/src/protyle/util/viewFoldRuntimeState.test.tsnew file mode 100644index 0000000000..68c79be157--- /dev/null+++ b/app/src/protyle/util/viewFoldRuntimeState.test.ts@@ -0,0 +1,52 @@+import * as assert from "node:assert/strict";+import {test} from "node:test";+import {+ clearViewFoldDefaultsForOccurrence,+ clearViewFoldOccurrenceRuntimeState,+} from "./viewFoldRuntimeState";++const getStateKey = (pane: string, rootID: string, occurrenceID: string, blockID: string) => [+ "fold",+ encodeURIComponent(pane),+ encodeURIComponent(rootID),+ encodeURIComponent(occurrenceID),+ encodeURIComponent(blockID),+].join(":");++const identity = {+ pane: "backlink pane",+ rootID: "root/id",+ occurrenceID: "occurrence:id",+};++test("clearing occurrence defaults preserves transient state", () => {+ const targetKey = getStateKey(identity.pane, identity.rootID, identity.occurrenceID, "block-a");+ const siblingKey = getStateKey(identity.pane, identity.rootID, "occurrence:id-child", "block-b");+ const state = {+ defaults: new Map([[targetKey, true], [siblingKey, false]]),+ transient: new Map([[targetKey, false], [siblingKey, true]]),+ };++ clearViewFoldDefaultsForOccurrence(state, identity);++ assert.equal(state.defaults.has(targetKey), false);+ assert.equal(state.defaults.get(siblingKey), false);+ assert.equal(state.transient.get(targetKey), false);+ assert.equal(state.transient.get(siblingKey), true);+});++test("removing an occurrence clears its default and transient state", () => {+ const targetKey = getStateKey(identity.pane, identity.rootID, identity.occurrenceID, "block-a");+ const siblingKey = getStateKey(identity.pane, identity.rootID, "other-occurrence", "block-b");+ const state = {+ defaults: new Map([[targetKey, true], [siblingKey, false]]),+ transient: new Map([[targetKey, false], [siblingKey, true]]),+ };++ clearViewFoldOccurrenceRuntimeState(state, identity);++ assert.equal(state.defaults.has(targetKey), false);+ assert.equal(state.transient.has(targetKey), false);+ assert.equal(state.defaults.get(siblingKey), false);+ assert.equal(state.transient.get(siblingKey), true);+});diff --git a/app/src/protyle/util/viewFoldRuntimeState.ts b/app/src/protyle/util/viewFoldRuntimeState.tsnew file mode 100644index 0000000000..2d3a48a5c6--- /dev/null+++ b/app/src/protyle/util/viewFoldRuntimeState.ts@@ -0,0 +1,42 @@+export interface IViewFoldRuntimeState {+ defaults?: Map<string, boolean>,+ transient?: Map<string, boolean>,+}++export interface IViewFoldOccurrenceIdentity {+ pane: string,+ rootID: string,+ occurrenceID: string,+}++const getOccurrencePrefix = (identity: IViewFoldOccurrenceIdentity) => [+ "fold",+ encodeURIComponent(identity.pane || ""),+ encodeURIComponent(identity.rootID || ""),+ encodeURIComponent(identity.occurrenceID || ""),+ "",+].join(":");++const clearEntries = (states: Map<string, boolean> | undefined, prefix: string) => {+ states?.forEach((_value, key) => {+ if (key.startsWith(prefix)) {+ states.delete(key);+ }+ });+};++export const clearViewFoldDefaultsForOccurrence = (+ state: IViewFoldRuntimeState,+ identity: IViewFoldOccurrenceIdentity,+) => {+ clearEntries(state.defaults, getOccurrencePrefix(identity));+};++export const clearViewFoldOccurrenceRuntimeState = (+ state: IViewFoldRuntimeState,+ identity: IViewFoldOccurrenceIdentity,+) => {+ const prefix = getOccurrencePrefix(identity);+ clearEntries(state.defaults, prefix);+ clearEntries(state.transient, prefix);+};diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.tsindex bcc4e5b17d..3b0f021186 100644--- a/app/src/protyle/wysiwyg/index.ts+++ b/app/src/protyle/wysiwyg/index.ts@@ -153,6 +153,7 @@ import {escapeAttr, escapeHtml} from "../../util/escape";import {openLink} from "../../editor/openLink";import {mathRender} from "../render/mathRender";import {editAssetItem} from "../render/av/asset";+import {hasViewFoldContext, sanitizeViewFoldHTML, setViewFold} from "../util/viewFold";import {img3115} from "../../boot/compatibleVersion";import {dragOverScroll, stopScrollAnimation} from "../../boot/globalEvent/dragover";import {globalClickHideMenu} from "../../boot/globalEvent/click";@@ -671,14 +672,15 @@ export class WYSIWYG {}));const textPlain = clipboardData.getData("text/plain");const parsedHTML = getTextSiyuanFromTextHTML(clipboardData.getData("text/html"));- const textSiyuan = clipboardData.getData("text/siyuan") || parsedHTML.textSiyuan;+ const textHTML = sanitizeViewFoldHTML(parsedHTML.textHtml);+ const textSiyuan = sanitizeViewFoldHTML(clipboardData.getData("text/siyuan") || parsedHTML.textSiyuan);if (!textPlain && !parsedHTML.textHtml) {showMessage(window.siyuan.languages.clipboardPermissionDenied, 7000, "error");return false;}const result = await writeClipboardData({textPlain,- textHTML: parsedHTML.textHtml,+ textHTML,textSiyuan,}, {fallbackToPlainText: false});if (result.status === "failed") {@@ -900,7 +902,9 @@ export class WYSIWYG {textPlain = textWithoutAttr;}// https://github.com/siyuan-note/siyuan/issues/13232- headingElement.removeAttribute("fold");+ if (!hasViewFoldContext(protyle)) {+ headingElement.removeAttribute("fold");+ }} else if (!["DIV", "TD", "TH", "TR"].includes(range.startContainer.parentElement.tagName)) {// 复制行内元素 https://github.com/siyuan-note/insider/issues/191tempElement.append(range.startContainer.parentElement.cloneNode(true));@@ -989,6 +993,7 @@ export class WYSIWYG {}}}+ html = sanitizeViewFoldHTML(html);if (protyle.disabled) {html = getEnableHTML(html);}@@ -3326,6 +3331,7 @@ export class WYSIWYG {}if (!isInCodeBlock) {+ html = sanitizeViewFoldHTML(html);enableLuteMarkdownSyntax(protyle);const blockDOMClipboardRichData = useBlockDOMClipboardRichData ?buildBlockDOMClipboardRichData(protyle.lute, html) : undefined;@@ -4633,7 +4639,7 @@ export class WYSIWYG {setFold(protyle, actionElement.parentElement);} else {let hasFold = true;- const oldHTML = actionElement.parentElement.parentElement.outerHTML;+ const listElement = actionElement.parentElement.parentElement;Array.from(actionElement.parentElement.parentElement.children).find((listItemElement) => {if (listItemElement.classList.contains("li")) {if (listItemElement.getAttribute("fold") !== "1" && listItemElement.childElementCount > 3) {@@ -4642,6 +4648,18 @@ export class WYSIWYG {}}});+ if (hasViewFoldContext(protyle)) {+ Array.from(listElement.children).forEach(listItemElement => {+ if (listItemElement.classList.contains("li") &&+ (hasFold || listItemElement.childElementCount > 3)) {+ setViewFold(protyle, listItemElement, !hasFold);+ }+ });+ hideElements(["gutter"], protyle);+ event.stopPropagation();+ return;+ }+ const oldHTML = listElement.outerHTML;Array.from(actionElement.parentElement.parentElement.children).find((listItemElement) => {if (listItemElement.classList.contains("li")) {if (hasFold) {@@ -4651,7 +4669,7 @@ export class WYSIWYG {}}});- updateTransaction(protyle, actionElement.parentElement.parentElement, oldHTML);+ updateTransaction(protyle, listElement, oldHTML);}hideElements(["gutter"], protyle);} else if (shouldOpenListItemAttr(event.shiftKey, protyle.disabled, actionElement)) {diff --git a/app/src/protyle/wysiwyg/input.ts b/app/src/protyle/wysiwyg/input.tsindex ea1fa3f874..a43f61711b 100644--- a/app/src/protyle/wysiwyg/input.ts+++ b/app/src/protyle/wysiwyg/input.ts@@ -374,7 +374,7 @@ export const input = async (protyle: IProtyle, blockElement: HTMLElement, range:) {if (blockElement.getAttribute("data-type") === "NodeHeading" && blockElement.getAttribute("fold") === "1" &&tempElement.content.firstElementChild.getAttribute("data-subtype") !== blockElement.dataset.subtype) {- setFold(protyle, blockElement, undefined, undefined, false);+ setFold(protyle, blockElement, undefined, undefined, false, false, false);html = html.replace(' fold="1"', "");protyle.wysiwyg.lastHTMLs[id] = blockElement.outerHTML;}diff --git a/app/src/protyle/wysiwyg/list.ts b/app/src/protyle/wysiwyg/list.tsindex b6ee801059..6850d88b68 100644--- a/app/src/protyle/wysiwyg/list.ts+++ b/app/src/protyle/wysiwyg/list.ts@@ -41,7 +41,7 @@ const getLastChildBlock = (element: Element) => {const unfoldElements = (protyle: IProtyle, elements: Element[]) => {elements.forEach(item => {if (item.getAttribute("fold") === "1") {- setFold(protyle, item, true);+ setFold(protyle, item, true, false, false, false, false);}});};diff --git a/app/src/protyle/wysiwyg/remove.ts b/app/src/protyle/wysiwyg/remove.tsindex f22780bd94..8b302e8ff6 100644--- a/app/src/protyle/wysiwyg/remove.ts+++ b/app/src/protyle/wysiwyg/remove.ts@@ -1184,11 +1184,11 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rangconst previousBlockElement = getPreviousBlockSibling(blockElement);if (previousBlockElement?.getAttribute("data-type") === "NodeHeading" &&previousBlockElement.getAttribute("fold") === "1") {- setFold(protyle, previousBlockElement, true, false, false);+ setFold(protyle, previousBlockElement, true, false, false, false, false);}if (blockType === "NodeHeading" &&blockElement.getAttribute("fold") === "1") {- setFold(protyle, blockElement, true, false, false);+ setFold(protyle, blockElement, true, false, false, false, false);}turnsIntoTransaction({protyle: protyle,diff --git a/app/src/protyle/wysiwyg/renderBacklink.ts b/app/src/protyle/wysiwyg/renderBacklink.tsindex da59075423..caeaebe9e7 100644--- a/app/src/protyle/wysiwyg/renderBacklink.ts+++ b/app/src/protyle/wysiwyg/renderBacklink.ts@@ -10,6 +10,12 @@ import {avRender} from "../render/av/render";import {hasClosestByAttribute} from "../util/hasClosest";import {isEncryptedBox} from "../../util/pathName";import {decodeHTML, escapeAttr, escapeHtml, escapeSearchHighlight} from "../../util/escape";+import {+ applyViewFoldStates,+ clearViewFoldDefaults,+ clearViewFoldOccurrenceState,+ markViewFoldDefault,+} from "../util/viewFold";interface IBacklinkData {id?: string,@@ -48,6 +54,7 @@ const createBacklinkDOMRecord = (item: IBacklinkData, index: number, id: string)const template = document.createElement("template");template.innerHTML = genBreadcrumb(item.blockPaths, false, index, id) + setBacklinkFold(item.dom, item.expand);const nodes = Array.from(template.content.childNodes);+ (nodes[0] as HTMLElement).setAttribute("data-backlink-revision", item.revision || "");return {record: {revision: item.revision || "",@@ -83,6 +90,7 @@ export const renderBacklink = (protyle: IProtyle, backlinkData: IBacklinkData[])const ids = new Set(backlinkData.map((item, index) => item.id || `legacy-${index}`));records.forEach((record, id) => {if (!ids.has(id)) {+ clearViewFoldOccurrenceState(protyle, id);removeBacklinkDOMRecord(record);records.delete(id);}@@ -98,6 +106,7 @@ export const renderBacklink = (protyle: IProtyle, backlinkData: IBacklinkData[])record = undefined;}if (!record || !item.revision || record.revision !== item.revision) {+ clearViewFoldDefaults(protyle, id);const created = createBacklinkDOMRecord(item, index, id);if (record) {created.nodes.forEach(node => element.insertBefore(node, record.anchor));@@ -128,24 +137,41 @@ export const renderBacklink = (protyle: IProtyle, backlinkData: IBacklinkData[])}}});- changedNodes.forEach(nodes => renderBacklinkDOMNodes(protyle, nodes));+ const applyPromises: Promise<void>[] = [];+ changedNodes.forEach(nodes => {+ renderBacklinkDOMNodes(protyle, nodes);+ nodes.forEach(node => {+ if (node instanceof HTMLElement) {+ applyPromises.push(applyViewFoldStates(protyle, node));+ }+ });+ });removeLoading(protyle);if (window.siyuan.config.readonly || window.siyuan.config.editor.readOnly) {disabledProtyle(protyle);}+ return Promise.all(applyPromises).then(() => undefined);};// 传递型折叠处理-export const foldPassiveType = (expand: boolean, element: HTMLElement | DocumentFragment) => {+export const foldPassiveType = (expand: boolean, element: HTMLElement | DocumentFragment, viewOnly = false) => {if (element.firstElementChild.classList.contains("li")) {if (expand) {element.querySelectorAll(".li .li").forEach(item => {if (item.childElementCount > 3) {- item.setAttribute("fold", "1");+ if (viewOnly) {+ markViewFoldDefault(item, true);+ } else {+ item.setAttribute("fold", "1");+ }}});} else {- element.firstElementChild.setAttribute("fold", "1");+ if (viewOnly) {+ markViewFoldDefault(element.firstElementChild, true);+ } else {+ element.firstElementChild.setAttribute("fold", "1");+ }}} else if (element.firstElementChild.getAttribute("data-type") === "NodeHeading") {Array.from(element.children).forEach((item, index) => {@@ -162,7 +188,7 @@ export const foldPassiveType = (expand: boolean, element: HTMLElement | Documentconst setBacklinkFold = (html: string, expand: boolean) => {const tempDom = document.createElement("template");tempDom.innerHTML = html;- foldPassiveType(expand, tempDom.content);+ foldPassiveType(expand, tempDom.content, true);return tempDom.innerHTML;};@@ -184,9 +210,11 @@ export const loadBreadcrumb = (protyle: IProtyle, element: HTMLElement) => {tempElement.remove();}element.parentElement.insertAdjacentHTML("afterend", setBacklinkFold(getResponse.data.content, true));+ clearViewFoldDefaults(protyle, element.parentElement.getAttribute("data-backlink-id"));processRender(element.parentElement.parentElement);avRender(element.parentElement.parentElement, protyle);blockRender(protyle, element.parentElement.parentElement);+ void applyViewFoldStates(protyle);if (getResponse.data.isSyncing) {disabledForeverProtyle(protyle);} else if (window.siyuan.config.readonly || window.siyuan.config.editor.readOnly) {diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex cd12317e9d..40f4b475a4 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -50,6 +50,14 @@ import {getPartialUpdateCleanupElements, shouldDeferCodeBlockCaretRestore} fromimport {getMoveAffectedEmbedElements, shouldSyncMoveCopies} from "./transactionEmbed";import {cloneMoveElements, getVisibleMoveElements} from "./transactionMove";import {normalizeHTMLAssetIFrameBlockDOM} from "../../asset/html";+import {+ applyViewFoldStates,+ handleViewFoldSourceOperation,+ hasViewFoldContext,+ invalidateViewFoldRequests,+ prepareViewFoldTransaction,+ setViewFoldTransient,+} from "../util/viewFold";const removeTopElement = (updateElement: Element, protyle: IProtyle) => {// 移动到其他文档中,该块需移除@@ -478,6 +486,7 @@ const promiseTransaction = (options: {undoOperations: options.undoOperations,// 目前用于 ws 推送更新大纲}]}, (response) => {+ invalidateViewFoldRequests(protyle);const ids: string[] = [];protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select").forEach(item => {ids.push(item.getAttribute("data-node-id"));@@ -485,6 +494,9 @@ const promiseTransaction = (options: {countBlockWord(ids, protyle.block.rootID, true);if (!options.skipSync) {response.data[0].doOperations.forEach((operation: IOperation) => {+ if (handleViewFoldSourceOperation(protyle, operation)) {+ return;+ }if (operation.action === "unfoldHeading" || operation.action === "foldHeading") {processFold(operation, protyle);return;@@ -509,6 +521,7 @@ const promiseTransaction = (options: {}});queueHeadingNumberRefresh(protyle, response.data[0].doOperations);+ void applyViewFoldStates(protyle);options.callback?.();}));};@@ -659,6 +672,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUndif (protyle.wysiwyg.element.firstElementChild?.classList.contains("protyle-password")) {return;}+ invalidateViewFoldRequests(protyle);const undoFocusContext = isUndo ? operations.find(item => item.context?.undoFocusId)?.context : undefined;const undoFocusEmbedElement = undoFocusContext?.undoFocusEmbedId ? protyle.wysiwyg.element.querySelector(`[data-type="NodeBlockQueryEmbed"][data-node-id="${undoFocusContext.undoFocusEmbedId}"]`@@ -666,6 +680,9 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUndconst deferUndoFocus = !!undoFocusContext?.undoFocusEmbedId;const pendingUndoEmbedElements = new Set<Element>();operations.forEach(operation => {+ if (handleViewFoldSourceOperation(protyle, operation)) {+ return;+ }const updateElements: Element[] = [];Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)).forEach(item => {updateElements.push(item);@@ -1284,6 +1301,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUndreturn;}});+ void applyViewFoldStates(protyle);pendingUndoEmbedElements.forEach(item => {if (!item.isConnected) {return;@@ -1817,6 +1835,14 @@ const unfoldListHeadings = async (protyle: IProtyle, nodeElements: Element[]) =>}const itemId = foldedHeading.getAttribute("data-node-id");unfoldedIds.add(itemId);+ if (hasViewFoldContext(protyle)) {+ await setViewFoldTransient(protyle, foldedHeading, false);+ foldOperations.push({+ action: "foldHeading",+ id: itemId,+ });+ continue;+ }foldedHeading.removeAttribute("fold");const response = await fetchSyncPost("/api/transactions", {session: protyle.id,@@ -1948,18 +1974,24 @@ export const turnListsRecursively = async (options: {const undoFoldOperations = foldOperations.map((operation) => ({...operation}));if (doOperations.length === 0) {if (doFoldOperations.length > 0) {- await fetchSyncPost("/api/transactions", {- session: options.protyle.id,- app: Constants.SIYUAN_APPID,- transactions: [{- doOperations: doFoldOperations- }]- });+ if (hasViewFoldContext(options.protyle)) {+ transaction(options.protyle, doFoldOperations, undoFoldOperations);+ } else {+ await fetchSyncPost("/api/transactions", {+ session: options.protyle.id,+ app: Constants.SIYUAN_APPID,+ transactions: [{+ doOperations: doFoldOperations+ }]+ });+ }}} else {transaction(options.protyle, doOperations.concat(doFoldOperations), undoOperations.concat(undoFoldOperations));}- onTransaction(options.protyle, doFoldOperations, false);+ if (!hasViewFoldContext(options.protyle)) {+ onTransaction(options.protyle, doFoldOperations, false);+ }focusByWbr(options.protyle.wysiwyg.element, getEditorRange(options.protyle.wysiwyg.element));options.protyle.wysiwyg.element.querySelectorAll('[data-type~="block-ref"]').forEach(item => {if (item.textContent === "") {@@ -2081,7 +2113,13 @@ export const transaction = (protyle: IProtyle, doOperations: IOperation[], undoOskipSync?: boolean,callback?: () => void,}) => {+ if (protyle) {+ const prepared = prepareViewFoldTransaction(protyle, doOperations, undoOperations);+ doOperations = prepared.doOperations;+ undoOperations = prepared.undoOperations;+ }if (doOperations.length === 0) {+ options?.callback?.();return;}cleanHeadingNumberOperations(doOperations);diff --git a/app/src/util/viewState.test.ts b/app/src/util/viewState.test.tsnew file mode 100644index 0000000000..63832aeaa5--- /dev/null+++ b/app/src/util/viewState.test.ts@@ -0,0 +1,301 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {+ getViewStateKey,+ type IViewStateTransport,+ type TViewStateData,+ ViewStateService+} from "./viewState";++const deferred = <T>() => {+ let resolve: (value: T | PromiseLike<T>) => void;+ let reject: (reason?: unknown) => void;+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });+ return {promise, resolve: resolve!, reject: reject!};+};++const createTransport = (options?: {+ get?: (key: string) => Promise<TViewStateData>,+ patch?: (key: string, values: TViewStateData, removeKeys: string[]) => Promise<void>,+}): IViewStateTransport => ({+ get: options?.get || (async () => ({})),+ patch: options?.patch || (async () => undefined),+});++const identity = {+ scope: "backlink",+ surface: "bottom",+ hostID: "20260820000000-host",+};++describe("getViewStateKey", () => {+ it("builds an unambiguous stable key from the complete identity", () => {+ assert.equal(getViewStateKey(identity), "backlink:bottom:20260820000000-host");+ assert.equal(getViewStateKey({+ scope: "scope:one",+ surface: "surface/two",+ hostID: "host three",+ }), "scope%3Aone:surface%2Ftwo:host%20three");+ assert.notEqual(+ getViewStateKey({scope: "a:b", surface: "c", hostID: "d"}),+ getViewStateKey({scope: "a", surface: "b:c", hostID: "d"}),+ );+ });++ it("rejects incomplete identities", () => {+ assert.throws(() => getViewStateKey({...identity, scope: ""}));+ assert.throws(() => getViewStateKey({...identity, surface: ""}));+ assert.throws(() => getViewStateKey({...identity, hostID: ""}));+ });+});++describe("ViewStateService", () => {+ it("loads only its exact key and sends field-level changes including false", async () => {+ const getKeys: string[] = [];+ const patches: Array<{key: string, values: TViewStateData, removeKeys: string[]}> = [];+ const service = new ViewStateService(identity, {+ flushDelay: 60_000,+ transport: createTransport({+ async get(key) {+ getKeys.push(key);+ return {unchanged: "remote", folded: true};+ },+ async patch(key, values, removeKeys) {+ patches.push({key, values, removeKeys});+ },+ }),+ });++ await service.ready;+ assert.deepEqual(getKeys, [service.key]);+ assert.equal(service.get<boolean>("folded"), true);+ service.set("folded", false);+ await service.flush();++ assert.equal(service.has("folded"), true);+ assert.equal(service.get<boolean>("folded"), false);+ assert.deepEqual(patches, [{+ key: service.key,+ values: {folded: false},+ removeKeys: [],+ }]);+ await service.destroy();+ });++ it("preserves local sets and removals made while loading", async () => {+ const loading = deferred<TViewStateData>();+ const patches: Array<{values: TViewStateData, removeKeys: string[]}> = [];+ const service = new ViewStateService(identity, {+ flushDelay: 60_000,+ transport: createTransport({+ get: async () => loading.promise,+ async patch(_key, values, removeKeys) {+ patches.push({values, removeKeys});+ },+ }),+ });++ service.set("folded", false);+ service.remove("removed");+ loading.resolve({folded: true, removed: "remote", untouched: 42});+ await service.ready;++ assert.equal(service.get<boolean>("folded"), false);+ assert.equal(service.has("removed"), false);+ assert.equal(service.get<number>("untouched"), 42);+ await service.flush();+ assert.deepEqual(patches, [{+ values: {folded: false},+ removeKeys: ["removed"],+ }]);+ await service.destroy();+ });++ it("serializes flushes and carries changes made during an active request", async () => {+ const firstStarted = deferred<void>();+ const firstRelease = deferred<void>();+ const calls: TViewStateData[] = [];+ let active = 0;+ let maxActive = 0;+ const service = new ViewStateService(identity, {+ flushDelay: 60_000,+ transport: createTransport({+ async patch(_key, values) {+ active++;+ maxActive = Math.max(maxActive, active);+ calls.push(values);+ if (calls.length === 1) {+ firstStarted.resolve();+ await firstRelease.promise;+ }+ active--;+ },+ }),+ });+ await service.ready;++ service.set("first", 1);+ const firstFlush = service.flush();+ await firstStarted.promise;+ service.set("second", 2);+ const secondFlush = service.flush();+ await Promise.resolve();+ assert.equal(calls.length, 1);+ firstRelease.resolve();+ await Promise.all([firstFlush, secondFlush]);++ assert.equal(maxActive, 1);+ assert.deepEqual(calls, [{first: 1}, {second: 2}]);+ await service.destroy();+ });++ it("debounces adjacent changes into one patch", async () => {+ const patched = deferred<void>();+ const calls: TViewStateData[] = [];+ const service = new ViewStateService(identity, {+ flushDelay: 10,+ transport: createTransport({+ async patch(_key, values) {+ calls.push(values);+ patched.resolve();+ },+ }),+ });+ await service.ready;++ service.set("first", 1);+ service.set("first", 2);+ service.set("second", false);+ await patched.promise;++ assert.deepEqual(calls, [{first: 2, second: false}]);+ await service.destroy();+ });++ it("requeues a failed patch without overwriting newer changes", async () => {+ const firstStarted = deferred<void>();+ const firstRelease = deferred<void>();+ const calls: TViewStateData[] = [];+ let failFirst = true;+ const service = new ViewStateService(identity, {+ flushDelay: 60_000,+ transport: createTransport({+ async patch(_key, values) {+ calls.push(values);+ if (failFirst) {+ failFirst = false;+ firstStarted.resolve();+ await firstRelease.promise;+ throw new Error("temporary failure");+ }+ },+ }),+ });+ await service.ready;++ service.set("value", 1);+ const failedFlush = service.flush();+ await firstStarted.promise;+ service.set("value", 2);+ firstRelease.resolve();+ await assert.rejects(failedFlush);+ await service.flush();++ assert.deepEqual(calls, [{value: 1}, {value: 2}]);+ await service.destroy();+ });++ it("waits for loading and flushes pending changes on destroy", async () => {+ const loading = deferred<TViewStateData>();+ const patches: TViewStateData[] = [];+ const service = new ViewStateService(identity, {+ flushDelay: 60_000,+ transport: createTransport({+ get: async () => loading.promise,+ async patch(_key, values) {+ patches.push(values);+ },+ }),+ });++ service.set("expanded", false);+ const destroying = service.destroy();+ await Promise.resolve();+ assert.deepEqual(patches, []);+ loading.resolve({expanded: true});+ await destroying;++ assert.deepEqual(patches, [{expanded: false}]);+ assert.throws(() => service.set("expanded", true));+ });++ it("continues with in-memory state when the initial read fails", async () => {+ const patches: TViewStateData[] = [];+ const originalConsoleError = console.error;+ console.error = () => undefined;+ const service = new ViewStateService(identity, {+ flushDelay: 60_000,+ transport: createTransport({+ get: async () => Promise.reject(new Error("unavailable")),+ async patch(_key, values) {+ patches.push(values);+ },+ }),+ });+ try {+ await service.ready;+ service.set("expanded", false);+ await service.flush();+ assert.deepEqual(patches, [{expanded: false}]);+ await service.destroy();+ } finally {+ console.error = originalConsoleError;+ }+ });++ it("splits large pending changes by the kernel patch limits", async () => {+ const patches: Array<{values: TViewStateData, removeKeys: string[]}> = [];+ const service = new ViewStateService(identity, {+ flushDelay: 60_000,+ transport: createTransport({+ async patch(_key, values, removeKeys) {+ patches.push({values, removeKeys});+ },+ }),+ });+ await service.ready;++ for (let index = 0; index < 1001; index++) {+ service.set(`field-${index}`, index);+ }+ await service.flush();++ assert.equal(patches.length, 2);+ assert.equal(Object.keys(patches[0].values).length, 1000);+ assert.equal(Object.keys(patches[1].values).length, 1);+ await service.destroy();+ });++ it("splits values by serialized byte size and rejects a single oversized value", async () => {+ const patches: TViewStateData[] = [];+ const service = new ViewStateService(identity, {+ flushDelay: 60_000,+ transport: createTransport({+ async patch(_key, values) {+ patches.push(values);+ },+ }),+ });+ await service.ready;++ service.set("first", "a".repeat(140 * 1024));+ service.set("second", "b".repeat(140 * 1024));+ await service.flush();+ assert.equal(patches.length, 2);+ assert.throws(() => service.set("oversized", "c".repeat(300 * 1024)));+ await service.destroy();+ });+});diff --git a/app/src/util/viewState.ts b/app/src/util/viewState.tsnew file mode 100644index 0000000000..98cb7248cb--- /dev/null+++ b/app/src/util/viewState.ts@@ -0,0 +1,263 @@+export type TViewStateValue = string | number | boolean | null | TViewStateValue[] | {+ [key: string]: TViewStateValue,+};++export type TViewStateData = Record<string, TViewStateValue>;++export interface IViewStateIdentity {+ scope: string,+ surface: string,+ hostID: string,+}++export interface IViewStateTransport {+ get(key: string): Promise<TViewStateData>,+ patch(key: string, values: TViewStateData, removeKeys: string[]): Promise<void>,+}++export interface IViewStateServiceOptions {+ flushDelay?: number,+ transport?: IViewStateTransport,+}++const DEFAULT_FLUSH_DELAY = 400;+const MAX_PATCH_ENTRIES = 1000;+const MAX_PATCH_BYTES = 256 * 1024;++const getPatchByteLength = (values: TViewStateData, removeKeys: string[]) => {+ const json = JSON.stringify({values, removeKeys});+ if (typeof json !== "string") {+ throw new Error("Invalid view state patch");+ }+ const goCompatibleJSON = json.replace(/[<>&\u2028\u2029]/g, character => {+ return `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`;+ });+ return new TextEncoder().encode(goCompatibleJSON).byteLength;+};++const isViewStateData = (value: unknown): value is TViewStateData => {+ return typeof value === "object" && value !== null && !Array.isArray(value);+};++const checkResponse = (response: IWebSocketData, action: string) => {+ if (!response || response.code !== 0) {+ throw new Error(response?.msg || `Failed to ${action} view state`);+ }+};++const defaultTransport: IViewStateTransport = {+ async get(key) {+ const {fetchSyncPost} = await import("./fetch");+ const response = await fetchSyncPost("/api/storage/getViewState", {key});+ checkResponse(response, "get");+ return isViewStateData(response.data) ? response.data : {};+ },+ async patch(key, values, removeKeys) {+ const {fetchSyncPost} = await import("./fetch");+ const response = await fetchSyncPost("/api/storage/patchViewState", {key, values, removeKeys});+ checkResponse(response, "patch");+ },+};++const validateIdentityPart = (name: string, value: string) => {+ if (!value) {+ throw new Error(`View state ${name} must not be empty`);+ }+};++const validateField = (field: string) => {+ if (!field || field.length > 2048) {+ throw new Error("Invalid view state field");+ }+};++export const getViewStateKey = (identity: IViewStateIdentity) => {+ validateIdentityPart("scope", identity.scope);+ validateIdentityPart("surface", identity.surface);+ validateIdentityPart("hostID", identity.hostID);+ const key = [identity.scope, identity.surface, identity.hostID].map(encodeURIComponent).join(":");+ if (key.length > 1024) {+ throw new Error("View state key is too long");+ }+ return key;+};++export class ViewStateService {+ public readonly key: string;+ public readonly ready: Promise<void>;+ private readonly data: TViewStateData = {};+ private readonly pendingValues = new Map<string, TViewStateValue>();+ private readonly pendingRemovals = new Set<string>();+ private readonly flushDelay: number;+ private readonly transport: IViewStateTransport;+ private flushTimer?: ReturnType<typeof setTimeout>;+ private flushChain: Promise<void> = Promise.resolve();+ private destroyed = false;+ private destroyPromise?: Promise<void>;++ constructor(identity: IViewStateIdentity, options: IViewStateServiceOptions = {}) {+ this.key = getViewStateKey(identity);+ this.flushDelay = options.flushDelay ?? DEFAULT_FLUSH_DELAY;+ this.transport = options.transport || defaultTransport;+ this.ready = this.load().catch(error => console.error(error));+ }++ public has(field: string) {+ validateField(field);+ return Object.prototype.hasOwnProperty.call(this.data, field);+ }++ public get<T = TViewStateValue>(field: string) {+ validateField(field);+ return this.data[field] as T | undefined;+ }++ public snapshot() {+ return {...this.data};+ }++ public set<T>(field: string, value: T) {+ this.ensureActive();+ validateField(field);+ const stateValue = value as TViewStateValue;+ this.validateValue(field, stateValue);+ this.data[field] = stateValue;+ this.pendingRemovals.delete(field);+ this.pendingValues.set(field, stateValue);+ this.scheduleFlush();+ }++ public patch(values: TViewStateData, removeKeys: string[] = []) {+ this.ensureActive();+ Object.entries(values).forEach(([field, value]) => {+ validateField(field);+ this.validateValue(field, value);+ });+ removeKeys.forEach(validateField);+ Object.entries(values).forEach(([field, value]) => {+ this.data[field] = value;+ this.pendingRemovals.delete(field);+ this.pendingValues.set(field, value);+ });+ removeKeys.forEach((field) => {+ delete this.data[field];+ this.pendingValues.delete(field);+ this.pendingRemovals.add(field);+ });+ if (Object.keys(values).length > 0 || removeKeys.length > 0) {+ this.scheduleFlush();+ }+ }++ public remove(field: string) {+ this.patch({}, [field]);+ }++ public flush() {+ this.clearFlushTimer();+ const result = this.flushChain.catch(() => undefined).then(async () => {+ await this.ready;+ while (this.pendingValues.size > 0 || this.pendingRemovals.size > 0) {+ await this.flushPending();+ }+ });+ this.flushChain = result.catch(() => undefined);+ return result;+ }++ public destroy() {+ if (this.destroyPromise) {+ return this.destroyPromise;+ }+ this.destroyed = true;+ this.destroyPromise = this.flush();+ return this.destroyPromise;+ }++ private async load() {+ const remoteData = await this.transport.get(this.key);+ Object.entries(remoteData).forEach(([field, value]) => {+ if (!this.pendingValues.has(field) && !this.pendingRemovals.has(field)) {+ this.data[field] = value;+ }+ });+ }++ private async flushPending() {+ const {values, removeKeys} = this.takePendingBatch();+ try {+ await this.transport.patch(this.key, values, removeKeys);+ } catch (error) {+ Object.entries(values).forEach(([field, value]) => {+ if (!this.pendingValues.has(field) && !this.pendingRemovals.has(field)) {+ this.pendingValues.set(field, value);+ }+ });+ removeKeys.forEach((field) => {+ if (!this.pendingValues.has(field) && !this.pendingRemovals.has(field)) {+ this.pendingRemovals.add(field);+ }+ });+ throw error;+ }+ }++ private takePendingBatch() {+ const values: TViewStateData = {};+ const removeKeys: string[] = [];+ let count = 0;+ for (const [field, value] of this.pendingValues) {+ const nextValues = {...values, [field]: value};+ if (count > 0 && (count >= MAX_PATCH_ENTRIES ||+ getPatchByteLength(nextValues, removeKeys) > MAX_PATCH_BYTES)) {+ break;+ }+ values[field] = value;+ this.pendingValues.delete(field);+ count++;+ }+ if (count < MAX_PATCH_ENTRIES && this.pendingValues.size === 0) {+ for (const field of this.pendingRemovals) {+ const nextRemoveKeys = [...removeKeys, field];+ if (count > 0 && (count >= MAX_PATCH_ENTRIES ||+ getPatchByteLength(values, nextRemoveKeys) > MAX_PATCH_BYTES)) {+ break;+ }+ removeKeys.push(field);+ this.pendingRemovals.delete(field);+ count++;+ }+ }+ if (count === 0) {+ throw new Error("View state patch cannot be split within the storage limits");+ }+ return {values, removeKeys};+ }++ private validateValue(field: string, value: TViewStateValue) {+ if (getPatchByteLength({[field]: value}, []) > MAX_PATCH_BYTES) {+ throw new Error("View state value is too large");+ }+ }++ private scheduleFlush() {+ this.clearFlushTimer();+ this.flushTimer = setTimeout(() => {+ this.flushTimer = undefined;+ this.flush().catch((error) => console.error(error));+ }, this.flushDelay);+ }++ private clearFlushTimer() {+ if (this.flushTimer !== undefined) {+ clearTimeout(this.flushTimer);+ this.flushTimer = undefined;+ }+ }++ private ensureActive() {+ if (this.destroyed) {+ throw new Error("View state service has been destroyed");+ }+ }+}diff --git a/kernel/api/router.go b/kernel/api/router.goindex f0e4271fa4..7f61e9de92 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -119,6 +119,9 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/storage/getOutlineStorage", model.CheckAuth, model.CheckAdminRole, getOutlineStorage)ginServer.Handle("POST", "/api/storage/setOutlineStorage", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setOutlineStorage)ginServer.Handle("POST", "/api/storage/removeOutlineStorage", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, removeOutlineStorage)+ ginServer.Handle("POST", "/api/storage/getViewState", model.CheckAuth, model.CheckAdminRole, getViewState)+ ginServer.Handle("POST", "/api/storage/patchViewState", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, patchViewState)+ ginServer.Handle("POST", "/api/storage/removeViewState", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, removeViewState)ginServer.Handle("POST", "/api/account/login", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, login)ginServer.Handle("POST", "/api/account/checkActivationcode", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, checkActivationcode)diff --git a/kernel/api/storage.go b/kernel/api/storage.goindex e24c288ec8..ad78c8723d 100644--- a/kernel/api/storage.go+++ b/kernel/api/storage.go@@ -18,6 +18,7 @@ package apiimport ("net/http"+ "strings""github.com/88250/gulu""github.com/gin-gonic/gin"@@ -533,3 +534,100 @@ func removeOutlineStorage(c *gin.Context) {return}}++func getViewState(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ arg, ok := util.JsonArg(c, ret)+ if !ok {+ return+ }++ var key string+ if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("key", &key, true, true)) {+ return+ }+ data, err := model.GetViewState(key)+ if err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ ret.Data = data+}++func patchViewState(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ arg, ok := util.JsonArg(c, ret)+ if !ok {+ return+ }++ var key string+ if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("key", &key, true, true)) {+ return+ }+ values := map[string]any{}+ if value, exists := arg["values"]; exists {+ var valid bool+ values, valid = value.(map[string]any)+ if !valid {+ ret.Code = -1+ ret.Msg = "Field [values]: should be of type [Object]"+ return+ }+ }+ removeKeys, valid := parseViewStateRemoveKeys(arg["removeKeys"])+ if !valid {+ ret.Code = -1+ ret.Msg = "Field [removeKeys]: each element should be a non-empty String"+ return+ }+ data, err := model.PatchViewState(key, values, removeKeys)+ if err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ ret.Data = data+}++func removeViewState(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ arg, ok := util.JsonArg(c, ret)+ if !ok {+ return+ }++ var key string+ if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("key", &key, true, true)) {+ return+ }+ if err := model.RemoveViewState(key); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ }+}++func parseViewStateRemoveKeys(value any) (ret []string, valid bool) {+ if nil == value {+ return []string{}, true+ }+ values, ok := value.([]any)+ if !ok {+ return nil, false+ }+ for _, item := range values {+ key, ok := item.(string)+ if !ok || "" == strings.TrimSpace(key) {+ return nil, false+ }+ ret = append(ret, key)+ }+ return ret, true+}diff --git a/kernel/api/storage_test.go b/kernel/api/storage_test.goindex d91ae5fc3b..48ed9c3182 100644--- a/kernel/api/storage_test.go+++ b/kernel/api/storage_test.go@@ -216,3 +216,246 @@ func TestGetOutlineStorageByRole(t *testing.T) {})}}++func TestGetViewStateByRole(t *testing.T) {+ gin.SetMode(gin.TestMode)++ oldDataDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() {+ util.DataDir = oldDataDir+ })++ const viewKey = "backlink:dock:20260820000000-host"+ if _, err := model.PatchViewState(viewKey, map[string]any{+ "fold:20260820000000-block": true,+ }, nil); err != nil {+ t.Fatal(err)+ }++ roles := []struct {+ name string+ role model.Role+ statusCode int+ }{+ {name: "administrator", role: model.RoleAdministrator, statusCode: http.StatusOK},+ {name: "reader", role: model.RoleReader, statusCode: http.StatusForbidden},+ }+ for _, role := range roles {+ t.Run(role.name, func(t *testing.T) {+ engine := gin.New()+ engine.Use(func(c *gin.Context) {+ c.Set(model.RoleContextKey, role.role)+ c.Next()+ })+ ServeAPI(engine)++ recorder := httptest.NewRecorder()+ request := httptest.NewRequest(+ http.MethodPost,+ "/api/storage/getViewState",+ strings.NewReader(`{"key":"`+viewKey+`"}`),+ )+ request.Header.Set("Content-Type", "application/json")+ engine.ServeHTTP(recorder, request)++ if recorder.Code != role.statusCode {+ t.Fatalf("unexpected status code: got %d, want %d", recorder.Code, role.statusCode)+ }+ if role.role == model.RoleReader {+ if strings.Contains(recorder.Body.String(), "20260820000000-block") {+ t.Fatalf("reader received administrator view state: %s", recorder.Body.String())+ }+ return+ }+ if !strings.Contains(recorder.Body.String(), "20260820000000-block") {+ t.Fatalf("administrator did not receive view state: %s", recorder.Body.String())+ }+ })+ }+}++func TestMutateViewStateByRoleAndReadonly(t *testing.T) {+ gin.SetMode(gin.TestMode)++ oldDataDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() {+ util.DataDir = oldDataDir+ })++ const (+ viewKey = "backlink:dock:20260820000000-host"+ field = "fold:20260820000000-block"+ )+ if _, err := model.PatchViewState(viewKey, map[string]any{field: true}, nil); err != nil {+ t.Fatal(err)+ }++ for _, path := range []string{"/api/storage/patchViewState", "/api/storage/removeViewState"} {+ engine := newViewStateAPIEngine(model.RoleReader)+ body := `{"key":"` + viewKey + `"}`+ if strings.HasSuffix(path, "patchViewState") {+ body = `{"key":"` + viewKey + `","values":{"` + field + `":false}}`+ }+ recorder := performViewStateAPIRequest(engine, path, body)+ if recorder.Code != http.StatusForbidden {+ t.Fatalf("reader mutation returned status %d for %s: %s", recorder.Code, path, recorder.Body.String())+ }+ }+ state, err := model.GetViewState(viewKey)+ if err != nil {+ t.Fatal(err)+ }+ if folded, ok := state[field].(bool); !ok || !folded {+ t.Fatalf("reader changed view state: %#v", state)+ }++ oldReadOnly := util.ReadOnly+ oldConf := model.Conf+ t.Cleanup(func() {+ util.ReadOnly = oldReadOnly+ model.Conf = oldConf+ })+ util.ReadOnly = true+ model.Conf = &model.AppConf{Lang: "en"}+ readOnlyRecorder := performViewStateAPIRequest(+ newViewStateAPIEngine(model.RoleAdministrator),+ "/api/storage/patchViewState",+ `{"key":"`+viewKey+`","values":{"`+field+`":false}}`,+ )+ util.ReadOnly = oldReadOnly+ model.Conf = oldConf+ if responseCode(t, readOnlyRecorder) != -1 {+ t.Fatalf("read-only mutation was not rejected: %s", readOnlyRecorder.Body.String())+ }+ state, err = model.GetViewState(viewKey)+ if err != nil {+ t.Fatal(err)+ }+ if folded, ok := state[field].(bool); !ok || !folded {+ t.Fatalf("read-only request changed view state: %#v", state)+ }++ adminEngine := newViewStateAPIEngine(model.RoleAdministrator)+ patchRecorder := performViewStateAPIRequest(+ adminEngine,+ "/api/storage/patchViewState",+ `{"key":"`+viewKey+`","values":{"`+field+`":false}}`,+ )+ if responseCode(t, patchRecorder) != 0 {+ t.Fatalf("administrator patch failed: %s", patchRecorder.Body.String())+ }+ state, err = model.GetViewState(viewKey)+ if err != nil {+ t.Fatal(err)+ }+ if folded, ok := state[field].(bool); !ok || folded {+ t.Fatalf("administrator patch was not persisted: %#v", state)+ }++ removeRecorder := performViewStateAPIRequest(+ adminEngine,+ "/api/storage/removeViewState",+ `{"key":"`+viewKey+`"}`,+ )+ if responseCode(t, removeRecorder) != 0 {+ t.Fatalf("administrator removal failed: %s", removeRecorder.Body.String())+ }+ state, err = model.GetViewState(viewKey)+ if err != nil {+ t.Fatal(err)+ }+ if 0 != len(state) {+ t.Fatalf("administrator removal was not persisted: %#v", state)+ }+}++func TestViewStateAPIRejectsInvalidArguments(t *testing.T) {+ gin.SetMode(gin.TestMode)++ oldDataDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() {+ util.DataDir = oldDataDir+ })++ tests := []struct {+ name string+ path string+ body string+ msg string+ }{+ {name: "missing key", path: "/api/storage/getViewState", body: `{}`, msg: "Field [key] is required"},+ {name: "empty key", path: "/api/storage/removeViewState", body: `{"key":" "}`, msg: "Field [key] must not be empty"},+ {+ name: "values is not an object",+ path: "/api/storage/patchViewState",+ body: `{"key":"view","values":[]}`,+ msg: "Field [values]: should be of type [Object]",+ },+ {+ name: "remove keys is not an array",+ path: "/api/storage/patchViewState",+ body: `{"key":"view","removeKeys":"field"}`,+ msg: "Field [removeKeys]: each element should be a non-empty String",+ },+ {+ name: "remove key is empty",+ path: "/api/storage/patchViewState",+ body: `{"key":"view","removeKeys":[""]}`,+ msg: "Field [removeKeys]: each element should be a non-empty String",+ },+ {+ name: "remove key is whitespace",+ path: "/api/storage/patchViewState",+ body: `{"key":"view","removeKeys":[" "]}`,+ msg: "Field [removeKeys]: each element should be a non-empty String",+ },+ }+ engine := newViewStateAPIEngine(model.RoleAdministrator)+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ recorder := performViewStateAPIRequest(engine, test.path, test.body)+ response := &struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ }{}+ if err := json.Unmarshal(recorder.Body.Bytes(), response); err != nil {+ t.Fatalf("unmarshal response failed: %v", err)+ }+ if response.Code != -1 || !strings.Contains(response.Msg, test.msg) {+ t.Fatalf("unexpected invalid argument response: %s", recorder.Body.String())+ }+ })+ }+}++func newViewStateAPIEngine(role model.Role) *gin.Engine {+ engine := gin.New()+ engine.Use(func(c *gin.Context) {+ c.Set(model.RoleContextKey, role)+ c.Next()+ })+ ServeAPI(engine)+ return engine+}++func performViewStateAPIRequest(engine *gin.Engine, path, body string) *httptest.ResponseRecorder {+ recorder := httptest.NewRecorder()+ request := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))+ request.Header.Set("Content-Type", "application/json")+ engine.ServeHTTP(recorder, request)+ return recorder+}++func responseCode(t *testing.T, recorder *httptest.ResponseRecorder) int {+ t.Helper()+ response := &struct {+ Code int `json:"code"`+ }{}+ if err := json.Unmarshal(recorder.Body.Bytes(), response); err != nil {+ t.Fatalf("unmarshal response failed: %v", err)+ }+ return response.Code+}diff --git a/kernel/model/block.go b/kernel/model/block.goindex 4e60eee46d..a47944174c 100644--- a/kernel/model/block.go+++ b/kernel/model/block.go@@ -982,9 +982,20 @@ func GetHeadingChildrenDOM(id string, removeFoldAttr bool) (ret string) {return}- nodes := append([]*ast.Node{}, heading)children := treenode.HeadingChildren(heading)- nodes = append(nodes, children...)+ nodes := prepareHeadingChildrenDOMNodes(heading, children, removeFoldAttr)++ luteEngine := util.NewLute()+ ret = renderBlockDOMByNodes(nodes, luteEngine)+ return+}++func prepareHeadingChildrenDOMNodes(heading *ast.Node, children []*ast.Node, removeFoldAttr bool) (ret []*ast.Node) {+ ret = append(ret, heading)+ ret = append(ret, children...)+ ret = cleanRenderNodes(ret, false)+ heading = ret[0]+ children = ret[1:]for _, child := range children {ast.Walk(child, func(n *ast.Node, entering bool) ast.WalkStatus {@@ -1002,7 +1013,7 @@ func GetHeadingChildrenDOM(id string, removeFoldAttr bool) (ret string) {if removeFoldAttr {child.RemoveIALAttr("parent-heading")} else {- child.SetIALAttr("parent-heading", id)+ child.SetIALAttr("parent-heading", heading.ID)}}@@ -1010,9 +1021,6 @@ func GetHeadingChildrenDOM(id string, removeFoldAttr bool) (ret string) {heading.RemoveIALAttr("fold")heading.RemoveIALAttr("heading-fold")}-- luteEngine := util.NewLute()- ret = renderCleanBlockDOMByNodes(nodes, luteEngine)return}diff --git a/kernel/model/render_fold_test.go b/kernel/model/render_fold_test.goindex 253ef1f516..19a6f6c019 100644--- a/kernel/model/render_fold_test.go+++ b/kernel/model/render_fold_test.go@@ -91,3 +91,29 @@ func TestCleanRenderDocumentHidesFoldedHeadingChildren(t *testing.T) {t.Fatal("document render should omit folded heading children")}}++func TestPrepareHeadingChildrenDOMNodesDoesNotMutateSource(t *testing.T) {+ heading := &ast.Node{Type: ast.NodeHeading, HeadingLevel: 1, ID: "heading"}+ child := &ast.Node{Type: ast.NodeParagraph, ID: "child"}+ treenode.SetSelfFolded(heading, true)+ treenode.SetSelfFolded(child, true)+ child.SetIALAttr("parent-heading", "original-parent")++ kept := prepareHeadingChildrenDOMNodes(heading, []*ast.Node{child}, false)+ if 2 != len(kept) || "1" != kept[0].IALAttr("fold") || "1" != kept[1].IALAttr("fold") {+ t.Fatal("rendered clones should preserve explicit fold attributes")+ }+ if "heading" != kept[1].IALAttr("parent-heading") {+ t.Fatalf("rendered child has unexpected parent heading: %q", kept[1].IALAttr("parent-heading"))+ }++ removed := prepareHeadingChildrenDOMNodes(heading, []*ast.Node{child}, true)+ if 2 != len(removed) || "" != removed[0].IALAttr("fold") || "" != removed[1].IALAttr("fold") ||+ "" != removed[1].IALAttr("parent-heading") {+ t.Fatal("rendered clones should remove fold and parent-heading attributes")+ }+ if "1" != heading.IALAttr("fold") || "1" != child.IALAttr("fold") ||+ "original-parent" != child.IALAttr("parent-heading") {+ t.Fatal("heading children rendering mutated the source AST")+ }+}diff --git a/kernel/model/sync.go b/kernel/model/sync.goindex b7d0b0f270..15fc4d2b1e 100644--- a/kernel/model/sync.go+++ b/kernel/model/sync.go@@ -905,6 +905,9 @@ func getSyncIgnoreLines() (ret []string) {ret = append(ret, "20210808180117-czj9bvb/**/*")ret = append(ret, "20211226090932-5lcq56f/**/*")ret = append(ret, "20240530133126-axarxgx/**/*")+ // 视图状态仅在当前设备使用,不参与数据同步。+ ret = append(ret, "/storage/view-state.json")+ ret = append(ret, "/storage/view-state-corrupted-*.json")// 忽略用户指南的数据库 JSON 文件for _, avName := range getAllUserGuideAVJSONFiles() {ret = append(ret, "/storage/av/"+avName)diff --git a/kernel/model/view_state.go b/kernel/model/view_state.gonew file mode 100644index 0000000000..f702456c61--- /dev/null+++ b/kernel/model/view_state.go@@ -0,0 +1,415 @@+// SiYuan - From thought to insight, with agents+// 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"+ "math"+ "os"+ "path/filepath"+ "sort"+ "strings"+ "sync"+ "time"++ "github.com/88250/gulu"+ "github.com/siyuan-note/filelock"+ "github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/util"+)++const (+ viewStateVersion = 1+ maxViewStateCount = 2000+ maxViewStateDataCount = 10000+ maxViewStatePatchCount = 1000+ maxViewStatePatchBytes = 256 * 1024+ maxViewStateStorageSize = 16 * 1024 * 1024+)++type ViewState struct {+ Updated int64 `json:"updatedAt"`+ Data map[string]any `json:"data"`+ Order []string `json:"fieldOrder,omitempty"`+}++type viewStateStorage struct {+ Version int `json:"version"`+ Views map[string]*ViewState `json:"views"`+}++type viewStatePatch struct {+ Values map[string]any `json:"values"`+ RemoveKeys []string `json:"removeKeys"`+}++var viewStateStorageLock = sync.Mutex{}++func GetViewState(key string) (ret map[string]any, err error) {+ if err = validateViewStateKey(key); err != nil {+ return+ }++ viewStateStorageLock.Lock()+ defer viewStateStorageLock.Unlock()++ storage, err := getViewStateStorage()+ if err != nil {+ return nil, err+ }+ state := storage.Views[key]+ if nil == state || nil == state.Data {+ return map[string]any{}, nil+ }+ return cloneViewStateData(state.Data)+}++func PatchViewState(key string, values map[string]any, removeKeys []string) (ret map[string]any, err error) {+ if err = validateViewStateKey(key); err != nil {+ return+ }+ if maxViewStatePatchCount < len(values)+len(removeKeys) {+ return nil, errors.New("view state patch contains too many entries")+ }+ for valueKey := range values {+ if err = validateViewStateDataKey(valueKey); err != nil {+ return nil, err+ }+ }+ for _, removeKey := range removeKeys {+ if err = validateViewStateDataKey(removeKey); err != nil {+ return nil, err+ }+ }+ patch := &viewStatePatch{Values: values, RemoveKeys: removeKeys}+ patchData, marshalErr := gulu.JSON.MarshalJSON(patch)+ if nil != marshalErr {+ return nil, marshalErr+ }+ if maxViewStatePatchBytes < len(patchData) {+ return nil, errors.New("view state patch is too large")+ }+ // 后续合并使用序列化快照,避免调用方在请求执行期间继续修改嵌套值。+ normalizedPatch := &viewStatePatch{}+ if err = gulu.JSON.UnmarshalJSON(patchData, &normalizedPatch); nil != err {+ return nil, err+ }+ values = normalizedPatch.Values+ removeKeys = normalizedPatch.RemoveKeys++ viewStateStorageLock.Lock()+ defer viewStateStorageLock.Unlock()++ storage, err := getViewStateStorage()+ if err != nil {+ return nil, err+ }+ state := storage.Views[key]+ if nil == state {+ state = &ViewState{Data: map[string]any{}, Order: []string{}}+ storage.Views[key] = state+ } else if nil == state.Data {+ state.Data = map[string]any{}+ }+ for valueKey, value := range values {+ state.Data[valueKey] = value+ }+ for _, removeKey := range removeKeys {+ delete(state.Data, removeKey)+ }+ touchViewStateFields(state, values)+ pruneViewStateFields(state)+ if 0 == len(state.Data) {+ delete(storage.Views, key)+ } else {+ state.Updated = nextViewStateUpdated(storage.Views)+ }+ pruneViewStates(storage.Views)+ if err = setViewStateStorage(storage); err != nil {+ return nil, err+ }+ if nil == storage.Views[key] {+ return map[string]any{}, nil+ }+ return cloneViewStateData(storage.Views[key].Data)+}++func cloneViewStateData(data map[string]any) (ret map[string]any, err error) {+ serialized, err := gulu.JSON.MarshalJSON(data)+ if nil != err {+ return nil, err+ }+ if err = gulu.JSON.UnmarshalJSON(serialized, &ret); nil != err {+ return nil, err+ }+ return+}++func RemoveViewState(key string) (err error) {+ if err = validateViewStateKey(key); err != nil {+ return+ }++ viewStateStorageLock.Lock()+ defer viewStateStorageLock.Unlock()++ storage, err := getViewStateStorage()+ if err != nil {+ return err+ }+ delete(storage.Views, key)+ return setViewStateStorage(storage)+}++func nextViewStateUpdated(views map[string]*ViewState) int64 {+ ret := time.Now().UnixMilli()+ for _, state := range views {+ if nil == state {+ continue+ }+ if math.MaxInt64 == state.Updated {+ keys := make([]string, 0, len(views))+ for key, candidate := range views {+ if nil != candidate {+ keys = append(keys, key)+ }+ }+ sort.Slice(keys, func(i, j int) bool {+ left, right := views[keys[i]], views[keys[j]]+ if left.Updated == right.Updated {+ return keys[i] < keys[j]+ }+ return left.Updated < right.Updated+ })+ for i, key := range keys {+ views[key].Updated = int64(i + 1)+ }+ return int64(len(keys) + 1)+ }+ if ret <= state.Updated {+ ret = state.Updated + 1+ }+ }+ return ret+}++func validateViewStateKey(key string) error {+ if "" == strings.TrimSpace(key) || 1024 < len(key) {+ return errors.New("invalid view state key")+ }+ return nil+}++func validateViewStateDataKey(key string) error {+ if "" == strings.TrimSpace(key) || 2048 < len(key) {+ return errors.New("invalid view state data key")+ }+ return nil+}++func pruneViewStates(views map[string]*ViewState) {+ if len(views) <= maxViewStateCount {+ return+ }++ keys := make([]string, 0, len(views))+ for key := range views {+ keys = append(keys, key)+ }+ sort.Slice(keys, func(i, j int) bool {+ left, right := views[keys[i]], views[keys[j]]+ if left.Updated == right.Updated {+ return keys[i] < keys[j]+ }+ return left.Updated < right.Updated+ })+ for _, key := range keys[:len(keys)-maxViewStateCount] {+ delete(views, key)+ }+}++func touchViewStateFields(state *ViewState, values map[string]any) {+ normalizeViewStateFieldOrder(state)+ touched := map[string]bool{}+ for key := range values {+ if _, exists := state.Data[key]; exists {+ touched[key] = true+ }+ }+ order := make([]string, 0, len(state.Order))+ for _, key := range state.Order {+ if !touched[key] {+ order = append(order, key)+ }+ }+ keys := make([]string, 0, len(touched))+ for key := range touched {+ keys = append(keys, key)+ }+ sort.Strings(keys)+ state.Order = append(order, keys...)+}++func normalizeViewStateFieldOrder(state *ViewState) {+ seen := map[string]bool{}+ order := make([]string, 0, len(state.Data))+ for _, key := range state.Order {+ if _, exists := state.Data[key]; exists && !seen[key] {+ seen[key] = true+ order = append(order, key)+ }+ }+ missing := make([]string, 0, len(state.Data)-len(order))+ for key := range state.Data {+ if !seen[key] {+ missing = append(missing, key)+ }+ }+ sort.Strings(missing)+ state.Order = append(order, missing...)+}++func pruneViewStateFields(state *ViewState) {+ normalizeViewStateFieldOrder(state)+ if len(state.Order) <= maxViewStateDataCount {+ return+ }+ for _, key := range state.Order[:len(state.Order)-maxViewStateDataCount] {+ delete(state.Data, key)+ }+ state.Order = state.Order[len(state.Order)-maxViewStateDataCount:]+}++func getViewStateStorage() (ret *viewStateStorage, err error) {+ ret = &viewStateStorage{+ Version: viewStateVersion,+ Views: map[string]*ViewState{},+ }+ dataPath := filepath.Join(util.DataDir, "storage", "view-state.json")+ if !filelock.IsExist(dataPath) {+ return+ }++ data, err := filelock.ReadFile(dataPath)+ if err != nil {+ logging.LogErrorf("read storage [view-state] failed: %s", err)+ return nil, err+ }+ header := struct {+ Version int `json:"version"`+ }{}+ if err = gulu.JSON.UnmarshalJSON(data, &header); err != nil {+ return backupCorruptedViewState(dataPath, err)+ }+ if viewStateVersion < header.Version {+ return nil, fmt.Errorf("unsupported view state version %d", header.Version)+ }+ if err = gulu.JSON.UnmarshalJSON(data, ret); err != nil {+ return backupCorruptedViewState(dataPath, err)+ }+ if nil == ret.Views {+ ret.Views = map[string]*ViewState{}+ }+ for key, state := range ret.Views {+ if nil == state {+ delete(ret.Views, key)+ continue+ }+ if nil == state.Data {+ state.Data = map[string]any{}+ }+ }+ pruneViewStates(ret.Views)+ for _, state := range ret.Views {+ pruneViewStateFields(state)+ }+ if maxViewStateStorageSize < len(data) {+ if _, err = marshalViewStateStorage(ret); nil != err {+ return nil, err+ }+ }+ ret.Version = viewStateVersion+ return+}++func backupCorruptedViewState(dataPath string, parseErr error) (ret *viewStateStorage, err error) {+ backupPath := filepath.Join(filepath.Dir(dataPath), fmt.Sprintf("view-state-corrupted-%d.json", time.Now().UnixMilli()))+ if err = os.Rename(dataPath, backupPath); nil != err {+ logging.LogErrorf("backup corrupted storage [view-state] failed: %s", err)+ return nil, parseErr+ }+ logging.LogWarnf("unmarshal storage [view-state] failed, moved to [%s]: %s", backupPath, parseErr)+ return &viewStateStorage{Version: viewStateVersion, Views: map[string]*ViewState{}}, nil+}++func setViewStateStorage(storage *viewStateStorage) (err error) {+ storageDir := filepath.Join(util.DataDir, "storage")+ if err = os.MkdirAll(storageDir, 0755); err != nil {+ logging.LogErrorf("create storage [view-state] dir failed: %s", err)+ return err+ }++ data, err := marshalViewStateStorage(storage)+ if err != nil {+ logging.LogErrorf("marshal storage [view-state] failed: %s", err)+ return err+ }++ dataPath := filepath.Join(storageDir, "view-state.json")+ if err = filelock.WriteFile(dataPath, data); err != nil {+ logging.LogErrorf("write storage [view-state] failed: %s", err)+ }+ return+}++func marshalViewStateStorage(storage *viewStateStorage) (data []byte, err error) {+ for {+ data, err = gulu.JSON.MarshalIndentJSON(storage, "", " ")+ if err != nil {+ return nil, err+ }+ if len(data) <= maxViewStateStorageSize {+ return+ }+ if len(storage.Views) <= 1 {+ key := oldestViewStateKey(storage.Views)+ state := storage.Views[key]+ normalizeViewStateFieldOrder(state)+ if 0 == len(state.Order) {+ return nil, errors.New("view state storage is too large")+ }+ delete(state.Data, state.Order[0])+ state.Order = state.Order[1:]+ if 0 == len(state.Data) {+ delete(storage.Views, key)+ }+ continue+ }+ delete(storage.Views, oldestViewStateKey(storage.Views))+ }+}++func oldestViewStateKey(views map[string]*ViewState) (ret string) {+ for key, state := range views {+ if "" == ret || state.Updated < views[ret].Updated ||+ (state.Updated == views[ret].Updated && key < ret) {+ ret = key+ }+ }+ return+}diff --git a/kernel/model/view_state_test.go b/kernel/model/view_state_test.gonew file mode 100644index 0000000000..e36584e235--- /dev/null+++ b/kernel/model/view_state_test.go@@ -0,0 +1,467 @@+// SiYuan - From thought to insight, with agents+// 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 (+ "encoding/json"+ "fmt"+ "math"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "testing"++ ignore "github.com/sabhiram/go-gitignore"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestPatchViewState(t *testing.T) {+ oldDataDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() {+ util.DataDir = oldDataDir+ })++ const key = "backlink:dock:20260820000000-host"+ if _, err := PatchViewState(key, map[string]any{+ "document:backlink:20260820000000-document": true,+ "fold:backlink:20260820000000-occurrence:20260820000000-block": true,+ }, nil); err != nil {+ t.Fatal(err)+ }+ if _, err := PatchViewState(key, map[string]any{+ "anchor:backlink": map[string]any{"blockID": "20260820000000-block", "offset": 24},+ }, []string{"document:backlink:20260820000000-document"}); err != nil {+ t.Fatal(err)+ }++ state, err := GetViewState(key)+ if err != nil {+ t.Fatal(err)+ }+ if _, exists := state["document:backlink:20260820000000-document"]; exists {+ t.Fatalf("removed view state value still exists: %#v", state)+ }+ if folded, ok := state["fold:backlink:20260820000000-occurrence:20260820000000-block"].(bool); !ok || !folded {+ t.Fatalf("fold state was not preserved: %#v", state)+ }+ if _, err = PatchViewState(key, map[string]any{+ "fold:backlink:20260820000000-occurrence:20260820000000-block": false,+ }, nil); err != nil {+ t.Fatal(err)+ }+ state, err = GetViewState(key)+ if err != nil {+ t.Fatal(err)+ }+ if folded, ok := state["fold:backlink:20260820000000-occurrence:20260820000000-block"].(bool); !ok || folded {+ t.Fatalf("explicit expanded state was not preserved: %#v", state)+ }+ anchor, ok := state["anchor:backlink"].(map[string]any)+ if !ok || anchor["blockID"] != "20260820000000-block" {+ t.Fatalf("anchor state was not merged: %#v", state)+ }++ if err = RemoveViewState(key); err != nil {+ t.Fatal(err)+ }+ state, err = GetViewState(key)+ if err != nil {+ t.Fatal(err)+ }+ if 0 != len(state) {+ t.Fatalf("removed view state is not empty: %#v", state)+ }+}++func TestViewStateValidationAndPatchLimits(t *testing.T) {+ if _, err := GetViewState(" "); nil == err {+ t.Fatal("whitespace-only view state key should be rejected")+ }+ if _, err := GetViewState(strings.Repeat("k", 1025)); nil == err {+ t.Fatal("oversized view state key should be rejected")+ }+ if _, err := PatchViewState("view", map[string]any{" ": true}, nil); nil == err {+ t.Fatal("whitespace-only view state data key should be rejected")+ }+ if _, err := PatchViewState("view", map[string]any{strings.Repeat("f", 2049): true}, nil); nil == err {+ t.Fatal("oversized view state data key should be rejected")+ }++ values := map[string]any{}+ for i := 0; i <= maxViewStatePatchCount; i++ {+ values[fmt.Sprintf("field-%04d", i)] = true+ }+ if _, err := PatchViewState("view", values, nil); nil == err {+ t.Fatal("oversized view state patch entry count should be rejected")+ }+ if _, err := PatchViewState("view", map[string]any{+ "value": strings.Repeat("x", maxViewStatePatchBytes),+ }, nil); nil == err {+ t.Fatal("oversized view state patch payload should be rejected")+ }+}++func TestPatchViewStateConcurrently(t *testing.T) {+ oldDataDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() {+ util.DataDir = oldDataDir+ })++ const key = "backlink:bottom:20260820000000-host"+ const count = 32+ errs := make(chan error, count)+ var waitGroup sync.WaitGroup+ for i := 0; i < count; i++ {+ waitGroup.Add(1)+ go func(index int) {+ defer waitGroup.Done()+ _, err := PatchViewState(key, map[string]any{+ fmt.Sprintf("fold:%02d", index): 0 == index%2,+ }, nil)+ errs <- err+ }(i)+ }+ waitGroup.Wait()+ close(errs)+ for err := range errs {+ if err != nil {+ t.Fatal(err)+ }+ }++ state, err := GetViewState(key)+ if err != nil {+ t.Fatal(err)+ }+ if count != len(state) {+ t.Fatalf("concurrent patches overwrote values: got %d, want %d", len(state), count)+ }+}++func TestGetViewStateReturnsDeepCopy(t *testing.T) {+ oldDataDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() {+ util.DataDir = oldDataDir+ })++ const key = "backlink:local:20260820000000-host"+ patched, err := PatchViewState(key, map[string]any{+ "anchor:backlink": map[string]any{+ "blockID": "20260820000000-block",+ "fallbackIDs": []any{+ "20260820000000-previous",+ "20260820000000-next",+ },+ },+ }, nil)+ if err != nil {+ t.Fatal(err)+ }+ patchedAnchor := patched["anchor:backlink"].(map[string]any)+ patchedAnchor["blockID"] = "mutated"+ patchedAnchor["fallbackIDs"].([]any)[0] = "mutated"++ state, err := GetViewState(key)+ if err != nil {+ t.Fatal(err)+ }+ anchor := state["anchor:backlink"].(map[string]any)+ if anchor["blockID"] != "20260820000000-block" ||+ anchor["fallbackIDs"].([]any)[0] != "20260820000000-previous" {+ t.Fatalf("patched view state shares nested data: %#v", state)+ }+ anchor["blockID"] = "mutated"+ anchor["fallbackIDs"].([]any)[0] = "mutated"++ state, err = GetViewState(key)+ if err != nil {+ t.Fatal(err)+ }+ anchor = state["anchor:backlink"].(map[string]any)+ if anchor["blockID"] != "20260820000000-block" ||+ anchor["fallbackIDs"].([]any)[0] != "20260820000000-previous" {+ t.Fatalf("returned view state shares nested data: %#v", state)+ }+}++func TestLoadViewStateAppliesLimits(t *testing.T) {+ oldDataDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() {+ util.DataDir = oldDataDir+ })++ views := map[string]*ViewState{}+ for i := 0; i < maxViewStateCount+2; i++ {+ views[fmt.Sprintf("view-%04d", i)] = &ViewState{+ Updated: int64(i),+ Data: map[string]any{"value": i},+ }+ }+ latest := views[fmt.Sprintf("view-%04d", maxViewStateCount+1)]+ latest.Data = map[string]any{}+ latest.Order = []string{}+ for i := 0; i < maxViewStateDataCount+2; i++ {+ key := fmt.Sprintf("field-%05d", i)+ latest.Data[key] = i+ latest.Order = append(latest.Order, key)+ }++ storageDir := filepath.Join(util.DataDir, "storage")+ if err := os.MkdirAll(storageDir, 0755); err != nil {+ t.Fatal(err)+ }+ data, err := json.Marshal(&viewStateStorage{Version: viewStateVersion, Views: views})+ if err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(filepath.Join(storageDir, "view-state.json"), data, 0644); err != nil {+ t.Fatal(err)+ }++ loaded, err := getViewStateStorage()+ if err != nil {+ t.Fatal(err)+ }+ if maxViewStateCount != len(loaded.Views) || nil != loaded.Views["view-0000"] || nil != loaded.Views["view-0001"] {+ t.Fatalf("loaded view count was not pruned: %d", len(loaded.Views))+ }+ latest = loaded.Views[fmt.Sprintf("view-%04d", maxViewStateCount+1)]+ if nil == latest || maxViewStateDataCount != len(latest.Data) || maxViewStateDataCount != len(latest.Order) {+ t.Fatalf("loaded field count was not pruned: %#v", latest)+ }+ if _, exists := latest.Data["field-00000"]; exists {+ t.Fatal("oldest loaded field was not pruned")+ }+ if _, exists := latest.Data["field-00001"]; exists {+ t.Fatal("second oldest loaded field was not pruned")+ }+}++func TestSetViewStateStoragePrunesOldestViewBySize(t *testing.T) {+ oldDataDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() {+ util.DataDir = oldDataDir+ })++ storage := oversizedViewStateStorage()+ if err := setViewStateStorage(storage); err != nil {+ t.Fatal(err)+ }+ if nil != storage.Views["old"] || nil == storage.Views["new"] {+ t.Fatalf("storage size pruning did not evict the oldest view: %#v", storage.Views)+ }+ info, err := os.Stat(filepath.Join(util.DataDir, "storage", "view-state.json"))+ if err != nil {+ t.Fatal(err)+ }+ if maxViewStateStorageSize < info.Size() {+ t.Fatalf("view state storage exceeds the size limit: %d", info.Size())+ }+}++func TestLoadViewStateStoragePrunesOldestViewBySize(t *testing.T) {+ oldDataDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() {+ util.DataDir = oldDataDir+ })++ storageDir := filepath.Join(util.DataDir, "storage")+ if err := os.MkdirAll(storageDir, 0755); err != nil {+ t.Fatal(err)+ }+ data, err := json.Marshal(oversizedViewStateStorage())+ if err != nil {+ t.Fatal(err)+ }+ if len(data) <= maxViewStateStorageSize {+ t.Fatalf("test storage does not exceed the size limit: %d", len(data))+ }+ if err = os.WriteFile(filepath.Join(storageDir, "view-state.json"), data, 0644); err != nil {+ t.Fatal(err)+ }+ loaded, err := getViewStateStorage()+ if err != nil {+ t.Fatal(err)+ }+ if nil != loaded.Views["old"] || nil == loaded.Views["new"] {+ t.Fatalf("loaded storage size pruning did not evict the oldest view: %#v", loaded.Views)+ }+}++func oversizedViewStateStorage() *viewStateStorage {+ return &viewStateStorage{Version: viewStateVersion, Views: map[string]*ViewState{+ "old": {+ Updated: 1,+ Data: map[string]any{+ "value": strings.Repeat("x", maxViewStateStorageSize),+ },+ Order: []string{"value"},+ },+ "new": {+ Updated: 2,+ Data: map[string]any{"value": true},+ Order: []string{"value"},+ },+ }}+}++func TestPruneViewStates(t *testing.T) {+ views := map[string]*ViewState{}+ for i := 0; i < maxViewStateCount+2; i++ {+ views[fmt.Sprintf("view-%04d", i)] = &ViewState{Updated: int64(i), Data: map[string]any{"value": i}}+ }+ pruneViewStates(views)+ if maxViewStateCount != len(views) {+ t.Fatalf("unexpected view state count: got %d, want %d", len(views), maxViewStateCount)+ }+ if nil != views["view-0000"] || nil != views["view-0001"] {+ t.Fatalf("oldest view states were not pruned")+ }+}++func TestNextViewStateUpdatedRebasesOverflow(t *testing.T) {+ views := map[string]*ViewState{+ "old": {Updated: 10, Data: map[string]any{"value": true}},+ "future": {Updated: math.MaxInt64, Data: map[string]any{"value": true}},+ }+ updated := nextViewStateUpdated(views)+ if views["old"].Updated >= views["future"].Updated || views["future"].Updated >= updated {+ t.Fatalf("view state timestamps were not rebased in LRU order: %#v, %d", views, updated)+ }+}++func TestPruneViewStateFieldsUsesFieldOrder(t *testing.T) {+ state := &ViewState{Data: map[string]any{}, Order: []string{}}+ for i := 0; i < maxViewStateDataCount+2; i++ {+ key := fmt.Sprintf("field-%05d", i)+ state.Data[key] = i+ state.Order = append(state.Order, key)+ }+ pruneViewStateFields(state)+ if maxViewStateDataCount != len(state.Data) || maxViewStateDataCount != len(state.Order) {+ t.Fatalf("unexpected field count after pruning: %d, %d", len(state.Data), len(state.Order))+ }+ if _, exists := state.Data["field-00000"]; exists {+ t.Fatal("oldest field was not pruned")+ }+ if _, exists := state.Data["field-00001"]; exists {+ t.Fatal("second oldest field was not pruned")+ }+}++func TestViewStateIsIgnoredBySync(t *testing.T) {+ oldDataDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() {+ util.DataDir = oldDataDir+ })++ ignoreLines := getSyncIgnoreLines()+ lines := map[string]bool{}+ for _, line := range ignoreLines {+ lines[line] = true+ }+ if !lines["/storage/view-state.json"] || !lines["/storage/view-state-corrupted-*.json"] {+ t.Fatalf("view state files are not ignored by sync: %#v", lines)+ }+ matcher := ignore.CompileIgnoreLines(ignoreLines...)+ for _, path := range []string{+ "/storage/view-state.json",+ "/storage/view-state-corrupted-20260820000000.json",+ } {+ if !matcher.MatchesPath(path) {+ t.Fatalf("view state path is not ignored by sync: %s", path)+ }+ }+}++func TestCorruptedViewStateIsBackedUp(t *testing.T) {+ oldDataDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() {+ util.DataDir = oldDataDir+ })++ storageDir := filepath.Join(util.DataDir, "storage")+ if err := os.MkdirAll(storageDir, 0755); err != nil {+ t.Fatal(err)+ }+ dataPath := filepath.Join(storageDir, "view-state.json")+ if err := os.WriteFile(dataPath, []byte("{"), 0644); err != nil {+ t.Fatal(err)+ }+ state, err := GetViewState("backlink:local:host")+ if err != nil {+ t.Fatal(err)+ }+ if 0 != len(state) {+ t.Fatalf("corrupted storage should recover as empty: %#v", state)+ }+ if _, err = os.Stat(dataPath); !os.IsNotExist(err) {+ t.Fatalf("corrupted storage was not moved: %v", err)+ }+ backups, err := filepath.Glob(filepath.Join(storageDir, "view-state-corrupted-*.json"))+ if err != nil || 1 != len(backups) {+ t.Fatalf("unexpected corrupted storage backups: %#v, %v", backups, err)+ }+ backupData, err := os.ReadFile(backups[0])+ if err != nil {+ t.Fatal(err)+ }+ if "{" != string(backupData) {+ t.Fatalf("corrupted storage backup was changed: %q", backupData)+ }+}++func TestFutureViewStateVersionIsNotOverwritten(t *testing.T) {+ oldDataDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() {+ util.DataDir = oldDataDir+ })++ storageDir := filepath.Join(util.DataDir, "storage")+ if err := os.MkdirAll(storageDir, 0755); err != nil {+ t.Fatal(err)+ }+ dataPath := filepath.Join(storageDir, "view-state.json")+ original := []byte(`{"version":2,"views":[{"future":"schema"}]}`)+ if err := os.WriteFile(dataPath, original, 0644); err != nil {+ t.Fatal(err)+ }+ if _, err := PatchViewState("backlink:local:host", map[string]any{"value": false}, nil); nil == err {+ t.Fatal("future view state version should be rejected")+ }+ data, err := os.ReadFile(dataPath)+ if err != nil {+ t.Fatal(err)+ }+ if string(original) != string(data) {+ t.Fatalf("future view state storage was overwritten: %s", data)+ }+ backups, err := filepath.Glob(filepath.Join(storageDir, "view-state-corrupted-*.json"))+ if err != nil || 0 != len(backups) {+ t.Fatalf("future view state storage was treated as corrupted: %#v, %v", backups, err)+ }+}