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 table rendering performance https://github.com/siyuan-note/siyuan/issues/19911
Danielf34a0ac89eea
diff --git a/app/src/protyle/render/searchMarkRender.ts b/app/src/protyle/render/searchMarkRender.tsindex 09899532b5..75df5cbb61 100644--- a/app/src/protyle/render/searchMarkRender.ts+++ b/app/src/protyle/render/searchMarkRender.ts@@ -1,5 +1,6 @@import {Constants} from "../../constants";import {isInEmbedBlock} from "../util/hasClosest";+import {restoreTableVirtualizationDOM} from "../util/tableVirtualizationDOM";export const searchMarkRender = (protyle: IProtyle, keys: string[], hlId?: string | number, cb?: () => void,options?: {@@ -11,6 +12,7 @@ export const searchMarkRender = (protyle: IProtyle, keys: string[], hlId?: strinreturn;}setTimeout(() => {+ restoreTableVirtualizationDOM(protyle.wysiwyg.element);protyle.highlight.markHL.clear();protyle.highlight.mark.clear();protyle.highlight.rangeIndex = 0;diff --git a/app/src/protyle/render/setLute.ts b/app/src/protyle/render/setLute.tsindex 17c62b29e1..d38d67c2fe 100644--- a/app/src/protyle/render/setLute.ts+++ b/app/src/protyle/render/setLute.ts@@ -1,5 +1,6 @@import {applyLuteMarkdownSyntax} from "./luteMarkdownSyntax";import {protectLuteInlineElementBoundaries} from "../util/inlineElementBoundary";+import {protectLuteTableVirtualization} from "../util/tableVirtualizationDOM";// Lute 配置全部读取全局 window.siyuan.config / window.siyuan.emojis,跨编辑器一致,// 因此所有 Protyle 编辑器共用同一个 Lute 实例,将内存与初始化开销从 O(编辑器数) 降为 O(1)。@@ -83,7 +84,7 @@ export const getAgentLute = (options: ILuteOptions): Lute => {lute.SetExportNormalizeTaskListMarker(true);lute.SetArbitraryTaskListItemMarker(true);lute.SetEnsureListItemParagraph(true);- return protectLuteInlineElementBoundaries(lute);+ return protectLuteTableVirtualization(protectLuteInlineElementBoundaries(lute));};/**@@ -137,5 +138,5 @@ const setLute = (options: ILuteOptions) => {lute.SetExportNormalizeTaskListMarker(true);lute.SetArbitraryTaskListItemMarker(true);lute.SetEnsureListItemParagraph(true); // 空列表项下创建子列表前补一个空段落- return protectLuteInlineElementBoundaries(lute);+ return protectLuteTableVirtualization(protectLuteInlineElementBoundaries(lute));};diff --git a/app/src/protyle/render/tableCellInput.test.ts b/app/src/protyle/render/tableCellInput.test.tsindex 369a0ff9b1..bbd88a9bc9 100644--- a/app/src/protyle/render/tableCellInput.test.ts+++ b/app/src/protyle/render/tableCellInput.test.ts@@ -293,7 +293,7 @@ test("table cell editors wait for outer input and table menu Enter is consumed",.includes(declaration.name.getText(selection)))).map(statement => statement.getText(selection)).join("\n");const source = ["../util/longTextWrap.ts", "../util/inlineElementBoundary.ts", "../toolbar/fontFamilyCore.ts",- "../../util/escape.ts", "setLute.ts", "../wysiwyg/codeBlockUtil.ts", "av/richTextValue.ts", "av/richText.ts",+ "../../util/escape.ts", "../util/tableVirtualizationDOM.ts", "setLute.ts", "../wysiwyg/codeBlockUtil.ts", "av/richTextValue.ts", "av/richText.ts","../wysiwyg/taskListMarker.ts", "../util/tableCellRichLute.ts", "../util/tableCellRichValue.ts", "../util/tableCellRich.ts","../util/hasClosest.ts", "../wysiwyg/getBlock.ts", "../util/table.ts", "../wysiwyg/input.ts"].map(file => compile(read(file))).join("\n") + "\n" + compile(selectionSource);diff --git a/app/src/protyle/util/onGet.ts b/app/src/protyle/util/onGet.tsindex c85987581d..556df89043 100644--- a/app/src/protyle/util/onGet.ts+++ b/app/src/protyle/util/onGet.ts@@ -269,7 +269,7 @@ const setHTML = (options: {});normalizeHTMLAssetIFrameSources(doc);updateWidgetCacheVersion(doc, Constants.SIYUAN_VERSION);- protyle.wysiwyg.prepareLargeListVirtualization(+ protyle.wysiwyg.prepareBlockVirtualization(doc.body,!options.action.includes(Constants.CB_GET_APPEND) && !options.action.includes(Constants.CB_GET_BEFORE));diff --git a/app/src/protyle/util/tableCellRichLute.test.ts b/app/src/protyle/util/tableCellRichLute.test.tsindex 35f6bdd3b3..6566d0e165 100644--- a/app/src/protyle/util/tableCellRichLute.test.ts+++ b/app/src/protyle/util/tableCellRichLute.test.ts@@ -527,7 +527,7 @@ test("table cells insert code through slash and Enter without losing soft breaks.replace(/^export /gm, ""), {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;const read = (file: string) => readFileSync(path.join(__dirname, file), "utf8");const source = ["longTextWrap.ts", "inlineElementBoundary.ts", "../toolbar/fontFamilyCore.ts", "../../util/escape.ts",- "../render/setLute.ts", "../wysiwyg/codeBlockUtil.ts", "../render/av/richTextValue.ts", "../render/av/richText.ts",+ "tableVirtualizationDOM.ts", "../render/setLute.ts", "../wysiwyg/codeBlockUtil.ts", "../render/av/richTextValue.ts", "../render/av/richText.ts","../wysiwyg/taskListMarker.ts", "../wysiwyg/codeBlockEnter.ts", "tableCellRichLute.ts", "tableCellRichValue.ts","tableCellRich.ts"].map(file => compile(read(file))).join("\n");const hint = createSourceFile("hint.ts", read("../hint/index.ts"), ScriptTarget.Latest, true);diff --git a/app/src/protyle/util/tableControl.ts b/app/src/protyle/util/tableControl.tsindex c630be7ba5..15b562d625 100644--- a/app/src/protyle/util/tableControl.ts+++ b/app/src/protyle/util/tableControl.ts@@ -1,4 +1,6 @@import {MenuItem} from "../../menus/Menu";+import {getTableGridRect, TableGridCache} from "./tableGridCache";+import {TABLE_VIRTUAL_ID} from "./tableVirtualizationDOM";import {clearTableCellContent, getTableCellPlainText, mergeTableCellContents} from "./tableCellRich";import {renderTableCellRichElements} from "../render/tableCellRich";import {updateTransaction} from "../wysiwyg/transaction";@@ -342,6 +344,11 @@ export class TableControl {private selectionElementIndex = 0;private selectedCells: HTMLTableCellElement[] = [];private selectionGrid: ITableGrid;+ private gridCache = new TableGridCache(table => {+ const grid = buildTableGrid(table);+ return {grid, cells: new Map(grid.cellInfos.map(info => [info.cell, info])),+ merged: grid.cellInfos.some(info => info.rowspan > 1 || info.colspan > 1)};+ });private frame: number;private dragState: IDragState;private resizeState: IResizeState;@@ -441,6 +448,7 @@ export class TableControl {this.cancelResize();this.abortController.abort();this.observer.disconnect();+ this.gridCache.destroy();this.pinnedTableResizeObserver.disconnect();this.pinnedTableActions.forEach(action => this.clearPinnedTableFrame(action));this.pinnedTableActions.clear();@@ -1086,26 +1094,7 @@ export class TableControl {return Math.max(table.getBoundingClientRect().bottom, table.parentElement.getBoundingClientRect().bottom);}- private getTableGridRect(table: HTMLTableElement) {- const rowRects = Array.from(table.rows).map(row => row.getBoundingClientRect()).filter(rect => rect.height > 0);- if (rowRects.length === 0) {- return table.getBoundingClientRect();- }- const left = Math.min(...rowRects.map(rect => rect.left));- const top = Math.min(...rowRects.map(rect => rect.top));- const right = Math.max(...rowRects.map(rect => rect.right));- const bottom = Math.max(...rowRects.map(rect => rect.bottom));- return {- left,- top,- right,- bottom,- width: right - left,- height: bottom - top,- };- }-- private getTableGridViewportRect(table: HTMLTableElement, gridRect = this.getTableGridRect(table)) {+ private getTableGridViewportRect(table: HTMLTableElement, gridRect = getTableGridRect(table)) {return intersectRects(this.getTableViewportRect(table), gridRect);}@@ -1140,15 +1129,14 @@ export class TableControl {private getEdgeHover(clientX: number, clientY: number) {const candidates: ITableEdgeHover[] = [];this.wysiwygElement.querySelectorAll<HTMLTableElement>('[data-type="NodeTable"] table').forEach(table => {- if (table.closest(".protyle-custom, .mindmap-view__preview-block")) {+ if (table.hasAttribute(TABLE_VIRTUAL_ID) || table.closest(".protyle-custom, .mindmap-view__preview-block")) {return;}- const gridRect = this.getTableGridRect(table);+ const gridRect = getTableGridRect(table);const addColumnEdge = gridRect.right;const viewportRect = this.getTableGridViewportRect(table, gridRect);const addRowEdge = this.getTableAddRowEdge(table);const contentRect = (this.protyle.contentElement || this.protyle.element).getBoundingClientRect();- const grid = buildTableGrid(table);const columnControlVisible = addColumnEdge <= viewportRect.right + 1 &&isTableResizeControlVisible(addColumnEdge, contentRect.right, TABLE_ADD_CONTROL_THICKNESS,TABLE_ADD_CONTROL_GAP);@@ -1158,7 +1146,7 @@ export class TableControl {clientX <= addColumnEdge + TABLE_ADD_CONTROL_GAP + TABLE_ADD_CONTROL_THICKNESS &&clientY >= addRowEdge &&clientY <= addRowEdge + TABLE_ADD_CONTROL_GAP + TABLE_ADD_CONTROL_THICKNESS) {- const cell = grid.cellInfos[0]?.cell;+ const cell = this.gridCache.get(table).grid.cellInfos[0]?.cell;if (cell) {candidates.push({cell,@@ -1171,7 +1159,7 @@ export class TableControl {clientX >= addColumnEdge &&clientX <= addColumnEdge + TABLE_ADD_CONTROL_GAP + TABLE_ADD_CONTROL_THICKNESS &&clientY >= viewportRect.top && clientY <= viewportRect.bottom) {- const cell = grid.cellInfos[0]?.cell;+ const cell = this.gridCache.get(table).grid.cellInfos[0]?.cell;if (cell) {candidates.push({cell,@@ -1184,7 +1172,7 @@ export class TableControl {clientY >= addRowEdge &&clientY <= addRowEdge + TABLE_ADD_CONTROL_GAP + TABLE_ADD_CONTROL_THICKNESS &&clientX >= viewportRect.left && clientX <= viewportRect.right) {- const cell = grid.cellInfos[0]?.cell;+ const cell = this.gridCache.get(table).grid.cellInfos[0]?.cell;if (cell) {candidates.push({cell,@@ -1252,7 +1240,7 @@ export class TableControl {item.classList.remove("protyle-table-control__add--active");});this.selectionElements.forEach(item => item.classList.add("fn__none"));- const gridRect = this.getTableGridRect(state.table);+ const gridRect = getTableGridRect(state.table);const addColumnEdge = gridRect.right;const viewportRect = this.getTableGridViewportRect(state.table, gridRect);const tableViewportRect = this.getTableViewportRect(state.table);@@ -1352,7 +1340,7 @@ export class TableControl {const cell = hoverCell || caretCell || selectionCell;const node = getTableNode(cell);const table = cell?.closest("table") as HTMLTableElement;- const visible = !!cell && !!node && !!table && !this.protyle.disabled;+ const visible = !!cell && !!node && !!table && !table.hasAttribute(TABLE_VIRTUAL_ID) && !this.protyle.disabled;[this.rowHandle, this.columnHandle, this.cellHandle, this.addRowButton, this.addColumnButton,this.addBothButton].forEach(item => {item.classList.add("fn__none");@@ -1360,7 +1348,7 @@ export class TableControl {});this.resizeLabel.classList.add("fn__none");if (visible) {- const gridRect = this.getTableGridRect(table);+ const gridRect = getTableGridRect(table);const addColumnEdge = gridRect.right;const viewportRect = this.getTableGridViewportRect(table, gridRect);const tableViewportRect = this.getTableViewportRect(table);@@ -1371,9 +1359,9 @@ export class TableControl {const columnControlVisible = addColumnEdge <= viewportRect.right + 1 &&isTableResizeControlVisible(addColumnEdge, contentRect.right, TABLE_ADD_CONTROL_THICKNESS,TABLE_ADD_CONTROL_GAP);- const grid = this.selection?.table === table && this.selectionGrid ?- this.selectionGrid : buildTableGrid(table);- const cellInfo = grid.cellInfos.find(item => item.cell === cell);+ const cached = this.gridCache.get(table);+ const grid = this.selection?.table === table && this.selectionGrid ? this.selectionGrid : cached.grid;+ const cellInfo = grid === cached.grid ? cached.cells.get(cell) : grid.cellInfos.find(item => item.cell === cell);const rowIndex = cellInfo?.row;const rowRect = typeof rowIndex === "number" ? table.rows[rowIndex]?.getBoundingClientRect() : undefined;const visibleRowRect = rowRect ? intersectRects(rowRect, viewportRect) : undefined;@@ -1381,7 +1369,7 @@ export class TableControl {const columnRect = typeof columnIndex === "number" ?this.getColumnRect(table, grid, columnIndex) : undefined;const visibleColumnRect = columnRect ? intersectRects(columnRect, viewportRect) : undefined;- const merged = grid.cellInfos.some(info => info.rowspan > 1 || info.colspan > 1);+ const merged = grid === cached.grid ? cached.merged : grid.cellInfos.some(info => info.rowspan > 1 || info.colspan > 1);this.rowHandle.classList.toggle("protyle-table-control__handle--drag-disabled", merged ||(this.selection?.table === table && this.selection.mode === "row" &&this.selection.indexes.size > 1 && this.selection.indexes.has(0)));@@ -1430,7 +1418,8 @@ export class TableControl {rowControlCenter);}}- if (!this.dragState && !this.selection && caretCell && getTableNode(caretCell) && !this.protyle.disabled) {+ if (!this.dragState && !this.selection && caretCell && getTableNode(caretCell) &&+ !caretCell.closest(`table[${TABLE_VIRTUAL_ID}]`) && !this.protyle.disabled) {const table = caretCell.closest("table") as HTMLTableElement;const viewportRect = table ? this.getTableGridViewportRect(table) : undefined;if (viewportRect) {@@ -1445,7 +1434,7 @@ export class TableControl {this.selectedCells = [];return;}- const selectionGridRect = this.getTableGridRect(this.selection.table);+ const selectionGridRect = getTableGridRect(this.selection.table);const selectionViewportRect = intersectRects(this.getTableViewportRect(this.selection.table), selectionGridRect);if (this.selection.mode === "row") {diff --git a/app/src/protyle/util/tableGridCache.ts b/app/src/protyle/util/tableGridCache.tsnew file mode 100644index 0000000000..34516b9a8f--- /dev/null+++ b/app/src/protyle/util/tableGridCache.ts@@ -0,0 +1,61 @@+// 网格只依赖单元格结构,滚动和文字编辑不需要重新构建。+export class TableGridCache<T> {+ private entries = new Map<HTMLTableElement, {observer: MutationObserver, value?: T}>();++ constructor(private build: (table: HTMLTableElement) => T) {+ }++ public get(table: HTMLTableElement): T {+ this.entries.forEach((entry, candidate) => {+ if (!candidate.isConnected) {+ entry.observer.disconnect();+ this.entries.delete(candidate);+ }+ });+ let entry = this.entries.get(table);+ if (!entry) {+ entry = {observer: new MutationObserver(records => {+ if (this.affectsGrid(records)) {+ entry.value = undefined;+ }+ })};+ entry.observer.observe(table, {childList: true, subtree: true, attributes: true,+ attributeFilter: ["rowspan", "colspan", "class"]});+ this.entries.set(table, entry);+ }+ // 同一事件中修改结构后立即读取时,观察回调尚未执行。+ if (this.affectsGrid(entry.observer.takeRecords())) {+ entry.value = undefined;+ }+ if (!entry.value) {+ entry.value = this.build(table);+ }+ return entry.value;+ }++ private affectsGrid(records: MutationRecord[]) {+ return records.some(record => record.type === "attributes" ?+ (record.target as Element).matches("td, th") :+ [...record.addedNodes, ...record.removedNodes].some(node => node instanceof Element &&+ (node.matches("tr, td, th, thead, tbody, tfoot") || !!node.querySelector("tr, td, th"))));+ }++ public destroy() {+ this.entries.forEach(entry => entry.observer.disconnect());+ this.entries.clear();+ }+}++// 表格分区的边界覆盖全部行,测量次数不随行数增长,并保留固定表头的独立位置。+export const getTableGridRect = (table: HTMLTableElement) => {+ const rects = Array.from(table.children).filter(section => ["THEAD", "TBODY", "TFOOT"].includes(section.tagName))+ .map(section => section.getBoundingClientRect()).filter(rect => rect.height > 0);+ if (rects.length === 0) {+ return table.getBoundingClientRect();+ }+ const left = Math.min(...rects.map(rect => rect.left));+ const top = Math.min(...rects.map(rect => rect.top));+ const right = Math.max(...rects.map(rect => rect.right));+ const bottom = Math.max(...rects.map(rect => rect.bottom));+ return {left, top, right, bottom, width: right - left, height: bottom - top};+};diff --git a/app/src/protyle/util/tableVirtualizationDOM.ts b/app/src/protyle/util/tableVirtualizationDOM.tsnew file mode 100644index 0000000000..e22bbb312e--- /dev/null+++ b/app/src/protyle/util/tableVirtualizationDOM.ts@@ -0,0 +1,48 @@+export const TABLE_VIRTUAL_ROWS = "data-sy-table-virtual-rows";+export const TABLE_VIRTUAL_ID = "data-sy-table-virtual-id";+export const TABLE_VIRTUAL_COLUMNS = "data-sy-table-virtual-columns";++// 占位行携带完整源内容,克隆、撤销快照和编辑器销毁后仍能独立还原。+export const restoreTableVirtualizationDOM = (root: ParentNode) => {+ root.querySelectorAll<HTMLTableRowElement>(`tr[${TABLE_VIRTUAL_ROWS}]`).forEach(placeholder => {+ const table = document.createElement("table");+ const body = table.createTBody();+ body.innerHTML = placeholder.getAttribute(TABLE_VIRTUAL_ROWS);+ placeholder.replaceWith(...Array.from(body.childNodes));+ });+ root.querySelectorAll(`[${TABLE_VIRTUAL_COLUMNS}]`).forEach(columns => {+ const table = document.createElement("table");+ table.innerHTML = columns.getAttribute(TABLE_VIRTUAL_COLUMNS);+ columns.replaceWith(...Array.from(table.childNodes));+ });+ root.querySelectorAll(`[${TABLE_VIRTUAL_ID}]`).forEach(table => table.removeAttribute(TABLE_VIRTUAL_ID));+ if (root instanceof Element) {+ root.removeAttribute(TABLE_VIRTUAL_ID);+ }+};++export const cleanTableVirtualizationHTML = (html: string): string => {+ if (!html.includes(TABLE_VIRTUAL_ROWS) && !html.includes(TABLE_VIRTUAL_ID) && !html.includes(TABLE_VIRTUAL_COLUMNS)) {+ return html;+ }+ const template = document.createElement("template");+ template.innerHTML = html;+ restoreTableVirtualizationDOM(template.content);+ return template.innerHTML;+};++// 所有消费块 DOM 的转换都先恢复源内容,避免占位行进入 Markdown、导出或表格变换。+export const protectLuteTableVirtualization = (lute: Lute): Lute => new Proxy(lute, {+ get(target, property) {+ const value = Reflect.get(target, property);+ if (typeof value !== "function") {+ return value;+ }+ return (...args: unknown[]) => {+ if (typeof args[0] === "string") {+ args[0] = cleanTableVirtualizationHTML(args[0]);+ }+ return value.apply(target, args);+ };+ },+});diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.tsindex 2e874ee19b..9c88362be2 100644--- a/app/src/protyle/wysiwyg/index.ts+++ b/app/src/protyle/wysiwyg/index.ts@@ -236,6 +236,7 @@ import {formatPainter} from "../toolbar/FormatPainter";import {shouldFoldEmbeddedListByAlt, shouldOpenListItemAttr} from "./listContext";import {getBlockEdgeCaretRange, isCaretRangeInsideElement} from "./blockEdgeCaret";import {LargeListVirtualizer} from "./listVirtualization";+import {LargeTableVirtualizer} from "./tableVirtualization";import {forEachPluginSubscriber} from "../../plugin/EventBusCore";import {areProtylePluginExtensionsEnabled} from "../runtimeCapabilities";import {syncRootAttributes} from "../util/syncRootAttributes";@@ -405,6 +406,7 @@ export class WYSIWYG {private persistComposition?: () => void;public tableControl: TableControl;private largeListVirtualizer?: LargeListVirtualizer;+ private largeTableVirtualizer?: LargeTableVirtualizer;private disposeSpellcheckFocus?: () => void;private disposeEmbedToolbarVisibility?: () => void;private disposeHeadingFoldIndicators?: () => void;@@ -584,10 +586,21 @@ export class WYSIWYG {this.disposeSpellcheckFocus?.();this.disposeBoundedBlockDragSelect?.();this.largeListVirtualizer?.destroy();+ this.largeTableVirtualizer?.destroy();}- public prepareLargeListVirtualization(contentElement: Element, replace: boolean) {+ public prepareBlockVirtualization(contentElement: Element, replace: boolean) {this.largeListVirtualizer?.prepare(contentElement, replace);+ const protyle = this.protyle;+ // 此时 initUI 已创建正文滚动容器,桌面和移动端共用表格窗口。+ if (!this.largeTableVirtualizer && !protyle.options.backlinkData && !protyle.lite) {+ this.largeTableVirtualizer = new LargeTableVirtualizer(protyle.element, this.element, protyle.contentElement,+ () => !!protyle.highlight?.ranges?.length ||+ this.pendingInputTimeouts.size > 0 || this.runningInputTasks.size > 0 ||+ !!this.tableControl?.getSelectedCells().length ||+ !!window.siyuan.menus?.menu?.element && !window.siyuan.menus.menu.element.classList.contains("fn__none") ||+ !!window.siyuan.dragElement || !!this.element.querySelector(".protyle-wysiwyg--select"));+ }}public renderCustom(ial: Record<string, string>) {diff --git a/app/src/protyle/wysiwyg/tableVirtualization.test.ts b/app/src/protyle/wysiwyg/tableVirtualization.test.tsnew file mode 100644index 0000000000..055c3f18d2--- /dev/null+++ b/app/src/protyle/wysiwyg/tableVirtualization.test.ts@@ -0,0 +1,319 @@+import * as assert from "node:assert/strict";+import {execFile} from "node:child_process";+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";+import {tmpdir} from "node:os";+import * as path from "node:path";+import {test} from "node:test";+import {promisify} from "node:util";+import {createSourceFile, isClassDeclaration, isVariableStatement, ScriptTarget, transpileModule} from "typescript";++const browserCases = async (source: string, css: string) => {+ const check: typeof assert = require("node:assert/strict");+ const api = new Function("Constants", "isInEmbedBlock", source ++ "\nreturn {LargeTableVirtualizer, cleanTableVirtualizationHTML, protectLuteTableVirtualization, " ++ "restoreTableVirtualizationDOM, TableGridCache, buildTableGrid, getTableGridRect, searchMarkRender, " ++ "cleanBlockSelectionModeOperations, createEditor: protyle => new VirtualizedEditor(protyle)};")({TIMEOUT_TRANSITION: 0}, () => false) as+ typeof import("./tableVirtualization") & typeof import("../util/tableVirtualizationDOM") &+ typeof import("../util/tableGridCache") & typeof import("../util/table") & typeof import("../render/searchMarkRender") & {+ cleanBlockSelectionModeOperations: (operations: IOperation[]) => void,+ createEditor: (protyle: IProtyle) => {+ prepareBlockVirtualization: (content: Element, replace: boolean) => void,+ virtualizer: import("./tableVirtualization").LargeTableVirtualizer,+ pending: Map<number, () => void>,+ },+ };+ Object.assign(window, {siyuan: {}});+ const tick = () => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => setTimeout(resolve, 30))));+ const style = document.createElement("style");+ style.textContent = css + `+body {margin:0; --b3-theme-surface-lighter:#ddd; --b3-font-size-editor:16px; --b3-border-radius-s:4px;}+.test-viewport {height:420px;width:640px;overflow:auto;}+.protyle-wysiwyg {font-size:16px;line-height:26px;padding:0;}+.table > div {overflow:auto;}+.table[custom-pinthead="true"] > div {max-height:300px;}+.table[custom-pinthead="true"] thead {position:sticky;top:0;}+.table tbody > tr:nth-child(even) {background-color:rgb(12, 34, 56);}+`;+ document.head.appendChild(style);+ const fixture = (count = 2000, pinned = false, mutate?: (table: HTMLTableElement) => void) => {+ getSelection().removeAllRanges();+ const root = document.createElement("div");+ root.innerHTML = '<div class="test-viewport protyle-content"><div class="protyle-wysiwyg" contenteditable="true">' ++ '<div class="table" data-type="NodeTable" data-node-id="20260927000000-testtbl"' ++ (pinned ? ' custom-pinthead="true"' : "") + '><div contenteditable="true"><table><thead><tr>' ++ Array.from({length: 5}, (_, index) => `<th>Column ${index}</th>`).join("") ++ "</tr></thead><tbody>" + Array.from({length: count}, (_, row) => "<tr>" ++ Array.from({length: 5}, (_, col) => `<td><span data-type="a" data-href="https://example.com/${row}/${col}">` ++ `Row ${row} cell ${col}${row % 19 === 0 && col === 2 ? "<br>Second line<br>Third line" : ""}</span></td>`).join("") ++ "</tr>").join("") + "</tbody></table></div></div></div></div>";+ document.body.appendChild(root);+ const viewport = root.firstElementChild as HTMLElement;+ const editor = viewport.firstElementChild as HTMLElement;+ const table = editor.querySelector("table");+ mutate?.(table);+ const original = editor.innerHTML;+ const height = table.getBoundingClientRect().height;+ const widths = Array.from(table.rows[1].cells).map(cell => cell.getBoundingClientRect().width);+ const scroller = pinned ? table.parentElement : viewport;+ const highlight = {ranges: [] as Range[], mark: new Highlight(), markHL: new Highlight(),+ rangeIndex: 0, styleElement: document.createElement("style")};+ highlight.styleElement.dataset.uuid = "table-test";+ const owner = {element: root, wysiwyg: {element: editor}, contentElement: viewport, highlight,+ options: {}, block: {rootID: "root"}} as unknown as IProtyle;+ const editorController = api.createEditor(owner);+ editorController.prepareBlockVirtualization(editor, true);+ const virtualizer = editorController.virtualizer;+ return {root, viewport, editor, table, original, height, widths, scroller, virtualizer, highlight,+ owner, editorController,+ destroy: () => { virtualizer.destroy(); root.remove(); }};+ };+ const reduced = (table: HTMLTableElement, phase = "") => {+ check.ok(table.querySelectorAll("tr[data-sy-table-virtual-rows]").length > 0,+ `screen-external chunks are serialized ${phase}: id=${table.getAttribute("data-sy-table-virtual-id")}, rows=${table.rows.length}`);+ check.ok(table.querySelectorAll("tr").length < 240, `bounded rendered rows: ${table.rows.length}`);+ };+ const rowsMatch = (html: string, count = 2000) => {+ const holder = document.createElement("div");+ holder.innerHTML = html;+ check.equal(holder.querySelectorAll("tbody > tr").length, count, `complete body: ${html.slice(0, 300)}`);+ check.ok(holder.textContent.includes(`Row ${count - 1} cell 4`));+ check.doesNotMatch(html, /data-sy-table-virtual/);+ };+ for (const pinned of [false, true]) {+ const f = fixture(2000, pinned);+ await tick();+ reduced(f.table, `initial pinned=${pinned}`);+ check.equal(api.cleanTableVirtualizationHTML(f.editor.innerHTML), f.original, "source round trip is lossless");+ check.ok(Math.abs(f.table.getBoundingClientRect().height - f.height) < 2, "initial height is retained");+ for (const progress of [0.4, 0.95, 0.1, 0.7, 0]) {+ f.scroller.scrollTop = (f.scroller.scrollHeight - f.scroller.clientHeight) * progress;+ await tick();+ reduced(f.table, `progress=${progress}, pinned=${pinned}`);+ check.ok(Math.abs(f.table.getBoundingClientRect().height - f.height) < 2, "scrolling retains variable row heights");+ const row = f.table.querySelector<HTMLTableRowElement>("tbody > tr:not([data-sy-table-virtual-rows])");+ Array.from(row.cells).forEach((cell, index) => {+ check.ok(Math.abs(cell.getBoundingClientRect().width - f.widths[index]) < 1, "column widths stay stable");+ });+ const rowIndex = Number(/Row (\d+)/.exec(row.textContent)[1]);+ check.equal(getComputedStyle(row).backgroundColor, rowIndex % 2 === 1 ? "rgb(12, 34, 56)" : "rgba(0, 0, 0, 0)",+ "window changes retain alternating row backgrounds");+ }+ const snapshot = f.editor.innerHTML;+ const lute = Lute.New();+ lute.SetSpin(true);+ lute.SetKramdownIAL(true);+ lute.SetHTMLTag2TextMark(true);+ lute.SetProtyleWYSIWYG(true);+ lute.SetTextMark(true);+ const protectedLute = api.protectLuteTableVirtualization(lute);+ check.ok(lute.BlockDOM2StdMd(f.original).includes("Row 1999 cell 4"));+ check.equal(protectedLute.BlockDOM2StdMd(snapshot), lute.BlockDOM2StdMd(f.original), "copy/export retains all rows");+ rowsMatch(protectedLute.SpinBlockDOM(snapshot));+ const operations: IOperation[] = [{action: "update", id: "table", data: snapshot},+ {action: "insert", id: "copy", data: snapshot}];+ api.cleanBlockSelectionModeOperations(operations);+ operations.forEach(operation => {+ check.equal(typeof operation.data, "string");+ if (typeof operation.data === "string") {+ rowsMatch(operation.data);+ }+ });+ f.virtualizer.destroy();+ rowsMatch(f.editor.innerHTML);+ check.equal(api.cleanTableVirtualizationHTML(snapshot), f.original, "snapshots outlive the editor and its caches");+ f.root.remove();+ }+ {+ const f = fixture(600, false, table => {+ const columns = document.createElement("colgroup");+ columns.innerHTML = '<col style="width:60px;background:rgb(20, 30, 40)">' + '<col style="width:60px">'.repeat(4);+ table.prepend(columns);+ });+ await tick();+ check.equal(api.cleanTableVirtualizationHTML(f.editor.innerHTML), f.original, "authored column styles survive virtualization");+ check.equal(f.table.querySelector("col").style.backgroundColor, "rgb(20, 30, 40)");+ f.editorController.pending.set(1, () => {});+ f.root.dispatchEvent(new WheelEvent("wheel", {bubbles: true}));+ await tick();+ rowsMatch(f.editor.innerHTML, 600);+ f.editorController.pending.clear();+ f.viewport.style.width = "320px";+ f.editor.style.fontSize = "28px";+ f.editor.style.lineHeight = "42px";+ await tick();+ check.ok(f.table.hasAttribute("data-sy-table-virtual-id"), "narrow layouts and large fonts rebuild the window");+ f.editor.dispatchEvent(new PointerEvent("pointerdown", {bubbles: true, pointerType: "touch"}));+ rowsMatch(f.editor.innerHTML, 600);+ f.editor.dispatchEvent(new Event("touchmove", {bubbles: true}));+ await tick();+ check.ok(f.table.hasAttribute("data-sy-table-virtual-id"), "touch scrolling uses the shared window");+ f.editor.dispatchEvent(new PointerEvent("pointerup", {bubbles: true, pointerType: "touch"}));+ const cells = f.table.querySelectorAll("tbody > tr:not([data-sy-table-virtual-rows]) td");+ const range = document.createRange();+ range.setStart(cells[0], 0);+ range.setEnd(cells[cells.length - 1], 1);+ getSelection().addRange(range);+ await tick();+ rowsMatch(f.editor.innerHTML, 600);+ f.destroy();+ }+ {+ const f = fixture();+ await tick();+ const cell = f.table.querySelector("tbody td");+ const range = document.createRange();+ range.selectNodeContents(cell);+ range.collapse(true);+ getSelection().addRange(range);+ f.scroller.scrollTop = f.scroller.scrollHeight / 2;+ await tick();+ check.ok(cell.isConnected, "caret chunk stays connected outside the viewport");+ check.equal(getSelection().anchorNode, range.startContainer);+ reduced(f.table);+ cell.dispatchEvent(new PointerEvent("pointerdown", {bubbles: true, pointerType: "mouse"}));+ check.equal(f.table.tBodies[0].rows.length, 2000, "pointer handling sees all rows synchronously");+ check.ok(cell.isConnected, "materialization preserves the clicked node");+ cell.dispatchEvent(new PointerEvent("pointerup", {bubbles: true, pointerType: "mouse"}));+ cell.textContent = "Edited cell";+ f.root.dispatchEvent(new WheelEvent("wheel", {bubbles: true}));+ await tick();+ reduced(f.table);+ const after = api.cleanTableVirtualizationHTML(f.editor.innerHTML);+ rowsMatch(after);+ check.ok(after.includes("Edited cell"));+ const next = f.table.querySelector<HTMLTableCellElement>("tbody > tr:not([data-sy-table-virtual-rows]) td");+ next.textContent = "Programmatic edit";+ await tick();+ rowsMatch(f.editor.innerHTML);+ check.ok(f.editor.textContent.includes("Programmatic edit"), "source updates keep visible edits and offscreen rows");+ f.destroy();+ }+ {+ const f = fixture();+ await tick();+ reduced(f.table);+ const owner = {wysiwyg: {element: f.editor}, contentElement: f.viewport, highlight: f.highlight,+ block: {rootID: "root"}} as unknown as IProtyle;+ await new Promise<void>(resolve => api.searchMarkRender(owner, ["Row 1999 cell 4"], undefined, resolve));+ check.equal(f.highlight.ranges.length, 1, "search includes rows outside the virtual window");+ check.equal(f.highlight.ranges[0].toString(), "Row 1999 cell 4");+ f.scroller.scrollTop = f.scroller.scrollHeight / 2;+ await tick();+ rowsMatch(f.editor.innerHTML);+ f.destroy();+ }+ for (const event of ["copy", "cut", "paste", "keydown", "beforeinput", "compositionstart", "beforeprint"]) {+ const f = fixture(300);+ await tick();+ check.ok(f.table.hasAttribute("data-sy-table-virtual-id"));+ f.editor.dispatchEvent(new Event(event, {bubbles: true}));+ rowsMatch(f.editor.innerHTML, 300);+ f.destroy();+ }+ for (const mutate of [+ (table: HTMLTableElement) => { table.rows[2].cells[0].rowSpan = 2; },+ (table: HTMLTableElement) => { table.rows[2].cells[0].colSpan = 2; },+ (table: HTMLTableElement) => { table.rows[2].cells[0].innerHTML = '<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==">'; },+ (table: HTMLTableElement) => { table.rows[2].cells[0].innerHTML = '<span class="table__cell-rich">Rich</span>'; },+ ]) {+ const f = fixture(300, false, mutate);+ await tick();+ check.equal(f.editor.innerHTML, f.original, "complex tables retain their complete rendering");+ f.destroy();+ }+ {+ const f = fixture(120);+ await tick();+ check.equal(f.editor.innerHTML, f.original, "small tables are unchanged");+ let builds = 0;+ const cache = new api.TableGridCache(table => { builds++; return api.buildTableGrid(table); });+ const grid = cache.get(f.table);+ for (let i = 0; i < 100; i++) {+ check.equal(cache.get(f.table), grid);+ }+ check.equal(builds, 1, "scroll/hover reads reuse the grid");+ f.table.rows[1].cells[0].textContent = "Changed";+ check.equal(cache.get(f.table), grid, "text changes do not invalidate cell structure");+ f.table.rows[1].cells[0].colSpan = 2;+ check.notEqual(cache.get(f.table), grid, "synchronous span changes invalidate the grid");+ const beforeRowInsert = cache.get(f.table);+ const row = f.table.tBodies[0].insertRow();+ row.insertCell();+ check.notEqual(cache.get(f.table), beforeRowInsert);+ let rowMeasurements = 0;+ Array.from(f.table.rows).forEach(row => {+ const measure = row.getBoundingClientRect.bind(row);+ row.getBoundingClientRect = () => { rowMeasurements++; return measure(); };+ });+ check.ok(api.getTableGridRect(f.table).height > 0);+ check.equal(rowMeasurements, 0, "bounds calculation does not visit individual rows");+ cache.destroy();+ f.destroy();+ }+ return "Large table virtualization cases passed";+};++test("large tables retain complete source, editing, selection, search and layout with bounded rendered rows", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 60000,+}, async () => {+ const read = (file: string) => readFileSync(path.join(__dirname, file), "utf8");+ const compile = (source: string) => transpileModule(source.replace(/^import [\s\S]*?;\r?\n/gm, "")+ .replace(/^export /gm, ""), {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;+ const extract = (file: string, name: string) => {+ const source = createSourceFile(file, read(file), ScriptTarget.Latest, true);+ return compile(source.statements.filter(isVariableStatement).find(statement =>+ statement.declarationList.declarations.some(declaration => declaration.name.getText(source) === name)).getText(source));+ };+ const source = ["../util/tableVirtualizationDOM.ts", "../util/tableGridCache.ts", "tableVirtualization.ts",+ "../render/searchMarkRender.ts"].map(file => compile(read(file))).join("\n") ++ "\nconst cleanListMindmapHTML = value => value; const cleanTableCellRichHTML = value => value; " ++ "const cleanBlockSelectionModeHTML = value => value;\n" ++ extract("../util/table.ts", "buildTableGrid") + extract("transaction.ts", "cleanBlockSelectionModeOperations");+ const wysiwyg = createSourceFile("index.ts", read("index.ts"), ScriptTarget.Latest, true);+ const prepare = wysiwyg.statements.find(isClassDeclaration).members.find(member =>+ member.name?.getText(wysiwyg) === "prepareBlockVirtualization");+ const integration = compile(`class VirtualizedEditor {+ pendingInputTimeouts = new Map();+ runningInputTasks = new Set();+ constructor(protyle) {this.protyle = protyle; this.element = protyle.wysiwyg.element;}+ get virtualizer() {return this.largeTableVirtualizer;}+ get pending() {return this.pendingInputTimeouts;}+ ${prepare.getText(wysiwyg)}+ }`);+ const css = require("sass").compile(path.resolve(__dirname, "../../assets/scss/component/_typography.scss")).css;+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-table-virtualization-"));+ const script = path.join(temporary, "run.cjs");+ const lutePath = path.resolve(__dirname, "../../../stage/protyle/js/lute/lute.min.js");+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});+app.commandLine.appendSwitch("disable-gpu");+app.whenReady().then(async () => {+ const win = new BrowserWindow({show:false, width:900, height:700,+ webPreferences:{nodeIntegration:true, contextIsolation:false, backgroundThrottling:false, offscreen:true}});+ try {+ await win.loadURL("data:text/html,<html><body></body></html>");+ await win.webContents.executeJavaScript(require("node:fs").readFileSync(${JSON.stringify(lutePath)}, "utf8"));+ console.log(await win.webContents.executeJavaScript(${JSON.stringify("const __name = value => value; (" ++ browserCases.toString() + ")(" + JSON.stringify(source + integration) + "," + JSON.stringify(css) + ")")}));+ win.destroy();+ app.exit(0);+ } catch (error) {+ console.error(error);+ win.destroy();+ app.exit(1);+ }+});`, "utf8");+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ try {+ const result = await promisify(execFile)(require("electron") as unknown as string, [script],+ {env, timeout: 55000, windowsHide: true});+ assert.match(result.stdout, /Large table virtualization cases passed/);+ } finally {+ if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) &&+ path.basename(temporary).startsWith("siyuan-table-virtualization-")) {+ rmSync(temporary, {recursive: true, force: true});+ }+ }+});diff --git a/app/src/protyle/wysiwyg/tableVirtualization.ts b/app/src/protyle/wysiwyg/tableVirtualization.tsnew file mode 100644index 0000000000..81ac4a8bf5--- /dev/null+++ b/app/src/protyle/wysiwyg/tableVirtualization.ts@@ -0,0 +1,303 @@+import {restoreTableVirtualizationDOM, TABLE_VIRTUAL_COLUMNS, TABLE_VIRTUAL_ID, TABLE_VIRTUAL_ROWS} from "../util/tableVirtualizationDOM";++export const LARGE_TABLE_ROW_THRESHOLD = 256;+// 奇数行替换为一个占位行后,后续内容的隔行底色顺序保持不变。+export const TABLE_VIRTUAL_CHUNK_SIZE = 33;+let tableVirtualSerial = 0;++interface ITableChunk {+ top: number;+ height: number;+ placeholder: HTMLTableRowElement;+ rows?: HTMLTableRowElement[];+}++interface ITableViewport {+ table: HTMLTableElement;+ body: HTMLTableSectionElement;+ chunks: ITableChunk[];+ rules: string;+ height: number;+}++export const isTableChunkVisible = (top: number, height: number, viewportTop: number, viewportBottom: number) =>+ top + height >= viewportTop && top <= viewportBottom;++// 普通表格仍使用完整块 DOM 编辑;浏览时将屏外行序列化为独立、可恢复的占位分段。+export class LargeTableVirtualizer {+ private states = new Map<HTMLTableElement, ITableViewport>();+ private excluded = new WeakSet<HTMLTableElement>();+ private styleElement = document.createElement("style");+ private observer: MutationObserver;+ private resizeObserver: ResizeObserver;+ private abortController = new AbortController();+ private frame = 0;+ private scan = true;+ private interacting = false;+ private composing = false;+ private font = "";+ private layout = "";++ constructor(private root: HTMLElement, private editor: HTMLElement, private viewport: HTMLElement,+ private blocked: () => boolean = () => false) {+ root.appendChild(this.styleElement);+ const signal = this.abortController.signal;+ this.observer = new MutationObserver(records => this.onMutations(records));+ this.observer.observe(editor, {childList: true, subtree: true, characterData: true, attributes: true,+ attributeFilter: ["style", "class", "rowspan", "colspan", "custom-pinthead"]});+ this.resizeObserver = new ResizeObserver(() => {+ const style = getComputedStyle(this.editor);+ const layout = [this.viewport.clientWidth, this.editor.clientWidth, style.paddingLeft, style.paddingRight].join("/");+ const changedHeight = Array.from(this.states.values()).some(state =>+ Math.abs(state.table.getBoundingClientRect().height - state.height) > 2);+ if (layout !== this.layout || style.font !== this.font || changedHeight) {+ this.layout = layout;+ this.font = style.font;+ this.restore();+ this.scan = true;+ this.schedule();+ }+ });+ this.resizeObserver.observe(viewport);+ this.resizeObserver.observe(editor);+ document.fonts?.addEventListener("loadingdone", () => {+ this.restore();+ this.scan = true;+ this.schedule();+ }, {signal});+ root.addEventListener("scroll", () => this.schedule(), {capture: true, passive: true, signal});+ // 输入和块级操作在事件分发前恢复全部行,原生选区及后续事件处理仍面对完整表格。+ ["pointerdown", "keydown", "beforeinput", "copy", "cut", "paste", "dragstart", "contextmenu"].forEach(type => {+ window.addEventListener(type, () => {+ this.interacting = type === "pointerdown" || type === "keydown";+ this.restore();+ }, {capture: true, signal});+ });+ window.addEventListener("pointerup", () => { this.interacting = false; }, {capture: true, signal});+ window.addEventListener("pointercancel", () => { this.interacting = false; }, {capture: true, signal});+ window.addEventListener("keyup", event => {+ this.interacting = false;+ if (["PageDown", "PageUp", "Home", "End"].includes(event.key)) {+ this.scan = true;+ this.schedule();+ }+ }, {capture: true, signal});+ root.addEventListener("compositionstart", () => {+ this.composing = true;+ this.restore();+ }, {capture: true, signal});+ root.addEventListener("compositionend", () => { this.composing = false; }, {capture: true, signal});+ root.addEventListener("wheel", () => {+ this.scan = true;+ this.schedule();+ }, {passive: true, signal});+ root.addEventListener("touchmove", () => {+ this.interacting = false;+ this.scan = true;+ this.schedule();+ }, {passive: true, signal});+ root.addEventListener("pointermove", event => {+ // 滚动引起的命中区域变化不退出虚拟窗口,实际移动指针后恢复表格操作控件。+ if (event.pointerType === "mouse" && event.buttons === 0 && (event.movementX || event.movementY)) {+ const table = (event.target as Element).closest?.<HTMLTableElement>(`table[${TABLE_VIRTUAL_ID}]`);+ if (table) {+ this.restore(table);+ }+ }+ }, {capture: true, signal});+ document.addEventListener("selectionchange", () => {+ const selection = getSelection();+ if (selection && !selection.isCollapsed && selection.rangeCount &&+ selection.getRangeAt(0).intersectsNode(this.editor)) {+ this.restore();+ }+ }, {signal});+ window.addEventListener("beforeprint", () => this.restore(), {signal});+ this.schedule();+ }++ private schedule() {+ if (!this.frame) {+ this.frame = requestAnimationFrame(() => {+ this.frame = 0;+ this.refresh();+ });+ }+ }++ private onMutations(records: MutationRecord[]) {+ if (records.length === 0) {+ return;+ }+ records.forEach(record => {+ const element = record.target instanceof Element ? record.target : record.target.parentElement;+ const table = element?.closest("table");+ if (table) {+ this.excluded.delete(table);+ }+ });+ this.states.forEach((state, table) => {+ if (!table.isConnected || records.some(record => table.contains(record.target) ||+ record.target instanceof Element && record.target.contains(table))) {+ this.restore(table);+ }+ });+ // 文档加载及事务替换会引入新的表格,单元格输入无需反复初始化。+ if (records.some(record => Array.from(record.addedNodes).some(node => node instanceof Element &&+ (node.matches('[data-type="NodeTable"]') || !!node.querySelector('[data-type="NodeTable"]'))))) {+ this.scan = true;+ this.schedule();+ }+ }++ public restore(table?: HTMLTableElement) {+ const tables = table ? [table] : Array.from(this.states.keys());+ tables.forEach(current => {+ restoreTableVirtualizationDOM(current);+ this.states.delete(current);+ });+ this.updateStyle();+ this.observer.takeRecords();+ }++ private updateStyle() {+ const rules = Array.from(this.states.values()).map(state => state.rules).join("\n");+ if (rules !== this.styleElement.textContent) {+ this.styleElement.textContent = rules;+ }+ }++ private prepare(table: HTMLTableElement): ITableViewport | undefined {+ const body = table.tBodies[0];+ if (table.tBodies.length !== 1 || table.tFoot || !body || body.rows.length <= LARGE_TABLE_ROW_THRESHOLD ||+ table.closest(".protyle-wysiwyg__embed, .protyle-custom, .mindmap-view, .table__cell-rich") ||+ table.querySelector("table, img, video, audio, iframe, canvas, svg, math, input, textarea, select, button, " ++ "object, embed, details, [hidden], [style*='display: none'], [style*='display:none'], " ++ ".table__cell-rich, .table__cell-editor, " ++ '[data-type~="inline-math"], [data-type~="search-mark"], [data-type~="block-ref"], ' ++ '[data-type~="virtual-block-ref"], wbr, .fn__none') ||+ table.querySelectorAll(":scope > colgroup").length > 1) {+ this.excluded.add(table);+ return;+ }+ const rows = Array.from(body.rows);+ const first = rows[0];+ const columns = first.cells.length;+ const originalColumns = table.querySelector(":scope > colgroup");+ if (!columns || Array.from(table.rows).some(row => row.cells.length !== columns ||+ Array.from(row.cells).some(cell => cell.rowSpan !== 1 || cell.colSpan !== 1)) ||+ originalColumns && (originalColumns.children.length !== columns ||+ Array.from(originalColumns.children).some(column => (column as HTMLTableColElement).span !== 1))) {+ this.excluded.add(table);+ return;+ }+ const tableRect = table.getBoundingClientRect();+ const bodyRect = body.getBoundingClientRect();+ if (tableRect.width <= 0 || bodyRect.height <= 0) {+ return;+ }+ // 一次性读取完整表格的列宽与分段高度,滚动时只计算视口与缓存区间。+ const widths = Array.from(first.cells).map(cell => cell.getBoundingClientRect().width);+ const chunks: ITableChunk[] = [];+ for (let i = 0; i < rows.length; i += TABLE_VIRTUAL_CHUNK_SIZE) {+ const chunkRows = rows.slice(i, i + TABLE_VIRTUAL_CHUNK_SIZE);+ const top = chunkRows[0].getBoundingClientRect().top - bodyRect.top;+ const end = chunkRows[chunkRows.length - 1].getBoundingClientRect().bottom - bodyRect.top;+ const placeholder = document.createElement("tr");+ placeholder.setAttribute("contenteditable", "false");+ placeholder.setAttribute("aria-hidden", "true");+ const cell = placeholder.insertCell();+ cell.colSpan = columns;+ // 占位单元格只保留布局高度,不能引入正文单元格的边距、边框或空内容最小高度。+ cell.style.cssText = `height:${end - top}px;padding:0;border:0;line-height:0;font-size:0;`;+ cell.textContent = "\u200b";+ chunks.push({top, height: end - top, placeholder, rows: chunkRows});+ }+ const group = originalColumns ? originalColumns.cloneNode(true) as HTMLTableColElement : document.createElement("colgroup");+ group.setAttribute(TABLE_VIRTUAL_COLUMNS, originalColumns?.outerHTML || "");+ widths.forEach((width, index) => {+ const column = group.children[index] as HTMLTableColElement || document.createElement("col");+ column.style.width = `${width}px`;+ if (!column.parentElement) {+ group.appendChild(column);+ }+ });+ if (originalColumns) {+ originalColumns.replaceWith(group);+ } else {+ table.insertBefore(group, table.firstChild);+ }+ const id = (++tableVirtualSerial).toString();+ table.setAttribute(TABLE_VIRTUAL_ID, id);+ const selector = `.protyle-wysiwyg table[${TABLE_VIRTUAL_ID}="${id}"]`;+ const rules = `${selector}{table-layout:fixed;width:${tableRect.width}px;}`;+ return {table, body, chunks, rules, height: tableRect.height};+ }++ private refresh() {+ this.onMutations(this.observer.takeRecords());+ const selection = getSelection();+ if (!this.editor.isConnected || this.interacting || this.composing || this.blocked() ||+ selection && !selection.isCollapsed && selection.rangeCount &&+ selection.getRangeAt(0).intersectsNode(this.editor)) {+ this.restore();+ return;+ }+ this.states.forEach((_state, table) => {+ if (!table.isConnected || !table.hasAttribute(TABLE_VIRTUAL_ID)) {+ this.restore(table);+ }+ });+ if (this.scan) {+ this.scan = false;+ this.editor.querySelectorAll<HTMLTableElement>('[data-type="NodeTable"] > div > table').forEach(table => {+ if (!this.states.has(table) && !this.excluded.has(table)) {+ const state = this.prepare(table);+ if (state) {+ this.states.set(table, state);+ }+ }+ });+ this.updateStyle();+ }+ const viewport = this.viewport.getBoundingClientRect();+ const plans = Array.from(this.states.values()).map(state => {+ const wrapper = state.table.parentElement.getBoundingClientRect();+ const top = Math.max(viewport.top, wrapper.top);+ const bottom = Math.min(viewport.bottom, wrapper.bottom);+ const bodyTop = state.body.getBoundingClientRect().top;+ const buffer = Math.max(0, Math.min(viewport.height, wrapper.height));+ return {state, top: top - buffer - bodyTop, bottom: bottom + buffer - bodyTop};+ });+ // 先完成全部几何读取,再移除或恢复行;光标所在分段保持连接以保护原生选区。+ plans.forEach(({state, top, bottom}) => {+ state.chunks.forEach(chunk => {+ const pinned = chunk.rows?.some(row => row.contains(selection?.anchorNode));+ if (pinned || isTableChunkVisible(chunk.top, chunk.height, top, bottom)) {+ if (!chunk.rows) {+ const source = document.createElement("tbody");+ source.innerHTML = chunk.placeholder.getAttribute(TABLE_VIRTUAL_ROWS);+ chunk.rows = Array.from(source.rows);+ chunk.placeholder.replaceWith(...chunk.rows);+ chunk.placeholder.removeAttribute(TABLE_VIRTUAL_ROWS);+ }+ } else if (chunk.rows) {+ chunk.placeholder.setAttribute(TABLE_VIRTUAL_ROWS, chunk.rows.map(row => row.outerHTML).join(""));+ chunk.rows[0].before(chunk.placeholder);+ chunk.rows.forEach(row => row.remove());+ chunk.rows = undefined;+ }+ });+ });+ this.observer.takeRecords();+ }++ public destroy() {+ cancelAnimationFrame(this.frame);+ this.abortController.abort();+ this.resizeObserver.disconnect();+ this.restore();+ this.observer.disconnect();+ this.styleElement.remove();+ }+}diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex addfcaaf17..024d24e552 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -77,6 +77,7 @@ import {import {isEmptyParagraph} from "./emptyTextBlock";import {getHeadingConversionElements, isListHeadingContainer} from "./headingConversion";import {cleanTableCellRichHTML, retainTableCellRichMetadata} from "../util/tableCellRich";+import {cleanTableVirtualizationHTML} from "../util/tableVirtualizationDOM";import {cleanListMindmapHTML, convertListMindmapToList, listMindmapConversionSource} from "../render/listMindmap/model";import {buildCancelListOperations} from "./cancelList";import {buildListConversionOperations} from "./listConversion";@@ -93,7 +94,8 @@ const cleanBlockSelectionModeOperations = (operations?: IOperation[]) => {operations?.forEach(operation => {if (["appendInsert", "insert", "prependInsert", "update"].includes(operation.action) &&typeof operation.data === "string") {- operation.data = cleanListMindmapHTML(cleanTableCellRichHTML(cleanBlockSelectionModeHTML(operation.data)));+ operation.data = cleanListMindmapHTML(cleanTableCellRichHTML(cleanBlockSelectionModeHTML(+ cleanTableVirtualizationHTML(operation.data))));}if (operation.action === "unfoldHeading" && typeof operation.retData === "string") {operation.retData = cleanBlockSelectionModeHTML(operation.retData);diff --git a/app/src/protyle/wysiwyg/transactionAV.test.ts b/app/src/protyle/wysiwyg/transactionAV.test.tsindex 29a8b7568c..480ab1408c 100644--- a/app/src/protyle/wysiwyg/transactionAV.test.ts+++ b/app/src/protyle/wysiwyg/transactionAV.test.ts@@ -27,6 +27,7 @@ const fixture = () => {({doOperations, undoOperations}),cleanBlockSelectionModeHTML: (html: string) => html,cleanTableCellRichHTML: (html: string) => html,+ cleanTableVirtualizationHTML: (html: string) => html,cleanListMindmapHTML: (html: string) => html,restoreInlineElementBoundaryHTML: (html: string) => html,normalizeHTMLAssetIFrameBlockDOM: (html: string) => html,