Skip to content

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

:zap: Keep large table drag selections virtualized https://github.com/siyuan-note/siyuan/issues/19911

Daniel6c472e002e6d
diff --git a/app/src/protyle/util/tableControl.ts b/app/src/protyle/util/tableControl.ts
index ca548a551d..f9d249f85a 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, TABLE_VIRTUAL_ROWS} from "./tableVirtualizationDOM";
+import {getVirtualTableGrid, setTableVirtualSelection, TABLE_VIRTUAL_ID, TABLE_VIRTUAL_ROWS} from "./tableVirtualizationDOM";
import {clearTableCellContent, getTableCellPlainText, mergeTableCellContents} from "./tableCellRich";
import {renderTableCellRichElements} from "../render/tableCellRich";
import {updateTransaction} from "../wysiwyg/transaction";
@@ -345,7 +345,7 @@ export class TableControl {
private selectedCells: HTMLTableCellElement[] = [];
private selectionGrid: ITableGrid;
private gridCache = new TableGridCache(table => {
- const grid = buildTableGrid(table);
+ const grid = table.hasAttribute(TABLE_VIRTUAL_ID) ? getVirtualTableGrid(table) : 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)};
});
@@ -457,6 +457,9 @@ export class TableControl {
}
public clear() {
+ if (this.selection) {
+ setTableVirtualSelection(this.selection.table);
+ }
this.cancelResize();
this.clearDragPreview();
this.dragState = undefined;
@@ -503,6 +506,7 @@ export class TableControl {
activeCell,
};
this.caretCell = undefined;
+ setTableVirtualSelection(table, [anchorCell, activeCell]);
this.updateSelectedCells(grid);
getSelection()?.removeAllRanges();
this.scheduleRender();
@@ -1034,6 +1038,10 @@ export class TableControl {
return this.selectedCells.filter(cell => cell.isConnected);
}
+ public hasVirtualCellSelection() {
+ return this.selection?.mode === "cell" && this.selection.table.hasAttribute(TABLE_VIRTUAL_ID);
+ }
+
private updateSelectedCells(grid?: ITableGrid) {
if (!this.selection) {
this.selectedCells = [];
@@ -1364,7 +1372,7 @@ export class TableControl {
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 rowRect = typeof rowIndex === "number" ? cell.parentElement.getBoundingClientRect() : undefined;
const visibleRowRect = rowRect ? intersectRects(rowRect, viewportRect) : undefined;
const columnIndex = cellInfo?.col;
const columnRect = typeof columnIndex === "number" ?
@@ -1472,7 +1480,8 @@ export class TableControl {
}
});
} else if (this.isRectangle()) {
- const cells = this.getSelectedCells();
+ const cells = this.hasVirtualCellSelection() ?
+ [this.selection.anchor as HTMLTableCellElement, this.selection.activeCell] : this.getSelectedCells();
const rects = cells.map(item => item.getBoundingClientRect());
if (rects.length > 0) {
const left = Math.min(...rects.map(rect => rect.left));
diff --git a/app/src/protyle/util/tableVirtualizationDOM.ts b/app/src/protyle/util/tableVirtualizationDOM.ts
index f9bc6652fe..1eb9e9cbf8 100644
--- a/app/src/protyle/util/tableVirtualizationDOM.ts
+++ b/app/src/protyle/util/tableVirtualizationDOM.ts
@@ -3,6 +3,44 @@ 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[]}>();
+const selectionEndpoints = new WeakMap<HTMLTableElement, HTMLTableCellElement[]>();
+
+export const setTableVirtualSelection = (table: HTMLTableElement, cells?: HTMLTableCellElement[]) => {
+ if (cells) {
+ selectionEndpoints.set(table, cells);
+ } else {
+ selectionEndpoints.delete(table);
+ }
+};
+
+export const isTableVirtualSelectionRow = (table: HTMLTableElement, row: HTMLTableRowElement) =>
+ selectionEndpoints.get(table)?.some(cell => row.contains(cell));
+
+// 普通虚拟表格没有合并单元格,逻辑网格直接复用屏外缓存,不挂载屏外行。
+export const getVirtualTableGrid = (table: HTMLTableElement): import("./table").ITableGrid => {
+ const rows = Array.from(table.rows).flatMap(row => {
+ const source = row.getAttribute(TABLE_VIRTUAL_ROWS);
+ if (source === null) {
+ return [row];
+ }
+ let cached = detachedRows.get(row);
+ if (cached?.html !== source) {
+ const body = document.createElement("tbody");
+ body.innerHTML = source;
+ cached = {html: source, rows: Array.from(body.rows)};
+ detachedRows.set(row, cached);
+ }
+ return cached.rows;
+ });
+ const grid = rows.map(row => Array.from(row.cells));
+ return {
+ grid,
+ rowCount: rows.length,
+ columnCount: grid[0]?.length || 0,
+ sectionOfRow: rows.map(row => row.parentElement?.tagName === "THEAD" ? "thead" : "tbody"),
+ cellInfos: grid.flatMap((cells, row) => cells.map((cell, col) => ({cell, row, col, rowspan: 1, colspan: 1}))),
+ };
+};
export const getTableVirtualRowIndex = (row: HTMLTableRowElement) => {
let index = 0;
diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.ts
index d0e69e748d..305a3a721e 100644
--- a/app/src/protyle/wysiwyg/index.ts
+++ b/app/src/protyle/wysiwyg/index.ts
@@ -145,6 +145,7 @@ import {
setTableCellStyle,
TableControl,
} from "../util/tableControl";
+import {TABLE_VIRTUAL_ID} from "../util/tableVirtualizationDOM";
import {countBlockWord, countSelectWord} from "../../layout/status";
import {showMessage} from "../../dialog/message";
import {getBacklinkHeadingMore, loadBreadcrumb} from "./renderBacklink";
@@ -597,9 +598,9 @@ export class WYSIWYG {
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 ||
+ !!this.tableControl?.getSelectedCells().length && !this.tableControl.hasVirtualCellSelection() ||
!!window.siyuan.menus?.menu?.element && !window.siyuan.menus.menu.element.classList.contains("fn__none") ||
- !!window.siyuan.dragElement || !!this.element.querySelector(".protyle-wysiwyg--select"));
+ !!window.siyuan.dragElement || !!this.element.querySelector(".protyle-wysiwyg--select"), !!this.tableControl);
}
}
@@ -2349,7 +2350,10 @@ export class WYSIWYG {
};
let selectionRects: ReturnType<typeof getCellRect>[] = [];
let logicalSelection = false;
- if (target.tagName === "TH" || target.tagName === "TD") {
+ if (tableElement.hasAttribute(TABLE_VIRTUAL_ID) && (target.tagName === "TH" || target.tagName === "TD")) {
+ selectionRects = [getCellRect(target), getCellRect(moveTarget)];
+ logicalSelection = true;
+ } else if (target.tagName === "TH" || target.tagName === "TD") {
if (!tableSelectionGrid) {
tableSelectionGrid = buildTableGrid(tableElement);
tableSelectionMerged = tableSelectionGrid.cellInfos.some(info =>
diff --git a/app/src/protyle/wysiwyg/tableVirtualization.test.ts b/app/src/protyle/wysiwyg/tableVirtualization.test.ts
index 059c0d728a..0c8c1f5552 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, getTableVirtualRowIndex, TableGridCache, buildTableGrid, getTableGridRect, searchMarkRender, " +
+ "restoreTableVirtualizationDOM, getTableVirtualRowIndex, getVirtualTableGrid, setTableVirtualSelection, 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") & {
@@ -184,7 +184,7 @@ body {margin:0; --b3-theme-surface-lighter:#ddd; --b3-font-size-editor:16px; --b
{
const f = fixture();
await tick();
- const cell = f.table.querySelector("tbody td");
+ const cell = f.table.querySelector<HTMLTableCellElement>("tbody td");
const range = document.createRange();
range.selectNodeContents(cell);
range.collapse(true);
@@ -197,9 +197,23 @@ body {margin:0; --b3-theme-surface-lighter:#ddd; --b3-font-size-editor:16px; --b
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");
+ reduced(f.table, "dragging inside the table does not materialize offscreen rows");
+ const logical = api.getVirtualTableGrid(f.table);
+ check.equal(logical.rowCount, 2001);
+ check.equal(logical.cellInfos.length, 10005);
+ check.equal(logical.grid[2000][0].parentElement, f.originalLastRow);
+ const renderedCells = f.table.querySelectorAll<HTMLTableCellElement>("tbody > tr:not([data-sy-table-virtual-rows]) td");
+ const endpoint = renderedCells[renderedCells.length - 1];
+ api.setTableVirtualSelection(f.table, [cell, endpoint]);
+ f.scroller.scrollTop = f.scroller.scrollHeight * 0.9;
+ await tick();
+ reduced(f.table, "drag scrolling retains a bounded window");
+ check.ok(cell.isConnected && endpoint.isConnected, "selection endpoints stay connected across scrolling");
cell.dispatchEvent(new PointerEvent("pointerup", {bubbles: true, pointerType: "mouse"}));
+ cell.dispatchEvent(new Event("copy", {bubbles: true}));
+ check.equal(f.table.tBodies[0].rows.length, 2000, "copy restores all selected rows");
+ check.ok(logical.grid[2000][0].isConnected, "logical selection identities survive materialization");
+ api.setTableVirtualSelection(f.table);
cell.textContent = "Edited cell";
f.root.dispatchEvent(new WheelEvent("wheel", {bubbles: true}));
await tick();
@@ -231,7 +245,7 @@ body {margin:0; --b3-theme-surface-lighter:#ddd; --b3-font-size-editor:16px; --b
{
const f = fixture();
await tick();
- const cell = f.table.querySelector("tbody td");
+ const cell = f.table.querySelector<HTMLTableCellElement>("tbody td");
cell.dispatchEvent(new PointerEvent("pointerdown", {bubbles: true}));
cell.innerHTML = '<div class="table__cell-editor table__cell--inline"><div contenteditable="true">Editing</div>' +
'<button class="fn__none"><svg></svg></button></div>';
@@ -328,6 +342,7 @@ test("large tables retain complete source, editing, selection, search and layout
const prepare = wysiwyg.statements.find(isClassDeclaration).members.find(member =>
member.name?.getText(wysiwyg) === "prepareBlockVirtualization");
const integration = compile(`class VirtualizedEditor {
+ tableControl = {getSelectedCells: () => [], hasVirtualCellSelection: () => false};
pendingInputTimeouts = new Map();
runningInputTasks = new Set();
constructor(protyle) {this.protyle = protyle; this.element = protyle.wysiwyg.element;}
diff --git a/app/src/protyle/wysiwyg/tableVirtualization.ts b/app/src/protyle/wysiwyg/tableVirtualization.ts
index 4b514593cb..24c76efed4 100644
--- a/app/src/protyle/wysiwyg/tableVirtualization.ts
+++ b/app/src/protyle/wysiwyg/tableVirtualization.ts
@@ -1,4 +1,4 @@
-import {cacheTableVirtualizationRows, restoreTableVirtualizationDOM, restoreTableVirtualizationRows, TABLE_VIRTUAL_COLUMNS, TABLE_VIRTUAL_ID} from "../util/tableVirtualizationDOM";
+import {cacheTableVirtualizationRows, isTableVirtualSelectionRow, restoreTableVirtualizationDOM, restoreTableVirtualizationRows, setTableVirtualSelection, TABLE_VIRTUAL_COLUMNS, TABLE_VIRTUAL_ID} from "../util/tableVirtualizationDOM";
export const LARGE_TABLE_ROW_THRESHOLD = 256;
// 奇数行替换为一个占位行后,后续内容的隔行底色顺序保持不变。
@@ -34,12 +34,13 @@ export class LargeTableVirtualizer {
private frame = 0;
private scan = true;
private interacting = false;
+ private dragTable?: HTMLTableElement;
private composing = false;
private font = "";
private layout = "";
constructor(private root: HTMLElement, private editor: HTMLElement, private viewport: HTMLElement,
- private blocked: () => boolean = () => false) {
+ private blocked: () => boolean = () => false, private virtualCellSelection = true) {
root.appendChild(this.styleElement);
const signal = this.abortController.signal;
this.observer = new MutationObserver(records => this.onMutations(records));
@@ -75,20 +76,27 @@ export class LargeTableVirtualizer {
this.interacting = type === "pointerdown" || type === "keydown";
if (type === "pointerdown") {
const pointer = event as PointerEvent;
- const cell = (event.target as Element).closest?.("td, th");
+ const cell = (event.target as Element).closest?.<HTMLTableCellElement>("td, th");
if (pointer.button === 0 && !pointer.shiftKey && !pointer.ctrlKey && !pointer.metaKey &&
!pointer.altKey && cell && this.states.has(cell.closest("table"))) {
+ if (this.virtualCellSelection && pointer.pointerType === "mouse") {
+ this.dragTable = cell.closest("table");
+ setTableVirtualSelection(this.dragTable, [cell]);
+ }
return;
}
}
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("pointerup", () => { this.interacting = false; this.dragTable = undefined; }, {capture: true, signal});
+ window.addEventListener("pointercancel", () => { this.interacting = false; this.dragTable = undefined; }, {capture: true, signal});
root.addEventListener("pointermove", event => {
if (event.buttons && (event.movementX || event.movementY)) {
- this.restore();
+ if (!this.dragTable?.contains(event.target as Node)) {
+ this.dragTable = undefined;
+ this.restore();
+ }
}
}, {capture: true, signal});
window.addEventListener("keyup", event => {
@@ -114,7 +122,7 @@ export class LargeTableVirtualizer {
}, {passive: true, signal});
document.addEventListener("selectionchange", () => {
const selection = getSelection();
- if (selection && !selection.isCollapsed && selection.rangeCount &&
+ if (!this.dragTable && selection && !selection.isCollapsed && selection.rangeCount &&
selection.getRangeAt(0).intersectsNode(this.editor)) {
this.restore();
}
@@ -284,11 +292,11 @@ export class LargeTableVirtualizer {
private refresh() {
this.onMutations(this.observer.takeRecords());
const selection = getSelection();
- if (this.interacting) {
+ if (this.interacting && !this.dragTable) {
return;
}
if (!this.editor.isConnected || this.composing || this.blocked() ||
- selection && !selection.isCollapsed && selection.rangeCount &&
+ !this.dragTable && selection && !selection.isCollapsed && selection.rangeCount &&
selection.getRangeAt(0).intersectsNode(this.editor)) {
this.restore();
return;
@@ -323,7 +331,7 @@ export class LargeTableVirtualizer {
plans.forEach(({state, top, bottom}) => {
state.chunks.forEach(chunk => {
// 内联单元格编辑器包含交互状态,即使光标移走也不能序列化或卸载。
- const pinned = chunk.rows?.some(row => row.contains(selection?.anchorNode) ||
+ const pinned = chunk.rows?.some(row => row.contains(selection?.anchorNode) || isTableVirtualSelectionRow(state.table, row) ||
!!row.querySelector(".table__cell-editor"));
if (pinned || isTableChunkVisible(chunk.top, chunk.height, top, bottom)) {
if (!chunk.rows) {