Skip to content

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

:zap: Improve large table interaction responsiveness https://github.com/siyuan-note/siyuan/issues/19911

Daniel7d24a9518c98
diff --git a/app/src/protyle/render/tableCellInput.test.ts b/app/src/protyle/render/tableCellInput.test.ts
index bbd88a9bc9..247bc0e919 100644
--- a/app/src/protyle/render/tableCellInput.test.ts
+++ b/app/src/protyle/render/tableCellInput.test.ts
@@ -41,10 +41,11 @@ const browserCases = async (source: string, queueSource: string, editorSource: s
const api = new Function(...Object.keys(dependencies), source + "\nreturn {input, insertRow, insertRowAbove, insertColumn, " +
"getAgentLute, configureAVRichTextLute, getTableCellEditorLute, getAVRichTextLute, " +
"getTableCellRichBlockDOM, serializeTableCellRich, cleanTableCellRichHTML, renderTableCellRich, " +
- "setTableCellRich, getTableCellInlineHTML, getSelectionOffset, focusByOffset};")(...Object.values(dependencies)) as
+ "setTableCellRich, getTableCellInlineHTML, getSelectionOffset, focusByOffset, " +
+ "getTableVirtualRowIndex, restoreTableVirtualizationDOM};")(...Object.values(dependencies)) as
typeof import("../wysiwyg/input") & typeof import("../util/table") & typeof import("./setLute") &
typeof import("./av/richText") & typeof import("./av/richTextValue") & typeof import("../util/tableCellRichLute") &
- typeof import("../util/tableCellRich") & typeof import("../util/selection");
+ typeof import("../util/tableCellRich") & typeof import("../util/selection") & typeof import("../util/tableVirtualizationDOM");
const lute = api.configureAVRichTextLute(api.getAgentLute({emojiSite: "/emojis", emojis: {},
headingAnchor: false, listStyle: false, paragraphBeginningSpace: true, sanitize: true}));
const Queue = new Function(queueSource + "\nreturn InputQueue;")() as new () => {
diff --git a/app/src/protyle/render/tableCellRichEditor.ts b/app/src/protyle/render/tableCellRichEditor.ts
index 7f8eb5334b..c02d9af3de 100644
--- a/app/src/protyle/render/tableCellRichEditor.ts
+++ b/app/src/protyle/render/tableCellRichEditor.ts
@@ -27,6 +27,7 @@ import {setTableCellRichContext} from "../util/tableCellRichContext";
import {updateOutlineCurrentBlock} from "../util/outlineBlock";
import {canEnterCodeBlock} from "../wysiwyg/codeBlockEnter";
import {bindLiteCodeActions} from "../lite/codeActions";
+import {getTableVirtualRowIndex, restoreTableVirtualizationDOM} from "../util/tableVirtualizationDOM";
let activeEditor: {cell: Element, finish: () => void} | undefined;
let openingEditor: object | undefined;
@@ -101,7 +102,7 @@ export const openTableCellRichEditor = async (owner: IProtyle, cell: HTMLTableCe
openingEditor = request;
const tableID = table.dataset.nodeId;
const tableParent = table.parentElement;
- const rowIndex = (cell.parentElement as HTMLTableRowElement).rowIndex;
+ const rowIndex = getTableVirtualRowIndex(cell.parentElement as HTMLTableRowElement);
const cellIndex = cell.cellIndex;
// 记录预览中被点击的公式位置,在重建单元格后打开对应公式的编辑面板。
const clickedMath = point?.target?.closest('[data-subtype="math"]');
@@ -237,6 +238,8 @@ export const openTableCellRichEditor = async (owner: IProtyle, cell: HTMLTableCe
contentChanged = false;
return;
}
+ // 事务的撤销定位使用完整单元格索引,提交修改前恢复屏外行。
+ restoreTableVirtualizationDOM(table);
const oldHTML = cleanTableCellRichHTML(table.outerHTML);
const redoSelection = captureRichCellSelection(fragment.wysiwyg, getSelection(), true) || undoSelection;
const tableRange = document.createRange();
diff --git a/app/src/protyle/util/tableControl.ts b/app/src/protyle/util/tableControl.ts
index 15b562d625..ca548a551d 100644
--- a/app/src/protyle/util/tableControl.ts
+++ b/app/src/protyle/util/tableControl.ts
@@ -1,6 +1,6 @@
import {MenuItem} from "../../menus/Menu";
import {getTableGridRect, TableGridCache} from "./tableGridCache";
-import {TABLE_VIRTUAL_ID} from "./tableVirtualizationDOM";
+import {TABLE_VIRTUAL_ID, TABLE_VIRTUAL_ROWS} from "./tableVirtualizationDOM";
import {clearTableCellContent, getTableCellPlainText, mergeTableCellContents} from "./tableCellRich";
import {renderTableCellRichElements} from "../render/tableCellRich";
import {updateTransaction} from "../wysiwyg/transaction";
@@ -117,7 +117,7 @@ const getCell = (target: EventTarget | Node) => {
const element = target instanceof Element ? target : (target as Node)?.parentElement;
const cell = element?.closest?.("th, td") as HTMLTableCellElement;
const editor = element?.closest?.(".table__cell-editor");
- return cell && !cell.closest(".mindmap-view__preview-block") &&
+ return cell && !cell.closest(`.mindmap-view__preview-block, tr[${TABLE_VIRTUAL_ROWS}]`) &&
(element.closest(".protyle-wysiwyg") === cell.closest(".protyle-wysiwyg") ||
editor?.parentElement === cell) ? cell : undefined;
};
@@ -484,9 +484,10 @@ export class TableControl {
if (!node || !table || getTableNode(activeCell) !== node || activeCell.closest("table") !== table) {
return false;
}
- const grid = buildTableGrid(table);
- const anchorInfo = grid.cellInfos.find(item => item.cell === anchorCell);
- const activeInfo = grid.cellInfos.find(item => item.cell === activeCell);
+ const cached = this.gridCache.get(table);
+ const grid = cached.grid;
+ const anchorInfo = cached.cells.get(anchorCell);
+ const activeInfo = cached.cells.get(activeCell);
const cells = getTableCellsInRectangle(grid.cellInfos, anchorInfo, activeInfo).map(item => item.cell);
if (cells.length === 0) {
return false;
@@ -1129,7 +1130,7 @@ export class TableControl {
private getEdgeHover(clientX: number, clientY: number) {
const candidates: ITableEdgeHover[] = [];
this.wysiwygElement.querySelectorAll<HTMLTableElement>('[data-type="NodeTable"] table').forEach(table => {
- if (table.hasAttribute(TABLE_VIRTUAL_ID) || table.closest(".protyle-custom, .mindmap-view__preview-block")) {
+ if (table.closest(".protyle-custom, .mindmap-view__preview-block")) {
return;
}
const gridRect = getTableGridRect(table);
@@ -1340,7 +1341,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 && !table.hasAttribute(TABLE_VIRTUAL_ID) && !this.protyle.disabled;
+ const visible = !!cell && !!node && !!table && !this.protyle.disabled;
[this.rowHandle, this.columnHandle, this.cellHandle, this.addRowButton, this.addColumnButton,
this.addBothButton].forEach(item => {
item.classList.add("fn__none");
@@ -1369,7 +1370,9 @@ export class TableControl {
const columnRect = typeof columnIndex === "number" ?
this.getColumnRect(table, grid, columnIndex) : undefined;
const visibleColumnRect = columnRect ? intersectRects(columnRect, viewportRect) : undefined;
- const merged = grid === cached.grid ? cached.merged : grid.cellInfos.some(info => info.rowspan > 1 || info.colspan > 1);
+ // 虚拟窗口的跨列占位行不属于合并单元格,操作前会恢复完整网格。
+ const merged = !table.hasAttribute(TABLE_VIRTUAL_ID) &&
+ (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)));
@@ -1418,8 +1421,7 @@ export class TableControl {
rowControlCenter);
}
}
- if (!this.dragState && !this.selection && caretCell && getTableNode(caretCell) &&
- !caretCell.closest(`table[${TABLE_VIRTUAL_ID}]`) && !this.protyle.disabled) {
+ if (!this.dragState && !this.selection && caretCell && getTableNode(caretCell) && !this.protyle.disabled) {
const table = caretCell.closest("table") as HTMLTableElement;
const viewportRect = table ? this.getTableGridViewportRect(table) : undefined;
if (viewportRect) {
diff --git a/app/src/protyle/util/tableVirtualizationDOM.ts b/app/src/protyle/util/tableVirtualizationDOM.ts
index e22bbb312e..f9bc6652fe 100644
--- a/app/src/protyle/util/tableVirtualizationDOM.ts
+++ b/app/src/protyle/util/tableVirtualizationDOM.ts
@@ -2,13 +2,59 @@ 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";
+const detachedRows = new WeakMap<HTMLTableRowElement, {html: string, rows: HTMLTableRowElement[]}>();
+
+export const getTableVirtualRowIndex = (row: HTMLTableRowElement) => {
+ let index = 0;
+ for (const current of Array.from(row.closest("table").rows)) {
+ if (current === row) {
+ return index;
+ }
+ const source = current.getAttribute(TABLE_VIRTUAL_ROWS);
+ if (source === null) {
+ index++;
+ } else {
+ const cached = detachedRows.get(current);
+ if (cached?.html === source) {
+ index += cached.rows.length;
+ } else {
+ const body = document.createElement("tbody");
+ body.innerHTML = source;
+ index += body.rows.length;
+ }
+ }
+ }
+ return row.rowIndex;
+};
+
+// 当前编辑器复用已卸载的行节点,快照仍由占位属性独立保存完整内容。
+export const cacheTableVirtualizationRows = (placeholder: HTMLTableRowElement, rows: HTMLTableRowElement[]) => {
+ const html = rows.map(row => row.outerHTML).join("");
+ placeholder.setAttribute(TABLE_VIRTUAL_ROWS, html);
+ detachedRows.set(placeholder, {html, rows});
+};
+
+export const restoreTableVirtualizationRows = (placeholder: HTMLTableRowElement) => {
+ const html = placeholder.getAttribute(TABLE_VIRTUAL_ROWS);
+ const cached = detachedRows.get(placeholder);
+ detachedRows.delete(placeholder);
+ let rows: HTMLTableRowElement[];
+ if (cached?.html === html) {
+ rows = cached.rows;
+ } else {
+ const body = document.createElement("tbody");
+ body.innerHTML = html;
+ rows = Array.from(body.rows);
+ }
+ placeholder.replaceWith(...rows);
+ placeholder.removeAttribute(TABLE_VIRTUAL_ROWS);
+ return rows;
+};
+
// 占位行携带完整源内容,克隆、撤销快照和编辑器销毁后仍能独立还原。
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));
+ restoreTableVirtualizationRows(placeholder);
});
root.querySelectorAll(`[${TABLE_VIRTUAL_COLUMNS}]`).forEach(columns => {
const table = document.createElement("table");
diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.ts
index 9c88362be2..d0e69e748d 100644
--- a/app/src/protyle/wysiwyg/index.ts
+++ b/app/src/protyle/wysiwyg/index.ts
@@ -2189,6 +2189,8 @@ export class WYSIWYG {
}
}
let moveCellElement: HTMLElement;
+ let tableSelectionGrid: ReturnType<typeof buildTableGrid>;
+ let tableSelectionMerged = false;
let hasLeftTableBlock = false;
let avDragSelectMode: "items" | "blocks" | undefined;
let avDragSelectFrame: number | undefined;
@@ -2327,7 +2329,9 @@ export class WYSIWYG {
tableBlockElement.firstElementChild.style.webkitUserModify = "read-only";
const tableElement = tableBlockElement.querySelector("table");
const tableRect = tableElement.getBoundingClientRect();
- const rowRects = Array.from(tableElement.rows).map(row => row.getBoundingClientRect());
+ const rowRects = Array.from(tableElement.children)
+ .filter(section => ["THEAD", "TBODY", "TFOOT"].includes(section.tagName))
+ .map(section => section.getBoundingClientRect()).filter(rect => rect.height > 0);
const gridRect = {
left: Math.min(...rowRects.map(rect => rect.left)) - tableRect.left,
top: Math.min(...rowRects.map(rect => rect.top)) - tableRect.top,
@@ -2346,12 +2350,19 @@ export class WYSIWYG {
let selectionRects: ReturnType<typeof getCellRect>[] = [];
let logicalSelection = false;
if (target.tagName === "TH" || target.tagName === "TD") {
- const grid = buildTableGrid(tableElement);
+ if (!tableSelectionGrid) {
+ tableSelectionGrid = buildTableGrid(tableElement);
+ tableSelectionMerged = tableSelectionGrid.cellInfos.some(info =>
+ info.rowspan > 1 || info.colspan > 1);
+ }
+ const grid = tableSelectionGrid;
const targetInfo = grid.cellInfos.find(item => item.cell === target);
const moveTargetInfo = grid.cellInfos.find(item => item.cell === moveTarget);
const selectedInfos = getTableCellsInRectangle(grid.cellInfos, targetInfo, moveTargetInfo);
if (selectedInfos.length > 0) {
- selectionRects = selectedInfos.map(item => getCellRect(item.cell));
+ // 无合并单元格时矩形由首尾确定,不逐个测量选中的单元格。
+ selectionRects = tableSelectionMerged ? selectedInfos.map(item => getCellRect(item.cell)) :
+ [getCellRect(target), getCellRect(moveTarget)];
logicalSelection = true;
}
}
diff --git a/app/src/protyle/wysiwyg/tableVirtualization.test.ts b/app/src/protyle/wysiwyg/tableVirtualization.test.ts
index 67a24a623c..059c0d728a 100644
--- a/app/src/protyle/wysiwyg/tableVirtualization.test.ts
+++ b/app/src/protyle/wysiwyg/tableVirtualization.test.ts
@@ -11,7 +11,7 @@ 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, " +
+ "restoreTableVirtualizationDOM, getTableVirtualRowIndex, 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") & {
@@ -52,6 +52,7 @@ body {margin:0; --b3-theme-surface-lighter:#ddd; --b3-font-size-editor:16px; --b
const table = editor.querySelector("table");
mutate?.(table);
const original = editor.innerHTML;
+ const originalLastRow = table.rows[table.rows.length - 1];
const height = table.getBoundingClientRect().height;
const widths = Array.from(table.rows[1].cells).map(cell => cell.getBoundingClientRect().width);
const scroller = pinned ? table.parentElement : viewport;
@@ -63,7 +64,7 @@ body {margin:0; --b3-theme-surface-lighter:#ddd; --b3-font-size-editor:16px; --b
const editorController = api.createEditor(owner);
editorController.prepareBlockVirtualization(editor, true);
const virtualizer = editorController.virtualizer;
- return {root, viewport, editor, table, original, height, widths, scroller, virtualizer, highlight,
+ return {root, viewport, editor, table, original, originalLastRow, height, widths, scroller, virtualizer, highlight,
owner, editorController,
destroy: () => { virtualizer.destroy(); root.remove(); }};
};
@@ -90,6 +91,11 @@ body {margin:0; --b3-theme-surface-lighter:#ddd; --b3-font-size-editor:16px; --b
});
await tick();
reduced(f.table, `initial pinned=${pinned}`);
+ f.table.querySelector("tbody td").dispatchEvent(new PointerEvent("pointermove", {
+ bubbles: true, pointerType: "mouse", movementX: 10, movementY: 5,
+ }));
+ await tick();
+ reduced(f.table, "hover does not materialize offscreen rows");
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]) {
@@ -103,6 +109,7 @@ body {margin:0; --b3-theme-surface-lighter:#ddd; --b3-font-size-editor:16px; --b
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(api.getTableVirtualRowIndex(row), rowIndex + 1, "cell editor indexes include offscreen rows");
check.equal(getComputedStyle(row).backgroundColor, rowIndex % 2 === 1 ? "rgb(12, 34, 56)" : "rgba(0, 0, 0, 0)",
"window changes retain alternating row backgrounds");
}
@@ -119,7 +126,11 @@ body {margin:0; --b3-theme-surface-lighter:#ddd; --b3-font-size-editor:16px; --b
const reference = f.table.querySelector('tbody [data-type="virtual-block-ref"]');
reference.dispatchEvent(new PointerEvent("pointerdown", {bubbles: true, pointerType: pinned ? "touch" : "mouse"}));
check.ok(reference.isConnected, "reference interaction retains its event target");
- check.equal(f.table.tBodies[0].rows.length, 2000, "reference interaction restores the complete table");
+ reduced(f.table, "single-cell interaction keeps offscreen rows detached");
+ reference.dispatchEvent(new Event("copy", {bubbles: true}));
+ check.equal(f.table.tBodies[0].rows.length, 2000, "copy restores the complete table");
+ check.equal(f.table.rows[f.table.rows.length - 1], f.originalLastRow,
+ "interaction reuses offscreen row nodes without parsing the table again");
reference.dispatchEvent(new PointerEvent("pointerup", {bubbles: true}));
rowsMatch(protectedLute.SpinBlockDOM(snapshot));
const operations: IOperation[] = [{action: "update", id: "table", data: snapshot},
@@ -184,6 +195,8 @@ body {margin:0; --b3-theme-surface-lighter:#ddd; --b3-font-size-editor:16px; --b
check.equal(getSelection().anchorNode, range.startContainer);
reduced(f.table);
cell.dispatchEvent(new PointerEvent("pointerdown", {bubbles: true, pointerType: "mouse"}));
+ reduced(f.table, "click does not materialize the entire table");
+ cell.dispatchEvent(new PointerEvent("pointermove", {bubbles: true, pointerType: "mouse", buttons: 1, movementX: 10}));
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"}));
@@ -197,7 +210,7 @@ body {margin:0; --b3-theme-surface-lighter:#ddd; --b3-font-size-editor:16px; --b
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);
+ rowsMatch(api.cleanTableVirtualizationHTML(f.editor.innerHTML));
check.ok(f.editor.textContent.includes("Programmatic edit"), "source updates keep visible edits and offscreen rows");
f.destroy();
}
@@ -223,8 +236,11 @@ body {margin:0; --b3-theme-surface-lighter:#ddd; --b3-font-size-editor:16px; --b
cell.innerHTML = '<div class="table__cell-editor table__cell--inline"><div contenteditable="true">Editing</div>' +
'<button class="fn__none"><svg></svg></button></div>';
const host = cell.firstElementChild;
+ cell.style.verticalAlign = "top";
+ f.editor.classList.add("protyle-wysiwyg--hiderange");
cell.dispatchEvent(new PointerEvent("pointerup", {bubbles: true}));
await tick();
+ reduced(f.table, "cell and selection styles do not materialize the table");
for (const progress of [0.5, 1, 0]) {
f.scroller.scrollTop = (f.scroller.scrollHeight - f.scroller.clientHeight) * progress;
f.root.dispatchEvent(new WheelEvent("wheel", {bubbles: true}));
diff --git a/app/src/protyle/wysiwyg/tableVirtualization.ts b/app/src/protyle/wysiwyg/tableVirtualization.ts
index 8dd56cadd1..4b514593cb 100644
--- a/app/src/protyle/wysiwyg/tableVirtualization.ts
+++ b/app/src/protyle/wysiwyg/tableVirtualization.ts
@@ -1,4 +1,4 @@
-import {restoreTableVirtualizationDOM, TABLE_VIRTUAL_COLUMNS, TABLE_VIRTUAL_ID, TABLE_VIRTUAL_ROWS} from "../util/tableVirtualizationDOM";
+import {cacheTableVirtualizationRows, restoreTableVirtualizationDOM, restoreTableVirtualizationRows, TABLE_VIRTUAL_COLUMNS, TABLE_VIRTUAL_ID} from "../util/tableVirtualizationDOM";
export const LARGE_TABLE_ROW_THRESHOLD = 256;
// 奇数行替换为一个占位行后,后续内容的隔行底色顺序保持不变。
@@ -50,12 +50,15 @@ export class LargeTableVirtualizer {
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) {
+ if (layout !== this.layout || style.font !== this.font) {
this.layout = layout;
this.font = style.font;
this.restore();
this.scan = true;
this.schedule();
+ } else if (changedHeight) {
+ this.states.forEach(state => this.measureChunks(state));
+ this.schedule();
}
});
this.resizeObserver.observe(viewport);
@@ -68,13 +71,26 @@ export class LargeTableVirtualizer {
root.addEventListener("scroll", () => this.schedule(), {capture: true, passive: true, signal});
// 输入和块级操作在事件分发前恢复全部行,原生选区及后续事件处理仍面对完整表格。
["pointerdown", "keydown", "beforeinput", "copy", "cut", "paste", "dragstart", "contextmenu"].forEach(type => {
- window.addEventListener(type, () => {
+ window.addEventListener(type, event => {
this.interacting = type === "pointerdown" || type === "keydown";
+ if (type === "pointerdown") {
+ const pointer = event as PointerEvent;
+ const cell = (event.target as Element).closest?.("td, th");
+ if (pointer.button === 0 && !pointer.shiftKey && !pointer.ctrlKey && !pointer.metaKey &&
+ !pointer.altKey && cell && this.states.has(cell.closest("table"))) {
+ return;
+ }
+ }
this.restore();
}, {capture: true, signal});
});
window.addEventListener("pointerup", () => { this.interacting = false; }, {capture: true, signal});
window.addEventListener("pointercancel", () => { this.interacting = false; }, {capture: true, signal});
+ root.addEventListener("pointermove", event => {
+ if (event.buttons && (event.movementX || event.movementY)) {
+ this.restore();
+ }
+ }, {capture: true, signal});
window.addEventListener("keyup", event => {
this.interacting = false;
if (["PageDown", "PageUp", "Home", "End"].includes(event.key)) {
@@ -96,15 +112,6 @@ export class LargeTableVirtualizer {
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 &&
@@ -144,8 +151,23 @@ export class LargeTableVirtualizer {
});
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);
+ record.type === "childList" && record.target instanceof Element && record.target.contains(table))) {
+ const relevant = records.filter(record => table.contains(record.target));
+ const cellContentOnly = table.isConnected && relevant.length > 0 && relevant.every(record => {
+ const element = record.target instanceof Element ? record.target : record.target.parentElement;
+ const cell = element?.closest("td, th");
+ return cell?.closest("table") === table && (record.type !== "attributes" ||
+ record.attributeName === "class" || record.attributeName === "style") &&
+ !cell.matches(".fn__none, [hidden], [style*='display: none'], [style*='display:none']") &&
+ !cell.querySelector(".table__cell-rich, table, img, video, audio, iframe, canvas, math") &&
+ !Array.from(record.addedNodes).some(node => node instanceof Element && node.matches("tr, td, th"));
+ });
+ if (cellContentOnly) {
+ this.measureChunks(state);
+ this.schedule();
+ } else {
+ this.restore(table);
+ }
}
});
// 内联编辑器异步挂载完成后重新扫描,避免首次滚动早于编辑器就绪而停留在完整表格。
@@ -180,6 +202,17 @@ export class LargeTableVirtualizer {
}
}
+ private measureChunks(state: ITableViewport) {
+ const top = state.body.getBoundingClientRect().top;
+ state.chunks.forEach(chunk => {
+ const first = (chunk.rows?.[0] || chunk.placeholder).getBoundingClientRect();
+ const last = (chunk.rows?.[chunk.rows.length - 1] || chunk.placeholder).getBoundingClientRect();
+ chunk.top = first.top - top;
+ chunk.height = last.bottom - first.top;
+ });
+ state.height = state.table.getBoundingClientRect().height;
+ }
+
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 ||
@@ -251,7 +284,10 @@ export class LargeTableVirtualizer {
private refresh() {
this.onMutations(this.observer.takeRecords());
const selection = getSelection();
- if (!this.editor.isConnected || this.interacting || this.composing || this.blocked() ||
+ if (this.interacting) {
+ return;
+ }
+ if (!this.editor.isConnected || this.composing || this.blocked() ||
selection && !selection.isCollapsed && selection.rangeCount &&
selection.getRangeAt(0).intersectsNode(this.editor)) {
this.restore();
@@ -291,14 +327,11 @@ export class LargeTableVirtualizer {
!!row.querySelector(".table__cell-editor"));
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);
+ chunk.rows = restoreTableVirtualizationRows(chunk.placeholder);
}
} else if (chunk.rows) {
- chunk.placeholder.setAttribute(TABLE_VIRTUAL_ROWS, chunk.rows.map(row => row.outerHTML).join(""));
+ chunk.placeholder.cells[0].style.height = `${chunk.height}px`;
+ cacheTableVirtualizationRows(chunk.placeholder, chunk.rows);
chunk.rows[0].before(chunk.placeholder);
chunk.rows.forEach(row => row.remove());
chunk.rows = undefined;