Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(lexical): gate importDOM claims (#5962)

Peter Chinman3812fd92726d
diff --git a/apps/web/src/features/block-email/util/appendedReplyRoundTrip.test.ts b/apps/web/src/features/block-email/util/appendedReplyRoundTrip.test.ts
new file mode 100644
index 0000000000..a5f2ed14e4
--- /dev/null
+++ b/apps/web/src/features/block-email/util/appendedReplyRoundTrip.test.ts
@@ -0,0 +1,138 @@
+// @vitest-environment jsdom
+import { $generateNodesFromDOM } from '@lexical/html';
+import {
+ $isClassedBlockNode,
+ SupportedNodeTypes,
+} from '@macro-inc/lexical-core';
+import type { ApiMessage } from '@service-email/generated/schemas';
+import {
+ $createParagraphNode,
+ $createTextNode,
+ $getRoot,
+ createEditor,
+ type LexicalNode,
+} from 'lexical';
+import { describe, expect, it } from 'vitest';
+import {
+ prepareEmailBody,
+ registerToggleAppendedThread,
+ TOGGLE_APPEND_EMAIL_THREAD_COMMAND,
+} from './prepareEmailBody';
+
+function decodeBodyHtml(encoded: string) {
+ const base64 = encoded.replace(/-/g, '+').replace(/_/g, '/');
+ return decodeURIComponent(escape(atob(base64)));
+}
+
+const replyingTo = {
+ replying_to_id: 'parent-message-id',
+ from: { name: 'Ada Lovelace', email: '[email protected]' },
+ to: [],
+ cc: [],
+ bcc: [],
+ subject: 'Numbers',
+ body_text: 'original message text',
+ internal_date_ts: '2026-08-01T12:00:00Z',
+ attachments: [],
+} as unknown as ApiMessage;
+
+function makeEditor() {
+ const editor = createEditor({
+ nodes: SupportedNodeTypes,
+ onError: (e) => {
+ throw e;
+ },
+ });
+ registerToggleAppendedThread(editor);
+ return editor;
+}
+
+function $collectMacroQuotes(): LexicalNode[] {
+ const found: LexicalNode[] = [];
+ const visit = (node: LexicalNode) => {
+ if ($isClassedBlockNode(node) && node.__classes.includes('macro_quote')) {
+ found.push(node);
+ }
+ if ('getChildren' in node) {
+ for (const child of (node as any).getChildren()) visit(child);
+ }
+ };
+ for (const child of $getRoot().getChildren()) visit(child);
+ return found;
+}
+
+function appendQuote(editor: ReturnType<typeof makeEditor>) {
+ editor.update(() => {
+ const p = $createParagraphNode();
+ p.append($createTextNode('my reply'));
+ $getRoot().append(p);
+ });
+ editor.dispatchCommand(TOGGLE_APPEND_EMAIL_THREAD_COMMAND, {
+ replyingTo,
+ replyType: 'reply',
+ visible: true,
+ });
+}
+
+function hideQuote(editor: ReturnType<typeof makeEditor>) {
+ editor.dispatchCommand(TOGGLE_APPEND_EMAIL_THREAD_COMMAND, {
+ replyingTo,
+ replyType: 'reply',
+ visible: false,
+ });
+}
+
+describe('appended reply draft round trip', () => {
+ it('hide removes a live-appended quote (control)', () => {
+ const editor = makeEditor();
+ appendQuote(editor);
+ editor.read(() => {
+ expect($collectMacroQuotes()).toHaveLength(1);
+ });
+ hideQuote(editor);
+ editor.read(() => {
+ expect($collectMacroQuotes()).toHaveLength(0);
+ });
+ });
+
+ it('the draft-save export keeps the classed-block marker', () => {
+ const editor = makeEditor();
+ appendQuote(editor);
+ // Draft saves run prepareEmailBody without appendReply (collectDraft).
+ const prepared = prepareEmailBody(editor);
+ expect(prepared).not.toBeNull();
+ const html = decodeBodyHtml(prepared!.bodyHtml);
+ const body = new DOMParser().parseFromString(html, 'text/html').body;
+ const quote = body.querySelector('.macro_quote');
+ expect(quote).not.toBeNull();
+ // ClassedBlockNode.importDOM only claims elements carrying this marker;
+ // the authored sanitizer keeps data-* attributes, so if it's present here
+ // it survives to body_html_sanitized.
+ expect(quote!.getAttribute('data-classed-block')).toBe('true');
+ });
+
+ it('reloading the saved draft keeps the quote removable (reload case)', () => {
+ const editorA = makeEditor();
+ appendQuote(editorA);
+ const prepared = prepareEmailBody(editorA);
+ const html = decodeBodyHtml(prepared!.bodyHtml);
+
+ // Reload path: setEditorStateFromHtml -> $generateNodesFromDOM.
+ const editorB = makeEditor();
+ editorB.update(() => {
+ const dom = new DOMParser().parseFromString(html, 'text/html');
+ const nodes = $generateNodesFromDOM(editorB, dom);
+ const root = $getRoot();
+ root.clear();
+ root.append(...nodes);
+ });
+
+ editorB.read(() => {
+ expect($collectMacroQuotes()).toHaveLength(1);
+ });
+ hideQuote(editorB);
+ editorB.read(() => {
+ expect($collectMacroQuotes()).toHaveLength(0);
+ });
+ });
+});
diff --git a/packages/lexical-core/nodes/DocumentCardNode.ts b/packages/lexical-core/nodes/DocumentCardNode.ts
index 5dc6a37c4f..c32d471001 100644
--- a/packages/lexical-core/nodes/DocumentCardNode.ts
+++ b/packages/lexical-core/nodes/DocumentCardNode.ts
@@ -222,7 +222,14 @@ export class DocumentCardNode extends DecoratorBlockNode<
};
return {
- div: () => ({ conversion: convert, priority: 1 }),
+ // Decline non-matching divs in the claim itself: the importer picks a
+ // single claimant per element (ties go to the first registered node)
+ // and never falls back when its conversion returns null, so an
+ // unconditional claim here would swallow every other node's divs.
+ div: (domNode: HTMLElement) =>
+ domNode.hasAttribute('data-document-card')
+ ? { conversion: convert, priority: 1 }
+ : null,
};
}
diff --git a/packages/lexical-core/nodes/HtmlRenderNode.ts b/packages/lexical-core/nodes/HtmlRenderNode.ts
index e2e867948d..ed20db6bf1 100644
--- a/packages/lexical-core/nodes/HtmlRenderNode.ts
+++ b/packages/lexical-core/nodes/HtmlRenderNode.ts
@@ -120,7 +120,15 @@ export class HtmlRenderNode extends DecoratorBlockNode<
};
return {
- div: () => ({ conversion: convert, priority: 1 }),
+ // Decline non-matching divs in the claim itself: the importer picks a
+ // single claimant per element (ties go to the first registered node)
+ // and never falls back when its conversion returns null, so an
+ // unconditional claim here would swallow every other node's divs.
+ div: (domNode: HTMLElement) =>
+ domNode.hasAttribute('data-html-render') ||
+ domNode.classList.contains('macro_html_render')
+ ? { conversion: convert, priority: 1 }
+ : null,
};
}
diff --git a/packages/lexical-core/nodes/ImageNode.ts b/packages/lexical-core/nodes/ImageNode.ts
index 83e5175027..7dbdea1bbb 100644
--- a/packages/lexical-core/nodes/ImageNode.ts
+++ b/packages/lexical-core/nodes/ImageNode.ts
@@ -177,8 +177,17 @@ export class ImageNode extends MediaNode<{ alt: string }> {
return null;
},
div: (domNode: HTMLElement) => {
- const img = domNode.querySelector('img');
- if (!img) return null;
+ // Match only the exported wrapper shape (<div> whose sole child is
+ // the <img>). Claiming any div with a descendant img would steal
+ // ancestor containers (quote wrappers, merged paragraph divs) and
+ // collapse them to just the image, dropping their other content.
+ const img = domNode.firstElementChild;
+ if (
+ domNode.childElementCount !== 1 ||
+ img?.tagName !== 'IMG' ||
+ domNode.textContent?.trim() !== ''
+ )
+ return null;
const src = img.getAttribute('src');
const alt = img.getAttribute('alt');
diff --git a/packages/lexical-core/nodes/PasteNode.ts b/packages/lexical-core/nodes/PasteNode.ts
index 1db09f4f22..e92908d24b 100644
--- a/packages/lexical-core/nodes/PasteNode.ts
+++ b/packages/lexical-core/nodes/PasteNode.ts
@@ -103,7 +103,14 @@ export class PasteNode extends DecoratorBlockNode<
};
return {
- div: () => ({ conversion: convert, priority: 1 }),
+ // Decline non-matching divs in the claim itself: the importer picks a
+ // single claimant per element (ties go to the first registered node)
+ // and never falls back when its conversion returns null, so an
+ // unconditional claim here would swallow every other node's divs.
+ div: (domNode: HTMLElement) =>
+ domNode.hasAttribute('data-paste-node')
+ ? { conversion: convert, priority: 1 }
+ : null,
};
}
diff --git a/packages/lexical-core/nodes/UnknownMentionNode.ts b/packages/lexical-core/nodes/UnknownMentionNode.ts
index 7ed8eac001..815a4b3386 100644
--- a/packages/lexical-core/nodes/UnknownMentionNode.ts
+++ b/packages/lexical-core/nodes/UnknownMentionNode.ts
@@ -100,7 +100,14 @@ export class UnknownMentionNode extends DecoratorNode<
};
return {
- div: () => ({ conversion: convert, priority: 1 }),
+ // Decline non-matching divs in the claim itself: the importer picks a
+ // single claimant per element (ties go to the first registered node)
+ // and never falls back when its conversion returns null, so an
+ // unconditional claim here would swallow every other node's divs.
+ div: (domNode: HTMLElement) =>
+ domNode.hasAttribute('data-unknown-mention')
+ ? { conversion: convert, priority: 1 }
+ : null,
};
}
diff --git a/packages/lexical-core/nodes/VideoNode.ts b/packages/lexical-core/nodes/VideoNode.ts
index 68abd0f7c1..7ec88243b5 100644
--- a/packages/lexical-core/nodes/VideoNode.ts
+++ b/packages/lexical-core/nodes/VideoNode.ts
@@ -181,8 +181,17 @@ export class VideoNode extends MediaNode<{ controls: boolean }> {
return null;
},
div: (domNode: HTMLElement) => {
- const video = domNode.querySelector('video');
- if (!video) return null;
+ // Match only the exported wrapper shape (<div> whose sole child is
+ // the <video>). Claiming any div with a descendant video would steal
+ // ancestor containers (quote wrappers, merged paragraph divs) and
+ // collapse them to just the video, dropping their other content.
+ const video = domNode.firstElementChild;
+ if (
+ domNode.childElementCount !== 1 ||
+ video?.tagName !== 'VIDEO' ||
+ domNode.textContent?.trim() !== ''
+ )
+ return null;
const src = video.getAttribute('src');
const controls = video.hasAttribute('controls');
diff --git a/packages/lexical-core/tests/mediaWrapperImport.test.ts b/packages/lexical-core/tests/mediaWrapperImport.test.ts
new file mode 100644
index 0000000000..fa5a61cb29
--- /dev/null
+++ b/packages/lexical-core/tests/mediaWrapperImport.test.ts
@@ -0,0 +1,66 @@
+// @vitest-environment jsdom
+import { $generateNodesFromDOM } from '@lexical/html';
+import { $getRoot, createEditor, type LexicalNode } from 'lexical';
+import { describe, expect, it } from 'vitest';
+import { SupportedNodeTypes } from '../node-list';
+import { $isImageNode } from '../nodes/ImageNode';
+
+const IMG =
+ '<img src="https://example.com/x.png" width="10" height="10" data-src-type="sfs" data-image-id="img-1">';
+
+function importHtml(html: string) {
+ const editor = createEditor({
+ nodes: SupportedNodeTypes,
+ onError: (e) => {
+ throw e;
+ },
+ });
+ editor.update(() => {
+ const dom = new DOMParser().parseFromString(html, 'text/html');
+ const nodes = $generateNodesFromDOM(editor, dom);
+ const root = $getRoot();
+ root.clear();
+ root.append(...nodes);
+ });
+ return editor;
+}
+
+function $collectImages(): LexicalNode[] {
+ const found: LexicalNode[] = [];
+ const visit = (node: LexicalNode) => {
+ if ($isImageNode(node)) found.push(node);
+ if ('getChildren' in node) {
+ for (const child of (node as any).getChildren()) visit(child);
+ }
+ };
+ for (const child of $getRoot().getChildren()) visit(child);
+ return found;
+}
+
+describe('media wrapper div import', () => {
+ it('imports the exported wrapper shape (<div><img/></div>) as an image', () => {
+ const editor = importHtml(`<body><div>${IMG}</div></body>`);
+ editor.read(() => {
+ expect($collectImages()).toHaveLength(1);
+ });
+ });
+
+ it('does not collapse a div holding an image plus other content', () => {
+ const editor = importHtml(`<body><div>hello there ${IMG}</div></body>`);
+ editor.read(() => {
+ expect($collectImages()).toHaveLength(1);
+ expect($getRoot().getTextContent()).toContain('hello there');
+ });
+ });
+
+ it('does not steal an ancestor container with a nested image', () => {
+ const editor = importHtml(
+ `<body><div data-classed-block="true" class="macro_quote gmail_quote"><div class="gmail_attr" data-classed-block="true">On ... wrote:</div><div>${IMG}</div><blockquote>quoted text</blockquote></div></body>`
+ );
+ editor.read(() => {
+ expect($collectImages()).toHaveLength(1);
+ expect($getRoot().getTextContent()).toContain('quoted text');
+ expect($getRoot().getTextContent()).toContain('On ... wrote:');
+ });
+ });
+});