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 sidebar performance https://github.com/siyuan-note/siyuan/issues/19911
Daniel364f2ffd0b75
diff --git a/app/src/protyle/wysiwyg/tableVirtualization.test.ts b/app/src/protyle/wysiwyg/tableVirtualization.test.tsindex deff7262fd..bc722dbaf6 100644--- a/app/src/protyle/wysiwyg/tableVirtualization.test.ts+++ b/app/src/protyle/wysiwyg/tableVirtualization.test.ts@@ -35,6 +35,7 @@ body {margin:0; --b3-theme-surface-lighter:#ddd; --b3-font-size-editor:16px; --b.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);}+.test-relative-table table {width:100%;}`;document.head.appendChild(style);const fixture = (count = 2000, pinned = false, mutate?: (table: HTMLTableElement) => void) => {@@ -82,6 +83,87 @@ body {margin:0; --b3-theme-surface-lighter:#ddd; --b3-font-size-editor:16px; --bcheck.ok(holder.textContent.includes(`Row ${count - 1} cell 4`));check.doesNotMatch(html, /data-sy-table-virtual/);};+ {+ const f = fixture(1000, false, table => {+ const block = table.parentElement.parentElement;+ block.after(block.cloneNode(true), block.cloneNode(true));+ });+ await tick();+ const tables = Array.from(f.editor.querySelectorAll("table"));+ tables.forEach(table => reduced(table));+ const ids = tables.map(table => table.getAttribute("data-sy-table-virtual-id"));+ let restores = 0;+ const restore = f.virtualizer.restore.bind(f.virtualizer);+ f.virtualizer.restore = table => { restores++; restore(table); };+ const outside = document.createElement("input");+ document.body.appendChild(outside);+ for (const type of ["pointerdown", "keydown", "beforeinput", "copy", "cut", "paste", "contextmenu"]) {+ outside.dispatchEvent(new Event(type, {bubbles: true}));+ }+ for (const width of [600, 540, 460, 380, 640]) {+ f.viewport.style.width = `${width}px`;+ f.editor.style.paddingLeft = `${(640 - width) / 10}px`;+ f.root.dispatchEvent(new Event("touchmove", {bubbles: true}));+ await tick();+ tables.forEach(table => reduced(table, "sidebar animation keeps all table windows"));+ }+ await new Promise(resolve => setTimeout(resolve, 250));+ await tick();+ check.equal(restores, 0, "outside interactions and viewport resizing do not materialize intrinsic-width tables");+ check.deepEqual(tables.map(table => table.getAttribute("data-sy-table-virtual-id")), ids,+ "sidebar animation does not rebuild table windows");+ tables.forEach(table => {+ check.ok(Math.abs(table.getBoundingClientRect().height - f.height) < 2);+ Array.from(table.rows[0].cells).forEach((cell, index) => {+ check.ok(Math.abs(cell.getBoundingClientRect().width - f.widths[index]) < 1);+ });+ });+ const other = fixture(300);+ await tick();+ other.editor.dispatchEvent(new Event("copy", {bubbles: true}));+ rowsMatch(other.editor.innerHTML, 300);+ tables.forEach(table => reduced(table, "another editor's clipboard events leave this editor virtualized"));+ other.destroy();+ outside.dispatchEvent(new KeyboardEvent("keydown", {bubbles: true, key: "f", ctrlKey: true}));+ tables.forEach(table => check.equal(table.tBodies[0].rows.length, 1000, "browser find restores every table"));+ outside.dispatchEvent(new KeyboardEvent("keyup", {bubbles: true, key: "f", ctrlKey: true}));+ outside.remove();+ f.destroy();+ }+ for (const sizing of ["inline", "theme", "fallback"]) {+ const f = fixture(600, false, table => {+ if (sizing !== "theme") {+ table.style.width = "100%";+ }+ if (sizing === "fallback") {+ Object.defineProperty(table, "computedStyleMap", {value: undefined});+ }+ table.querySelectorAll("th, td").forEach(cell => { cell.textContent = "Cell"; });+ });+ await tick();+ let restores = 0;+ const restore = f.virtualizer.restore.bind(f.virtualizer);+ f.virtualizer.restore = table => { restores++; restore(table); };+ if (sizing === "theme") {+ f.root.classList.add("test-relative-table");+ }+ for (const width of [600, 520, 440, 360]) {+ f.viewport.style.width = `${width}px`;+ await tick();+ reduced(f.table);+ }+ await new Promise(resolve => setTimeout(resolve, 250));+ await tick();+ check.equal(restores, 1, "container-dependent tables are measured once after resizing settles");+ check.ok(Math.abs(f.table.getBoundingClientRect().width - f.table.parentElement.clientWidth) < 2,+ "percentage widths follow the final container size");+ reduced(f.table);+ f.viewport.style.width = "500px";+ await tick();+ f.destroy();+ await new Promise(resolve => setTimeout(resolve, 250));+ check.equal(restores, 2, "destroy cancels the pending layout refresh");+ }for (const pinned of [false, true]) {const f = fixture(2000, pinned, table => {// 自动识别的虚拟块引用可出现在表头和任意正文行中。@@ -228,8 +310,11 @@ body {margin:0; --b3-theme-surface-lighter:#ddd; --b3-font-size-editor:16px; --browsMatch(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";+ const tableWidth = f.table.getBoundingClientRect().width;+ next.textContent = "Programmatic edit " + "Long cell content ".repeat(40);await tick();+ check.ok(Math.abs(f.table.getBoundingClientRect().width - tableWidth) < 1,+ "cell edits preserve the column widths used by offscreen row measurements");rowsMatch(api.cleanTableVirtualizationHTML(f.editor.innerHTML));check.ok(f.editor.textContent.includes("Programmatic edit"), "source updates keep visible edits and offscreen rows");f.destroy();diff --git a/app/src/protyle/wysiwyg/tableVirtualization.ts b/app/src/protyle/wysiwyg/tableVirtualization.tsindex dfd5bf1c3f..2e2e053e8b 100644--- a/app/src/protyle/wysiwyg/tableVirtualization.ts+++ b/app/src/protyle/wysiwyg/tableVirtualization.ts@@ -21,6 +21,15 @@ interface ITableViewport {height: number;}+// 固有宽度表格的列宽不随侧栏伸缩变化;无法读取原始宽度语义时保留重新测量。+const isTableResizeDependent = (table: HTMLTableElement) => {+ const styles = (table as HTMLTableElement & {+ computedStyleMap?: () => {get: (property: string) => {toString: () => string}},+ }).computedStyleMap?.();+ return !styles || styles.get("width")?.toString() !== "max-content" ||+ !["0px", "auto"].includes(styles.get("min-width")?.toString()) || styles.get("max-width")?.toString() !== "none";+};+export const isTableChunkVisible = (top: number, height: number, viewportTop: number, viewportBottom: number) =>top + height >= viewportTop && top <= viewportBottom;@@ -39,6 +48,7 @@ export class LargeTableVirtualizer {private composing = false;private font = "";private layout = "";+ private resizeTimeout = 0;constructor(private root: HTMLElement, private editor: HTMLElement, private viewport: HTMLElement,private blocked: () => boolean = () => false, private virtualCellSelection = true) {@@ -47,21 +57,51 @@ export class LargeTableVirtualizer {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"]});+ const initialStyle = getComputedStyle(editor);+ this.font = initialStyle.font;+ this.layout = [viewport.clientWidth, editor.clientWidth, initialStyle.paddingLeft, initialStyle.paddingRight].join("/");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) {- this.layout = layout;+ if (style.font !== this.font) {+ clearTimeout(this.resizeTimeout);this.font = style.font;this.restore();this.scan = true;this.schedule();- } else if (changedHeight) {- this.states.forEach(state => this.measureChunks(state));+ } else if (layout !== this.layout) {+ clearTimeout(this.resizeTimeout);+ // 侧栏动画和正文内边距会连续变化,待尺寸稳定后再检查表格的原始宽度规则。+ this.resizeTimeout = window.setTimeout(() => {+ const sheet = this.styleElement.sheet;+ if (!sheet || !this.editor.isConnected || !this.states.size) {+ return;+ }+ const disabled = sheet.disabled;+ let tables: HTMLTableElement[];+ // 查询期间只切换样式规则,不挂载屏外行;随后立即恢复固定列宽,保护行高缓存。+ sheet.disabled = true;+ try {+ tables = Array.from(this.states.keys()).filter(isTableResizeDependent);+ } finally {+ sheet.disabled = disabled;+ }+ if (tables.length) {+ tables.forEach(table => this.restore(table));+ this.scan = true;+ this.schedule();+ }+ }, 200);+ this.scan = true;this.schedule();}+ this.layout = layout;+ this.states.forEach(state => {+ if (Math.abs(state.table.getBoundingClientRect().height - state.height) > 2) {+ this.measureChunks(state);+ this.schedule();+ }+ });});this.resizeObserver.observe(viewport);this.resizeObserver.observe(editor);@@ -75,8 +115,19 @@ export class LargeTableVirtualizer {["pointerdown", "keydown", "beforeinput", "copy", "cut", "paste", "dragstart", "contextmenu"].forEach(type => {window.addEventListener(type, event => {const host = getTableCellRichEventTarget(event);+ const selection = getSelection();+ const globalFind = event instanceof KeyboardEvent && type === "keydown" &&+ (event.key === "F3" || !event.altKey && (event.ctrlKey || event.metaKey) &&+ ["f", "g"].includes(event.key.toLowerCase()));+ const selectedClipboard = ["copy", "cut"].includes(type) && selection?.rangeCount &&+ selection.getRangeAt(0).intersectsNode(this.editor);+ // 侧栏、其他编辑器和外部输入框的操作不恢复本编辑器,浏览器查找和正文选区复制仍读取完整内容。+ if (!globalFind && !selectedClipboard &&+ !(event.target instanceof Node && this.root.contains(event.target)) && !(host && this.root.contains(host))) {+ return;+ }if (host && ["keydown", "beforeinput", "copy", "cut", "paste"].includes(type) &&- (getSelection()?.isCollapsed || getTableCellRichSelectionHost(getSelection()) === host)) {+ (selection?.isCollapsed || getTableCellRichSelectionHost(selection) === host)) {return;}this.interacting = type === "pointerdown" || type === "keydown";@@ -363,6 +414,7 @@ export class LargeTableVirtualizer {public destroy() {cancelAnimationFrame(this.frame);+ clearTimeout(this.resizeTimeout);this.abortController.abort();this.resizeObserver.disconnect();this.restore();