An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:zap: Improve large list rendering performance with virtual scrolling https://github.com/siyuan-note/siyuan/issues/13572
Daniel62b54aea262e
diff --git a/app/src/protyle/util/destroy.ts b/app/src/protyle/util/destroy.tsindex 443bfeac38..84df835f3d 100644--- a/app/src/protyle/util/destroy.ts+++ b/app/src/protyle/util/destroy.ts@@ -21,6 +21,7 @@ export const destroy = (protyle: IProtyle) => {protyle.element.classList.remove("protyle");protyle.element.removeAttribute("style");if (protyle.wysiwyg) {+ protyle.wysiwyg.destroy();protyle.wysiwyg.tableControl?.destroy();protyle.wysiwyg.lastHTMLs = {};}diff --git a/app/src/protyle/util/onGet.ts b/app/src/protyle/util/onGet.tsindex 480e6586cd..93612adf34 100644--- a/app/src/protyle/util/onGet.ts+++ b/app/src/protyle/util/onGet.ts@@ -234,6 +234,10 @@ const setHTML = (options: {});normalizeHTMLAssetIFrameSources(doc);updateWidgetCacheVersion(doc, Constants.SIYUAN_VERSION);+ protyle.wysiwyg.prepareLargeListVirtualization(+ doc.body,+ !options.action.includes(Constants.CB_GET_APPEND) && !options.action.includes(Constants.CB_GET_BEFORE)+ );options.content = doc.body.innerHTML;const REMOVED_OVER_HEIGHT = protyle.contentElement.clientHeight * 8;const updateReadonly = typeof options.updateReadonly === "undefined" ? protyle.wysiwyg.element.innerHTML === "" : options.updateReadonly;diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.tsindex 171e1e8e40..bcc4e5b17d 100644--- a/app/src/protyle/wysiwyg/index.ts+++ b/app/src/protyle/wysiwyg/index.ts@@ -194,6 +194,7 @@ import {isCrossBlockTextRange} from "../gutter/multiSelect";import {formatPainter} from "../toolbar/FormatPainter";import {shouldOpenListItemAttr} from "./listContext";import {getBlockEdgeCaretRange, isCaretRangeInsideElement} from "./blockEdgeCaret";+import {LargeListVirtualizer} from "./listVirtualization";interface IShiftClickBlockPoint {blockElement: HTMLElement;@@ -345,6 +346,7 @@ export class WYSIWYG {private inputTimeout: number;private pendingInputTimeouts = new Map<number, () => void | Promise<void>>();public tableControl: TableControl;+ private largeListVirtualizer?: LargeListVirtualizer;private scheduleInput(callback: () => void | Promise<void>, delay = 0, replace = true) {if (replace && this.inputTimeout) {@@ -462,10 +464,21 @@ export class WYSIWYG {if (protyle.options.action.includes(Constants.CB_GET_HISTORY)) {return;}+ if (!isMobile() && !protyle.options.backlinkData && !protyle.lite) {+ this.largeListVirtualizer = new LargeListVirtualizer(protyle.element, this.element, protyle.id);+ }keydown(protyle, this.element);dropEvent(protyle, this.element);}+ public destroy() {+ this.largeListVirtualizer?.destroy();+ }++ public prepareLargeListVirtualization(contentElement: Element, replace: boolean) {+ this.largeListVirtualizer?.prepare(contentElement, replace);+ }+public renderCustom(ial: Record<string, string>) {let isFullWidth = ial[Constants.CUSTOM_SY_FULLWIDTH];if (!isFullWidth) {diff --git a/app/src/protyle/wysiwyg/listVirtualization.test.ts b/app/src/protyle/wysiwyg/listVirtualization.test.tsnew file mode 100644index 0000000000..ebf55bb002--- /dev/null+++ b/app/src/protyle/wysiwyg/listVirtualization.test.ts@@ -0,0 +1,165 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {+ buildLargeListVirtualizationStyle,+ getListVirtualizationPlans,+ LARGE_LIST_CONTENT_BLOCK_THRESHOLD,+ type IListVirtualizationNodeState,+} from "./listVirtualization";++interface ITestNode {+ id?: string;+ type?: string;+ folded?: boolean;+ ignored?: boolean;+ children: ITestNode[];+}++const node = (type?: string, children: ITestNode[] = [], options?: {+ id?: string,+ folded?: boolean,+ ignored?: boolean,+}): ITestNode => ({+ type,+ id: options?.id,+ children,+ folded: options?.folded,+ ignored: options?.ignored,+});++const getState = (item: ITestNode): IListVirtualizationNodeState<ITestNode> => ({+ id: item.id,+ type: item.type,+ folded: item.folded,+ ignoreSubtree: item.ignored,+ children: item.children,+});++describe("large list virtualization", () => {+ it("starts after 192 content blocks", () => {+ const itemCount = LARGE_LIST_CONTENT_BLOCK_THRESHOLD / 2;+ const exactThreshold = node("NodeList", Array.from({length: itemCount}, () =>+ node("NodeListItem", [node("NodeParagraph")])+ ), {id: "exact"});+ const aboveThreshold = node("NodeList", [+ ...exactThreshold.children,+ node("NodeListItem", [node("NodeParagraph")]),+ ], {id: "above"});++ assert.deepEqual(getListVirtualizationPlans(exactThreshold, getState), []);+ assert.deepEqual(getListVirtualizationPlans(aboveThreshold, getState), [{+ listID: "above",+ excludedItemIDs: [],+ }]);+ });++ it("does not count container blocks but includes their content", () => {+ const list = node("NodeList", [+ node("NodeListItem", [+ node("NodeBlockquote", [node("NodeParagraph")]),+ node("NodeSuperBlock", [node("NodeParagraph")]),+ node("NodeCallout", [node("NodeParagraph")]),+ ]),+ ], {id: "list"});++ assert.deepEqual(getListVirtualizationPlans(list, getState, 3), [{+ listID: "list",+ excludedItemIDs: [],+ }]);+ assert.deepEqual(getListVirtualizationPlans(list, getState, 4), []);+ });++ it("skips folded descendants and rendered embed results", () => {+ const list = node("NodeList", [+ node("NodeListItem", [node("NodeParagraph"), node("NodeParagraph")], {folded: true}),+ node("NodeListItem", [+ node("NodeBlockQueryEmbed", [+ node(undefined, [node("NodeParagraph"), node("NodeParagraph")], {ignored: true}),+ ]),+ ]),+ ], {id: "list"});++ assert.deepEqual(getListVirtualizationPlans(list, getState, 3), []);+ assert.deepEqual(getListVirtualizationPlans(list, getState, 2), [{+ listID: "list",+ excludedItemIDs: [],+ }]);+ });++ it("virtualizes nested lists without containing their parent item", () => {+ const nested = node("NodeList", [node("NodeListItem"), node("NodeListItem")], {id: "nested"});+ const list = node("NodeList", [node("NodeListItem", [nested], {id: "parent"})], {id: "outer"});+ const plans = getListVirtualizationPlans(list, getState, 1);++ assert.deepEqual(plans, [{+ listID: "nested",+ excludedItemIDs: [],+ }, {+ listID: "outer",+ excludedItemIDs: ["parent"],+ }]);+ });++ it("does not exclude a folded item whose nested list is hidden", () => {+ const nested = node("NodeList", [node("NodeListItem"), node("NodeListItem")], {id: "nested"});+ const list = node("NodeList", [+ node("NodeListItem", [nested], {id: "parent", folded: true}),+ node("NodeListItem", [], {id: "sibling"}),+ ], {id: "outer"});++ assert.deepEqual(getListVirtualizationPlans(list, getState, 1), [{+ listID: "outer",+ excludedItemIDs: [],+ }]);+ });++ it("skips an outer plan when its nested parent item has no ID", () => {+ const nested = node("NodeList", [node("NodeListItem"), node("NodeListItem")], {id: "nested"});+ const list = node("NodeList", [node("NodeListItem", [nested])], {id: "outer"});++ assert.deepEqual(getListVirtualizationPlans(list, getState, 1), [{+ listID: "nested",+ excludedItemIDs: [],+ }]);+ });++ it("excludes only the outer item that contains a deeply nested list", () => {+ const nested = node("NodeList", [node("NodeListItem"), node("NodeListItem")], {id: "nested"});+ const list = node("NodeList", [+ node("NodeListItem", [node("NodeBlockquote", [nested])], {id: "parent"}),+ node("NodeListItem", [], {id: "sibling"}),+ ], {id: "outer"});+ const plans = getListVirtualizationPlans(list, getState, 1);++ assert.deepEqual(plans, [{+ listID: "nested",+ excludedItemIDs: [],+ }, {+ listID: "outer",+ excludedItemIDs: ["parent"],+ }]);+ });++ it("builds screen-only rules without changing block DOM", () => {+ const style = buildLargeListVirtualizationStyle("scope", [{+ listID: "list-b",+ excludedItemIDs: [],+ }, {+ listID: "list-a",+ excludedItemIDs: ["parent"],+ }, {+ listID: "list-a",+ excludedItemIDs: ["parent-2"],+ }]);++ assert.match(style, /^@supports/);+ assert.match(style, /@media screen/);+ assert.ok(style.indexOf('data-node-id="list-a"') < style.indexOf('data-node-id="list-b"'));+ assert.match(style, /content-visibility: auto/);+ assert.match(style, /contain-intrinsic-block-size: auto/);+ assert.match(style, /protyle-wysiwyg__embed[^\n]+data-node-id="list-a"/);+ assert.match(style, /data-node-id="parent"/);+ assert.match(style, /data-node-id="parent-2"/);+ assert.match(style, /content-visibility: visible/);+ });+});diff --git a/app/src/protyle/wysiwyg/listVirtualization.ts b/app/src/protyle/wysiwyg/listVirtualization.tsnew file mode 100644index 0000000000..f0f69015d4--- /dev/null+++ b/app/src/protyle/wysiwyg/listVirtualization.ts@@ -0,0 +1,195 @@+export const LARGE_LIST_CONTENT_BLOCK_THRESHOLD = 192;++const LIST_VIRTUALIZATION_SCOPE_ATTRIBUTE = "data-list-virtualization-scope";+const EXCLUDED_CONTAINER_TYPES = new Set([+ "NodeList",+ "NodeBlockquote",+ "NodeSuperBlock",+ "NodeCallout",+]);++export interface IListVirtualizationNodeState<T> {+ id?: string;+ type?: string;+ folded?: boolean;+ ignoreSubtree?: boolean;+ children: ArrayLike<T>;+}++export interface IListVirtualizationPlan {+ listID: string;+ excludedItemIDs: string[];+}++// 一次后序遍历同时统计内容块并识别嵌套列表,避免对每个列表重复扫描后代。+export const getListVirtualizationPlans = <T>(+ root: T,+ getState: (node: T) => IListVirtualizationNodeState<T>,+ threshold = LARGE_LIST_CONTENT_BLOCK_THRESHOLD,+) => {+ const plans: IListVirtualizationPlan[] = [];+ const maxCount = threshold + 1;+ const scan = (node: T, state = getState(node)): { count: number, containsList: boolean } => {+ if (state.ignoreSubtree) {+ return {count: 0, containsList: false};+ }++ const counted = state.type?.startsWith("Node") && !EXCLUDED_CONTAINER_TYPES.has(state.type);+ let count = counted ? 1 : 0;+ if (counted && state.folded) {+ return {count, containsList: false};+ }++ let containsList = state.type === "NodeList";+ const excludedItemIDs: string[] = [];+ let hasUnaddressableNestedItem = false;+ for (let i = 0; i < state.children.length; i++) {+ const child = state.children[i];+ const childState = getState(child);+ const childResult = scan(child, childState);+ count = Math.min(maxCount, count + childResult.count);+ containsList ||= childResult.containsList;+ if (state.type === "NodeList" && childState.type === "NodeListItem" && childResult.containsList) {+ if (childState.id) {+ excludedItemIDs.push(childState.id);+ } else {+ hasUnaddressableNestedItem = true;+ }+ }+ }+ if (state.type === "NodeList" && state.id && count > threshold && !hasUnaddressableNestedItem) {+ plans.push({+ listID: state.id,+ excludedItemIDs,+ });+ }+ return {count, containsList};+ };+ scan(root);+ return plans;+};++const getElementState = (element: Element): IListVirtualizationNodeState<Element> => ({+ id: element.getAttribute("data-node-id") || undefined,+ type: element.hasAttribute("data-node-id") ? element.getAttribute("data-type") : undefined,+ folded: element.getAttribute("fold") === "1",+ ignoreSubtree: element.classList.contains("protyle-wysiwyg__embed"),+ children: element.children,+});++const escapeCSSAttributeValue = (value: string) => value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');++// 样式放在块 DOM 之外,保证序列化、事务和插件读取到的仍是完整内容。+export const buildLargeListVirtualizationStyle = (scope: string, plans: Iterable<IListVirtualizationPlan>) => {+ const escapedScope = escapeCSSAttributeValue(scope);+ const selectorPrefix = `[${LIST_VIRTUALIZATION_SCOPE_ATTRIBUTE}="${escapedScope}"] > ` ++ ".protyle-content > .protyle-wysiwyg";+ const normalizedPlans = new Map<string, Set<string>>();+ for (const plan of plans) {+ const excludedItemIDs = normalizedPlans.get(plan.listID) || new Set<string>();+ plan.excludedItemIDs.forEach((id) => excludedItemIDs.add(id));+ normalizedPlans.set(plan.listID, excludedItemIDs);+ }+ const autoSelectors: string[] = [];+ const visibleSelectors: string[] = [];+ Array.from(normalizedPlans).sort(([idA], [idB]) => idA.localeCompare(idB)).forEach(([listID, excludedItemIDs]) => {+ const escapedListID = escapeCSSAttributeValue(listID);+ const listSelector = `[data-type="NodeList"][data-node-id="${escapedListID}"]`;+ autoSelectors.push(`${selectorPrefix} ${listSelector} > [data-type="NodeListItem"]`);+ visibleSelectors.push(`${selectorPrefix} .protyle-wysiwyg__embed ${listSelector} > [data-type="NodeListItem"]`);+ Array.from(excludedItemIDs).sort().forEach((itemID) => {+ const escapedItemID = escapeCSSAttributeValue(itemID);+ visibleSelectors.push(`${selectorPrefix} ${listSelector} > ` ++ `[data-type="NodeListItem"][data-node-id="${escapedItemID}"]`);+ });+ });+ if (autoSelectors.length === 0) {+ return "";+ }+ return `@supports (content-visibility: auto) and (contain-intrinsic-block-size: auto 1px) {+@media screen {+${autoSelectors.join(",\n")} {+ content-visibility: auto;+ contain-intrinsic-block-size: auto calc(1.625em + 8px);+}+${visibleSelectors.join(",\n")} {+ content-visibility: visible;+ contain-intrinsic-block-size: none;+}+}+}`;+};++export class LargeListVirtualizer {+ private readonly rootElement: HTMLElement;+ private readonly wysiwygElement: HTMLElement;+ private readonly scope: string;+ private readonly styleElement: HTMLStyleElement;+ private readonly observer: MutationObserver;+ private virtualizedPlans: IListVirtualizationPlan[] = [];+ private refreshFrame = 0;++ constructor(rootElement: HTMLElement, wysiwygElement: HTMLElement, scope: string) {+ this.rootElement = rootElement;+ this.wysiwygElement = wysiwygElement;+ this.scope = scope;+ this.rootElement.setAttribute(LIST_VIRTUALIZATION_SCOPE_ATTRIBUTE, scope);+ this.styleElement = document.createElement("style");+ this.styleElement.dataset.listVirtualization = scope;+ this.rootElement.appendChild(this.styleElement);++ this.observer = new MutationObserver((records) => {+ if (records.length > 0) {+ // 同一帧内的编辑变更只触发一次完整扫描。+ this.scheduleRefresh();+ }+ });+ this.observer.observe(this.wysiwygElement, {+ attributes: true,+ attributeFilter: ["data-node-id", "data-type", "fold"],+ childList: true,+ subtree: true,+ });+ this.refresh(this.wysiwygElement, true);+ }++ public prepare(contentElement: Element, replace: boolean) {+ this.refresh(contentElement, replace);+ }++ public destroy() {+ this.observer.disconnect();+ if (this.refreshFrame) {+ cancelAnimationFrame(this.refreshFrame);+ this.refreshFrame = 0;+ }+ this.styleElement.remove();+ if (this.rootElement.getAttribute(LIST_VIRTUALIZATION_SCOPE_ATTRIBUTE) === this.scope) {+ this.rootElement.removeAttribute(LIST_VIRTUALIZATION_SCOPE_ATTRIBUTE);+ }+ this.virtualizedPlans = [];+ }++ private scheduleRefresh() {+ if (this.refreshFrame) {+ return;+ }+ this.refreshFrame = requestAnimationFrame(() => {+ this.refreshFrame = 0;+ this.refresh(this.wysiwygElement, true);+ });+ }++ private refresh(contentElement: Element, replace: boolean) {+ const nextPlans = getListVirtualizationPlans(contentElement, getElementState);+ if (!replace) {+ nextPlans.push(...this.virtualizedPlans);+ }+ const nextStyle = buildLargeListVirtualizationStyle(this.scope, nextPlans);+ if (nextStyle === this.styleElement.textContent) {+ return;+ }+ this.virtualizedPlans = nextPlans;+ this.styleElement.textContent = nextStyle;+ }+}