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: Keep large table cell editing virtualized https://github.com/siyuan-note/siyuan/issues/19911
Daniel07df6c64021f
diff --git a/app/src/protyle/render/tableCellInput.test.ts b/app/src/protyle/render/tableCellInput.test.tsindex 247bc0e919..a358b13f5b 100644--- a/app/src/protyle/render/tableCellInput.test.ts+++ b/app/src/protyle/render/tableCellInput.test.ts@@ -7,7 +7,7 @@ import {test} from "node:test";import {promisify} from "node:util";import {createSourceFile, isClassDeclaration, isVariableStatement, ScriptTarget, transpileModule} from "typescript";-const browserCases = async (source: string, queueSource: string, editorSource: string, menuSource: string) => {+const browserCases = async (source: string, queueSource: string, editorSource: string, menuSource: string, transactionSource: string) => {const check: typeof assert = require("node:assert/strict");const noop = () => {};const tick = () => new Promise(resolve => setTimeout(resolve, 0));@@ -17,7 +17,8 @@ const browserCases = async (source: string, queueSource: string, editorSource: sgetSelection().addRange(range);};Object.assign(window, {siyuan: {- config: {editor: {markdown: {}}, keymap: {editor: {table: new Proxy({}, {get: () => ({custom: ""})})}}},+ config: {editor: {markdown: {}}, keymap: {editor: {table: new Proxy({}, {get: () => ({custom: ""})}),+ general: {undo: {custom: "Ctrl+Z"}, redo: {custom: "Ctrl+Y"}}}}},storage: {}, languages: new Proxy({}, {get: () => "${x}"}), menus: {menu: {remove: noop}},}});const dependencies = {@@ -41,11 +42,13 @@ const browserCases = async (source: string, queueSource: string, editorSource: sconst api = new Function(...Object.keys(dependencies), source + "\nreturn {input, insertRow, insertRowAbove, insertColumn, " +"getAgentLute, configureAVRichTextLute, getTableCellEditorLute, getAVRichTextLute, " +"getTableCellRichBlockDOM, serializeTableCellRich, cleanTableCellRichHTML, renderTableCellRich, " +- "setTableCellRich, getTableCellInlineHTML, getSelectionOffset, focusByOffset, " +- "getTableVirtualRowIndex, restoreTableVirtualizationDOM};")(...Object.values(dependencies)) as+ "setTableCellRich, getTableCellInlineHTML, getSelectionOffset, focusByOffset, getTableBlockHTML, updateTableCellEditingValue, " ++ "updateTableCellContentLayout, captureRichCellSelection, restoreRichCellSelection, setTableCellRichEventTarget, " ++ "LargeTableVirtualizer, getTableVirtualCellIndex, getTableVirtualRowIndex, restoreTableVirtualizationDOM};")(...Object.values(dependencies)) astypeof 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/tableVirtualizationDOM");+ typeof import("../util/tableCellRich") & typeof import("../util/selection") & typeof import("../util/tableVirtualizationDOM") &+ typeof import("../wysiwyg/tableVirtualization") & typeof import("../util/tableCellRichContext") & typeof import("../util/tableCellRichSelection");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 () => {@@ -93,11 +96,16 @@ const browserCases = async (source: string, queueSource: string, editorSource: s...dependencies, ...api, TABLE_CELL_INLINE_ATTRIBUTE: "data-sy-table-cell-inline",TABLE_CELL_RICH_ATTRIBUTE: "data-sy-table-cell-rich", TABLE_CELL_SLASH_IDS: new Set(),hintRef: noop, hintTag: noop, registerBuiltinSlashHint: (callback: unknown) => callback,- getDefaultToolbar: (): string[] => [], captureRichCellSelection: noop, updateOutlineCurrentBlock: noop,+ getDefaultToolbar: (): string[] => [], updateOutlineCurrentBlock: noop,setMobileToolbarUndo: noop, setTableCellRichContext: noop, bindTableCellRichDrag: noop,- bindLiteCodeActions: noop, updateTableCellContentLayout: noop,+ bindLiteCodeActions: noop, highlightRender: noop,+ matchHotKey: () => false,+ getUndoFocusContext: (_element: Element, range: Range) => {+ const table = (range.startContainer as Element).closest('[data-type="NodeTable"]');+ return {undoFocusId: table.getAttribute("data-node-id"), undoFocusIndex: "0", undoFocusStart: "0", undoFocusEnd: "0"};+ },showMessage: (message: string) => { throw new Error(message); },- mountProtyleLiteFragment: (host: HTMLElement, options: {initialBlockHTML: string}) => {+ mountProtyleLiteFragment: (host: HTMLElement, options: {initialBlockHTML: string, onChange: () => void}) => {// 保留会被 Lute 误读为正文的界面,验证输入任务与实际挂载边界的交接。host.innerHTML = '<div class="protyle-content"><div class="protyle-wysiwyg">' +options.initialBlockHTML + '</div></div><div class="protyle-preview">DesktopTabletMobile</div>' +@@ -106,6 +114,8 @@ const browserCases = async (source: string, queueSource: string, editorSource: sconst wysiwyg = host.querySelector<HTMLElement>(".protyle-wysiwyg");const hidden = document.createElement("div");hidden.className = "fn__none";+ api.updateTableCellContentLayout(host, options.initialBlockHTML);+ wysiwyg.addEventListener("input", () => options.onChange());return {wysiwyg, hintElement: hidden,protyle: {block: {}, toolbar: {element: hidden, subElement: hidden}, undo: {clear: noop}},@@ -119,6 +129,22 @@ const browserCases = async (source: string, queueSource: string, editorSource: s};},};+ let snapshotParses = 0;+ const transactionDependencies = {...dependencies, ...api,+ TABLE_VIRTUAL_ID: "data-sy-table-virtual-id",+ cleanListMindmapHTML: (html: string) => html, cleanHeadingNumberHTML: (html: string) => html,+ cleanBlockSelectionModeHTML: (html: string) => html,+ getVisibleFoldHeadingHTML: (html: string) => { snapshotParses++; return html; },+ getEmbedChildOperationContext: noop,+ isInEmbedBlock: (element: Element) => element.closest(".protyle-wysiwyg__embed"),+ captureBlockSelectionModeState: noop, restoreBlockSelectionModeState: noop,+ disposeCustomBlocksInElement: noop, processRender: noop, highlightRender: noop,+ focusRestoredBlockSelectionMode: noop, syncTrackedRanges: noop, queueTransactionBatch: noop,+ };+ delete transactionDependencies.updateTransaction;+ const transactionAPI = new Function(...Object.keys(transactionDependencies),+ transactionSource + "\nreturn {updateTransaction, promiseTransaction};")(...Object.values(transactionDependencies));+ editorDependencies.updateTransaction = transactionAPI.updateTransaction;const open = new Function(...Object.keys(editorDependencies), editorSource + "\nreturn openTableCellRichEditor;")(...Object.values(editorDependencies)) as typeof import("./tableCellRichEditor").openTableCellRichEditor;const noUI = (html: string) => check.doesNotMatch(html, /DesktopTabletMobile|Font family|Font Size|search-mark-regression|table__cell-editor/);@@ -132,6 +158,136 @@ const browserCases = async (source: string, queueSource: string, editorSource: sawait tick();};+ {+ const {owner, element, wysiwyg, table} = fixture();+ await open(owner, table.querySelector("th"));+ const host = table.querySelector(".table__cell-editor");+ const operation = {action: "update", id: table.dataset.nodeId, data: api.getTableBlockHTML(table)};+ transactionAPI.promiseTransaction({protyle: owner, doOperations: [operation]});+ check.equal(snapshotParses, 0, "saving the active block without embedded copies never parses its complete HTML");+ const copy = table.cloneNode(true) as HTMLElement;+ copy.querySelector("th").textContent = "stale";+ wysiwyg.appendChild(copy);+ const embed = document.createElement("div");+ embed.className = "protyle-wysiwyg__embed";+ embed.dataset.id = table.dataset.nodeId;+ embed.innerHTML = `<div data-node-id="${table.dataset.nodeId}">stale embedded table</div>`;+ wysiwyg.appendChild(embed);+ const unrelated = document.createElement("div");+ unrelated.className = "protyle-wysiwyg__embed";+ unrelated.dataset.id = "other";+ unrelated.innerHTML = '<div data-node-id="other">Keep unrelated</div>';+ wysiwyg.appendChild(unrelated);+ transactionAPI.promiseTransaction({protyle: owner, doOperations: [operation]});+ check.equal(copy.isConnected, false, "another visible copy receives the complete snapshot");+ check.equal(embed.querySelector("th").textContent, "Hello", "embedded copies still synchronize");+ check.equal(unrelated.textContent, "Keep unrelated");+ check.equal(snapshotParses, 4, "one shared lookup snapshot serves all embedded copies");+ check.ok(host.isConnected && host.contains(getSelection().anchorNode), "local synchronization preserves the current editor");+ await finish(element);+ }++ for (const mobile of [false, true]) {+ const {owner, element, wysiwyg, table} = fixture();+ element.style.cssText = "height:240px;width:640px;overflow:auto";+ table.querySelector("tbody").innerHTML = Array.from({length: 600}, (_, row) =>+ `<tr style="height:28px"><td>Row ${row}</td><td>Value ${row}</td><td>Keep ${row}</td></tr>`).join("");+ const actualTable = table.querySelector("table");+ const target = actualTable.rows[401].cells[1];+ const lastRow = actualTable.rows[600];+ element.scrollTop = target.offsetTop - 40;+ const virtualizer = new api.LargeTableVirtualizer(element, wysiwyg, element, () => false, !mobile);+ const frame = () => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => setTimeout(resolve, 30))));+ await frame();+ const bounded = (phase = "input") => {+ check.ok(actualTable.rows.length < 180,+ `cell editing keeps offscreen rows detached (${phase}): ${actualTable.rows.length}, ${actualTable.outerHTML.slice(0, 400)}`);+ check.equal(lastRow.isConnected, false);+ };+ bounded("before opening");+ check.ok(target.isConnected);+ await open(owner, target);+ await frame();+ bounded("after opening");+ const host = target.querySelector<HTMLElement>(".table__cell-editor");+ const editable = host.querySelector<HTMLElement>('[contenteditable="true"]');+ const focus = () => {+ const range = document.createRange();+ range.selectNodeContents(editable);+ range.collapse(false);+ focusByRange(range);+ };+ const input = async (text: string) => {+ editable.dispatchEvent(new InputEvent("beforeinput", {bubbles: true, inputType: "insertText", data: text}));+ editable.textContent += text;+ focus();+ editable.dispatchEvent(new InputEvent("input", {bubbles: true, inputType: "insertText", data: text}));+ await frame();+ bounded();+ check.ok(host.contains(getSelection().anchorNode), "saving preserves the native caret");+ };+ const readCell = (operation: IOperation, expected: string) => {+ const html = operationHTML(operation);+ check.doesNotMatch(html, /data-sy-table-virtual|data-sy-table-cell-inline/);+ const snapshot = document.createElement("div");+ snapshot.innerHTML = html;+ const rows = snapshot.querySelector("table").rows;+ check.equal(rows.length, 601);+ check.equal(rows[401].cells[1].textContent, expected);+ check.equal(rows[600].cells[2].textContent, "Keep 599");+ check.equal(operation.context.undoFocusTableCell, (401 * 3 + 1).toString());+ return snapshot;+ };+ focus();+ await input(" A");+ check.equal(changes.length, 1, "the first edit is submitted immediately");+ const firstSnapshot = operationHTML(changes[0].doOperations[0]);+ readCell(changes[0].undoOperations[0], "Value 400");+ readCell(changes[0].doOperations[0], "Value 400 A");+ await input(" B");+ check.equal(changes.length, 2, "successive edits retain separate transactions");+ readCell(changes[1].undoOperations[0], "Value 400 A");+ readCell(changes[1].doOperations[0], "Value 400 A B");+ check.equal(operationHTML(changes[0].doOperations[0]), firstSnapshot, "later edits do not mutate earlier snapshots");+ editable.dispatchEvent(new CompositionEvent("compositionstart", {bubbles: true}));+ await input("中文");+ check.equal(changes.length, 2, "IME intermediate text is not committed");+ editable.dispatchEvent(new CompositionEvent("compositionend", {bubbles: true, data: "中文"}));+ await frame();+ bounded();+ check.equal(changes.length, 3, "IME completion is committed once");+ readCell(changes[2].doOperations[0], "Value 400 A B中文");+ const selection = JSON.parse(changes[2].doOperations[0].context.undoFocusTableSelection);+ check.equal(selection.start, editable.textContent.length);+ const replay = readCell(changes[2].undoOperations[0], "Value 400 A B");+ const previousCell = replay.querySelector("table").rows[401].cells[1];+ previousCell.innerHTML = api.getTableCellRichBlockDOM(previousCell);+ document.body.appendChild(replay);+ check.ok(api.restoreRichCellSelection(previousCell, JSON.parse(changes[2].undoOperations[0].context.undoFocusTableSelection)));+ check.equal(getSelection().anchorOffset, "Value 400 A B".length, "undo restores the previous caret offset");+ replay.remove();+ focus();+ const range = document.createRange();+ range.selectNodeContents(editable);+ focusByRange(range);+ document.dispatchEvent(new Event("selectionchange"));+ for (const type of ["copy", "cut", "paste"]) {+ editable.dispatchEvent(new Event(type, {bubbles: true}));+ bounded();+ }+ focus();+ editable.dispatchEvent(new KeyboardEvent("keydown", {bubbles: true, key: "a"}));+ bounded();+ // 多块内容切换回完整表格,事务仍包含全部行和最后一次内联内容。+ editable.parentElement.insertAdjacentHTML("afterend", '<div data-type="NodeParagraph"><div contenteditable="true">Second paragraph</div></div>');+ editable.dispatchEvent(new Event("input", {bubbles: true}));+ check.equal(actualTable.rows.length, 601);+ readCell(changes[3].undoOperations[0], "Value 400 A B中文");+ check.ok(operationHTML(changes[3].doOperations[0]).includes("data-sy-table-cell-rich"));+ virtualizer.destroy();+ await finish(element);+ }+for (const count of [1, 5]) {for (const running of [false, true]) {for (const text of ["", "**pending**"]) {@@ -296,6 +452,7 @@ test("table cell editors wait for outer input and table menu Enter is consumed",const source = ["../util/longTextWrap.ts", "../util/inlineElementBoundary.ts", "../toolbar/fontFamilyCore.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/tableCellRichContext.ts", "../util/tableCellRichSelection.ts", "../wysiwyg/tableVirtualization.ts","../util/hasClosest.ts", "../wysiwyg/getBlock.ts", "../util/table.ts", "../wysiwyg/input.ts"].map(file => compile(read(file))).join("\n") + "\n" + compile(selectionSource);const wysiwyg = createSourceFile("wysiwyg.ts", read("../wysiwyg/index.ts"), ScriptTarget.Latest, true);@@ -306,6 +463,11 @@ test("table cell editors wait for outer input and table menu Enter is consumed",const menu = read("../../menus/protyle.ts");const menuStart = menu.indexOf("const insertMenus = [];", menu.indexOf("export const tableMenu"));const menuSource = compile(menu.substring(menuStart, menu.indexOf("menus.push(...insertMenus);", menuStart)));+ const transactionFile = createSourceFile("transaction.ts", read("../wysiwyg/transaction.ts"), ScriptTarget.Latest, true);+ const transactionSource = compile(transactionFile.statements.filter(isVariableStatement).filter(statement =>+ statement.declarationList.declarations.some(declaration =>+ ["updateTransaction", "promiseTransaction"].includes(declaration.name.getText(transactionFile))))+ .map(statement => statement.getText(transactionFile)).join("\n"));const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-table-cell-input-test-"));const script = path.join(temporary, "run.cjs");const lutePath = path.resolve(__dirname, "../../../stage/protyle/js/lute/lute.min.js");@@ -313,12 +475,14 @@ test("table cell editors wait for outer input and table menu Enter is consumed",app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});app.commandLine.appendSwitch("disable-gpu");app.whenReady().then(async () => {- const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});+ const win = new BrowserWindow({show: false, webPreferences: {+ nodeIntegration: true, contextIsolation: false, offscreen: true, backgroundThrottling: false,+ }});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() + ")(" + [source, queue, compile(read("tableCellRichEditor.ts")), menuSource]+ browserCases.toString() + ")(" + [source, queue, compile(read("tableCellRichEditor.ts")), menuSource, transactionSource].map(value => JSON.stringify(value)).join(",") + ")")}));win.destroy();app.exit(0);diff --git a/app/src/protyle/render/tableCellRichEditor.ts b/app/src/protyle/render/tableCellRichEditor.tsindex c02d9af3de..cbd9e52b5f 100644--- a/app/src/protyle/render/tableCellRichEditor.ts+++ b/app/src/protyle/render/tableCellRichEditor.ts@@ -11,7 +11,7 @@ import {configureAVRichTextLute, getAVRichTextLute, getAVRichTextUnsupportedPastimport {highlightRender} from "./highlightRender";import {mathRender} from "./mathRender";import {renderTableCellRichElements} from "./tableCellRich";-import {cleanTableCellRichHTML, getTableCellInlineHTML, getTableCellRichBlockDOM, renderTableCellRich, serializeTableCellRich, setTableCellRich, TABLE_CELL_INLINE_ATTRIBUTE, updateTableCellEditingValue} from "../util/tableCellRich";+import {getTableBlockHTML, getTableCellInlineHTML, getTableCellRichBlockDOM, renderTableCellRich, serializeTableCellRich, setTableCellRich, TABLE_CELL_INLINE_ATTRIBUTE, updateTableCellEditingValue} from "../util/tableCellRich";import {TABLE_CELL_RICH_ATTRIBUTE} from "../util/tableCellRichValue";import {focusByOffset, focusByRange, getSelectionOffset, getUndoFocusContext} from "../util/selection";import {getAdjacentRichTableCell, isTableCellCaretAtBoundary} from "../util/tableCellRichNavigation";@@ -23,11 +23,11 @@ import {captureRichCellSelection, captureRichCellSelectionAtPoint, restoreRichCeimport {matchHotKey} from "../util/hotKey";import {bindTableCellRichDrag} from "../util/tableCellRichDrag";import {getTableCellEditorLute} from "../util/tableCellRichLute";-import {setTableCellRichContext} from "../util/tableCellRichContext";+import {setTableCellRichContext, setTableCellRichEventTarget} from "../util/tableCellRichContext";import {updateOutlineCurrentBlock} from "../util/outlineBlock";import {canEnterCodeBlock} from "../wysiwyg/codeBlockEnter";import {bindLiteCodeActions} from "../lite/codeActions";-import {getTableVirtualRowIndex, restoreTableVirtualizationDOM} from "../util/tableVirtualizationDOM";+import {getTableVirtualCellIndex, getTableVirtualRowIndex, restoreTableVirtualizationDOM} from "../util/tableVirtualizationDOM";let activeEditor: {cell: Element, finish: () => void} | undefined;let openingEditor: object | undefined;@@ -166,6 +166,7 @@ export const openTableCellRichEditor = async (owner: IProtyle, cell: HTMLTableCectrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey,bubbles: true, cancelable: true,});+ setTableCellRichEventTarget(forwarded, host);if (!owner.element.dispatchEvent(forwarded)) {event.preventDefault();}@@ -238,18 +239,19 @@ export const openTableCellRichEditor = async (owner: IProtyle, cell: HTMLTableCecontentChanged = false;return;}- // 事务的撤销定位使用完整单元格索引,提交修改前恢复屏外行。- restoreTableVirtualizationDOM(table);- const oldHTML = cleanTableCellRichHTML(table.outerHTML);+ if (getTableCellInlineHTML(serialized.blockDOM) === null) {+ restoreTableVirtualizationDOM(table);+ }+ const oldHTML = getTableBlockHTML(table);const redoSelection = captureRichCellSelection(fragment.wysiwyg, getSelection(), true) || undoSelection;const tableRange = document.createRange();tableRange.selectNodeContents(cell);tableRange.collapse(true);const context = getUndoFocusContext(owner.wysiwyg.element, tableRange, true);- const cellIndex = Array.from(table.querySelectorAll("th, td")).indexOf(cell).toString();+ // 索引以完整表格为参照,读取屏外行计数即可记录撤销位置。+ context.undoFocusTableCell = getTableVirtualCellIndex(cell).toString();const focusContext = (saved: typeof undoSelection) => saved ? {...context,- undoFocusTableCell: cellIndex,undoFocusTableSelection: JSON.stringify(saved),} : context;source = serialized.markdown;@@ -303,6 +305,7 @@ export const openTableCellRichEditor = async (owner: IProtyle, cell: HTMLTableCe}// 先提交当前单元格,再由所属文档撤销,保证切换单元格后仍可连续回退。finish();+ restoreTableVirtualizationDOM(table);const range = document.createRange();range.selectNodeContents(cell);range.collapse(true);@@ -419,6 +422,7 @@ export const openTableCellRichEditor = async (owner: IProtyle, cell: HTMLTableCeevent.stopImmediatePropagation();// 先提交内嵌编辑内容,再以所属单元格执行表格快捷键。finish();+ restoreTableVirtualizationDOM(table);const range = document.createRange();range.selectNodeContents(cell);range.collapse(true);@@ -450,6 +454,7 @@ export const openTableCellRichEditor = async (owner: IProtyle, cell: HTMLTableCeisTableCellCaretAtBoundary(fragment.wysiwyg, range, event.key)) {event.preventDefault();event.stopImmediatePropagation();+ restoreTableVirtualizationDOM(table);const nextCell = getAdjacentRichTableCell(cell, event.key);if (nextCell) {const goalX = getCaretGoalX(range);@@ -473,6 +478,7 @@ export const openTableCellRichEditor = async (owner: IProtyle, cell: HTMLTableCeevent.preventDefault();event.stopImmediatePropagation();finish();+ restoreTableVirtualizationDOM(table);const tableRange = document.createRange();tableRange.selectNodeContents(cell);tableRange.collapse(true);diff --git a/app/src/protyle/util/tableCellRich.ts b/app/src/protyle/util/tableCellRich.tsindex 4f275404d6..2348c69ad1 100644--- a/app/src/protyle/util/tableCellRich.ts+++ b/app/src/protyle/util/tableCellRich.ts@@ -2,6 +2,7 @@ import {getAVRichTextBlockDOM, getAVRichTextLute, sanitizeAVRichTextBlockDOM, seimport {decodeTableCellRich, encodeTableCellRich, TABLE_CELL_RICH_ATTRIBUTE, TABLE_RICH_ATTRIBUTE} from "./tableCellRichValue";import {restoreInlineElementBoundaries} from "./inlineElementBoundary";import {getTextWithoutSemanticMarkers} from "./inlineElementMarker";+import {getTableVirtualizationHTML, TABLE_VIRTUAL_ID} from "./tableVirtualizationDOM";export const TABLE_CELL_INLINE_ATTRIBUTE = "data-sy-table-cell-inline";@@ -242,6 +243,21 @@ export const cleanTableCellRichHTML = (html: string) => {return template.innerHTML;};+// 编辑器界面只在单元格副本中替换,完整表格快照由可见行与屏外缓存拼接。+export const getTableBlockHTML = (table: Element) => {+ if (!table.querySelector(`[${TABLE_VIRTUAL_ID}]`)) {+ return cleanTableCellRichHTML(table.outerHTML);+ }+ const replacements = new Map<Element, string>();+ table.querySelectorAll(`th[${TABLE_CELL_RICH_ATTRIBUTE}], td[${TABLE_CELL_RICH_ATTRIBUTE}], ` ++ `th[${TABLE_CELL_INLINE_ATTRIBUTE}], td[${TABLE_CELL_INLINE_ATTRIBUTE}]`).forEach(cell => {+ const clone = cell.cloneNode(false) as Element;+ renderTableCellRich(clone);+ replacements.set(cell, clone.outerHTML);+ });+ return getTableVirtualizationHTML(table, replacements);+};+export const retainTableCellRichMetadata = (html: string, changedHTML: string) => {if (!changedHTML.includes(TABLE_RICH_ATTRIBUTE)) {return html;diff --git a/app/src/protyle/util/tableCellRichContext.ts b/app/src/protyle/util/tableCellRichContext.tsindex 5c7158aa91..3c6a3cd8ed 100644--- a/app/src/protyle/util/tableCellRichContext.ts+++ b/app/src/protyle/util/tableCellRichContext.ts@@ -1,6 +1,24 @@type TableCellContext = {owner: IProtyle, cell: HTMLTableCellElement, finish: () => void};const contexts = new WeakMap<IProtyle, TableCellContext>();+const forwardedEventTargets = new WeakMap<Event, HTMLElement>();++export const setTableCellRichEventTarget = (event: Event, host: HTMLElement) => {+ forwardedEventTargets.set(event, host);+};++const getInlineEditor = (node: EventTarget | null) => {+ const element = node instanceof Element ? node : node instanceof Node ? node.parentElement : undefined;+ return element?.closest<HTMLElement>(".table__cell-editor.table__cell--inline");+};++export const getTableCellRichEventTarget = (event: Event) =>+ getInlineEditor(forwardedEventTargets.get(event) || event.target);++export const getTableCellRichSelectionHost = (selection: Selection) => {+ const host = getInlineEditor(selection?.anchorNode);+ return selection?.rangeCount === 1 && host?.contains(selection.focusNode) ? host : undefined;+};export const setTableCellRichContext = (protyle: IProtyle, context: TableCellContext) => {contexts.set(protyle, context);diff --git a/app/src/protyle/util/tableCellRichLute.test.ts b/app/src/protyle/util/tableCellRichLute.test.tsindex 6566d0e165..51cf636c05 100644--- a/app/src/protyle/util/tableCellRichLute.test.ts+++ b/app/src/protyle/util/tableCellRichLute.test.ts@@ -13,12 +13,12 @@ const browserCases = async (source: string, enterSource: string, hintSource: strconst codeTabAttribute = "custom-sy-code-tab-spaces";const api = new Function("Constants", source + "\nreturn {getAgentLute, configureAVRichTextLute, getTableCellEditorLute, " +"canEnterCodeBlock, hasCodeBlockFence, getTableCellInlineHTML, serializeTableCellRich, " +- "updateTableCellEditingValue, getTableCellRichBlockDOM, sanitizeAVRichTextBlockDOM};")({+ "updateTableCellEditingValue, getTableCellRichBlockDOM, sanitizeAVRichTextBlockDOM, restoreTableVirtualizationDOM};")({CUSTOM_SY_CODE_TAB_SPACES: codeTabAttribute,}) astypeof import("../render/setLute") & typeof import("../render/av/richTextValue") &typeof import("./tableCellRichLute") & typeof import("../wysiwyg/codeBlockEnter") &- typeof import("./tableCellRich") & typeof import("../render/av/richText");+ typeof import("./tableCellRich") & typeof import("../render/av/richText") & typeof import("./tableVirtualizationDOM");const base = api.configureAVRichTextLute(api.getAgentLute({emojiSite: "/emojis", emojis: {},headingAnchor: false, listStyle: false, paragraphBeginningSpace: true, sanitize: true}));const lute = api.getTableCellEditorLute(base);@@ -182,7 +182,7 @@ const browserCases = async (source: string, enterSource: string, hintSource: strtypeof import("../wysiwyg/enter").enter;const fill = new Function(...Object.keys(dependencies), hintSource + "\nreturn Hint.prototype.fill;")(...Object.values(dependencies));const fragment = {wysiwyg, protyle, hintElement, getBlockHTML: () => wysiwyg.innerHTML};- const keyDependencies = {...dependencies, host, cell, fragment, owner: protyle, signal: new AbortController().signal,+ const keyDependencies = {...dependencies, host, cell, table: cell.closest("table"), fragment, owner: protyle, signal: new AbortController().signal,captureBeforeChange: () => {}, composing: false, matchHotKey: () => false, finish: () => {},fixTable: () => { calls.navigated++; }};new Function(...Object.keys(keyDependencies), keydownSource)(...Object.values(keyDependencies));diff --git a/app/src/protyle/util/tableVirtualizationDOM.ts b/app/src/protyle/util/tableVirtualizationDOM.tsindex 1eb9e9cbf8..56aeb66884 100644--- a/app/src/protyle/util/tableVirtualizationDOM.ts+++ b/app/src/protyle/util/tableVirtualizationDOM.ts@@ -65,6 +65,47 @@ export const getTableVirtualRowIndex = (row: HTMLTableRowElement) => {return row.rowIndex;};+export const getTableVirtualCellIndex = (cell: HTMLTableCellElement) => {+ const table = cell.closest("table");+ if (table.hasAttribute(TABLE_VIRTUAL_ID)) {+ return getTableVirtualRowIndex(cell.parentElement as HTMLTableRowElement) * table.rows[0].cells.length + cell.cellIndex;+ }+ return Array.from(table.querySelectorAll("th, td")).indexOf(cell);+};++// 只序列化可见内容与容器,屏外分段直接使用源字符串;不挂载或修改快照对应的节点。+export const getTableVirtualizationHTML = (root: Element, cellReplacements = new Map<Element, string>()): string => {+ const replacements = new Map(cellReplacements);+ root.querySelectorAll(`[${TABLE_VIRTUAL_ROWS}], [${TABLE_VIRTUAL_COLUMNS}]`).forEach(element => {+ replacements.set(element, element.getAttribute(TABLE_VIRTUAL_ROWS) ?? element.getAttribute(TABLE_VIRTUAL_COLUMNS));+ });+ const ancestors = new Set<Element>();+ [...replacements.keys(), ...Array.from(root.querySelectorAll(`[${TABLE_VIRTUAL_ID}]`)), root].forEach(element => {+ while (element && !ancestors.has(element) && root.contains(element)) {+ ancestors.add(element);+ element = element.parentElement;+ }+ });+ const holder = document.createElement("div");+ const serialize = (node: Node): string => {+ if (!(node instanceof Element)) {+ holder.replaceChildren(node.cloneNode(true));+ return holder.innerHTML;+ }+ if (replacements.has(node)) {+ return replacements.get(node);+ }+ if (!ancestors.has(node)) {+ return node.outerHTML;+ }+ const shell = node.cloneNode(false) as Element;+ shell.removeAttribute(TABLE_VIRTUAL_ID);+ const closing = `</${node.localName}>`;+ return shell.outerHTML.slice(0, -closing.length) + Array.from(node.childNodes).map(serialize).join("") + closing;+ };+ return serialize(root);+};+// 当前编辑器复用已卸载的行节点,快照仍由占位属性独立保存完整内容。export const cacheTableVirtualizationRows = (placeholder: HTMLTableRowElement, rows: HTMLTableRowElement[]) => {const html = rows.map(row => row.outerHTML).join("");diff --git a/app/src/protyle/wysiwyg/tableVirtualization.test.ts b/app/src/protyle/wysiwyg/tableVirtualization.test.tsindex 0c8c1f5552..deff7262fd 100644--- a/app/src/protyle/wysiwyg/tableVirtualization.test.ts+++ b/app/src/protyle/wysiwyg/tableVirtualization.test.ts@@ -11,10 +11,12 @@ 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, getVirtualTableGrid, setTableVirtualSelection, TableGridCache, buildTableGrid, getTableGridRect, searchMarkRender, " ++ "restoreTableVirtualizationDOM, getTableVirtualizationHTML, getTableVirtualCellIndex, setTableCellRichEventTarget, " ++ "getTableVirtualRowIndex, getVirtualTableGrid, setTableVirtualSelection, TableGridCache, buildTableGrid, getTableGridRect, searchMarkRender, " +"cleanBlockSelectionModeOperations, createEditor: protyle => new VirtualizedEditor(protyle)};")({TIMEOUT_TRANSITION: 0}, () => false) astypeof import("./tableVirtualization") & typeof import("../util/tableVirtualizationDOM") &- typeof import("../util/tableGridCache") & typeof import("../util/table") & typeof import("../render/searchMarkRender") & {+ typeof import("../util/tableCellRichContext") & 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,@@ -97,6 +99,9 @@ body {margin:0; --b3-theme-surface-lighter:#ddd; --b3-font-size-editor:16px; --bawait 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.equal(api.getTableVirtualizationHTML(f.editor.firstElementChild), f.original,+ "a complete snapshot is serialized directly without mounting cached rows");+ reduced(f.table, "snapshot preserves the live window");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;@@ -110,6 +115,7 @@ body {margin:0; --b3-theme-surface-lighter:#ddd; --b3-font-size-editor:16px; --b});const rowIndex = Number(/Row (\d+)/.exec(row.textContent)[1]);check.equal(api.getTableVirtualRowIndex(row), rowIndex + 1, "cell editor indexes include offscreen rows");+ check.equal(api.getTableVirtualCellIndex(row.cells[3]), (rowIndex + 1) * 5 + 3);check.equal(getComputedStyle(row).backgroundColor, rowIndex % 2 === 1 ? "rgb(12, 34, 56)" : "rgba(0, 0, 0, 0)","window changes retain alternating row backgrounds");}@@ -247,7 +253,7 @@ body {margin:0; --b3-theme-surface-lighter:#ddd; --b3-font-size-editor:16px; --bawait tick();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>' ++ cell.innerHTML = '<div class="table__cell-editor table__cell--inline"><div class="protyle-wysiwyg" contenteditable="true">Editing</div>' +'<button class="fn__none"><svg></svg></button></div>';const host = cell.firstElementChild;cell.style.verticalAlign = "top";@@ -255,6 +261,22 @@ body {margin:0; --b3-theme-surface-lighter:#ddd; --b3-font-size-editor:16px; --bcell.dispatchEvent(new PointerEvent("pointerup", {bubbles: true}));await tick();reduced(f.table, "cell and selection styles do not materialize the table");+ const editable = host.querySelector('[contenteditable="true"]');+ const textRange = document.createRange();+ textRange.selectNodeContents(editable);+ getSelection().addRange(textRange);+ document.dispatchEvent(new Event("selectionchange"));+ for (const type of ["keydown", "beforeinput", "copy", "cut", "paste", "compositionstart", "compositionend"]) {+ editable.dispatchEvent(new Event(type, {bubbles: true}));+ await tick();+ reduced(f.table, `cell-local ${type} keeps the window`);+ }+ const forwarded = new KeyboardEvent("keydown", {bubbles: true, key: "a"});+ api.setTableCellRichEventTarget(forwarded, host as HTMLElement);+ f.root.dispatchEvent(forwarded);+ reduced(f.table, "forwarded shortcuts retain their cell editor origin");+ editable.dispatchEvent(new PointerEvent("pointermove", {bubbles: true, buttons: 1, movementX: 10}));+ reduced(f.table, "text selection inside the editor keeps the window");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}));@@ -333,7 +355,7 @@ test("large tables retain complete source, editing, selection, search and layoutreturn 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",+ const source = ["../util/tableVirtualizationDOM.ts", "../util/tableCellRichContext.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" +diff --git a/app/src/protyle/wysiwyg/tableVirtualization.ts b/app/src/protyle/wysiwyg/tableVirtualization.tsindex 24c76efed4..dfd5bf1c3f 100644--- a/app/src/protyle/wysiwyg/tableVirtualization.ts+++ b/app/src/protyle/wysiwyg/tableVirtualization.ts@@ -1,4 +1,5 @@import {cacheTableVirtualizationRows, isTableVirtualSelectionRow, restoreTableVirtualizationDOM, restoreTableVirtualizationRows, setTableVirtualSelection, TABLE_VIRTUAL_COLUMNS, TABLE_VIRTUAL_ID} from "../util/tableVirtualizationDOM";+import {getTableCellRichEventTarget, getTableCellRichSelectionHost} from "../util/tableCellRichContext";export const LARGE_TABLE_ROW_THRESHOLD = 256;// 奇数行替换为一个占位行后,后续内容的隔行底色顺序保持不变。@@ -23,7 +24,7 @@ interface ITableViewport {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>();@@ -70,9 +71,14 @@ export class LargeTableVirtualizer {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, event => {+ const host = getTableCellRichEventTarget(event);+ if (host && ["keydown", "beforeinput", "copy", "cut", "paste"].includes(type) &&+ (getSelection()?.isCollapsed || getTableCellRichSelectionHost(getSelection()) === host)) {+ return;+ }this.interacting = type === "pointerdown" || type === "keydown";if (type === "pointerdown") {const pointer = event as PointerEvent;@@ -85,6 +91,9 @@ export class LargeTableVirtualizer {}return;}+ if (host && pointer.button === 0) {+ return;+ }}this.restore();}, {capture: true, signal});@@ -93,7 +102,7 @@ export class LargeTableVirtualizer {window.addEventListener("pointercancel", () => { this.interacting = false; this.dragTable = undefined; }, {capture: true, signal});root.addEventListener("pointermove", event => {if (event.buttons && (event.movementX || event.movementY)) {- if (!this.dragTable?.contains(event.target as Node)) {+ if (!getTableCellRichEventTarget(event) && !this.dragTable?.contains(event.target as Node)) {this.dragTable = undefined;this.restore();}@@ -106,7 +115,10 @@ export class LargeTableVirtualizer {this.schedule();}}, {capture: true, signal});- root.addEventListener("compositionstart", () => {+ root.addEventListener("compositionstart", event => {+ if (getTableCellRichEventTarget(event)) {+ return;+ }this.composing = true;this.restore();}, {capture: true, signal});@@ -122,7 +134,7 @@ export class LargeTableVirtualizer {}, {passive: true, signal});document.addEventListener("selectionchange", () => {const selection = getSelection();- if (!this.dragTable && selection && !selection.isCollapsed && selection.rangeCount &&+ if (!this.dragTable && !getTableCellRichSelectionHost(selection) && selection && !selection.isCollapsed && selection.rangeCount &&selection.getRangeAt(0).intersectsNode(this.editor)) {this.restore();}@@ -296,7 +308,7 @@ export class LargeTableVirtualizer {return;}if (!this.editor.isConnected || this.composing || this.blocked() ||- !this.dragTable && selection && !selection.isCollapsed && selection.rangeCount &&+ !this.dragTable && !getTableCellRichSelectionHost(selection) && selection && !selection.isCollapsed && selection.rangeCount &&selection.getRangeAt(0).intersectsNode(this.editor)) {this.restore();return;diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex 024d24e552..6fc12745b1 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -76,8 +76,8 @@ import {} from "./blockSelection";import {isEmptyParagraph} from "./emptyTextBlock";import {getHeadingConversionElements, isListHeadingContainer} from "./headingConversion";-import {cleanTableCellRichHTML, retainTableCellRichMetadata} from "../util/tableCellRich";-import {cleanTableVirtualizationHTML} from "../util/tableVirtualizationDOM";+import {cleanTableCellRichHTML, getTableBlockHTML, retainTableCellRichMetadata} from "../util/tableCellRich";+import {cleanTableVirtualizationHTML, TABLE_VIRTUAL_ID} from "../util/tableVirtualizationDOM";import {cleanListMindmapHTML, convertListMindmapToList, listMindmapConversionSource} from "../render/listMindmap/model";import {buildCancelListOperations} from "./cancelList";import {buildListConversionOperations} from "./listConversion";@@ -292,8 +292,7 @@ const promiseTransaction = (options: {updatedEmbed = true;};- const allTempElement = document.createElement("template");- allTempElement.innerHTML = cleanBlockSelectionModeHTML(getVisibleFoldHeadingHTML(operation.data));+ let allTempElement: HTMLTemplateElement;updateElements.forEach((item) => {if ((currentEmbedElement && isInEmbedBlock(item, false) === currentEmbedElement) ||(range && (item === range.startContainer || item.contains(range.startContainer)))) {@@ -311,6 +310,11 @@ const promiseTransaction = (options: {item.removeAttribute(Constants.ATTRIBUTE_EDITING);} else {// https://github.com/siyuan-note/siyuan/issues/14495+ // 仅在嵌入副本需要查找子块时解析完整快照,当前块的本地输入无需构建整块 DOM。+ if (!allTempElement) {+ allTempElement = document.createElement("template");+ allTempElement.innerHTML = cleanBlockSelectionModeHTML(getVisibleFoldHeadingHTML(operation.data));+ }const newTempElement = allTempElement.content.querySelector(`[data-node-id="${item.getAttribute("data-id")}"]`);if (newTempElement && !isInEmbedBlock(newTempElement)) {updateHTML(item.querySelector("[data-node-id]"), newTempElement.outerHTML);@@ -2597,14 +2601,16 @@ export const updateTransaction = (protyle: IProtyle, element: Element, oldHTML:refreshSbResize(element);}const id = element.getAttribute("data-node-id");- let newHTML = cleanListMindmapHTML(cleanHeadingNumberHTML(cleanTableCellRichHTML(cleanBlockSelectionModeHTML(element.outerHTML))));+ const getHTML = () => element.getAttribute("data-type") === "NodeTable" && element.querySelector(`[${TABLE_VIRTUAL_ID}]`) ?+ getTableBlockHTML(element) : element.outerHTML;+ let newHTML = cleanListMindmapHTML(cleanHeadingNumberHTML(cleanTableCellRichHTML(cleanBlockSelectionModeHTML(getHTML()))));const cleanOldHTML = cleanListMindmapHTML(cleanHeadingNumberHTML(cleanTableCellRichHTML(cleanBlockSelectionModeHTML(oldHTML))));if (newHTML === cleanOldHTML.replace("<wbr>", "") && !additionalOperations) {return;}if (element.getAttribute("data-type") === "NodeTable") {element.setAttribute("updated", dayjs().format("YYYYMMDDHHmmss"));- newHTML = cleanListMindmapHTML(cleanHeadingNumberHTML(cleanTableCellRichHTML(cleanBlockSelectionModeHTML(element.outerHTML))));+ newHTML = cleanListMindmapHTML(cleanHeadingNumberHTML(cleanTableCellRichHTML(cleanBlockSelectionModeHTML(getHTML()))));}element.setAttribute(Constants.ATTRIBUTE_EDITING, "true");const doOperations: IOperation[] = [{