1d755983ff
# Email editor for Compose campaigns
## Short version
Campaign bodies are currently plain rich text. This PR turns the
composer into an email editor: a centered email canvas with section,
column, button, divider, image and raw-HTML blocks, each editable
through a settings side panel, rendered to email-safe HTML per recipient
at send time. Modelled on Resend's Broadcast editor.
**Product**
- Email canvas with page/body styling (background, width, padding,
corner radius, border, text colour, alignment)
- Blocks: section, 2/3 columns, button, divider, raw HTML, images —
insertable from a floating left rail or the slash menu
- A **section is a container whose typography cascades to its
contents**, so one part of an email can have its own look
- Block settings panel focuses whatever you select and shows its
effective values
- Per-recipient variables (`{{firstName}}`, `{{lastName}}`,
`{{fullName}}`, `{{email}}`, `{{personId}}`) usable in text,
button/link/image URLs, image labels and raw HTML
- Image upload by drag-drop, paste or file picker
**Technical**
- Presets now declare **capabilities** instead of surfaces forking the
editor; the UI derives itself from loaded extensions
- Editor behavior lives in `twenty-front`; the versioned email-document
schema and structural traversal live in `twenty-shared`; rendering lives
in `twenty-emails` — HTML is produced server-side per recipient
- Section typography cascade is **resolved at render time**, not left to
CSS: react-email hardcodes `fontSize`/`lineHeight` on every paragraph
and Outlook ignores `inherit`
- Logic vendored from Resend (MIT); all controls rebuilt on `twenty-ui`
+ Linaria
**Also fixes:** the unsubscribe footer was being appended *after*
`</html>`, outside the document, where Gmail strips it — legally
significant since unsubscribe is required.
---
## Detailed version
### Product requirements
**Problem.** The Compose campaign body was a single rich-text field.
Marketing email needs layout — banded sections, columns, call-to-action
buttons, images with links — and it needs that layout to survive
Outlook, which means table-based HTML rather than the divs a text editor
produces. It also needs per-recipient personalisation.
**Reference.** Resend's Broadcast editor, chosen because it solves the
same problem (TipTap authoring → react-email output) and is MIT
licensed.
#### What a user can now do
| Area | Capability |
|---|---|
| Canvas | Email renders as a centered page with its own background,
width, padding, corner radius and border |
| Blocks | Section, 2/3 columns, button, divider, raw HTML, image |
| Insertion | Floating left rail (pointer-first) or the `/` slash menu
(keyboard-first) |
| Sections | Own text colour, font size, line height, letter spacing and
alignment, cascading to everything inside |
| Images | Upload by drag-drop, paste or picker; link URL, alt text,
width, spacing, border |
| Raw HTML | Edited as source in the panel, previewed on the canvas with
scripts neutralised |
| Variables | `{{firstName}}`, `{{lastName}}`, `{{fullName}}`,
`{{email}}`, `{{personId}}` in text, button URLs, link hrefs and raw
HTML |
| Settings panel | Follows selection; shows effective values; opens
automatically when a block is clicked |
#### Deliberate product decisions
- **Variables display as literal placeholders**, not prose labels, so
the syntax is copyable into HTML blocks and button URLs by hand.
- **Sections inherit until they override.** The panel shows what
actually renders rather than blank fields, but writes nothing until you
edit — so changing the body text colour still flows into sections.
- **Headings keep their own scale** inside a styled section; only
colour, family and spacing cascade, otherwise every heading would
collapse to body size.
- **Clicking a block opens its settings**, but only on whole-node
selections, so typing inside a section does not reopen a panel you just
closed.
### Technical strategy
#### 1. Capability presets (the foundation)
Per-surface variation previously worked by **forking**: three separate
`useEditor` call sites with hardcoded extension arrays. Inside the
shared tree there was no variation at all — all five surfaces received a
byte-identical extension list, and presets controlled only sizing,
chrome and serialization format. Adding email blocks that way meant
either leaking section/column nodes into the record rich-text field and
workflow email body, or writing a fourth fork.
Now:
- a preset declares a **capability list** (`basicMarks`, `headings`,
`lists`, `links`, `images`, `campaignVariables`, `slashCommand`,
`blocks`, `mentions`)
- capabilities resolve to extensions through a factory registry
- the UI derives itself from the loaded extensions via
`hasEditorExtension` — no capability list is prop-drilled into a menu,
because the `Editor` already knows what it can do
The acceptance test was collapsing the AI chat fork into an `aiChat`
preset with no visible change to that composer. `campaignBody` is the
only preset opting into the shared `EMAIL_DOCUMENT_CAPABILITIES` today.
Workflow email keeps its current field UI, but can opt into the same
canvas, block settings and image uploader later without adding another
schema or renderer.
#### 2. Schema / renderer split
The hard constraint: **our HTML is produced server-side, per recipient,
at send time**, because variables substitute into nodes rather than into
a serialized string. That rules out Resend's
`renderToReactEmail`-on-the-extension pattern.
```
twenty-front TipTap extensions + node views + shared email settings UI
twenty-shared versioned email-document schema + structural traversal
twenty-emails react-email renderers (imported by twenty-server)
twenty-server surface-specific variable resolution, validation, send
```
Logic was **vendored, not depended on** — Resend's TipTap is 3.17
against our 3.4, and their UI is Radix. We copied the schema/serializer
approach and rebuilt every control on `twenty-ui` + Linaria.
#### 3. Section typography cascade
The subtle part, and the one that would have silently shipped broken.
Section typography *looks* like it should cascade via CSS. It does not:
```js
// react-email's Text
style: { fontSize: "14px", lineHeight: "24px", ...style, ...margins }
```
Every paragraph re-declares `fontSize` and `lineHeight`, overriding any
enclosing section. `inherit` is not a fix either — Outlook's Word engine
ignores it.
So the cascade is **resolved in the renderer**: the tree walk threads
the enclosing section's typography down and writes computed values
explicitly onto each text node. Nested sections refine what they
inherit.
Verified against real rendered output:
| | rendered |
|---|---|
| paragraph inside section | `font-size:22px; color:rgb(255,0,0);
letter-spacing:2px` |
| h1 inside section | `font-size:32px` (own scale) + section colour and
spacing |
| paragraph outside | `font-size:14px`, no colour — untouched |
#### 4. Storage
`bodyTemplate` stays serialized TipTap JSON in a `TEXT` column. Block
attributes are ProseMirror node attrs, so richer blocks add keys to JSON
already being serialized — no migration, and it flows into the existing
500 ms debounced draft save unchanged.
Since the feature has not shipped, the legacy HTML-string body path was
removed rather than maintained. That is a tightening, not just a
deletion: `bodyTemplate` is writable through the record API, and the old
fallback would interpolate an arbitrary string and email it as markup. A
body that is neither empty nor a valid TipTap document is now rejected
at the send gate.
#### 5. Image hosting
Inline assets use an `EmailImage` file folder with
`ignoreExpirationToken: true` and immutable cache headers, because
recipients' mail clients never authenticate and may open an email years
later. The shared uploader returns `{ fileId, url }`; the image node
keeps both the durable file identity and its delivery URL so
ownership/lifecycle or URL resolution can evolve later without a
document migration. The server verifies the uploaded bytes and only
accepts GIF, JPEG, PNG and WebP.
This is intentionally separate from workflow/email **attachments**.
Attachments remain private files that the server reads and embeds as
MIME parts at send time; inline images need a durable recipient-facing
URL. A future workflow canvas should reuse `useUploadEmailImage` for
inline content while keeping its existing attachment control unchanged.
Adding the folder requires three registrations — the folder config, the
route guard's `SUPPORTED_FILE_FOLDERS`, and `DIRECT_UPLOAD_FILE_FOLDERS`
in the upload service.
### Bugs fixed along the way
- **Unsubscribe footer was appended after `</html>`**, outside the
document, where Gmail strips it. Legally significant, since an
unsubscribe link is required. Now inserted before `</body>`.
- **Body text colour never reached the email.**
- **`onImageUpload` was declared but never passed** by any production
call site, so drag-drop and paste image upload were inert everywhere
outside Storybook.
- **Message lists were not user-facing**, so members could not be added
from the list page.
- **Image resize wrote an undeclared `width` attribute** that TipTap
silently dropped.
- **The text bubble menu appeared over selected atom blocks** with
nothing to format.
### Review notes / known limitations
**Security posture to check.** Anything in `EmailImage` is readable by
anyone holding the URL, forever. The server now enforces an image-only
MIME allowlist from sniffed bytes, but it cannot determine whether the
image itself is confidential. This remains a deliberate trade-off for
recipient-visible inline assets.
**Test gap.** The section typography cascade has no regression test:
react-email's `render()` hangs under Jest (tried 60s), and
`twenty-emails` has no test target at all. Verified by rendering through
the built package instead. Adding a test target there is worthwhile
follow-up.
**Sending needs configuration.** `EMAILING_DOMAIN_DRIVER` defaults to
`LOG`, which fakes a messageId, reports any domain as verified, and only
logs — a campaign reaches "sent" with nothing delivered. Real sending
needs `AWS_SES`.
**Unrelated platform bug found.** The pinned "Create new record" command
throws on viewless objects like `messageListMember`, because
`recordIndexId` derives from the current view.
**Not done.** Panel chrome from the reference: breadcrumb (`Page style /
Section`), collapsible groups, per-side spacing grid, and a
variable-insert button inside link fields. All presentation over the
same data.
**Deferred.** Drag-to-reorder blocks.
`@tiptap/extension-drag-handle-react@3.4.2` matches our pinned versions
exactly, so no upgrade is needed, but its behaviour around atom node
views (HTML block, image) is unverified and belongs in its own change.
<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/twentyhq/twenty/pull/23657?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
---------
Co-authored-by: Félix Malfait <felix.malfait@gmail.com>
Co-authored-by: Félix Malfait <felix@twenty.com>
237 lines
6.1 KiB
TypeScript
237 lines
6.1 KiB
TypeScript
import { ImageBubbleMenu } from '@/advanced-text-editor/components/ImageBubbleMenu';
|
|
import { LinkBubbleMenu } from '@/advanced-text-editor/components/LinkBubbleMenu';
|
|
import { TextBubbleMenu } from '@/advanced-text-editor/components/TextBubbleMenu';
|
|
import { type AdvancedTextEditorChrome } from '@/advanced-text-editor/types/AdvancedTextEditorPreset';
|
|
import { hasEditorExtension } from '@/advanced-text-editor/utils/hasEditorExtension';
|
|
import { FORM_FIELD_PLACEHOLDER_STYLES } from '@/object-record/record-field/ui/form-types/constants/FormFieldPlaceholderStyles';
|
|
import { styled } from '@linaria/react';
|
|
import { EditorContent, type Editor, useEditorState } from '@tiptap/react';
|
|
import { isDefined, resolveCanvasTheme } from 'twenty-shared/utils';
|
|
import { themeCssVariables } from 'twenty-ui/theme-constants';
|
|
|
|
const StyledEditorContainer = styled.div<{
|
|
readonly?: boolean;
|
|
minHeight: number;
|
|
}>`
|
|
box-sizing: border-box;
|
|
display: flex;
|
|
flex-direction: column;
|
|
height: 100%;
|
|
width: 100%;
|
|
|
|
.editor-content {
|
|
flex-grow: 1;
|
|
height: 100%;
|
|
min-height: ${({ minHeight }) => minHeight}px;
|
|
width: 100%;
|
|
}
|
|
|
|
.tiptap {
|
|
border: none !important;
|
|
box-sizing: border-box;
|
|
color: ${({ readonly }) =>
|
|
readonly
|
|
? themeCssVariables.font.color.secondary
|
|
: themeCssVariables.font.color.primary};
|
|
font-family: ${themeCssVariables.font.family};
|
|
font-size: ${themeCssVariables.font.size.sm};
|
|
font-weight: ${themeCssVariables.font.weight.regular};
|
|
height: 100%;
|
|
padding: ${themeCssVariables.spacing[1]} ${themeCssVariables.spacing[2]};
|
|
|
|
p.is-editor-empty:first-of-type::before {
|
|
${FORM_FIELD_PLACEHOLDER_STYLES}
|
|
content: attr(data-placeholder);
|
|
float: left;
|
|
height: 0;
|
|
pointer-events: none;
|
|
}
|
|
|
|
p {
|
|
line-height: 1.5;
|
|
margin: 0;
|
|
}
|
|
|
|
.variable-tag {
|
|
background-color: ${themeCssVariables.color.blue3};
|
|
border-radius: ${themeCssVariables.border.radius.sm};
|
|
color: ${themeCssVariables.color.blue};
|
|
padding: ${themeCssVariables.spacing[1]};
|
|
}
|
|
|
|
h1 {
|
|
font-size: 1.5em;
|
|
}
|
|
|
|
h2 {
|
|
font-size: 1.3em;
|
|
}
|
|
|
|
h3 {
|
|
font-size: 1.1em;
|
|
}
|
|
|
|
li {
|
|
line-height: 1.5;
|
|
margin-bottom: ${themeCssVariables.spacing[2]};
|
|
}
|
|
|
|
.block-section {
|
|
border-radius: ${themeCssVariables.border.radius.sm};
|
|
box-sizing: border-box;
|
|
margin-bottom: ${themeCssVariables.spacing[2]};
|
|
outline: 1px dashed transparent;
|
|
outline-offset: 2px;
|
|
|
|
&:hover {
|
|
outline-color: ${themeCssVariables.border.color.medium};
|
|
}
|
|
}
|
|
|
|
.block-columns {
|
|
box-sizing: border-box;
|
|
display: flex;
|
|
gap: ${themeCssVariables.spacing[2]};
|
|
margin-bottom: ${themeCssVariables.spacing[2]};
|
|
}
|
|
|
|
.block-column {
|
|
box-sizing: border-box;
|
|
flex: 1;
|
|
min-width: 0;
|
|
outline: 1px dashed ${themeCssVariables.border.color.light};
|
|
outline-offset: 2px;
|
|
border-radius: ${themeCssVariables.border.radius.sm};
|
|
}
|
|
|
|
.block-button-wrapper {
|
|
margin-bottom: ${themeCssVariables.spacing[2]};
|
|
}
|
|
|
|
.block-button {
|
|
box-sizing: border-box;
|
|
cursor: text;
|
|
width: fit-content;
|
|
}
|
|
|
|
.block-divider {
|
|
border-left: none;
|
|
border-right: none;
|
|
border-bottom: none;
|
|
}
|
|
|
|
.ProseMirror-selectednode {
|
|
outline: 2px solid ${themeCssVariables.color.blue};
|
|
}
|
|
}
|
|
|
|
.ProseMirror-focused {
|
|
outline: none;
|
|
}
|
|
|
|
.ProseMirror-hideselection * {
|
|
caret-color: transparent;
|
|
}
|
|
`;
|
|
|
|
const StyledCanvasBackdrop = styled.div`
|
|
box-sizing: border-box;
|
|
flex-grow: 1;
|
|
min-height: 100%;
|
|
padding: ${themeCssVariables.spacing[8]} ${themeCssVariables.spacing[4]};
|
|
width: 100%;
|
|
`;
|
|
|
|
const StyledCanvasPage = styled.div`
|
|
box-sizing: border-box;
|
|
margin: 0 auto;
|
|
max-width: 100%;
|
|
min-height: 400px;
|
|
|
|
.editor-content {
|
|
min-height: inherit;
|
|
}
|
|
|
|
.tiptap {
|
|
color: inherit;
|
|
min-height: inherit;
|
|
padding: 0;
|
|
}
|
|
`;
|
|
|
|
type AdvancedTextEditorProps = {
|
|
readonly: boolean | undefined;
|
|
editor: Editor;
|
|
minHeight: number;
|
|
chrome?: AdvancedTextEditorChrome;
|
|
};
|
|
|
|
const TEXT_BUBBLE_MENU_EXTENSION_NAMES = [
|
|
'bold',
|
|
'italic',
|
|
'underline',
|
|
'strike',
|
|
'bulletList',
|
|
'orderedList',
|
|
'heading',
|
|
'link',
|
|
];
|
|
|
|
export const AdvancedTextEditor = ({
|
|
readonly,
|
|
editor,
|
|
minHeight,
|
|
chrome,
|
|
}: AdvancedTextEditorProps) => {
|
|
const hasTextBubbleMenu = TEXT_BUBBLE_MENU_EXTENSION_NAMES.some(
|
|
(extensionName) => hasEditorExtension(editor, extensionName),
|
|
);
|
|
|
|
const canvasTheme = useEditorState({
|
|
editor,
|
|
selector: ({ editor: currentEditor }) =>
|
|
resolveCanvasTheme(currentEditor.state.doc.attrs.canvasTheme),
|
|
});
|
|
|
|
const hasCanvasChrome = chrome === 'canvas' && isDefined(canvasTheme);
|
|
|
|
return (
|
|
<StyledEditorContainer readonly={readonly} minHeight={minHeight}>
|
|
{hasCanvasChrome ? (
|
|
<StyledCanvasBackdrop
|
|
style={{
|
|
backgroundColor: canvasTheme.pageBackground,
|
|
padding: canvasTheme.pagePadding,
|
|
}}
|
|
>
|
|
<StyledCanvasPage
|
|
style={{
|
|
backgroundColor: canvasTheme.bodyBackground || undefined,
|
|
border:
|
|
canvasTheme.borderWidth !== '' &&
|
|
canvasTheme.borderWidth !== '0px'
|
|
? `${canvasTheme.borderWidth} solid ${canvasTheme.borderColor}`
|
|
: undefined,
|
|
borderRadius: canvasTheme.cornerRadius,
|
|
color: canvasTheme.textColor,
|
|
padding: canvasTheme.padding,
|
|
textAlign: canvasTheme.textAlign,
|
|
width: canvasTheme.width,
|
|
}}
|
|
>
|
|
<EditorContent className="editor-content" editor={editor} />
|
|
</StyledCanvasPage>
|
|
</StyledCanvasBackdrop>
|
|
) : (
|
|
<EditorContent className="editor-content" editor={editor} />
|
|
)}
|
|
{hasEditorExtension(editor, 'image') &&
|
|
!hasEditorExtension(editor, 'section') && (
|
|
<ImageBubbleMenu editor={editor} />
|
|
)}
|
|
{hasTextBubbleMenu && <TextBubbleMenu editor={editor} />}
|
|
{hasEditorExtension(editor, 'link') && <LinkBubbleMenu editor={editor} />}
|
|
</StyledEditorContainer>
|
|
);
|
|
};
|