An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Resolve table cell command IDs and preserve undo metadata https://github.com/siyuan-note/siyuan/issues/20613
Danieled5f81774aaf
diff --git a/app/src/boot/globalEvent/command/protyle.ts b/app/src/boot/globalEvent/command/protyle.tsindex c7381f4fa1..c290bea570 100644--- a/app/src/boot/globalEvent/command/protyle.ts+++ b/app/src/boot/globalEvent/command/protyle.ts@@ -36,7 +36,7 @@ export const onlyProtyleCommand = (options: {if (!options.previousRange) {return false;}- const nodeElement = hasClosestBlock(options.previousRange.startContainer);+ const nodeElement = hasClosestBlock(options.previousRange.startContainer, true);if (!nodeElement) {return false;}diff --git a/app/src/boot/globalEvent/keydown.ts b/app/src/boot/globalEvent/keydown.tsindex ef6a02d99f..948d9e9f0b 100644--- a/app/src/boot/globalEvent/keydown.ts+++ b/app/src/boot/globalEvent/keydown.ts@@ -484,10 +484,13 @@ const editKeydown = (app: App, event: KeyboardEvent) => {} else {const selectElement: Element[] = [];protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select").forEach(item => {- selectElement.push(item);+ const block = hasClosestBlock(item, true) || item;+ if (!selectElement.includes(block)) {+ selectElement.push(block);+ }});if (selectElement.length === 0) {- const nodeElement = hasClosestBlock(range.startContainer);+ const nodeElement = hasClosestBlock(range.startContainer, true);if (nodeElement) {selectElement.push(nodeElement);}@@ -524,12 +527,13 @@ const editKeydown = (app: App, event: KeyboardEvent) => {event.stopPropagation();let selectsElement: HTMLElement[] = Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));if (selectsElement.length === 0) {- const nodeElement = hasClosestBlock(range.startContainer);+ const nodeElement = hasClosestBlock(range.startContainer, true);if (nodeElement) {const rangeElements = range.collapsed ? [] : getBlockElementsByRange(range);selectsElement = rangeElements.length > 0 ? rangeElements : [nodeElement];}}+ selectsElement = Array.from(new Set(selectsElement.map(element => hasClosestBlock(element, true) || element)));duplicateBlock(selectsElement, protyle);return true;}@@ -599,7 +603,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {if (hasClosestByClassName(range.startContainer, "protyle-title")) {copyTextByType([protyle.block.rootID], "ref");} else {- const nodeElement = hasClosestBlock(range.startContainer);+ const nodeElement = hasClosestBlock(range.startContainer, true);if (!nodeElement) {return false;}@@ -608,7 +612,8 @@ const editKeydown = (app: App, event: KeyboardEvent) => {copyPNGByLink(selectImgElement.querySelector("img").getAttribute("src"));return true;}- const ids = Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select")).map(item => item.getAttribute("data-node-id"));+ const ids = Array.from(new Set(Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"))+ .map(item => (hasClosestBlock(item, true) || item).getAttribute("data-node-id"))));if (ids.length > 0) {copyTextByType(ids, "ref");return true;diff --git a/app/src/command/context.ts b/app/src/command/context.tsindex 7cbcda6113..6e045a9240 100644--- a/app/src/command/context.ts+++ b/app/src/command/context.ts@@ -204,11 +204,13 @@ export const captureCommandContext = (options: ICaptureCommandContextOptions): Iif (!range) {range = cloneCommandRange(protyle?.toolbar?.range);}- const blockElement = range ? hasClosestBlock(range.startContainer) : false;+ const blockElement = range ? hasClosestBlock(range.startContainer, true) : false;const block = getBlockContext(blockElement);const selectedBlocks = protyle?.wysiwyg?.element ?Array.from(protyle.wysiwyg.element.querySelectorAll<HTMLElement>(".protyle-wysiwyg--select"))- .map(element => getBlockContext(element)).filter((item): item is ICommandBlockContext => Boolean(item)) : [];+ .map(element => getBlockContext(hasClosestBlock(element, true) || element))+ .filter((item, index, items): item is ICommandBlockContext => item !== undefined &&+ items.findIndex(other => other?.id === item.id) === index) : [];const tableCellElement = range && (hasClosestByTag(range.startContainer, "TD") ||hasClosestByTag(range.startContainer, "TH"));const focus = resolveCommandFocus({diff --git a/app/src/command/contextTargets.test.ts b/app/src/command/contextTargets.test.tsindex 098fe7d6d2..eb1793089c 100644--- a/app/src/command/contextTargets.test.ts+++ b/app/src/command/contextTargets.test.ts@@ -4,8 +4,11 @@ import {getCommandBlocks, getCommandDocument, hasCommandEditorTarget} from "./coimport type {ICommandContextSnapshot} from "./types";const createEditorContext = () => {- const first = {isConnected: true, getAttribute: () => "first"} as unknown as HTMLElement;- const second = {isConnected: true, getAttribute: () => "second"} as unknown as HTMLElement;+ const block = (id: string) => ({isConnected: true, nodeType: 1, tagName: "DIV",+ classList: {contains: () => false}, hasAttribute: () => true, closest: (): null => null,+ getAttribute: (name: string) => name === "data-type" ? "NodeParagraph" : id}) as unknown as HTMLElement;+ const first = block("first");+ const second = block("second");const state = {selected: [] as HTMLElement[], nodes: [first, second]};const element = {isConnected: true,diff --git a/app/src/command/contextTargets.ts b/app/src/command/contextTargets.tsindex 21c8bfaba7..ddb0dd3118 100644--- a/app/src/command/contextTargets.ts+++ b/app/src/command/contextTargets.ts@@ -1,4 +1,5 @@import type {ICommandContextSnapshot} from "./types";+import {hasClosestBlock} from "../protyle/util/hasClosest";export const getCommandBlocks = (context: ICommandContextSnapshot) =>context.selectedBlocks.length ? context.selectedBlocks : context.block ? [context.block] : [];@@ -20,7 +21,8 @@ export const hasCommandEditorTarget = (context: ICommandContextSnapshot) => {return false;}// 面板打开后选中集合发生变化时取消操作,避免底层函数使用新的选中目标。- const selected = Array.from(editor.querySelectorAll(".protyle-wysiwyg--select"));+ const selected = Array.from(new Set(Array.from(editor.querySelectorAll(".protyle-wysiwyg--select"))+ .map(element => hasClosestBlock(element, true) || element)));return selected.length === context.selectedBlocks.length &&context.selectedBlocks.every(block => selected.includes(block.element));};diff --git a/app/src/command/nativeRuntime.ts b/app/src/command/nativeRuntime.tsindex 6822194ef3..25226020f3 100644--- a/app/src/command/nativeRuntime.ts+++ b/app/src/command/nativeRuntime.ts@@ -202,7 +202,7 @@ export const executeLegacyNativeCommand = async (command: string, context: ICommbreak;case "move":if (!isFileFocus && range) {- const nodeElement = hasClosestBlock(range.startContainer);+ const nodeElement = hasClosestBlock(range.startContainer, true);if (protyle.title?.editElement.contains(range.startContainer) || !nodeElement ||window.siyuan.menus.menu.element.getAttribute("data-name") === Constants.MENU_TITLE) {movePathTo({@@ -222,6 +222,7 @@ export const executeLegacyNativeCommand = async (command: string, context: ICommif (selectElements.length === 0) {selectElements = [nodeElement];}+ selectElements = Array.from(new Set(selectElements.map(element => hasClosestBlock(element, true) || element)));movePathTo({cb: (toPath) => {void hintMoveBlock(toPath[0], selectElements, protyle);diff --git a/app/src/protyle/render/av/addToDatabase.ts b/app/src/protyle/render/av/addToDatabase.tsindex f77e74c8b4..4d77aa980a 100644--- a/app/src/protyle/render/av/addToDatabase.ts+++ b/app/src/protyle/render/av/addToDatabase.ts@@ -76,13 +76,17 @@ export const addEditorToDatabase = (protyle: IProtyle, range: Range, type?: strilet targetElement: HTMLElement;const ids: string[] = [];protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select").forEach((item: HTMLElement) => {+ const block = hasClosestBlock(item, true) || item;if (!targetElement) {- targetElement = item;+ targetElement = block;+ }+ const id = block.getAttribute("data-node-id");+ if (!ids.includes(id)) {+ ids.push(id);}- ids.push(item.getAttribute("data-node-id"));});if (!targetElement) {- const nodeElement = hasClosestBlock(range.startContainer);+ const nodeElement = hasClosestBlock(range.startContainer, true);if (nodeElement) {targetElement = nodeElement;ids.push(nodeElement.getAttribute("data-node-id"));diff --git a/app/src/protyle/render/tableCellInput.test.ts b/app/src/protyle/render/tableCellInput.test.tsindex 592248dd61..6bef26d777 100644--- a/app/src/protyle/render/tableCellInput.test.ts+++ b/app/src/protyle/render/tableCellInput.test.ts@@ -8,7 +8,8 @@ import {promisify} from "node:util";import {createSourceFile, forEachChild, isCallExpression, isClassDeclaration, isVariableStatement, ScriptTarget, transpileModule} from "typescript";const browserCases = async (source: string, queueSource: string, editorSource: string, menuSource: string,- transactionSource: string, copyPlainSource: string, gutterSource: string, mouseDownSource: string) => {+ transactionSource: string, copyPlainSource: string, gutterSource: string, mouseDownSource: string,+ commandSource: string) => {const check: typeof assert = require("node:assert/strict");const noop = () => {};const tick = () => new Promise(resolve => setTimeout(resolve, 0));@@ -53,11 +54,13 @@ const browserCases = async (source: string, queueSource: string, editorSource: s"getTableCellRichBlockDOM, serializeTableCellRich, cleanTableCellRichHTML, renderTableCellRich, buildTableGrid, " +"setTableCellRich, getTableCellInlineHTML, getTableCellPlainText, getSelectionOffset, focusByOffset, getTableBlockHTML, updateTableCellEditingValue, " +"updateTableCellContentLayout, captureRichCellSelection, captureRichCellSelectionAtPoint, restoreRichCellSelection, setTableCellRichEventTarget, " +- "LargeTableVirtualizer, getTableVirtualCellIndex, getTableVirtualRowIndex, restoreTableVirtualizationDOM};")(...Object.values(dependencies)) as+ "LargeTableVirtualizer, getTableVirtualCellIndex, getTableVirtualRowIndex, restoreTableVirtualizationDOM, " ++ "hasClosestBlock, hasClosestByClassName, hasClosestByTag};")(...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("../wysiwyg/tableVirtualization") & typeof import("../util/tableCellRichContext") & typeof import("../util/tableCellRichSelection");+ typeof import("../wysiwyg/tableVirtualization") & typeof import("../util/tableCellRichContext") & typeof import("../util/tableCellRichSelection") &+ typeof import("../util/hasClosest");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 () => {@@ -197,6 +200,72 @@ const browserCases = async (source: string, queueSource: string, editorSource: sawait tick();};+ for (const rich of [false, true]) {+ const {owner, element, table} = fixture();+ const cell = table.querySelector("th");+ if (rich) {+ api.setTableCellRich(cell, "first\n\nsecond");+ }+ await open(owner, cell);+ const host = cell.querySelector<HTMLElement>(".table__cell-editor");+ const blocks = Array.from(host.querySelectorAll<HTMLElement>("[data-node-id]"));+ check.ok(blocks.length > 0);+ const child = blocks[0];+ const range = document.createRange();+ range.selectNodeContents(child.querySelector('[contenteditable="true"]'));+ focusByRange(range);+ check.equal(api.hasClosestBlock(range.startContainer), child, "local editing retains the fragment identity");+ check.equal(api.hasClosestBlock(range.startContainer, true), table, "document commands resolve the table identity");+ const writes: {ids: string[], type: string}[] = [];+ const duplicated: Element[][] = [];+ const general = window.siyuan.config.keymap.editor.general;+ const bindings = new Proxy({}, {get: (_target, key) => key});+ window.siyuan.config.keymap.editor.general = bindings;+ window.siyuan.config.keymap.general = bindings;+ const commandDependencies = {...api,+ matchHotKey: (binding: string, event: KeyboardEvent) => binding === event.key,+ getEditorRange: () => getSelection().getRangeAt(0),+ getBlockElementsByRange: () => blocks,+ getAllEditor: () => [{protyle: owner}], getActiveTab: noop,+ documentKeydown: () => false, handleDocumentBoundaryHotkey: () => false,+ cloneCommandRange: (range: Range) => range?.cloneRange(),+ getDockElement: noop, resolveCommandFocus: () => "editor", getFrontend: () => "desktop",+ createCommandContextSnapshot: (value: unknown) => value,+ copyTextByType: (ids: string[], type: string) => writes.push({ids, type}),+ getContentByInlineHTML: (range: Range, callback: (text: string) => void) => callback(range.toString()),+ writeText: (text: string) => writes.push({ids: [text], type: "text"}),+ duplicateBlock: (elements: Element[]) => duplicated.push(elements),+ };+ const commands = new Function(...Object.keys(commandDependencies), commandSource ++ "\nreturn {commonHotkey, editKeydown, captureCommandContext, hasCommandEditorTarget};")(...Object.values(commandDependencies));+ const event = (key: string) => ({key, target: child, preventDefault: noop, stopPropagation: noop});+ for (const [key, type] of [["copyID", "id"], ["copyProtocol", "protocol"],+ ["copyProtocolInMd", "protocolMd"], ["copyBlockEmbed", "blockEmbed"]]) {+ writes.length = 0;+ commands.commonHotkey(owner, event(key), child);+ check.deepEqual(writes, [{ids: [table.dataset.nodeId], type}]);+ }+ writes.length = 0;+ check.equal(commands.editKeydown({}, event("copyBlockRef")), true);+ check.deepEqual(writes, [{ids: [`((${table.dataset.nodeId} "${range.toString().trim()}"))`], type: "text"}]);+ range.collapse(true);+ writes.length = 0;+ commands.editKeydown({}, event("copyBlockRef"));+ check.deepEqual(writes, [{ids: [table.dataset.nodeId], type: "ref"}]);+ blocks.forEach(block => block.classList.add("protyle-wysiwyg--select"));+ writes.length = 0;+ commands.editKeydown({}, event("copyBlockRef"));+ check.deepEqual(writes, [{ids: [table.dataset.nodeId], type: "ref"}], "selected cell fragments are deduplicated");+ commands.editKeydown({}, event("duplicate"));+ check.deepEqual(duplicated, [[table]]);+ const context = commands.captureCommandContext({app: {}, source: "commandPanel", protyle: owner, range});+ check.equal(context.block.id, table.dataset.nodeId);+ check.deepEqual(context.selectedBlocks.map((block: {id: string}) => block.id), [table.dataset.nodeId]);+ check.equal(commands.hasCommandEditorTarget(context), true, "normalized cell selections retain a valid command target");+ window.siyuan.config.keymap.editor.general = general;+ await finish(element);+ }+for (const index of [0, 1]) {const {owner, element, table} = fixture();const cell = table.querySelectorAll("th")[index];@@ -733,6 +802,15 @@ test("table cell editors wait for outer input and table menu Enter is consumed",statement.declarationList.declarations.some(declaration =>["updateTransaction", "promiseTransaction"].includes(declaration.name.getText(transactionFile)))).map(statement => statement.getText(transactionFile)).join("\n"));+ const commandSource = [["../wysiwyg/commonHotkey.ts", "commonHotkey"],+ ["../../boot/globalEvent/keydown.ts", "editKeydown"], ["../../command/context.ts", "getBlockContext"],+ ["../../command/context.ts", "captureCommandContext"], ["../../command/contextTargets.ts", "getCommandBlocks"],+ ["../../command/contextTargets.ts", "hasCommandEditorTarget"]].map(([file, name]) => {+ const parsed = createSourceFile(file, read(file), ScriptTarget.Latest, true);+ return compile(parsed.statements.filter(isVariableStatement).filter(statement =>+ statement.declarationList.declarations.some(declaration => declaration.name.getText(parsed) === name))+ .map(statement => statement.getText(parsed)).join("\n"));+ }).join("\n");const wysiwygSource = read("../wysiwyg/index.ts");const copyEnd = wysiwygSource.indexOf("copyPlainText(textPlain.slice(0, -1));") + "copyPlainText(textPlain.slice(0, -1));".length;const copyStart = wysiwygSource.lastIndexOf('let textPlain = "";', copyEnd);@@ -777,7 +855,7 @@ app.whenReady().then(async () => {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, transactionSource, copyPlainSource, gutterSource, mouseDownSource]+ browserCases.toString() + ")(" + [source, queue, compile(read("tableCellRichEditor.ts")), menuSource, transactionSource, copyPlainSource, gutterSource, mouseDownSource, commandSource].map(value => JSON.stringify(value)).join(",") + ")")}));win.destroy();app.exit(0);diff --git a/app/src/protyle/util/hasClosest.ts b/app/src/protyle/util/hasClosest.tsindex e18bacd0f8..d692306313 100644--- a/app/src/protyle/util/hasClosest.ts+++ b/app/src/protyle/util/hasClosest.ts@@ -104,9 +104,16 @@ export const hasClosestByClassName = (element: Node, className: string, top = fareturn isClosest && e;};-export const hasClosestBlock = (element: Node) => {+export const hasClosestBlock = (element: Node, resolveTable = false) => {const nodeElement = hasClosestByAttribute(element, "data-node-id", null);- if (isBlockElement(nodeElement as Element)) {+ if (nodeElement && isBlockElement(nodeElement)) {+ // 文档级命令使用表格块身份,单元格片段内部的编辑操作保留自身节点。+ if (resolveTable) {+ const table = nodeElement.closest(".table__cell-editor")?.closest<HTMLElement>('[data-type="NodeTable"]');+ if (table) {+ return table;+ }+ }return nodeElement;}return false;diff --git a/app/src/protyle/wysiwyg/commonHotkey.test.ts b/app/src/protyle/wysiwyg/commonHotkey.test.tsindex 803a32e9e9..13b507dc3a 100644--- a/app/src/protyle/wysiwyg/commonHotkey.test.ts+++ b/app/src/protyle/wysiwyg/commonHotkey.test.ts@@ -18,6 +18,7 @@ const copy = (options: {selected?: string[], rangeBlocks?: string[], collapsed?:let rangeReads = 0;let prevented = false;const dependencies = {+ hasClosestBlock: (element: unknown) => element,matchHotKey: (value: string) => value === "embed",getEditorRange: () => range,getBlockElementsByRange: (value: unknown) => {diff --git a/app/src/protyle/wysiwyg/commonHotkey.ts b/app/src/protyle/wysiwyg/commonHotkey.tsindex de50ad429c..e26a19b5be 100644--- a/app/src/protyle/wysiwyg/commonHotkey.ts+++ b/app/src/protyle/wysiwyg/commonHotkey.ts@@ -16,7 +16,7 @@ import {Constants} from "../../constants";import dayjs from "dayjs";import {net2LocalAssets} from "../breadcrumb/action";import {copyTextByType} from "../toolbar/util";-import {hasClosestByTag, hasTopClosestByClassName} from "../util/hasClosest";+import {hasClosestBlock, hasClosestByTag, hasTopClosestByClassName} from "../util/hasClosest";import {removeEmbed} from "./removeEmbed";import {clearBlockElement} from "../util/clear";import {remapTabsDOMIDs} from "../util/tabsCopy";@@ -29,6 +29,8 @@ import {areProtylePluginExtensionsEnabled} from "../runtimeCapabilities";import {waitForPendingTransactions} from "../util/transactionQueue";export const commonHotkey = (protyle: IProtyle, event: KeyboardEvent, nodeElement?: HTMLElement) => {+ const getCopyIDs = (elements: Element[]) => Array.from(new Set(elements.map(element =>+ (hasClosestBlock(element, true) || element).getAttribute("data-node-id"))));if (matchHotKey(window.siyuan.config.keymap.editor.general.netImg2LocalAsset, event)) {net2LocalAssets(protyle, "Img");event.preventDefault();@@ -68,7 +70,7 @@ export const commonHotkey = (protyle: IProtyle, event: KeyboardEvent, nodeElemenif (selectElements.length === 0) {selectElements.push(nodeElement);}- copyTextByType(selectElements.map(item => item.getAttribute("data-node-id")), "protocolMd");+ copyTextByType(getCopyIDs(selectElements), "protocolMd");} else {copyTextByType([protyle.block.rootID], "protocolMd");}@@ -83,7 +85,7 @@ export const commonHotkey = (protyle: IProtyle, event: KeyboardEvent, nodeElemenif (selectElements.length === 0) {selectElements.push(nodeElement);}- copyTextByType(selectElements.map(item => item.getAttribute("data-node-id")), "id");+ copyTextByType(getCopyIDs(selectElements), "id");} else {copyTextByType([protyle.block.rootID], "id");}@@ -97,7 +99,7 @@ export const commonHotkey = (protyle: IProtyle, event: KeyboardEvent, nodeElemenif (selectElements.length === 0) {selectElements.push(nodeElement);}- copyTextByType(selectElements.map(item => item.getAttribute("data-node-id")), "protocol");+ copyTextByType(getCopyIDs(selectElements), "protocol");} else {copyTextByType([protyle.block.rootID], "protocol");}@@ -118,7 +120,7 @@ export const commonHotkey = (protyle: IProtyle, event: KeyboardEvent, nodeElemenif (selectElements.length === 0) {selectElements.push(nodeElement);}- copyTextByType(selectElements.map(item => item.getAttribute("data-node-id")), "blockEmbed");+ copyTextByType(getCopyIDs(selectElements), "blockEmbed");} else {copyTextByType([protyle.block.rootID], "blockEmbed");}diff --git a/kernel/model/table_cell_rich_fts5_test.go b/kernel/model/table_cell_rich_fts5_test.goindex 7b791e963b..f1172f6eb2 100644--- a/kernel/model/table_cell_rich_fts5_test.go+++ b/kernel/model/table_cell_rich_fts5_test.go@@ -3,6 +3,7 @@package modelimport (+ "strings""testing""github.com/88250/lute/ast"@@ -12,6 +13,107 @@ import ("github.com/siyuan-note/siyuan/kernel/util")+func TestTableCellRichUpgradeUndoRedo(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ originalLog := GlobalUndoLog+ GlobalUndoLog = newUndoLog(128)+ t.Cleanup(func() { GlobalUndoLog = originalLog })+ tree, err := LoadTreeByBlockID(fixture.sourceID)+ if err != nil {+ t.Fatal(err)+ }+ luteEngine := util.NewLute()+ tableID := ast.NewNodeID()+ makeTable := func(text string, rich bool) *parse.Tree {+ result := parse.Parse("", []byte("| Header |\n| --- |\n| "+text+" |"), luteEngine.ParseOptions)+ table := result.Root.FirstChild+ table.ID = tableID+ table.SetIALAttr("id", tableID)+ if rich {+ table.LastChild.FirstChild.TableCellRich = &ast.TableCellRich{Spec: 1, Format: "kramdown", Content: "first\n\nsecond"}+ if err := treenode.RefreshTableCellRichProjection(result.Root); err != nil {+ t.Fatal(err)+ }+ }+ return result+ }+ dom := func(table *parse.Tree) string {+ return luteEngine.Tree2BlockDOM(table, luteEngine.RenderOptions, luteEngine.ParseOptions)+ }+ initial := makeTable("initial", false)+ plain := makeTable("edited", false)+ rich := makeTable("rich", true)+ tree.Root.AppendChild(initial.Root.FirstChild)+ if _, err = filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ previous := dom(makeTable("initial", false))+ for _, updated := range []*parse.Tree{plain, rich} {+ next := dom(updated)+ tx := &Transaction{fromAPI: true,+ DoOperations: []*Operation{{Action: "update", ID: tableID, Data: next}},+ UndoOperations: []*Operation{{Action: "update", ID: tableID, Data: previous}}}+ if err = PerformTxSync(tx); err != nil {+ t.Fatal(err)+ }+ previous = next+ }+ assertTable := func(text string, hasRich bool) {+ t.Helper()+ restored, err := LoadTreeByBlockID(tableID)+ if err != nil {+ t.Fatal(err)+ }+ table := treenode.GetNodeInTree(restored, tableID)+ cell := table.LastChild.FirstChild+ if (cell.TableCellRich != nil) != hasRich || !strings.Contains(cell.Text(), text) ||+ table.IALAttr(treenode.TableCellRichTableAttribute) != "1" {+ t.Fatalf("unexpected restored table: %s, %#v", cell.Text(), cell.TableCellRich)+ }+ }+ for cycle := 0; cycle < 2; cycle++ {+ for _, text := range []string{"edited", "initial"} {+ entry := GlobalUndoLog.Undo(fixture.sourceID)+ if entry == nil {+ t.Fatal("missing undo entry")+ }+ tx := &Transaction{isReplay: true, DoOperations: entry.UndoOperationsForReplay()}+ if err = PerformTxSync(tx); err != nil {+ t.Fatalf("undo %s: %s", text, err)+ }+ GlobalUndoLog.UndoCommit(entry, fixture.sourceID)+ assertTable(text, false)+ if !strings.Contains(tx.DoOperations[0].Data.(string), treenode.TableCellRichTableAttribute+`="1"`) {+ t.Fatal("replayed DOM omitted table format metadata")+ }+ }+ for index, text := range []string{"edited", "first"} {+ entry := GlobalUndoLog.Redo(fixture.sourceID)+ if entry == nil {+ t.Fatal("missing redo entry")+ }+ if err = PerformTxSync(&Transaction{isReplay: true, DoOperations: entry.DoOperationsForReplay()}); err != nil {+ t.Fatalf("redo %s: %s", text, err)+ }+ GlobalUndoLog.RedoCommit(entry, fixture.sourceID)+ assertTable(text, index == 1)+ }+ }+ for _, replay := range []bool{false, true} {+ updated := makeTable("invalid", false)+ if replay {+ updated.Root.FirstChild.SetIALAttr(treenode.TableCellRichTableAttribute, "2")+ }+ if err = PerformTxSync(&Transaction{isReplay: replay,+ DoOperations: []*Operation{{Action: "update", ID: tableID, Data: dom(updated)}}}); err == nil {+ t.Fatalf("accepted missing or unknown format metadata, replay=%v", replay)+ }+ assertTable("first", true)+ }+}+func TestTableCellRichCodeSettingsTransactions(t *testing.T) {fixture := setupStructureTransactionTest(t)setupFoldTransactionDatabase(t, fixture)diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex f3d8321c5d..152e27e741 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -2017,7 +2017,13 @@ func (tx *Transaction) doUpdate(operation *Operation) (ret *TxErr) {if ast.NodeTable == oldNode.Type && ast.NodeTable == updatedNode.Type &&(treenode.HasTableCellRich(oldNode) || "1" == oldNode.IALAttr(treenode.TableCellRichTableAttribute)) &&"1" != updatedNode.IALAttr(treenode.TableCellRichTableAttribute) {- return &TxErr{code: TxErrCodeReloadUI, msg: "table update omitted rich text format metadata", id: id}+ if !tx.isReplay || "" != updatedNode.IALAttr(treenode.TableCellRichTableAttribute) {+ return &TxErr{code: TxErrCodeReloadUI, msg: "table update omitted rich text format metadata", id: id}+ }+ // 撤销日志中的普通表格快照保留富文本格式标记,确保连续撤销和重做可恢复。+ updatedNode.SetIALAttr(treenode.TableCellRichTableAttribute, "1")+ data = tx.luteEngine.Tree2BlockDOM(subTree, tx.luteEngine.RenderOptions, tx.luteEngine.ParseOptions)+ operation.Data = data}if err = treenode.ValidateTableCellRich(updatedNode); nil != err {return &TxErr{code: TxErrCodeReloadUI, msg: err.Error(), id: id}