An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Temporarily expand focused headings https://github.com/siyuan-note/siyuan/issues/19483
Daniel60fa55398459
diff --git a/app/src/protyle/util/destroy.ts b/app/src/protyle/util/destroy.tsindex 2c47499e5b..4b0a1414ab 100644--- a/app/src/protyle/util/destroy.ts+++ b/app/src/protyle/util/destroy.ts@@ -8,11 +8,13 @@ import {forEachPluginSubscriber} from "../../plugin/EventBusCore";import {unregisterCustomBlockRoot} from "../../plugin/customBlockRender";import {destroyTrackedRanges} from "./trackedRange";import {areProtylePluginExtensionsEnabled} from "../runtimeCapabilities";+import {invalidateFocusFoldRequests} from "./focusFold";export const destroy = (protyle: IProtyle) => {if (!protyle) {return;}+ invalidateFocusFoldRequests(protyle);destroyTrackedRanges(protyle);cancelAssetUploads(protyle);unmountBreadcrumbButtons(protyle);diff --git a/app/src/protyle/util/focusFold.test.ts b/app/src/protyle/util/focusFold.test.tsindex e6d3434443..829541be01 100644--- a/app/src/protyle/util/focusFold.test.ts+++ b/app/src/protyle/util/focusFold.test.ts@@ -1,8 +1,9 @@import {describe, it} from "node:test";import * as assert from "node:assert/strict";-import {applyFocusFold, stopFocusFold, updateFocusFoldSource} from "./focusFold";+import {applyFocusFold, invalidateFocusFoldRequests, stopFocusFold, updateFocusFoldSource} from "./focusFold";class FoldElement {+ isConnected = true;attrs: Record<string, string>;constructor(id: string, type = "NodeListItem", fold = "1") {@@ -32,7 +33,8 @@ const editor = (elements: FoldElement[]) => ({wysiwyg: {element: {querySelector: (selector: string) => elements.find(element =>- selector === `[data-node-id="${element.attrs["data-node-id"]}"][data-type="${element.attrs["data-type"]}"]`),+ selector === `[data-node-id="${element.attrs["data-node-id"]}"]`),+ contains: (element: FoldElement) => elements.includes(element),},},} as unknown as IProtyle);@@ -122,7 +124,7 @@ describe("focused list folding", () => {assert.equal(parent.getAttribute("fold"), null);});- it("does not unfold headings, ordinary document views, or backlink views", () => {+ it("requires a loader for headings and excludes ordinary document and backlink views", () => {const heading = new FoldElement("parent", "NodeHeading");applyFocusFold(editor([heading]));assert.equal(heading.getAttribute("fold"), "1");@@ -137,3 +139,115 @@ describe("focused list folding", () => {assert.equal(parent.getAttribute("fold"), "1");});});++describe("focused heading loading", () => {+ it("loads once, preserves child folds, and restores the source on exit", async () => {+ const heading = new FoldElement("parent", "NodeHeading");+ const child = new FoldElement("child", "NodeHeading");+ const protyle = editor([heading, child]);+ let loads = 0;+ const load = async () => {+ loads++;+ return true;+ };+ await applyFocusFold(protyle, load);+ await applyFocusFold(protyle, load);+ assert.equal(loads, 1);+ assert.equal(heading.getAttribute("fold"), null);+ assert.equal(heading.getAttribute("data-view-fold-source"), "1");+ assert.equal(child.getAttribute("fold"), "1");+ protyle.block.showAll = false;+ await applyFocusFold(protyle, load);+ assert.equal(heading.getAttribute("fold"), "1");+ });++ it("shares an in-flight load and ignores it after a focus switch", async () => {+ const protyle = editor([new FoldElement("parent", "NodeHeading")]);+ let complete: (value: boolean) => void;+ let valid: () => boolean;+ const load = (_element: Element, isValid: () => boolean) => {+ valid = isValid;+ return new Promise<boolean>(resolve => complete = resolve);+ };+ const request = applyFocusFold(protyle, load);+ assert.equal(applyFocusFold(protyle, load), request);+ await Promise.resolve();+ protyle.block.id = "another";+ assert.equal(valid(), false);+ complete(true);+ await request;+ });++ it("invalidates pending content after an edit and allows a fresh request", async () => {+ const protyle = editor([new FoldElement("parent", "NodeHeading")]);+ let complete: (value: boolean) => void;+ let valid: () => boolean;+ const request = applyFocusFold(protyle, (_element, isValid) => {+ valid = isValid;+ return new Promise<boolean>(resolve => complete = resolve);+ });+ await Promise.resolve();+ invalidateFocusFoldRequests(protyle);+ assert.equal(valid(), false);+ let fresh = false;+ await applyFocusFold(protyle, async () => {+ fresh = true;+ return true;+ });+ complete(false);+ await request;+ assert.equal(fresh, true);+ assert.equal(protyle.wysiwyg.element.querySelector('[data-node-id="parent"]').getAttribute("fold"), null);+ });++ it("honors manual folding while loading and after refreshing the heading", async () => {+ const elements = [new FoldElement("parent", "NodeHeading")];+ const protyle = editor(elements);+ let complete: (value: boolean) => void;+ let valid: () => boolean;+ const request = applyFocusFold(protyle, (_element, isValid) => {+ valid = isValid;+ return new Promise<boolean>(resolve => complete = resolve);+ });+ await Promise.resolve();+ stopFocusFold(protyle, "parent");+ elements[0].setAttribute("fold", "1");+ assert.equal(valid(), false);+ complete(true);+ await request;+ elements[0] = new FoldElement("parent", "NodeHeading");+ await applyFocusFold(protyle, async () => assert.fail("manual folding must survive refresh"));+ assert.equal(elements[0].getAttribute("fold"), "1");+ });++ it("rejects a detached or replaced heading and reloads the new element", async () => {+ const elements = [new FoldElement("parent", "NodeHeading")];+ const protyle = editor(elements);+ let complete: (value: boolean) => void;+ let valid: () => boolean;+ const request = applyFocusFold(protyle, (_element, isValid) => {+ valid = isValid;+ return new Promise<boolean>(resolve => complete = resolve);+ });+ await Promise.resolve();+ elements[0].isConnected = false;+ assert.equal(valid(), false);+ elements[0] = new FoldElement("parent", "NodeHeading");+ await applyFocusFold(protyle, async () => true);+ complete(false);+ await request;+ assert.equal(elements[0].getAttribute("fold"), null);+ });++ it("restores folding on failure without repeatedly retrying and retries after refresh", async () => {+ const elements = [new FoldElement("parent", "NodeHeading")];+ const protyle = editor(elements);+ await applyFocusFold(protyle, async () => false);+ assert.equal(elements[0].getAttribute("fold"), "1");+ assert.equal(elements[0].hasAttribute("data-view-fold-source"), false);+ await applyFocusFold(protyle, async () => assert.fail("failed loads must not loop"));+ elements[0] = new FoldElement("parent", "NodeHeading");+ await applyFocusFold(protyle, async () => true);+ assert.equal(elements[0].getAttribute("fold"), null);+ });+});diff --git a/app/src/protyle/util/focusFold.ts b/app/src/protyle/util/focusFold.tsindex 0ad27aac74..65f00f4805 100644--- a/app/src/protyle/util/focusFold.ts+++ b/app/src/protyle/util/focusFold.ts@@ -5,6 +5,10 @@ interface IFocusFoldState {rootID: string,manual: boolean,element?: Element,+ generation?: number,+ headingLoaded?: boolean,+ headingFailed?: boolean,+ headingRequest?: Promise<void>,}const states = new WeakMap<IProtyle, IFocusFoldState>();@@ -19,7 +23,8 @@ const restoreElement = (element?: Element) => {element?.removeAttribute(SOURCE_FOLD);};-export const applyFocusFold = (protyle: IProtyle) => {+export const applyFocusFold = (protyle: IProtyle,+ loadHeading?: (element: Element, isValid: () => boolean) => Promise<boolean>) => {let state = states.get(protyle);const {id, rootID, showAll} = protyle.block;const focused = showAll && id !== rootID && !protyle.options.backlinkData && !protyle.lite;@@ -31,8 +36,9 @@ export const applyFocusFold = (protyle: IProtyle) => {if (!focused || state?.manual) {return;}- const element = protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"][data-type="NodeListItem"]`);- if (!element) {+ const element = protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`);+ const type = element?.getAttribute("data-type");+ if (type !== "NodeListItem" && (type !== "NodeHeading" || !loadHeading)) {return;}if (!state) {@@ -42,12 +48,63 @@ export const applyFocusFold = (protyle: IProtyle) => {if (state.element !== element) {restoreElement(state.element);state.element = element;+ state.generation = (state.generation || 0) + 1;+ state.headingLoaded = false;+ state.headingFailed = false;+ state.headingRequest = undefined;+ }+ if (state.headingFailed) {+ return;}// 复用视图折叠的源属性标记,编辑内容序列化时仍保留文档中的折叠状态。if (!element.hasAttribute(SOURCE_FOLD)) {element.setAttribute(SOURCE_FOLD, element.getAttribute("fold") === "1" ? "1" : "0");}element.removeAttribute("fold");+ if (type !== "NodeHeading" || state.headingLoaded) {+ return;+ }+ if (state.headingRequest) {+ return state.headingRequest;+ }+ const currentState = state;+ const generation = state.generation;+ const isValid = () => states.get(protyle) === currentState && !currentState.manual &&+ currentState.generation === generation && currentState.element === element && element.isConnected &&+ protyle.wysiwyg.element.contains(element) && protyle.block.showAll &&+ protyle.block.id === id && protyle.block.rootID === rootID;+ // 加载期间发生编辑、切换聚焦或手动折叠时,丢弃该次请求,避免插入过期内容。+ const request = Promise.resolve().then(() => isValid() ? loadHeading(element, isValid) : false)+ .then(loaded => {+ if (!isValid()) {+ return;+ }+ currentState.headingLoaded = loaded;+ currentState.headingFailed = !loaded;+ if (!loaded) {+ restoreElement(element);+ }+ }).catch(error => {+ console.error(error);+ if (isValid()) {+ currentState.headingFailed = true;+ restoreElement(element);+ }+ }).finally(() => {+ if (currentState.headingRequest === request) {+ currentState.headingRequest = undefined;+ }+ });+ state.headingRequest = request;+ return request;+};++export const invalidateFocusFoldRequests = (protyle: IProtyle) => {+ const state = states.get(protyle);+ if (state) {+ state.generation = (state.generation || 0) + 1;+ state.headingRequest = undefined;+ }};export const stopFocusFold = (protyle: IProtyle, id: string) => {@@ -64,5 +121,7 @@ export const updateFocusFoldSource = (protyle: IProtyle, id: string, folded: booconst state = states.get(protyle);if (state?.id === id && !state.manual) {state.element?.setAttribute(SOURCE_FOLD, folded ? "1" : "0");+ state.headingLoaded = false;+ state.headingFailed = false;}};diff --git a/app/src/protyle/util/focusHeading.test.ts b/app/src/protyle/util/focusHeading.test.tsnew file mode 100644index 0000000000..1d1b0113f0--- /dev/null+++ b/app/src/protyle/util/focusHeading.test.ts@@ -0,0 +1,231 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+import {getFocusedHeadingChildren} from "./heading";+import * as focusFold from "./focusFold";++class HeadingElement {+ isConnected = true;+ children: HeadingElement[] = [];+ parent: HeadingElement;+ classList = {contains: (name: string) => this.attrs.class === name};++ constructor(public attrs: Record<string, string> = {}) {}++ get firstElementChild() {+ return this.children[0] || null;+ }++ get lastElementChild() {+ return this.children[this.children.length - 1] || null;+ }++ get nextElementSibling() {+ return this.parent?.children[this.parent.children.indexOf(this) + 1] || null;+ }++ getAttribute(name: string) {+ return this.attrs[name] ?? null;+ }++ hasAttribute(name: string) {+ return name in this.attrs;+ }++ setAttribute(name: string, value: string) {+ this.attrs[name] = value;+ }++ removeAttribute(name: string) {+ delete this.attrs[name];+ }++ contains(element: HeadingElement): boolean {+ return element === this || this.children.some(child => child.contains(element));+ }++ querySelector(selector: string): HeadingElement {+ return this.children.find(child => selector === `[data-node-id="${child.getAttribute("data-node-id")}"]`);+ }++ append(...children: HeadingElement[]) {+ children.forEach(child => {+ if (child.parent) {+ child.remove();+ }+ child.parent = this;+ this.children.push(child);+ });+ return this;+ }++ appendChild(child: HeadingElement) {+ this.append(child);+ return child;+ }++ after(fragment: HeadingElement) {+ const children = [...fragment.children];+ children.forEach(child => {+ child.remove();+ child.parent = this.parent;+ });+ this.parent.children.splice(this.parent.children.indexOf(this) + 1, 0, ...children);+ }++ remove() {+ this.parent.children.splice(this.parent.children.indexOf(this), 1);+ this.parent = undefined;+ }++ querySelectorAll(): HeadingElement[] {+ return this.children.flatMap(child => [+ ...(child.attrs["data-type"] === "NodeHeading" && child.attrs.fold === "1" ? [child] : []),+ ...child.querySelectorAll(),+ ]);+ }++ asFragment() {+ return this as unknown as DocumentFragment;+ }+}++const heading = (id: string, level: number, folded = false) => new HeadingElement({+ "data-node-id": id,+ "data-type": "NodeHeading",+ "data-subtype": `h${level}`,+ fold: folded ? "1" : "0",+});++const compiledViewFold = transpileModule(readFileSync("src/protyle/util/viewFold.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;++const loadView = (responseContent: HeadingElement) => {+ const exports = {} as {applyFocusFold: (protyle: IProtyle) => Promise<void>};+ let requests = 0;+ const dependencies = {+ fetchSyncPost: async (url: string, data: {id: string, removeFoldAttr: boolean}) => {+ assert.equal(url, "/api/block/getHeadingChildrenDOM");+ assert.equal(data.id, "parent");+ assert.equal(data.removeFoldAttr, false);+ requests++;+ return {code: 0, data: "heading response"};+ },+ normalizeHTMLAssetIFrameBlockDOM: (html: string) => html,+ processRender: (): void => undefined,+ highlightRender: (): void => undefined,+ avRender: (): void => undefined,+ blockRender: (): void => undefined,+ renderHeadingNumbers: (): void => undefined,+ queueHeadingNumberRefresh: (): void => undefined,+ updateDocumentBottomEof: (): void => undefined,+ };+ runInNewContext(compiledViewFold, {+ exports,+ require: (id: string) => id === "./focusFold" ? focusFold :+ id === "./heading" ? {getFocusedHeadingChildren} : dependencies,+ document: {+ createElement: () => ({content: responseContent.asFragment(), innerHTML: ""}),+ createDocumentFragment: () => new HeadingElement(),+ },+ });+ return {apply: exports.applyFocusFold, requests: () => requests};+};++describe("focused heading view integration", () => {+ it("merges missing content without overwriting edited blocks and preserves the bottom boundary", async () => {+ const parent = heading("parent", 1, true);+ const edited = paragraph("edited");+ edited.setAttribute("custom-value", "local edit");+ edited.setAttribute("data-eof", "2");+ const root = new HeadingElement().append(parent, edited);+ const response = new HeadingElement().append(+ heading("parent", 1, true), paragraph("intro"), paragraph("edited"),+ heading("child", 2, true), paragraph("hidden"), heading("sibling", 2), paragraph("visible"),+ );+ const view = loadView(response);+ const protyle = {+ block: {id: "parent", rootID: "doc", showAll: true},+ options: {render: {scroll: false}},+ wysiwyg: {element: root},+ } as unknown as IProtyle;+ await view.apply(protyle);+ assert.deepEqual(root.children.map(element => element.getAttribute("data-node-id")), [+ "parent", "intro", "edited", "child", "sibling", "visible",+ ]);+ assert.equal(root.children[2], edited);+ assert.equal(edited.getAttribute("custom-value"), "local edit");+ assert.equal(edited.getAttribute("data-eof"), null);+ assert.equal(root.lastElementChild.getAttribute("data-eof"), "2");+ assert.equal(parent.getAttribute("fold"), null);+ assert.equal(parent.getAttribute("data-view-fold-source"), "1");+ assert.equal(root.children[3].getAttribute("fold"), "1");+ await view.apply(protyle);+ assert.equal(view.requests(), 1);+ });++ it("keeps already loaded, unfolded heading content without another request", async () => {+ const root = new HeadingElement().append(heading("parent", 1), paragraph("content"));+ const view = loadView(new HeadingElement());+ await view.apply({+ block: {id: "parent", rootID: "doc", showAll: true},+ options: {render: {scroll: false}},+ wysiwyg: {element: root},+ } as unknown as IProtyle);+ assert.equal(view.requests(), 0);+ assert.equal(root.children.length, 2);+ });+});+const paragraph = (id: string) => new HeadingElement({"data-node-id": id, "data-type": "NodeParagraph"});++describe("focused heading content", () => {+ it("reveals the parent content while omitting folded subheadings' content", () => {+ const parent = heading("parent", 1, true);+ const child = heading("child", 2, true);+ const sibling = heading("sibling", 2);+ const content = new HeadingElement().append(+ parent, paragraph("intro"), child, paragraph("hidden"),+ heading("grandchild", 3, true), paragraph("deep-hidden"),+ sibling, paragraph("visible"), heading("expanded-grandchild", 3), paragraph("deep-visible"),+ );+ const result = getFocusedHeadingChildren(content.asFragment(), "parent");+ assert.equal(result.folded, true);+ assert.deepEqual(result.children.map(element => element.getAttribute("data-node-id")), [+ "intro", "child", "sibling", "visible", "expanded-grandchild", "deep-visible",+ ]);+ assert.equal(child.getAttribute("fold"), "1");+ assert.equal(sibling.getAttribute("fold"), "0");+ });++ it("preserves list folding and prunes headings inside containers without removing their attributes", () => {+ const foldedList = new HeadingElement({"data-type": "NodeListItem", fold: "1"})+ .append(paragraph("list-content"));+ const nestedHeading = heading("nested", 3, true);+ const attributes = new HeadingElement({class: "protyle-attr"});+ const quote = new HeadingElement({"data-type": "NodeBlockquote"})+ .append(nestedHeading, paragraph("hidden"), attributes);+ const content = new HeadingElement().append(heading("parent", 1, true), foldedList, quote);+ const result = getFocusedHeadingChildren(content.asFragment(), "parent");+ assert.equal(result.children.length, 2);+ assert.equal(foldedList.getAttribute("fold"), "1");+ assert.equal(foldedList.children.length, 1);+ assert.deepEqual(quote.children, [nestedHeading, attributes]);+ });++ it("accepts an empty heading and rejects mismatched or invalid responses without modifying them", () => {+ const empty = new HeadingElement().append(heading("parent", 1));+ const result = getFocusedHeadingChildren(empty.asFragment(), "parent");+ assert.equal(result.folded, false);+ assert.equal(result.children.length, 0);+ const wrong = new HeadingElement().append(heading("other", 1), paragraph("content"));+ assert.equal(getFocusedHeadingChildren(wrong.asFragment(), "parent"), undefined);+ assert.equal(wrong.children.length, 2);+ const invalid = new HeadingElement().append(paragraph("parent"));+ assert.equal(getFocusedHeadingChildren(invalid.asFragment(), "parent"), undefined);+ assert.equal(invalid.children.length, 1);+ assert.equal(getFocusedHeadingChildren(new HeadingElement().asFragment(), "parent"), undefined);+ });+});diff --git a/app/src/protyle/util/heading.ts b/app/src/protyle/util/heading.tsindex 283e264239..c3d19097bb 100644--- a/app/src/protyle/util/heading.ts+++ b/app/src/protyle/util/heading.ts@@ -13,3 +13,15 @@ export const removeFoldHeading = (nodeElement: Element) => {}}};++export const getFocusedHeadingChildren = (content: DocumentFragment, id: string) => {+ const heading = content.firstElementChild;+ if (heading?.getAttribute("data-node-id") !== id || heading.getAttribute("data-type") !== "NodeHeading") {+ return;+ }+ const folded = heading.getAttribute("fold") === "1";+ // 聚焦标题自身不参与筛选,子标题仍按普通编辑器的折叠规则省略下方内容。+ heading.remove();+ Array.from(content.querySelectorAll('[data-type="NodeHeading"][fold="1"]')).reverse().forEach(removeFoldHeading);+ return {folded, children: Array.from(content.children)};+};diff --git a/app/src/protyle/util/onGet.ts b/app/src/protyle/util/onGet.tsindex 64ed0ecdfb..af81d99cb9 100644--- a/app/src/protyle/util/onGet.ts+++ b/app/src/protyle/util/onGet.ts@@ -39,7 +39,7 @@ import {forEachPluginSubscriber} from "../../plugin/EventBusCore";import {disposeCustomBlocksInElement, setCustomBlockRootReady} from "../../plugin/customBlockRender";import {invalidateTrackedRanges, invalidateTrackedRangesInElement} from "./trackedRange";import {areProtylePluginExtensionsEnabled} from "../runtimeCapabilities";-import {applyFocusFold} from "./focusFold";+import {applyFocusFold} from "./viewFold";/// #if MOBILEimport {updateMobileTitleReadonly} from "./setEditMode";/// #endifdiff --git a/app/src/protyle/util/viewFold.ts b/app/src/protyle/util/viewFold.tsindex b3b5b15c19..7da8a6556a 100644--- a/app/src/protyle/util/viewFold.ts+++ b/app/src/protyle/util/viewFold.ts@@ -9,7 +9,10 @@ import {clearViewFoldOccurrenceRuntimeState,} from "./viewFoldRuntimeState";import {normalizeHTMLAssetIFrameBlockDOM} from "../../asset/html";-import {applyFocusFold, stopFocusFold, updateFocusFoldSource} from "./focusFold";+import {applyFocusFold as applyFocusFoldState, invalidateFocusFoldRequests, stopFocusFold, updateFocusFoldSource} from "./focusFold";+import {getFocusedHeadingChildren} from "./heading";+import {queueHeadingNumberRefresh, renderHeadingNumbers} from "./headingNumber";+import {updateDocumentBottomEof} from "./documentRange";const VIEW_FOLD_SOURCE = "data-view-fold-source";const VIEW_FOLD_VALUE = "data-view-fold";@@ -132,7 +135,7 @@ const getHeadingToken = (protyle: IProtyle, heading: Element) => {return encodeKeyPart(getViewFoldStateKey(protyle, heading) || heading.getAttribute("data-node-id"));};-const renderHeadingChildren = (protyle: IProtyle, heading: Element, children: Element[]) => {+const renderHeadingChildren = (protyle: IProtyle, heading: Element, children: Element[], insertAfter = heading) => {if (children.length === 0) {return;}@@ -143,7 +146,7 @@ const renderHeadingChildren = (protyle: IProtyle, heading: Element, children: Elchild.setAttribute(VIEW_HEADING_OWNER, token);fragment.appendChild(child);});- heading.after(fragment);+ insertAfter.after(fragment);children.forEach(child => {processRender(child);highlightRender(child);@@ -155,6 +158,60 @@ const renderHeadingChildren = (protyle: IProtyle, heading: Element, children: El}};+export const applyFocusFold = (protyle: IProtyle) => applyFocusFoldState(protyle, async (heading, isValid) => {+ if (!getSourceFold(heading) && getHeadingChildren(heading).length > 0) {+ return true;+ }+ const response = await fetchSyncPost("/api/block/getHeadingChildrenDOM", {+ id: heading.getAttribute("data-node-id"),+ removeFoldAttr: false,+ });+ if (!isValid() || response.code !== 0 || typeof response.data !== "string") {+ return false;+ }+ const template = document.createElement("template");+ template.innerHTML = normalizeHTMLAssetIFrameBlockDOM(response.data);+ const content = getFocusedHeadingChildren(template.content, heading.getAttribute("data-node-id"));+ if (!content) {+ return false;+ }+ updateFocusFoldSource(protyle, heading.getAttribute("data-node-id"), content.folded);+ const lastElement = protyle.wysiwyg.element.lastElementChild;+ const wasBottom = lastElement?.getAttribute("data-eof") === "2";+ const existing = new Map(getHeadingChildren(heading).map(element => [element.getAttribute("data-node-id"), element]));+ let previous = heading;+ let pending: Element[] = [];+ const flush = () => {+ if (pending.length > 0) {+ renderHeadingChildren(protyle, heading, pending, previous);+ previous = pending[pending.length - 1];+ pending = [];+ }+ };+ // 加载期间新增的块和已编辑的 DOM 保持原样,只按响应顺序补入缺少的子块。+ content.children.forEach(child => {+ const current = existing.get(child.getAttribute("data-node-id"));+ if (current) {+ flush();+ previous = current;+ } else {+ pending.push(child);+ }+ });+ flush();+ if (wasBottom && lastElement !== protyle.wysiwyg.element.lastElementChild) {+ lastElement.removeAttribute("data-eof");+ protyle.wysiwyg.element.lastElementChild.setAttribute("data-eof", "2");+ }+ updateDocumentBottomEof(protyle.wysiwyg.element);+ renderHeadingNumbers(protyle);+ queueHeadingNumberRefresh(protyle);+ if (protyle.options.render.scroll) {+ protyle.scroll.update(protyle);+ }+ return true;+});+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)) {@@ -319,6 +376,7 @@ export const clearViewFoldOccurrenceState = (protyle: IProtyle, occurrenceID: st};export const invalidateViewFoldRequests = (protyle: IProtyle) => {+ invalidateFocusFoldRequests(protyle);const context = viewFoldContexts.get(protyle);if (context) {context.generation = (context.generation || 0) + 1;@@ -370,10 +428,10 @@ export const setViewFoldTransient = async (protyle: IProtyle, element: Element,};export const applyViewFoldStates = async (protyle: IProtyle, scope?: ParentNode) => {- applyFocusFold(protyle);+ const focusRequest = applyFocusFold(protyle);const context = viewFoldContexts.get(protyle);if (!context) {- return;+ return focusRequest;}const root = scope || protyle.wysiwyg.element;const elements: Element[] = [];@@ -404,7 +462,7 @@ export const applyViewFoldStates = async (protyle: IProtyle, scope?: ParentNode)headings.push(ensureHeadingChildren(protyle, element, stateKey, true));}});- await Promise.all(headings);+ await Promise.all([...headings, focusRequest]);};const restoreViewFoldElement = (element: Element) => {