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.

feat(email): gmail-style forward composer with collapsible quoted content (#4717)

Evan Hutnik467df88a11c0
diff --git a/js/app/packages/block-email/component/BaseInput.tsx b/js/app/packages/block-email/component/BaseInput.tsx
index 472624b37e..6f4dae5977 100644
--- a/js/app/packages/block-email/component/BaseInput.tsx
+++ b/js/app/packages/block-email/component/BaseInput.tsx
@@ -105,7 +105,7 @@ import {
} from '@ui';
import { iosCursorScrollPlugin } from 'core/component/LexicalMarkdown/plugins/ios-cursor-scroll';
import { registerHotkey, useHotkeyDOMScope } from 'core/hotkey/hotkeys';
-import { $getRoot } from 'lexical';
+import { $addUpdateTag, $getRoot } from 'lexical';
import {
type Accessor,
createEffect,
@@ -536,6 +536,11 @@ export function BaseInput(props: {
const [bodyMacro, setBodyMacro] = createSignal<string>('');
const [scrollContainer, setScrollContainer] = createSignal<HTMLElement>();
+ // Gmail-style sizing: the composer opens compact and grows to the full cap
+ // once the user scrolls the content
+ const [composerExpanded, setComposerExpanded] = createSignal(false);
+ // Appended quoted thread starts hidden behind a "⋯" pill (desktop)
+ const [quoteCollapsed, setQuoteCollapsed] = createSignal(true);
const [showExpandedRecipients, setShowExpandedRecipients] =
createSignal<boolean>(false);
const [isDragging, setIsDragging] = createSignal<boolean>();
@@ -633,7 +638,11 @@ export function BaseInput(props: {
form().setCapturedEditor(currentEditor);
const html = initialHtml();
if (html) {
- setEditorStateFromHtml(currentEditor, html);
+ // Restore content without letting selection reconciliation grab focus
+ currentEditor.update(() => {
+ $addUpdateTag('skip-dom-selection');
+ setEditorStateFromHtml(currentEditor, html, true);
+ });
}
};
@@ -780,6 +789,52 @@ export function BaseInput(props: {
}
}
+ // Lexical setup after the quote append (decorator mounts, mutation flushes)
+ // keeps flushing stale selections into the editor, yanking focus out of the
+ // To field. While armed, bounce those grabs back to To; any deliberate user
+ // interaction (pointer, Tab/Escape, focus leaving the composer) disarms it.
+ let bounceEditorFocusGrabs = false;
+
+ onMount(() => {
+ const disarm = () => {
+ bounceEditorFocusGrabs = false;
+ };
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (e.key === 'Tab' || e.key === 'Escape') disarm();
+ };
+ const onFocusIn = (e: FocusEvent) => {
+ if (!bounceEditorFocusGrabs) return;
+ const target = e.target as Node;
+ if (!composeContainerRef?.contains(target)) {
+ disarm();
+ return;
+ }
+ if (scrollContainer()?.contains(target)) {
+ toRef()?.focus();
+ }
+ };
+ document.addEventListener('pointerdown', disarm, true);
+ document.addEventListener('keydown', onKeyDown, true);
+ document.addEventListener('focusin', onFocusIn, true);
+ onCleanup(() => {
+ document.removeEventListener('pointerdown', disarm, true);
+ document.removeEventListener('keydown', onKeyDown, true);
+ document.removeEventListener('focusin', onFocusIn, true);
+ });
+ });
+
+ const focusForwardRecipients = () => {
+ setShowExpandedRecipients(true);
+ setTimeout(() => {
+ if (toRef()) {
+ bounceEditorFocusGrabs = true;
+ toRef()?.focus();
+ }
+ // After the quoted thread is appended, keep the send bar in view
+ bottomBarRef?.scrollIntoView({ block: 'nearest' });
+ }, 100);
+ };
+
// Attach side-effect handlers on mount; they replay against current state
onMount(() => {
form().setOnDirty(() => {
@@ -787,16 +842,14 @@ export function BaseInput(props: {
});
form().setOnReplyTypeApplied((rt) => {
+ setComposerExpanded(false);
if (rt === 'forward') {
- setShowExpandedRecipients(true);
- setTimeout(() => {
- if (toRef()) {
- toRef()?.focus();
- }
- }, 100);
+ setQuoteCollapsed(true);
+ focusForwardRecipients();
} else if (rt === 'reply' || rt === 'reply-all') {
setTimeout(() => {
editor()?.focus();
+ bottomBarRef?.scrollIntoView({ block: 'nearest' });
}, 100);
}
});
@@ -1001,8 +1054,15 @@ export function BaseInput(props: {
if (form().replyType() !== requestReplyType) {
form().setReplyType(requestReplyType);
+ } else if (requestReplyType === 'forward') {
+ // setReplyType is skipped when the type is unchanged, so land the
+ // cursor in the To field explicitly
+ focusForwardRecipients();
+ }
+ // Forwards focus the To field; focusing the editor would steal it back
+ if (requestReplyType !== 'forward') {
+ form().setShouldFocusInput(true);
}
- form().setShouldFocusInput(true);
ctx.replyRequest.clear();
});
@@ -1090,6 +1150,7 @@ export function BaseInput(props: {
const [attachComposeHotkeys, composeHotkeyScope] =
useHotkeyDOMScope('compose-message');
let composeContainerRef: HTMLDivElement | undefined;
+ let bottomBarRef: HTMLDivElement | undefined;
useTouchOutsideToDismissKeyboard(() => composeContainerRef);
const [isFocused, setIsFocused] = createSignal(false);
@@ -1406,6 +1467,12 @@ export function BaseInput(props: {
form().setShouldFocusInput(false);
return;
}
+ // Forwards focus the To field; a stale flag consumed here after the
+ // editor mounts would move the caret into the editor body instead.
+ if (effectiveReplyType() === 'forward') {
+ form().setShouldFocusInput(false);
+ return;
+ }
const ed = editor();
if (!ed) return;
requestAnimationFrame(() => {
@@ -1593,6 +1660,8 @@ export function BaseInput(props: {
const currentlyAppended = form().replyAppended();
form().setReplyAppended(!currentlyAppended);
+ // Explicitly showing quoted text via the toolbar reveals it uncollapsed
+ if (!currentlyAppended) setQuoteCollapsed(false);
editor()?.dispatchCommand(TOGGLE_APPEND_EMAIL_THREAD_COMMAND, {
replyingTo,
@@ -1605,6 +1674,60 @@ export function BaseInput(props: {
});
};
+ const AttachmentsRow = (rowProps?: { class?: string }) => (
+ <Show when={form().attachments.list().length > 0}>
+ <div
+ class={cn(
+ 'ph-no-capture shrink-0 flex gap-1 flex-wrap w-full py-2',
+ rowProps?.class
+ )}
+ >
+ <For each={form().attachments.list()}>
+ {(attachment) => (
+ <Switch>
+ <Match when={attachment.type === 'local' && attachment}>
+ {(attachment) => (
+ <EmailAttachmentPill
+ attachment={{
+ fileName: attachment().file.name,
+ mimeType: attachment().file.type,
+ }}
+ removable
+ onRemove={() => handleRemoveAttachment(attachment())}
+ />
+ )}
+ </Match>
+ <Match when={attachment.type === 'remote' && attachment}>
+ {(attachment) => (
+ <EmailAttachmentPill
+ attachment={{
+ fileName: attachment().fileName,
+ mimeType: attachment().contentType,
+ }}
+ removable
+ onRemove={() => handleRemoveAttachment(attachment())}
+ />
+ )}
+ </Match>
+ <Match when={attachment.type === 'forwarded' && attachment}>
+ {(attachment) => (
+ <EmailAttachmentPill
+ attachment={{
+ fileName: attachment().fileName,
+ mimeType: attachment().mimeType,
+ }}
+ removable
+ onRemove={() => handleRemoveAttachment(attachment())}
+ />
+ )}
+ </Match>
+ </Switch>
+ )}
+ </For>
+ </div>
+ </Show>
+ );
+
const AttachButton = (buttonProps?: {
variant?: 'ghost' | 'base';
class?: string;
@@ -1834,6 +1957,7 @@ export function BaseInput(props: {
To
</div>
<RecipientSelector<EmailRecipient['kind']>
+ openOnFocus={false}
class="min-w-0 bg-transparent rounded-none! [&_input]:ml-0!"
inputRef={setToRef}
options={ctx.recipientOptions}
@@ -1863,6 +1987,7 @@ export function BaseInput(props: {
Cc
</div>
<RecipientSelector<EmailRecipient['kind']>
+ openOnFocus={false}
class="min-w-0 bg-transparent rounded-none! [&_input]:ml-0!"
inputRef={setCcRef}
options={ctx.recipientOptions}
@@ -1893,6 +2018,7 @@ export function BaseInput(props: {
Bcc
</div>
<RecipientSelector<EmailRecipient['kind']>
+ openOnFocus={false}
class="min-w-0 bg-transparent rounded-none! [&_input]:ml-0!"
inputRef={setBccRef}
options={ctx.recipientOptions}
@@ -1944,6 +2070,7 @@ export function BaseInput(props: {
>
<div class="shrink-0 text-ink-placeholder">To:</div>
<RecipientSelector<EmailRecipient['kind']>
+ openOnFocus={false}
class={mobileRecipientSelectorClass}
inputRef={setToRef}
options={ctx.recipientOptions}
@@ -1986,6 +2113,7 @@ export function BaseInput(props: {
>
<div class="shrink-0 text-ink-placeholder">Cc:</div>
<RecipientSelector<EmailRecipient['kind']>
+ openOnFocus={false}
class={mobileRecipientSelectorClass}
inputRef={setCcRef}
options={ctx.recipientOptions}
@@ -2014,6 +2142,7 @@ export function BaseInput(props: {
>
<div class="shrink-0 text-ink-placeholder">Bcc:</div>
<RecipientSelector<EmailRecipient['kind']>
+ openOnFocus={false}
class={mobileRecipientSelectorClass}
inputRef={setBccRef}
options={ctx.recipientOptions}
@@ -2089,8 +2218,23 @@ export function BaseInput(props: {
'relative min-h-18 w-full flex flex-col placeholder:text-ink-placeholder placeholder:opacity-50 px-4 py-1',
isMobileDrawer()
? 'max-h-none flex-1 overflow-visible px-5 pt-6 pb-4'
- : 'max-h-[calc(60*var(--dvh,1dvh))] overflow-y-auto mobile:max-h-[calc(32*var(--dvh,1dvh))]'
+ : cn(
+ 'overflow-y-auto mobile:max-h-[calc(32*var(--dvh,1dvh))]',
+ composerExpanded()
+ ? // Cap to the thread viewport (minus composer chrome) so the
+ // recipients row and send bar stay on screen together
+ 'max-h-[min(calc(60*var(--dvh,1dvh)),calc(var(--thread-height,9999px)-14rem))]'
+ : 'max-h-56'
+ )
)}
+ onScroll={(e) => {
+ if (composerExpanded() || e.currentTarget.scrollTop <= 0) return;
+ setComposerExpanded(true);
+ // Keep the send bar pinned while the box grows
+ requestAnimationFrame(() => {
+ bottomBarRef?.scrollIntoView({ block: 'nearest' });
+ });
+ }}
onclick={() => {
editor()?.focus();
}}
@@ -2131,6 +2275,10 @@ export function BaseInput(props: {
class={cn(
'ph-no-capture cursor-text wrap-break-word text-ink h-auto overflow-visible',
isMobileDrawer() ? 'text-[17px] leading-6' : 'text-sm',
+ // Quoted thread collapses behind the "⋯" pill below
+ // (rule lives in LexicalMarkdown/styles.css — Tailwind arbitrary
+ // variants turn the underscore in .macro_quote into a space)
+ quoteCollapsed() && 'quote-collapsed',
isDragging() && 'blur'
)}
disabled={sendMutation.isPending}
@@ -2144,7 +2292,31 @@ export function BaseInput(props: {
refFn={(el) => props.markdownDomRef?.(el)}
onConnect={handleEditorConnect}
/>
- <Show when={isMobileDrawer() && props.replyingTo()}>
+ <Show when={form().replyAppended() && quoteCollapsed()}>
+ <div class="flex items-center py-1.5">
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ class="rounded-md text-ink-extra-muted hover:text-ink-muted hover:bg-active"
+ tooltip="Show quoted text"
+ onclick={(e: MouseEvent) => {
+ e.stopPropagation();
+ setQuoteCollapsed(false);
+ setComposerExpanded(true);
+ }}
+ >
+ <DotsThree />
+ </Button>
+ </div>
+ </Show>
+ <Show
+ when={
+ isMobileDrawer() &&
+ props.replyingTo() &&
+ // The collapse pill above already covers this state
+ !(form().replyAppended() && quoteCollapsed())
+ }
+ >
<div
class="shrink-0 pt-2 pb-1"
data-corvu-no-drag=""
@@ -2175,50 +2347,9 @@ export function BaseInput(props: {
<MacroSignatureButton />
</div>
</Show>
- <div class="ph-no-capture flex gap-1 flex-wrap w-full py-2">
- <For each={form().attachments.list()}>
- {(attachment) => (
- <Switch>
- <Match when={attachment.type === 'local' && attachment}>
- {(attachment) => (
- <EmailAttachmentPill
- attachment={{
- fileName: attachment().file.name,
- mimeType: attachment().file.type,
- }}
- removable
- onRemove={() => handleRemoveAttachment(attachment())}
- />
- )}
- </Match>
- <Match when={attachment.type === 'remote' && attachment}>
- {(attachment) => (
- <EmailAttachmentPill
- attachment={{
- fileName: attachment().fileName,
- mimeType: attachment().contentType,
- }}
- removable
- onRemove={() => handleRemoveAttachment(attachment())}
- />
- )}
- </Match>
- <Match when={attachment.type === 'forwarded' && attachment}>
- {(attachment) => (
- <EmailAttachmentPill
- attachment={{
- fileName: attachment().fileName,
- mimeType: attachment().mimeType,
- }}
- removable
- onRemove={() => handleRemoveAttachment(attachment())}
- />
- )}
- </Match>
- </Switch>
- )}
- </For>
- </div>
+ <Show when={isMobileDrawer()}>
+ <AttachmentsRow />
+ </Show>
<Show when={scrollAreaSignatureHtml()}>
{(html) => (
<SignaturePreview
@@ -2229,6 +2360,8 @@ export function BaseInput(props: {
</Show>
</div>
<Show when={!isMobileDrawer()}>
+ {/* Below the scroll area so quoted email content can never overlap it */}
+ <AttachmentsRow class="px-4" />
<Show when={footerSignatureHtml()}>
{(html) => (
<SignaturePreview
@@ -2240,7 +2373,10 @@ export function BaseInput(props: {
{/* No fixed height: the send button (size-7.5) is taller than the icon
buttons, and a fixed h-9 minus the vertical padding left it 4px short
— with items-end it bled upward over the signature bar above. */}
- <div class="shrink-0 flex flex-row w-full justify-between items-end space-x-2 px-2 pb-2 pt-1.5">
+ <div
+ ref={bottomBarRef}
+ class="shrink-0 flex flex-row w-full justify-between items-end space-x-2 px-2 pb-2 pt-1.5"
+ >
<div class="flex flex-row items-center gap-1">
<div class="relative flex">
<AttachButton />
diff --git a/js/app/packages/block-email/component/EmailMessageBody.tsx b/js/app/packages/block-email/component/EmailMessageBody.tsx
index 0de2ea7adb..b7a22175f3 100644
--- a/js/app/packages/block-email/component/EmailMessageBody.tsx
+++ b/js/app/packages/block-email/component/EmailMessageBody.tsx
@@ -98,13 +98,25 @@ export function EmailMessageBody(props: EmailMessageBodyProps) {
: parsedBodyReplyless();
};
+ // Sent-from-Macro messages strip the quoted thread from body_macro at send
+ // time, and the backend skips replyless trimming for "Fwd:" subjects — so a
+ // quote in the full html means there is hidden content regardless of
+ // body_replyless.
+ const bodyHtmlHasQuote = createMemo(() => {
+ const html = props.message.body_html_sanitized;
+ if (!html || !props.message.body_macro) return false;
+ const doc = new DOMParser().parseFromString(html.toString(), 'text/html');
+ return doc.body.querySelector('.macro_quote') !== null;
+ });
+
const hasHiddenReplyStructure = () => {
return (
!isPlaintext() &&
- ((bodyReplyless() &&
- bodyReplyless().toString().replace(/\s+/g, '').length !==
- props.message.body_html_sanitized?.toString().replace(/\s+/g, '')
- .length) ||
+ (bodyHtmlHasQuote() ||
+ (bodyReplyless() &&
+ bodyReplyless().toString().replace(/\s+/g, '').length !==
+ props.message.body_html_sanitized?.toString().replace(/\s+/g, '')
+ .length) ||
source()?.signature)
);
};
diff --git a/js/app/packages/block-email/component/MessageList.tsx b/js/app/packages/block-email/component/MessageList.tsx
index 64f7df2763..d152d3fc9a 100644
--- a/js/app/packages/block-email/component/MessageList.tsx
+++ b/js/app/packages/block-email/component/MessageList.tsx
@@ -55,6 +55,8 @@ export function MessageList(props: MessageListProps) {
'--thread-bottom-pad',
`${Math.round(list.clientHeight * LAST_MESSAGE_REST_FRACTION)}px`
);
+ // Lets the inline composer cap its height to the visible thread area
+ list.style.setProperty('--thread-height', `${list.clientHeight}px`);
});
observer.observe(list);
onCleanup(() => observer.disconnect());
diff --git a/js/app/packages/block-email/component/createEmailFormState.ts b/js/app/packages/block-email/component/createEmailFormState.ts
index 29f1e8214d..d097403c3c 100644
--- a/js/app/packages/block-email/component/createEmailFormState.ts
+++ b/js/app/packages/block-email/component/createEmailFormState.ts
@@ -260,7 +260,10 @@ export function createEmailFormState(
if (rt === 'forward') {
setState('withQuotedText', true);
const editor = capturedEditor();
- if (editor) {
+ // The captured editor can be a stale one from an unmounted composer
+ // (this state outlives the component); dispatching into it is a no-op,
+ // so defer the append to the next editor capture instead.
+ if (editor?.getRootElement()?.isConnected) {
editor.dispatchCommand(TOGGLE_APPEND_EMAIL_THREAD_COMMAND, {
replyingTo: replyingTo,
replyType: rt,
diff --git a/js/app/packages/block-email/util/prepareEmailBody.ts b/js/app/packages/block-email/util/prepareEmailBody.ts
index b3140f3fd3..b0b5d0eabb 100644
--- a/js/app/packages/block-email/util/prepareEmailBody.ts
+++ b/js/app/packages/block-email/util/prepareEmailBody.ts
@@ -12,11 +12,13 @@ import {
} from '@lexical-core';
import type { ApiMessage } from '@service-email/generated/schemas';
import {
+ $addUpdateTag,
$createLineBreakNode,
$createParagraphNode,
$createTextNode,
$getRoot,
$isLineBreakNode,
+ $setSelection,
COMMAND_PRIORITY_EDITOR,
createCommand,
type LexicalEditor,
@@ -109,11 +111,22 @@ function $generateHeaderNodes(
): LexicalNode[] {
const descriptor = buildHeaderDescriptor(replyingTo, replyType);
if (descriptor.kind === 'forward') {
- return descriptor.lines.map((line) => {
- const p = $createParagraphNode();
- p.append($createTextNode(line));
- return p;
+ // Match Gmail's forward markup: headers live in a gmail_attr div inside
+ // the gmail_quote — quote-trimming (ours and Gmail's) keys off it
+ const emailHeader = $createClassedBlockNode({
+ tag: 'div',
+ classes: ['gmail_attr'],
+ attributes: replyingTo.replying_to_id
+ ? {
+ [REPLYING_TO_ID_ATTRIBUTE]: replyingTo.replying_to_id,
+ }
+ : undefined,
+ });
+ descriptor.lines.forEach((line, i) => {
+ if (i > 0) emailHeader.append($createLineBreakNode());
+ emailHeader.append($createTextNode(line));
});
+ return [emailHeader];
}
const emailHeader = $createClassedBlockNode({
tag: 'div',
@@ -160,9 +173,11 @@ const $appendPreviousEmail = (
} else {
const parser = new DOMParser();
const dom = parser.parseFromString(replyingToBodyHTML, 'text/html');
- // We are checking if the appended reply contains a table. This is not exact, but is a good indicator that an email will contain content that we can not render correctly, in which case the appended reply will be a non-editable HTML Render Node.
+ // Forwards always embed the original as a non-editable HTML Render Node so
+ // the recipient gets the exact original markup. For replies, a table is a
+ // good indicator of content we can't convert into editable nodes correctly.
const hasTable = Boolean(dom.querySelector('table'));
- if (hasTable) {
+ if (replyType === 'forward' || hasTable) {
const htmlNode = $createHtmlRenderNode({ html: replyingToBodyHTML });
quoteNode.append(htmlNode);
} else {
@@ -208,6 +223,7 @@ function removeAppendedThread(
editor.update(
() => {
+ $addUpdateTag('skip-dom-selection');
for (const node of $findPreviousEmailNode(replyingToID)) {
if (!node) continue;
@@ -222,6 +238,9 @@ export function registerToggleAppendedThread(editor: LexicalEditor) {
return editor.registerCommand(
TOGGLE_APPEND_EMAIL_THREAD_COMMAND,
({ replyingTo, visible, replyType }) => {
+ // Programmatic content change: don't let selection reconciliation
+ // move DOM focus into the editor
+ $addUpdateTag('skip-dom-selection');
const replyingToID = replyingTo?.replying_to_id ?? undefined;
if (!visible) {
@@ -230,6 +249,9 @@ export function registerToggleAppendedThread(editor: LexicalEditor) {
}
$appendPreviousEmail(editor, replyingTo, replyType);
+ // Appending leaves a dirty selection inside the quote; any later
+ // update would flush it to the DOM and steal focus into the editor
+ $setSelection(null);
return true;
},
@@ -489,6 +511,15 @@ export function prepareEmailBody(
// Convert Macro document mentions to HTML links in the parsed DOM
const mentions = convertMentionsToLinks(parsed.body);
+ // HtmlRenderNode exports as declarative shadow DOM; email clients and the
+ // backend sanitizer drop template content, so inline it
+ for (const host of parsed.body.querySelectorAll('div[data-html-render]')) {
+ const template = host.querySelector('template[shadowrootmode]');
+ if (template instanceof HTMLTemplateElement) {
+ host.replaceChildren(template.content.cloneNode(true));
+ }
+ }
+
if (appendReply && !parsed.body.querySelector('.macro_quote')) {
const appendedReplyElement = getAppendedReplyElement(
appendReply.replyingTo,
@@ -534,8 +565,10 @@ export function hasDraftContent(
}
export function prepareMacroBody(bodyMacro: string): string {
- // Remove macro-quote blocks from the markdown string
+ // Remove appended-quote blocks from the markdown string
// We want these in the HTML, but not in body_macro
// TODO (seamus + peter) Add logic for binding a markdown signal that skips certain transforms
- return bodyMacro.replace(/<macro-quote>.*?<\/macro-quote>/gs, '').trim();
+ return bodyMacro
+ .replace(/<m-email-thread-embed>.*?<\/m-email-thread-embed>/gs, '')
+ .trim();
}
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/HtmlRender.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/HtmlRender.tsx
index ab32cb3252..6fd7c0c889 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/decorator/HtmlRender.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/HtmlRender.tsx
@@ -30,7 +30,13 @@ export const HtmlRender: Component<HtmlRenderDecoratorProps> = (props) => {
<>
<div ref={marker} style={{ display: 'contents' }} />
<Portal mount={shadowContainer()}>
- <div data-html-render="true" innerHTML={props.html} />
+ {/* contain: floats/positioned content in email HTML must size and
+ paint within this node, not over siblings below the editor */}
+ <div
+ data-html-render="true"
+ style={{ contain: 'layout' }}
+ innerHTML={props.html}
+ />
</Portal>
</>
);
diff --git a/js/app/packages/core/component/LexicalMarkdown/styles.css b/js/app/packages/core/component/LexicalMarkdown/styles.css
index 039cacfb5d..589dd7095f 100644
--- a/js/app/packages/core/component/LexicalMarkdown/styles.css
+++ b/js/app/packages/core/component/LexicalMarkdown/styles.css
@@ -13,6 +13,11 @@
display: contents;
}
+/* Email composer collapses the appended quoted thread behind an expander pill */
+.quote-collapsed .macro_quote {
+ display: none;
+}
+
.md * {
caret-color: currentcolor;
}
diff --git a/js/app/packages/core/component/RecipientSelector.tsx b/js/app/packages/core/component/RecipientSelector.tsx
index 21e884778c..30a38636ef 100644
--- a/js/app/packages/core/component/RecipientSelector.tsx
+++ b/js/app/packages/core/component/RecipientSelector.tsx
@@ -266,6 +266,8 @@ type RecipientSelectorProps<K extends CombinedRecipientKind> = {
inputRef?: (ref: HTMLInputElement) => void;
inputId?: string;
focusOnMount?: boolean;
+ /** Open the suggestions dropdown when the input gains focus (default true) */
+ openOnFocus?: boolean;
triggerMode?: ComboboxTriggerMode;
hideBorder?: boolean;
noPadding?: boolean;
@@ -758,7 +760,9 @@ export function RecipientSelector<K extends CombinedRecipientKind>(
}}
class="flex-1 min-h-7 p-1 min-w-50 outline-none placeholder:text-ink-placeholder"
classList={{ 'ml-1': selectedLen() === 0 }}
- onFocus={() => setIsOpen(true)}
+ onFocus={() => {
+ if (props.openOnFocus ?? true) setIsOpen(true);
+ }}
onKeyDown={(e) => {
if (
(e.key === 'a' && e.ctrlKey) ||
diff --git a/js/lexical-core/nodes/HtmlRenderNode.ts b/js/lexical-core/nodes/HtmlRenderNode.ts
index 849e42854a..f669a6ec17 100644
--- a/js/lexical-core/nodes/HtmlRenderNode.ts
+++ b/js/lexical-core/nodes/HtmlRenderNode.ts
@@ -83,7 +83,12 @@ export class HtmlRenderNode extends DecoratorBlockNode<
static importDOM(): DOMConversionMap<HTMLDivElement> | null {
const convert = (domNode: HTMLElement) => {
- if (!domNode.hasAttribute('data-html-render')) {
+ // The backend sanitizer strips data-* attributes but keeps classes, so
+ // the class marker is what survives a draft save/restore round-trip
+ if (
+ !domNode.hasAttribute('data-html-render') &&
+ !domNode.classList.contains('macro_html_render')
+ ) {
return null;
}
@@ -107,6 +112,7 @@ export class HtmlRenderNode extends DecoratorBlockNode<
exportDOM() {
const host = document.createElement('div');
host.setAttribute('data-html-render', 'true');
+ host.className = 'macro_html_render';
const template = document.createElement('template');
template.setAttribute('shadowrootmode', 'open');
diff --git a/js/lexical-core/tests/htmlRender.test.ts b/js/lexical-core/tests/htmlRender.test.ts
new file mode 100644
index 0000000000..f0cc23d2ec
--- /dev/null
+++ b/js/lexical-core/tests/htmlRender.test.ts
@@ -0,0 +1,89 @@
+import {
+ $convertFromMarkdownString,
+ $convertToMarkdownString,
+} from '@lexical/markdown';
+import { $createQuoteNode } from '@lexical/rich-text';
+import { $dfsIterator } from '@lexical/utils';
+import {
+ $createParagraphNode,
+ $createTextNode,
+ $getRoot,
+ createEditor,
+} from 'lexical';
+import { describe, expect, it } from 'vitest';
+import { SupportedNodeTypes } from '../node-list';
+import { $createClassedBlockNode } from '../nodes/ClassedBlockNode';
+import { $isHtmlRenderNode, HtmlRenderNode } from '../nodes/HtmlRenderNode';
+import { INTERNAL_TRANSFORMERS } from '../transformers';
+
+const QUOTED_HTML =
+ '<table><tbody><tr><td><a href="https://example.com">Join</a> the meeting</td></tr></tbody></table>';
+
+function $buildForwardEditorState() {
+ const root = $getRoot();
+ const paragraph = $createParagraphNode();
+ paragraph.append($createTextNode('should i go'));
+ root.append(paragraph);
+
+ // Same shape the composer builds for a forward: quote wrapper containing
+ // the header lines and a blockquote holding the rendered original email.
+ const wrapper = $createClassedBlockNode({
+ tag: 'div',
+ classes: ['macro_quote', 'gmail_quote'],
+ });
+ const header = $createParagraphNode();
+ header.append($createTextNode('---------- Forwarded message ----------'));
+ wrapper.append(header);
+
+ const quote = $createQuoteNode();
+ quote.append(new HtmlRenderNode(QUOTED_HTML));
+ wrapper.append(quote);
+ root.append(wrapper);
+}
+
+describe('HtmlRenderNode - m-html-render transformer', () => {
+ it('round-trips rendered email html nested in a forward quote', async () => {
+ const editor = createEditor({
+ nodes: SupportedNodeTypes,
+ onError: console.error,
+ });
+
+ await new Promise<void>((resolve) => {
+ editor.update(() => $buildForwardEditorState(), {
+ onUpdate: () => resolve(),
+ });
+ });
+
+ let markdown = '';
+ editor.getEditorState().read(() => {
+ markdown = $convertToMarkdownString(INTERNAL_TRANSFORMERS);
+ });
+
+ // The quoted html must survive serialization (angle brackets escaped)
+ expect(markdown).toContain('<m-html-render>');
+ expect(markdown).toContain('</m-html-render>');
+ expect(markdown).not.toContain('<table>');
+ expect(markdown).toContain('\\u003ctable\\u003e');
+
+ // Import back and verify the node is restored with the original html
+ const editor2 = createEditor({
+ nodes: SupportedNodeTypes,
+ onError: console.error,
+ });
+ await new Promise<void>((resolve) => {
+ editor2.update(
+ () => $convertFromMarkdownString(markdown, INTERNAL_TRANSFORMERS),
+ { onUpdate: () => resolve() }
+ );
+ });
+
+ editor2.getEditorState().read(() => {
+ const htmlNodes = [];
+ for (const { node } of $dfsIterator()) {
+ if ($isHtmlRenderNode(node)) htmlNodes.push(node);
+ }
+ expect(htmlNodes).toHaveLength(1);
+ expect(htmlNodes[0].exportComponentProps().html).toBe(QUOTED_HTML);
+ });
+ });
+});
diff --git a/js/lexical-core/transformers/classedBlock.ts b/js/lexical-core/transformers/classedBlock.ts
index 58e9792433..9568184b83 100644
--- a/js/lexical-core/transformers/classedBlock.ts
+++ b/js/lexical-core/transformers/classedBlock.ts
@@ -14,6 +14,7 @@ import {
isAllowedTagName,
} from '../nodes/ClassedBlockNode';
import { CUSTOM_TRANSFORMERS } from './customTransformers';
+import { I_HTML_RENDER } from './htmlRender';
import { I_EQUATION_NODE } from './katex';
import {
I_CONTACT_MENTION,
@@ -34,6 +35,7 @@ const REG_EXP_HTML_BLOCKQUOTE_TAG = /<\/?blockquote\b[^>]*>/gi;
// Transformers used inside macro_quote blocks
const MACRO_QUOTE_TRANSFORMERS = [
+ I_HTML_RENDER,
...CUSTOM_TRANSFORMERS,
I_EQUATION_NODE,
I_USER_MENTION,
@@ -45,6 +47,7 @@ const MACRO_QUOTE_TRANSFORMERS = [
function htmlBlockquoteTransformers() {
return [
HTML_BLOCKQUOTE,
+ I_HTML_RENDER,
...CUSTOM_TRANSFORMERS,
I_EQUATION_NODE,
I_USER_MENTION,
@@ -234,7 +237,11 @@ export const I_MACRO_QUOTE: ElementTransformer = {
const metadata = JSON.parse(metadataMatch[1]);
const { tag, classes } = metadata;
- if (typeof tag !== 'string' || !isAllowedTagName(tag) || !Array.isArray(classes)) {
+ if (
+ typeof tag !== 'string' ||
+ !isAllowedTagName(tag) ||
+ !Array.isArray(classes)
+ ) {
throw new Error('Invalid macro-quote metadata');
}
diff --git a/js/lexical-core/transformers/customTransformers.ts b/js/lexical-core/transformers/customTransformers.ts
index 048f1a2279..3ecc9087ce 100644
--- a/js/lexical-core/transformers/customTransformers.ts
+++ b/js/lexical-core/transformers/customTransformers.ts
@@ -1,3 +1,4 @@
+import { $isListNode } from '@lexical/list';
import {
CHECK_LIST,
type ElementTransformer,
@@ -6,7 +7,6 @@ import {
type Transformer,
UNORDERED_LIST,
} from '@lexical/markdown';
-import { $isListNode } from '@lexical/list';
import { $isHeadingNode } from '@lexical/rich-text';
import { $isElementNode, type ElementNode, type LexicalNode } from 'lexical';
diff --git a/js/lexical-core/transformers/htmlRender.ts b/js/lexical-core/transformers/htmlRender.ts
new file mode 100644
index 0000000000..38d54c718f
--- /dev/null
+++ b/js/lexical-core/transformers/htmlRender.ts
@@ -0,0 +1,47 @@
+import type { TextMatchTransformer } from '@lexical/markdown';
+import type { TextNode } from 'lexical';
+import {
+ $createHtmlRenderNode,
+ $isHtmlRenderNode,
+ HtmlRenderNode,
+} from '../nodes/HtmlRenderNode';
+import {
+ replaceTextWithUnknownMention,
+ UnknownMentionNode,
+} from './unknownFallback';
+
+// Internal transformer — carries the raw HTML payload so rendered email
+// content (e.g. a forwarded message with tables) survives the markdown
+// round-trip. Text-match rather than element: element transformers only run
+// on top-level nodes, and this node lives nested inside blockquotes, where
+// only text-match transformers are consulted.
+export const I_HTML_RENDER: TextMatchTransformer = {
+ dependencies: [HtmlRenderNode, UnknownMentionNode],
+ type: 'text-match',
+ regExp: /<m-html-render>(.*?)<\/m-html-render>/,
+ importRegExp: /<m-html-render>(.*?)<\/m-html-render>/,
+ export: (node) => {
+ if (!$isHtmlRenderNode(node)) return null;
+
+ // Escape angle brackets as unicode escapes so tags inside the HTML don't
+ // get matched by other transformers during import. JSON.parse handles
+ // them natively.
+ const data = JSON.stringify(node.exportComponentProps())
+ .replace(/</g, '\\u003c')
+ .replace(/>/g, '\\u003e');
+
+ return `<m-html-render>${data}</m-html-render>`;
+ },
+ replace: (node: TextNode, match: RegExpMatchArray) => {
+ try {
+ const data = JSON.parse(match[1] ?? '');
+ if (typeof data.html !== 'string') {
+ throw new Error('Missing html field');
+ }
+ node.replace($createHtmlRenderNode({ html: data.html }));
+ } catch (e) {
+ console.error('Failed to parse m-html-render:', e);
+ replaceTextWithUnknownMention(node, 'Unknown Content');
+ }
+ },
+};
diff --git a/js/lexical-core/transformers/index.ts b/js/lexical-core/transformers/index.ts
index 6daa9234eb..79dcb2a170 100644
--- a/js/lexical-core/transformers/index.ts
+++ b/js/lexical-core/transformers/index.ts
@@ -2,6 +2,7 @@ import type { Transformer } from '@lexical/markdown';
import { I_AWAIT_NODE } from './await';
import { HTML_BLOCKQUOTE, I_MACRO_QUOTE } from './classedBlock';
import { CUSTOM_TRANSFORMERS } from './customTransformers';
+import { I_HTML_RENDER } from './htmlRender';
import { I_IMAGE_CONSTRAINED, IMAGE } from './image';
import {
E_BLOCK_EQUATION_NODE,
@@ -53,6 +54,7 @@ export { isConversionOnlyTransformer };
export const INTERNAL_TRANSFORMERS: Transformer[] = [
I_SNAPSHOT_NODE, // Must be before mentions to avoid matching inner tags in snapshot content
I_PASTE_NODE, // Must be before mentions to avoid matching inner tags in paste content
+ I_HTML_RENDER,
PRESERVE_LINES,
LINK_XML, // Prefer internal xml link to handle []() in link text
MARK_XML,
@@ -118,6 +120,7 @@ export const EXTERNAL_TRANSFORMERS: Transformer[] = [
export const ALL_TRANSFORMERS: Transformer[] = [
I_SNAPSHOT_NODE, // Must be before mentions to avoid matching inner tags in snapshot content
I_PASTE_NODE, // Must be before mentions to avoid matching inner tags in paste content
+ I_HTML_RENDER,
E_PASTE_NODE,
PRESERVE_LINES,
LINK_XML, // Prefer internal xml link to handle []() in link text