Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(editor-runtime): keep CDATA sections intact in LiteXML block diff (#22207)

Innei538f2a16375a
diff --git a/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.real.test.ts b/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.real.test.ts
index 3bf3b283f06..36921551edb 100644
--- a/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.real.test.ts
+++ b/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.real.test.ts
@@ -7,11 +7,13 @@ import {
MarkdownPlugin,
moment,
} from '@lobehub/editor';
+import { createHeadlessEditor, DEFAULT_HEADLESS_EDITOR_PLUGINS } from '@lobehub/editor/headless';
import { DiffAction, LITEXML_DIFFNODE_ALL_COMMAND } from '@lobehub/editor/litexml-commands';
import { $getRoot, type ElementNode, type TextNode } from 'lexical';
import { describe, expect, it } from 'vitest';
import { normalizeEditorDataDiffNodes } from '../../../../src/libs/editor/normalizeDiffNodes';
+import { alignLiteXMLBlocks } from '../alignLiteXMLBlocks';
import { EditorRuntime } from '../EditorRuntime';
import { diffLiteXMLBlocks } from '../liteXMLBlockDiff';
@@ -70,6 +72,16 @@ const setup = async (markdown: string) => {
};
};
+const chartNodesOf = (editorData: { root: unknown }) => {
+ const charts: Record<string, unknown>[] = [];
+ const walk = (node: any) => {
+ if (node?.type === 'chart') charts.push(node);
+ node?.children?.forEach(walk);
+ };
+ walk(editorData.root);
+ return charts;
+};
+
const topLevelIds = (xml: string) =>
[...xml.matchAll(/^ {2}<\w+ id="([^"]+)"/gm)].map((match) => match[1]);
@@ -346,4 +358,40 @@ describe('diffLiteXMLBlocks against a real editor', () => {
expect(result.successCount).toBe(result.totalCount);
expect(page.markdownOf()).toBe('para ONE\n\npara two\n\npara THREE');
});
+
+ it('keeps a chart parseable when its block is applied from a diff', async () => {
+ const spec = {
+ data: [{ k: 'a', v: 1 }],
+ series: [{ key: 'v' }],
+ type: 'bar',
+ version: 1,
+ x: 'k',
+ };
+ const headless = () => createHeadlessEditor({ plugins: DEFAULT_HEADLESS_EDITOR_PLUGINS });
+ const room = headless();
+ const target = headless();
+ room.hydrateMarkdown('intro\n\nold body\n', { keepId: true });
+ target.hydrateMarkdown(`intro\n\n\`\`\`chart\n${JSON.stringify(spec)}\n\`\`\`\n`, {
+ keepId: true,
+ });
+
+ const current = room.export({ litexml: true }).litexml ?? '';
+ const aligned = alignLiteXMLBlocks(current, target.export({ litexml: true }).litexml ?? '');
+ if (!aligned) throw new Error('blocks did not align');
+ const diff = diffLiteXMLBlocks(current, aligned);
+ if (!diff.ok) throw new Error(diff.reason);
+ await room.applyLiteXML(
+ diff.operations.map((operation) =>
+ operation.action === 'modify'
+ ? { action: 'replace' as const, litexml: operation.litexml }
+ : operation,
+ ),
+ );
+
+ expect(chartNodesOf(room.export().editorData)).toEqual([
+ expect.objectContaining({ spec: expect.objectContaining({ type: 'bar', x: 'k' }) }),
+ ]);
+ room.destroy();
+ target.destroy();
+ });
});
diff --git a/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.test.ts b/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.test.ts
index ce4df7c3dc7..c8f17b077f2 100644
--- a/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.test.ts
+++ b/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.test.ts
@@ -300,6 +300,48 @@ describe('diffLiteXMLBlocks', () => {
expect(result.ok).toBe(false);
});
+ describe('CDATA sections', () => {
+ const chart = (id: string, json: string) => `<chart id="${id}"><![CDATA[${json}]]></chart>`;
+ const spec = '{"type":"bar","note":"a < b && c > d"}';
+
+ it('inserts a chart with its CDATA section intact', () => {
+ const result = ok(doc(A, B), doc(A, chart('c1', spec), B));
+
+ expect(result.operations).toEqual([
+ { action: 'insert', afterId: 'a', litexml: `<chart><![CDATA[${spec}]]></chart>` },
+ ]);
+ });
+
+ it('modifies a chart whose CDATA body changed', () => {
+ const next = '{"type":"line"}';
+ const result = ok(doc(A, chart('c1', spec)), doc(A, chart('c1', next)));
+
+ expect(result.operations).toEqual([
+ { action: 'modify', litexml: `<chart id="c1"><![CDATA[${next}]]></chart>` },
+ ]);
+ });
+
+ it('returns no operations for an unchanged chart', () => {
+ const result = ok(doc(A, chart('c1', spec)), doc(A, chart('c1', spec)));
+
+ expect(result.operations).toEqual([]);
+ });
+
+ it('keeps a body split across adjacent CDATA sections', () => {
+ const split = '<chart><![CDATA[{"note":"]]]]><![CDATA[>"}]]></chart>';
+ const result = ok(doc(A), doc(A, split));
+
+ expect(result.operations).toEqual([{ action: 'insert', afterId: 'a', litexml: split }]);
+ });
+
+ it('does not read markup inside a CDATA section as tags', () => {
+ const markup = '<chart><![CDATA[<p id="x">not a block</p>]]></chart>';
+ const result = ok(doc(A), doc(A, markup));
+
+ expect(result.operations).toEqual([{ action: 'insert', afterId: 'a', litexml: markup }]);
+ });
+ });
+
it('rejects an edit that strips most ids from a similar-length document', () => {
const result = diffLiteXMLBlocks(doc(A, B, C), doc('<p>A</p>', '<p>B</p>', '<p>C2</p>'));
diff --git a/packages/editor-runtime/src/liteXMLBlockDiff.ts b/packages/editor-runtime/src/liteXMLBlockDiff.ts
index 787bc2ec43d..4c2e9027c66 100644
--- a/packages/editor-runtime/src/liteXMLBlockDiff.ts
+++ b/packages/editor-runtime/src/liteXMLBlockDiff.ts
@@ -3,7 +3,7 @@ import type { ModifyOperation } from './types';
type Token =
| { kind: 'close'; raw: string; tag: string }
| { kind: 'open' | 'self'; raw: string; tag: string }
- | { kind: 'text'; raw: string; verbatim: boolean };
+ | { cdata?: boolean; kind: 'text'; raw: string; verbatim: boolean };
export interface LiteXMLBlock {
/** {@link LiteXMLBlock.xml} without the ids on its tags; ids in its text stay. */
@@ -28,6 +28,8 @@ const TAG = /<(\/?)([a-z][\w-]*)(?:\s+[\w:-]+(?:="[^"]*")?)*\s*(\/?)>/iy;
const ID_ATTRIBUTE = /\bid="([^"]+)"/;
// The LiteXML exporter writes text inside these elements without escaping `<`.
const VERBATIM_TAGS = new Set(['code', 'span']);
+const CDATA_OPEN = '<![CDATA[';
+const CDATA_CLOSE = ']]>';
const tokenize = (litexml: string): Token[] => {
const tokens: Token[] = [];
@@ -45,6 +47,16 @@ const tokenize = (litexml: string): Token[] => {
i += 1;
continue;
}
+ if (litexml.startsWith(CDATA_OPEN, i)) {
+ const end = litexml.indexOf(CDATA_CLOSE, i + CDATA_OPEN.length);
+ if (end !== -1) {
+ flushText();
+ const raw = litexml.slice(i, end + CDATA_CLOSE.length);
+ tokens.push({ cdata: true, kind: 'text', raw, verbatim: true });
+ i += raw.length;
+ continue;
+ }
+ }
if (litexml.startsWith('<?', i) || litexml.startsWith('<!--', i)) {
const close = litexml.startsWith('<?', i) ? '?>' : '-->';
const end = litexml.indexOf(close, i);
@@ -116,6 +128,9 @@ const toPayload = (tokens: Token[], { stripIds = false } = {}) =>
.filter((token) => !isLayoutWhitespace(token))
.map((token) => {
if (token.kind === 'text') {
+ // DOMParser reads a CDATA body as-is; escaping it turns the markers into
+ // literal text that the node (e.g. a chart's JSON spec) can no longer parse.
+ if (token.cdata) return token.raw;
const text = escapeText(token.raw);
return /^\s+$/.test(token.raw) ? `<text>${text}</text>` : text;
}
@@ -127,7 +142,9 @@ const toPayload = (tokens: Token[], { stripIds = false } = {}) =>
const blockText = (tokens: Token[]) =>
tokens
.filter((token) => token.kind === 'text')
- .map((token) => token.raw)
+ .map((token) =>
+ token.cdata ? token.raw.slice(CDATA_OPEN.length, -CDATA_CLOSE.length) : token.raw,
+ )
.join('')
.replaceAll(/\s+/g, ' ')
.trim();