Skip to content

The open alternative to Salesforce, designed for AI.

Refactor outbound email content compilation (#23782)

Félix Malfait29e68a7f8787
diff --git a/packages/twenty-emails/src/utils/email-renderer/renderers/render-mark.tsx b/packages/twenty-emails/src/utils/email-renderer/renderers/render-mark.tsx
index 28c212a7512..0892a12e26c 100644
--- a/packages/twenty-emails/src/utils/email-renderer/renderers/render-mark.tsx
+++ b/packages/twenty-emails/src/utils/email-renderer/renderers/render-mark.tsx
@@ -1,10 +1,11 @@
import { type JSONContent } from '@tiptap/core';
import { type ReactNode } from 'react';
import {
+ type EmailDocumentMarkType,
+ isEmailDocumentMarkType,
type TipTapMark,
- type TipTapMarkType,
- TIPTAP_MARKS_RENDER_ORDER,
TIPTAP_MARK_TYPES,
+ TIPTAP_MARKS_RENDER_ORDER,
} from 'twenty-shared/utils';
import { bold } from '@/utils/email-renderer/marks/bold';
import { italic } from '@/utils/email-renderer/marks/italic';
@@ -18,11 +19,14 @@ const MARK_RENDERERS = {
[TIPTAP_MARK_TYPES.UNDERLINE]: underline,
[TIPTAP_MARK_TYPES.STRIKE]: strike,
[TIPTAP_MARK_TYPES.LINK]: link,
-} as const;
+} as const satisfies Record<
+ EmailDocumentMarkType,
+ (mark: TipTapMark, children: ReactNode) => ReactNode
+>;
export const renderMark = (node: JSONContent): ReactNode => {
const text = node?.text || <>&nbsp;</>;
- const marks = (node?.marks as TipTapMark[]) || [];
+ const marks = [...((node?.marks as TipTapMark[]) || [])];
// Sort marks according to the defined render order
marks.sort((a, b) => {
@@ -34,13 +38,11 @@ export const renderMark = (node: JSONContent): ReactNode => {
// Apply marks from innermost to outermost
return marks.reduce((children: ReactNode, mark: TipTapMark) => {
- const renderer = MARK_RENDERERS[mark.type as TipTapMarkType];
-
- if (!renderer) {
+ if (!isEmailDocumentMarkType(mark.type)) {
// Fallback for unknown mark types - skip unknown marks
return children;
}
- return renderer(mark, children);
+ return MARK_RENDERERS[mark.type](mark, children);
}, text);
};
diff --git a/packages/twenty-emails/src/utils/email-renderer/renderers/render-node.tsx b/packages/twenty-emails/src/utils/email-renderer/renderers/render-node.tsx
index efe5ce545d9..b7e52a91aa8 100644
--- a/packages/twenty-emails/src/utils/email-renderer/renderers/render-node.tsx
+++ b/packages/twenty-emails/src/utils/email-renderer/renderers/render-node.tsx
@@ -15,7 +15,16 @@ import { variableTag } from '@/utils/email-renderer/nodes/variable-tag';
import { type JSONContent } from '@tiptap/core';
import { Fragment, type JSX, type ReactNode } from 'react';
import { type InheritedTypography } from 'src/utils/email-renderer/utils/inherited-typography';
-import { TIPTAP_NODE_TYPES } from 'twenty-shared/utils';
+import {
+ isRenderedEmailDocumentNodeType,
+ TIPTAP_NODE_TYPES,
+ type RenderedEmailDocumentNodeType,
+} from 'twenty-shared/utils';
+
+type EmailNodeRenderer = (
+ node: JSONContent,
+ inherited: InheritedTypography,
+) => ReactNode;
const NODE_RENDERERS = {
[TIPTAP_NODE_TYPES.PARAGRAPH]: paragraph,
@@ -32,19 +41,20 @@ const NODE_RENDERERS = {
[TIPTAP_NODE_TYPES.BUTTON]: button,
[TIPTAP_NODE_TYPES.DIVIDER]: divider,
[TIPTAP_NODE_TYPES.HTML]: html,
-};
+} satisfies Record<RenderedEmailDocumentNodeType, EmailNodeRenderer>;
const renderNode = (
node: JSONContent,
inherited: InheritedTypography,
): ReactNode => {
- const renderer = NODE_RENDERERS[node.type as keyof typeof NODE_RENDERERS];
-
- if (!renderer) {
+ if (
+ typeof node.type !== 'string' ||
+ !isRenderedEmailDocumentNodeType(node.type)
+ ) {
return null;
}
- return renderer(node, inherited);
+ return NODE_RENDERERS[node.type](node, inherited);
};
export const mappedNodeContent = (
diff --git a/packages/twenty-front/src/modules/activities/emails/components/CampaignBodyField.tsx b/packages/twenty-front/src/modules/activities/emails/components/CampaignBodyField.tsx
index fe0fb60a3a7..1b225055ccb 100644
--- a/packages/twenty-front/src/modules/activities/emails/components/CampaignBodyField.tsx
+++ b/packages/twenty-front/src/modules/activities/emails/components/CampaignBodyField.tsx
@@ -6,11 +6,13 @@ import { isDefined } from 'twenty-shared/utils';
import { useCampaignBodyState } from '@/activities/emails/hooks/useCampaignBodyState';
import { useCampaignEmailEditorVariables } from '@/activities/emails/hooks/useCampaignEmailEditorVariables';
-import { InsertRail } from '@/advanced-text-editor/components/InsertRail';
-import { useUploadEmailImage } from '@/advanced-text-editor/hooks/useUploadEmailImage';
-import { activeEmailEditorState } from '@/advanced-text-editor/states/activeEmailEditorState';
+import { EmailEditorCanvas } from '@/activities/emails/editor/components/EmailEditorCanvas';
+import { CAMPAIGN_BODY_EDITOR_PROFILE } from '@/activities/emails/editor/constants/CampaignBodyEditorProfile';
+import { useUploadEmailImage } from '@/activities/emails/hooks/useUploadEmailImage';
+import { activeEmailEditorState } from '@/activities/emails/states/activeEmailEditorState';
import { type MessageCampaign } from '@/activities/emails/types/MessageCampaign';
-import { FormAdvancedTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormAdvancedTextFieldInput';
+import { FormAdvancedTextFieldInput } from '@/advanced-text-editor/components/FormAdvancedTextFieldInput';
+import { AdvancedTextEditorInsertRail } from '@/advanced-text-editor/components/AdvancedTextEditorInsertRail';
import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
const StyledContainer = styled.div`
@@ -47,12 +49,13 @@ export const CampaignBodyField = ({ campaign }: CampaignBodyFieldProps) => {
defaultValue={body}
onChange={setBody}
placeholder={t`Type something or press "/" to see commands`}
- preset="campaignBody"
+ profile={CAMPAIGN_BODY_EDITOR_PROFILE}
+ EditorComponent={EmailEditorCanvas}
onEditorReady={handleEditorReady}
onImageUpload={uploadEmailImage}
/>
{isDefined(bodyEditor) && (
- <InsertRail
+ <AdvancedTextEditorInsertRail
editor={bodyEditor}
onImageUpload={uploadEmailImage}
variables={variables}
diff --git a/packages/twenty-front/src/modules/activities/emails/components/CampaignSentPreview.tsx b/packages/twenty-front/src/modules/activities/emails/components/CampaignSentPreview.tsx
index aeef9b9e2f5..c6f66443ee9 100644
--- a/packages/twenty-front/src/modules/activities/emails/components/CampaignSentPreview.tsx
+++ b/packages/twenty-front/src/modules/activities/emails/components/CampaignSentPreview.tsx
@@ -2,7 +2,9 @@ import { styled } from '@linaria/react';
import { t } from '@lingui/core/macro';
import { type MessageCampaign } from '@/activities/emails/types/MessageCampaign';
-import { FormAdvancedTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormAdvancedTextFieldInput';
+import { EmailEditorCanvas } from '@/activities/emails/editor/components/EmailEditorCanvas';
+import { CAMPAIGN_BODY_EDITOR_PROFILE } from '@/activities/emails/editor/constants/CampaignBodyEditorProfile';
+import { FormAdvancedTextFieldInput } from '@/advanced-text-editor/components/FormAdvancedTextFieldInput';
const StyledContainer = styled.div`
display: flex;
@@ -21,7 +23,8 @@ export const CampaignSentPreview = ({ campaign }: CampaignSentPreviewProps) => {
<FormAdvancedTextFieldInput
defaultValue={campaign.bodyTemplate}
readonly
- preset="campaignBody"
+ profile={CAMPAIGN_BODY_EDITOR_PROFILE}
+ EditorComponent={EmailEditorCanvas}
placeholder={t`No content`}
/>
</StyledContainer>
diff --git a/packages/twenty-front/src/modules/activities/emails/components/EmailComposerFields.tsx b/packages/twenty-front/src/modules/activities/emails/components/EmailComposerFields.tsx
index 66727e4ef8a..354f06a9bc1 100644
--- a/packages/twenty-front/src/modules/activities/emails/components/EmailComposerFields.tsx
+++ b/packages/twenty-front/src/modules/activities/emails/components/EmailComposerFields.tsx
@@ -6,7 +6,9 @@ import { EmailRecipientsFieldInput } from '@/activities/emails/recipients/compon
import { type EmailComposerContextRecord } from '@/activities/emails/recipients/types/EmailComposerContextRecord';
import { getEmailRecipientKey } from '@/activities/emails/recipients/utils/getEmailRecipientKey';
import { type EmailComposerState } from '@/activities/emails/types/EmailComposerState';
-import { FormAdvancedTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormAdvancedTextFieldInput';
+import { INLINE_EMAIL_BODY_EDITOR_PROFILE } from '@/activities/emails/editor/constants/InlineEmailBodyEditorProfile';
+import { useUploadEmailImage } from '@/activities/emails/hooks/useUploadEmailImage';
+import { FormAdvancedTextFieldInput } from '@/advanced-text-editor/components/FormAdvancedTextFieldInput';
import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
import { GET_MY_CONNECTED_ACCOUNTS } from '@/settings/accounts/graphql/queries/getMyConnectedAccounts';
import { Select } from '@/ui/input/components/Select';
@@ -55,6 +57,7 @@ export const EmailComposerFields = ({
composerState,
contextRecord,
}: EmailComposerFieldsProps) => {
+ const { uploadEmailImage } = useUploadEmailImage();
const { data: accountsData } = useQuery<{
myConnectedAccounts: { id: string; handle: string }[];
}>(GET_MY_CONNECTED_ACCOUNTS);
@@ -138,7 +141,8 @@ export const EmailComposerFields = ({
defaultValue={composerState.initialBody}
onChange={composerState.setBody}
placeholder={t`Type something or press "/" to see commands`}
- preset="inlineEmailBody"
+ profile={INLINE_EMAIL_BODY_EDITOR_PROFILE}
+ onImageUpload={uploadEmailImage}
/>
<EmailAttachmentsField
label={t`Attachments`}
diff --git a/packages/twenty-front/src/modules/activities/emails/editor/components/EmailEditorCanvas.tsx b/packages/twenty-front/src/modules/activities/emails/editor/components/EmailEditorCanvas.tsx
new file mode 100644
index 00000000000..093a1e09d9d
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/emails/editor/components/EmailEditorCanvas.tsx
@@ -0,0 +1,76 @@
+import { AdvancedTextEditor } from '@/advanced-text-editor/components/AdvancedTextEditor';
+import { type AdvancedTextEditorComponentProps } from '@/advanced-text-editor/types/AdvancedTextEditorComponentProps';
+import { styled } from '@linaria/react';
+import { useEditorState } from '@tiptap/react';
+import { CANVAS_THEME_DEFAULTS, resolveCanvasTheme } from 'twenty-shared/utils';
+import { themeCssVariables } from 'twenty-ui/theme-constants';
+
+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,
+ .tiptap {
+ min-height: inherit;
+ }
+
+ .tiptap {
+ color: inherit;
+ padding: 0;
+ }
+`;
+
+type EmailEditorCanvasProps = AdvancedTextEditorComponentProps;
+
+export const EmailEditorCanvas = ({
+ editor,
+ readonly,
+ minHeight,
+}: EmailEditorCanvasProps) => {
+ const storedCanvasTheme = useEditorState({
+ editor,
+ selector: ({ editor: currentEditor }) =>
+ resolveCanvasTheme(currentEditor.state.doc.attrs.canvasTheme),
+ });
+ const canvasTheme = storedCanvasTheme ?? CANVAS_THEME_DEFAULTS;
+
+ return (
+ <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,
+ }}
+ >
+ <AdvancedTextEditor
+ editor={editor}
+ readonly={readonly}
+ minHeight={minHeight}
+ />
+ </StyledCanvasPage>
+ </StyledCanvasBackdrop>
+ );
+};
diff --git a/packages/twenty-front/src/modules/activities/emails/editor/constants/CampaignBodyEditorProfile.ts b/packages/twenty-front/src/modules/activities/emails/editor/constants/CampaignBodyEditorProfile.ts
new file mode 100644
index 00000000000..a6a30008112
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/emails/editor/constants/CampaignBodyEditorProfile.ts
@@ -0,0 +1,17 @@
+import { EmailThemedDocument } from '@/activities/emails/editor/extensions/EmailThemedDocument';
+import { CampaignVariableTag } from '@/activities/emails/editor/extensions/campaign-variables/CampaignVariableTag';
+import { ADVANCED_TEXT_EDITOR_BLOCK_EXTENSIONS } from '@/advanced-text-editor/constants/AdvancedTextEditorBlockExtensions';
+import { type AdvancedTextEditorProfile } from '@/advanced-text-editor/types/AdvancedTextEditorProfile';
+import { buildFullRichTextExtensions } from '@/advanced-text-editor/utils/buildFullRichTextExtensions';
+
+export const CAMPAIGN_BODY_EDITOR_PROFILE = {
+ chrome: 'document',
+ minHeight: 0,
+ enableFullScreen: false,
+ documentExtension: EmailThemedDocument,
+ buildExtensions: (context) => [
+ ...buildFullRichTextExtensions(context),
+ CampaignVariableTag,
+ ...ADVANCED_TEXT_EDITOR_BLOCK_EXTENSIONS,
+ ],
+} satisfies AdvancedTextEditorProfile;
diff --git a/packages/twenty-front/src/modules/activities/emails/editor/constants/InlineEmailBodyEditorProfile.ts b/packages/twenty-front/src/modules/activities/emails/editor/constants/InlineEmailBodyEditorProfile.ts
new file mode 100644
index 00000000000..e71c93c8baa
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/emails/editor/constants/InlineEmailBodyEditorProfile.ts
@@ -0,0 +1,11 @@
+import { type AdvancedTextEditorProfile } from '@/advanced-text-editor/types/AdvancedTextEditorProfile';
+import { buildFullRichTextWithVariableTagExtensions } from '@/advanced-text-editor/utils/buildFullRichTextExtensions';
+import { parseLegacyHtmlDocument } from '@/advanced-text-editor/utils/parseLegacyHtmlDocument';
+
+export const INLINE_EMAIL_BODY_EDITOR_PROFILE = {
+ chrome: 'field',
+ minHeight: 120,
+ enableFullScreen: true,
+ parseLegacyDocument: parseLegacyHtmlDocument,
+ buildExtensions: buildFullRichTextWithVariableTagExtensions,
+} satisfies AdvancedTextEditorProfile;
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/extensions/blocks/ThemedDocument.ts b/packages/twenty-front/src/modules/activities/emails/editor/extensions/EmailThemedDocument.ts
similarity index 86%
rename from packages/twenty-front/src/modules/advanced-text-editor/extensions/blocks/ThemedDocument.ts
rename to packages/twenty-front/src/modules/activities/emails/editor/extensions/EmailThemedDocument.ts
index 67aaf8489d7..6d805c50224 100644
--- a/packages/twenty-front/src/modules/advanced-text-editor/extensions/blocks/ThemedDocument.ts
+++ b/packages/twenty-front/src/modules/activities/emails/editor/extensions/EmailThemedDocument.ts
@@ -4,7 +4,7 @@ import {
CANVAS_THEME_DEFAULTS,
} from 'twenty-shared/utils';
-export const ThemedDocument = Document.extend({
+export const EmailThemedDocument = Document.extend({
addAttributes() {
return {
canvasTheme: {
diff --git a/packages/twenty-front/src/modules/activities/emails/editor/extensions/campaign-variables/CampaignVariableChip.tsx b/packages/twenty-front/src/modules/activities/emails/editor/extensions/campaign-variables/CampaignVariableChip.tsx
new file mode 100644
index 00000000000..55dc9f43b4b
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/emails/editor/extensions/campaign-variables/CampaignVariableChip.tsx
@@ -0,0 +1,17 @@
+import { VariableChip } from '@/advanced-text-editor/extensions/variable-tag/VariableChip';
+import { type NodeViewProps } from '@tiptap/react';
+
+type CampaignVariableChipProps = NodeViewProps;
+
+export const CampaignVariableChip = ({
+ deleteNode,
+ editor,
+ node,
+}: CampaignVariableChipProps) => {
+ const variable =
+ typeof node.attrs.variable === 'string' ? node.attrs.variable : '';
+
+ return (
+ <VariableChip deleteNode={deleteNode} editor={editor} label={variable} />
+ );
+};
diff --git a/packages/twenty-front/src/modules/activities/emails/editor/extensions/campaign-variables/CampaignVariableTag.ts b/packages/twenty-front/src/modules/activities/emails/editor/extensions/campaign-variables/CampaignVariableTag.ts
new file mode 100644
index 00000000000..b157bc3c994
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/emails/editor/extensions/campaign-variables/CampaignVariableTag.ts
@@ -0,0 +1,10 @@
+import { ReactNodeViewRenderer } from '@tiptap/react';
+
+import { CampaignVariableChip } from '@/activities/emails/editor/extensions/campaign-variables/CampaignVariableChip';
+import { VariableTag } from '@/advanced-text-editor/extensions/variable-tag/VariableTag';
+
+export const CampaignVariableTag = VariableTag.extend({
+ addNodeView() {
+ return ReactNodeViewRenderer(CampaignVariableChip);
+ },
+});
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/hooks/useUploadEmailImage.ts b/packages/twenty-front/src/modules/activities/emails/hooks/useUploadEmailImage.ts
similarity index 100%
rename from packages/twenty-front/src/modules/advanced-text-editor/hooks/useUploadEmailImage.ts
rename to packages/twenty-front/src/modules/activities/emails/hooks/useUploadEmailImage.ts
diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldChip.tsx b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldChip.tsx
index b5ea3f7ba5f..c85a1507b64 100644
--- a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldChip.tsx
+++ b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldChip.tsx
@@ -7,7 +7,7 @@ import { type EmailRecipientResolution } from '@/activities/emails/recipients/ho
import { type EmailRecipient } from '@/activities/emails/recipients/types/EmailRecipient';
import { formatEmailRecipient } from '@/activities/emails/recipients/utils/formatEmailRecipient';
import { getEmailIdentityDisplayName } from '@/activities/emails/utils/getEmailIdentityDisplayName';
-import { BaseChip } from '@/object-record/record-field/ui/form-types/components/BaseChip';
+import { BaseChip } from '@/ui/input/components/BaseChip';
import { Dropdown } from '@/ui/layout/dropdown/components/Dropdown';
import { getAbsoluteImageUrl } from '~/utils/image/getAbsoluteImageUrl';
diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldInput.tsx b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldInput.tsx
index 17763cad87b..7090b3e895f 100644
--- a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldInput.tsx
+++ b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldInput.tsx
@@ -29,8 +29,8 @@ import { type EmailRecipient } from '@/activities/emails/recipients/types/EmailR
import { getEmailRecipientKey } from '@/activities/emails/recipients/utils/getEmailRecipientKey';
import { isValidEmailRecipientAddress } from '@/activities/emails/recipients/utils/isValidEmailRecipientAddress';
import { parseEmailRecipients } from '@/activities/emails/recipients/utils/parseEmailRecipients';
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
-import { FORM_FIELD_PLACEHOLDER_STYLES } from '@/object-record/record-field/ui/form-types/constants/FormFieldPlaceholderStyles';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
+import { FORM_FIELD_PLACEHOLDER_STYLES } from '@/ui/input/constants/FormFieldPlaceholderStyles';
import { InputLabel } from '@/ui/input/components/InputLabel';
import { Dropdown } from '@/ui/layout/dropdown/components/Dropdown';
import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/states/activeEmailEditorState.ts b/packages/twenty-front/src/modules/activities/emails/states/activeEmailEditorState.ts
similarity index 100%
rename from packages/twenty-front/src/modules/advanced-text-editor/states/activeEmailEditorState.ts
rename to packages/twenty-front/src/modules/activities/emails/states/activeEmailEditorState.ts
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/components/AdvancedTextEditor.tsx b/packages/twenty-front/src/modules/advanced-text-editor/components/AdvancedTextEditor.tsx
index f7528dbf700..3e620e5cd20 100644
--- a/packages/twenty-front/src/modules/advanced-text-editor/components/AdvancedTextEditor.tsx
+++ b/packages/twenty-front/src/modules/advanced-text-editor/components/AdvancedTextEditor.tsx
@@ -1,12 +1,11 @@
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 { type AdvancedTextEditorComponentProps } from '@/advanced-text-editor/types/AdvancedTextEditorComponentProps';
import { hasEditorExtension } from '@/advanced-text-editor/utils/hasEditorExtension';
-import { FORM_FIELD_PLACEHOLDER_STYLES } from '@/object-record/record-field/ui/form-types/constants/FormFieldPlaceholderStyles';
+import { FORM_FIELD_PLACEHOLDER_STYLES } from '@/ui/input/constants/FormFieldPlaceholderStyles';
import { styled } from '@linaria/react';
-import { EditorContent, type Editor, useEditorState } from '@tiptap/react';
-import { isDefined, resolveCanvasTheme } from 'twenty-shared/utils';
+import { EditorContent } from '@tiptap/react';
import { themeCssVariables } from 'twenty-ui/theme-constants';
const StyledEditorContainer = styled.div<{
@@ -96,12 +95,12 @@ const StyledEditorContainer = styled.div<{
}
.block-column {
+ border-radius: ${themeCssVariables.border.radius.sm};
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 {
@@ -115,9 +114,9 @@ const StyledEditorContainer = styled.div<{
}
.block-divider {
+ border-bottom: none;
border-left: none;
border-right: none;
- border-bottom: none;
}
.ProseMirror-selectednode {
@@ -134,38 +133,6 @@ const StyledEditorContainer = styled.div<{
}
`;
-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',
@@ -177,54 +144,20 @@ const TEXT_BUBBLE_MENU_EXTENSION_NAMES = [
'link',
];
+type AdvancedTextEditorProps = AdvancedTextEditorComponentProps;
+
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} />
- )}
+ <EditorContent className="editor-content" editor={editor} />
{hasEditorExtension(editor, 'image') &&
!hasEditorExtension(editor, 'section') && (
<ImageBubbleMenu editor={editor} />
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/components/InsertRail.tsx b/packages/twenty-front/src/modules/advanced-text-editor/components/AdvancedTextEditorInsertRail.tsx
similarity index 86%
rename from packages/twenty-front/src/modules/advanced-text-editor/components/InsertRail.tsx
rename to packages/twenty-front/src/modules/advanced-text-editor/components/AdvancedTextEditorInsertRail.tsx
index e9538150b5b..3d4ff7aa9af 100644
--- a/packages/twenty-front/src/modules/advanced-text-editor/components/InsertRail.tsx
+++ b/packages/twenty-front/src/modules/advanced-text-editor/components/AdvancedTextEditorInsertRail.tsx
@@ -5,28 +5,23 @@ import { useRef, useState } from 'react';
import { EMAIL_IMAGE_MIME_TYPES } from 'twenty-shared/constants';
import { isDefined, TIPTAP_NODE_TYPES } from 'twenty-shared/utils';
import {
- IconBox,
- IconClick,
- IconCode,
- IconColumns,
IconH1,
IconH2,
IconH3,
IconLayoutGrid,
IconList,
IconListNumbers,
- IconMinus,
IconPhoto,
IconTypography,
IconVariable,
} from 'twenty-ui/icon';
-
-import { hasEditorExtension } from '@/advanced-text-editor/utils/hasEditorExtension';
import { Button, LightIconButton } from 'twenty-ui/input';
import { MenuItem } from 'twenty-ui/navigation';
import { themeCssVariables } from 'twenty-ui/theme-constants';
+import { ADVANCED_TEXT_EDITOR_BLOCK_INSERTION_RECIPES } from '@/advanced-text-editor/constants/AdvancedTextEditorBlockInsertionRecipes';
import { type UploadedImage } from '@/advanced-text-editor/types/UploadedImage';
+import { hasEditorExtension } from '@/advanced-text-editor/utils/hasEditorExtension';
import { TextInput } from '@/ui/input/components/TextInput';
const StyledRail = styled.div`
@@ -86,23 +81,18 @@ const StyledImageHint = styled.div`
font-size: ${themeCssVariables.font.size.xs};
`;
-const columnJson = () => ({
- type: TIPTAP_NODE_TYPES.COLUMN,
- content: [{ type: TIPTAP_NODE_TYPES.PARAGRAPH }],
-});
-
-type InsertRailProps = {
+type AdvancedTextEditorInsertRailProps = {
editor: Editor;
onImageUpload?: (file: File) => Promise<UploadedImage>;
variables?: Array<{ label: string; value: string }>;
};
-export const InsertRail = ({
+export const AdvancedTextEditorInsertRail = ({
editor,
onImageUpload,
variables = [],
-}: InsertRailProps) => {
- const { t } = useLingui();
+}: AdvancedTextEditorInsertRailProps) => {
+ const { i18n, t } = useLingui();
const imageFileInputRef = useRef<HTMLInputElement>(null);
const [isUploadingImage, setIsUploadingImage] = useState(false);
const [openMenu, setOpenMenu] = useState<
@@ -207,50 +197,14 @@ export const InsertRail = ({
setImageUrl('');
};
- const blockItems = [
- {
- Icon: IconBox,
- label: t`Section`,
- content: {
- type: TIPTAP_NODE_TYPES.SECTION,
- content: [{ type: TIPTAP_NODE_TYPES.PARAGRAPH }],
- },
- },
- {
- Icon: IconColumns,
- label: t`2 Columns`,
- content: {
- type: TIPTAP_NODE_TYPES.COLUMNS,
- content: [columnJson(), columnJson()],
- },
- },
- {
- Icon: IconColumns,
- label: t`3 Columns`,
- content: {
- type: TIPTAP_NODE_TYPES.COLUMNS,
- content: [columnJson(), columnJson(), columnJson()],
- },
- },
- {
- Icon: IconClick,
- label: t`Button`,
- content: {
- type: TIPTAP_NODE_TYPES.BUTTON,
- content: [{ type: TIPTAP_NODE_TYPES.TEXT, text: t`Click here` }],
- },
- },
- {
- Icon: IconMinus,
- label: t`Divider`,
- content: { type: TIPTAP_NODE_TYPES.DIVIDER },
- },
- {
- Icon: IconCode,
- label: t`HTML`,
- content: { type: TIPTAP_NODE_TYPES.HTML },
- },
- ];
+ const blockItems = ADVANCED_TEXT_EDITOR_BLOCK_INSERTION_RECIPES.map(
+ ({ createContent, icon, id, title }) => ({
+ id,
+ Icon: icon,
+ label: i18n._(title),
+ content: createContent((message) => i18n._(message)),
+ }),
+ );
return (
<StyledRailContainer>
@@ -332,9 +286,9 @@ export const InsertRail = ({
)}
{openMenu === 'blocks' && (
<StyledPopover>
- {blockItems.map(({ Icon, label, content }) => (
+ {blockItems.map(({ Icon, id, label, content }) => (
<MenuItem
- key={label}
+ key={id}
LeftIcon={Icon}
text={label}
onClick={() => insertAtEnd(content)}
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormAdvancedTextFieldInput.tsx b/packages/twenty-front/src/modules/advanced-text-editor/components/FormAdvancedTextFieldInput.tsx
similarity index 85%
rename from packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormAdvancedTextFieldInput.tsx
rename to packages/twenty-front/src/modules/advanced-text-editor/components/FormAdvancedTextFieldInput.tsx
index 2624b83ef08..62d82482735 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormAdvancedTextFieldInput.tsx
+++ b/packages/twenty-front/src/modules/advanced-text-editor/components/FormAdvancedTextFieldInput.tsx
@@ -1,15 +1,13 @@
import { AdvancedTextEditor } from '@/advanced-text-editor/components/AdvancedTextEditor';
-import {
- ADVANCED_TEXT_EDITOR_PRESETS,
- type AdvancedTextEditorPresetName,
-} from '@/advanced-text-editor/constants/AdvancedTextEditorPresets';
import { useAdvancedTextEditor } from '@/advanced-text-editor/hooks/useAdvancedTextEditor';
+import { type AdvancedTextEditorComponentProps } from '@/advanced-text-editor/types/AdvancedTextEditorComponentProps';
+import { type AdvancedTextEditorProfile } from '@/advanced-text-editor/types/AdvancedTextEditorProfile';
import { type UploadedImage } from '@/advanced-text-editor/types/UploadedImage';
-import { serializeAdvancedTextEditorContent } from '@/advanced-text-editor/utils/serializeAdvancedTextEditorContent';
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
-import { type VariablePickerComponent } from '@/object-record/record-field/ui/form-types/types/VariablePickerComponent';
+import { serializeAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializeAdvancedTextEditorDocument';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { InputHint } from '@/ui/input/components/InputHint';
import { InputLabel } from '@/ui/input/components/InputLabel';
+import { type VariablePickerComponent } from '@/ui/input/types/VariablePickerComponent';
import { useFullScreenModal } from '@/ui/layout/fullscreen/hooks/useFullScreenModal';
import { type BreadcrumbProps } from '@/ui/navigation/bread-crumb/components/Breadcrumb';
import { usePushFocusItemToFocusStack } from '@/ui/utilities/focus/hooks/usePushFocusItemToFocusStack';
@@ -18,7 +16,7 @@ import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentTyp
import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
import { type Editor } from '@tiptap/core';
-import { useEffect, useId, useState } from 'react';
+import { type ComponentType, useEffect, useId, useState } from 'react';
import { isDefined } from 'twenty-shared/utils';
import { IconMaximize } from 'twenty-ui/icon';
import { LightIconButton } from 'twenty-ui/input';
@@ -33,8 +31,8 @@ const StyledAdvancedTextFieldContainerWrapper = styled.div<{
flex-grow: 1;
min-height: 0;
- /* FormFieldInputContainer is shared by every form field and does not carry a
- height, so the document chrome stretches its one child here instead. */
+ /* Document editors stretch to their available height; field editors keep
+ their intrinsic height so they compose naturally inside forms. */
& > * {
flex-grow: ${({ hasFieldChrome }) => (hasFieldChrome ? 0 : 1)};
min-height: 0;
@@ -102,8 +100,8 @@ type FormAdvancedTextFieldInputProps = {
VariablePicker?: VariablePickerComponent;
onImageUpload?: (file: File) => Promise<UploadedImage>;
onImageUploadError?: (error: Error, file: File) => void;
- preset: AdvancedTextEditorPresetName;
- // Escape hatch for surfaces that share a preset but need their own height.
+ profile: AdvancedTextEditorProfile;
+ EditorComponent?: ComponentType<AdvancedTextEditorComponentProps>;
minHeight?: number;
enableFullScreen?: boolean;
fullScreenBreadcrumbs?: BreadcrumbProps['links'];
@@ -121,21 +119,17 @@ export const FormAdvancedTextFieldInput = ({
VariablePicker,
onImageUpload,
onImageUploadError,
- preset,
+ profile,
+ EditorComponent = AdvancedTextEditor,
minHeight,
enableFullScreen,
fullScreenBreadcrumbs,
onEditorReady,
}: FormAdvancedTextFieldInputProps) => {
- const {
- contentType,
- chrome,
- minHeight: presetMinHeight,
- enableFullScreen: presetEnableFullScreen,
- } = ADVANCED_TEXT_EDITOR_PRESETS[preset];
+ const { chrome, minHeight: profileMinHeight } = profile;
- const editorMinHeight = minHeight ?? presetMinHeight;
- const isFullScreenEnabled = enableFullScreen ?? presetEnableFullScreen;
+ const editorMinHeight = minHeight ?? profileMinHeight;
+ const isFullScreenEnabled = enableFullScreen ?? profile.enableFullScreen;
const instanceId = useId();
const isMobile = useIsMobile();
@@ -148,12 +142,12 @@ export const FormAdvancedTextFieldInput = ({
const editor = useAdvancedTextEditor(
{
- preset,
+ profile,
placeholder: placeholder,
readonly,
defaultValue,
onUpdate: (editor) => {
- onChange?.(serializeAdvancedTextEditorContent({ editor, contentType }));
+ onChange?.(serializeAdvancedTextEditorDocument(editor));
},
onFocus: () => {
pushFocusItemToFocusStack({
@@ -224,11 +218,10 @@ export const FormAdvancedTextFieldInput = ({
? renderFullScreenModal(
<div data-globally-prevent-click-outside="true">
<StyledFullScreenEditorContainer>
- <AdvancedTextEditor
+ <EditorComponent
editor={editor}
readonly={readonly}
minHeight={editorMinHeight}
- chrome={chrome}
/>
</StyledFullScreenEditorContainer>
</div>,
@@ -249,11 +242,10 @@ export const FormAdvancedTextFieldInput = ({
hasFieldChrome={chrome === 'field'}
>
{!isFullScreen && (
- <AdvancedTextEditor
+ <EditorComponent
editor={editor}
readonly={readonly}
minHeight={editorMinHeight}
- chrome={chrome}
/>
)}
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/components/__stories__/AdvancedTextEditor.stories.tsx b/packages/twenty-front/src/modules/advanced-text-editor/components/__stories__/AdvancedTextEditor.stories.tsx
index 9acab64be85..39eb4148876 100644
--- a/packages/twenty-front/src/modules/advanced-text-editor/components/__stories__/AdvancedTextEditor.stories.tsx
+++ b/packages/twenty-front/src/modules/advanced-text-editor/components/__stories__/AdvancedTextEditor.stories.tsx
@@ -1,9 +1,10 @@
import { AdvancedTextEditor } from '@/advanced-text-editor/components/AdvancedTextEditor';
-import { type AdvancedTextEditorPresetName } from '@/advanced-text-editor/constants/AdvancedTextEditorPresets';
import { useAdvancedTextEditor } from '@/advanced-text-editor/hooks/useAdvancedTextEditor';
+import { type AdvancedTextEditorProfile } from '@/advanced-text-editor/types/AdvancedTextEditorProfile';
+import { buildFullRichTextWithVariableTagExtensions } from '@/advanced-text-editor/utils/buildFullRichTextExtensions';
import { type Meta, type StoryObj } from '@storybook/react-vite';
import { expect, fn, userEvent, waitFor } from 'storybook/test';
-import { isDefined } from 'twenty-shared/utils';
+import { isDefined, TIPTAP_DOCUMENT_SCHEMA_VERSION } from 'twenty-shared/utils';
import { ComponentDecorator, RouterDecorator } from 'twenty-ui/testing';
import { ObjectMetadataItemsDecorator } from '~/testing/decorators/ObjectMetadataItemsDecorator';
import { SnackBarDecorator } from '~/testing/decorators/SnackBarDecorator';
@@ -12,23 +13,40 @@ import { WorkflowStepDecorator } from '~/testing/decorators/WorkflowStepDecorato
import { WorkspaceDecorator } from '~/testing/decorators/WorkspaceDecorator';
import { graphqlMocks } from '~/testing/graphqlMocks';
+const STORY_RICH_TEXT_PROFILE = {
+ chrome: 'document',
+ minHeight: 200,
+ enableFullScreen: false,
+ buildExtensions: buildFullRichTextWithVariableTagExtensions,
+} satisfies AdvancedTextEditorProfile;
+
+const STORY_MINIMAL_PROFILE = {
+ chrome: 'document',
+ minHeight: 200,
+ enableFullScreen: false,
+ buildExtensions: () => [],
+} satisfies AdvancedTextEditorProfile;
+
const EditorWrapper = ({
readonly = false,
placeholder = 'Enter text content...',
defaultValue = null,
onUpdate = fn(),
minHeight = 200,
- preset = 'recordRichTextField',
+ extensionSet = 'richText',
}: {
readonly?: boolean;
placeholder?: string;
defaultValue?: string | null;
onUpdate?: (content: string) => void;
minHeight?: number;
- preset?: AdvancedTextEditorPresetName;
+ extensionSet?: 'richText' | 'minimal';
}) => {
const editor = useAdvancedTextEditor({
- preset,
+ profile:
+ extensionSet === 'richText'
+ ? STORY_RICH_TEXT_PROFILE
+ : STORY_MINIMAL_PROFILE,
placeholder,
readonly,
defaultValue,
@@ -89,6 +107,7 @@ export const WithContent: Story = {
args: {
defaultValue: JSON.stringify({
type: 'doc',
+ attrs: { schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION },
content: [
{
type: 'paragraph',
@@ -144,6 +163,7 @@ export const WithHeadings: Story = {
args: {
defaultValue: JSON.stringify({
type: 'doc',
+ attrs: { schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION },
content: [
{
type: 'heading',
@@ -182,6 +202,7 @@ export const WithLinks: Story = {
args: {
defaultValue: JSON.stringify({
type: 'doc',
+ attrs: { schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION },
content: [
{
type: 'paragraph',
@@ -217,6 +238,7 @@ export const WithVariableTags: Story = {
args: {
defaultValue: JSON.stringify({
type: 'doc',
+ attrs: { schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION },
content: [
{
type: 'paragraph',
@@ -250,6 +272,7 @@ export const ReadOnly: Story = {
readonly: true,
defaultValue: JSON.stringify({
type: 'doc',
+ attrs: { schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION },
content: [
{
type: 'paragraph',
@@ -281,9 +304,9 @@ export const Empty: Story = {
},
};
-export const AiChatPreset: Story = {
+export const MinimalDocument: Story = {
args: {
- preset: 'aiChat',
+ extensionSet: 'minimal',
placeholder: 'Ask, search or make anything...',
},
};
@@ -306,6 +329,7 @@ export const WithLists: Story = {
args: {
defaultValue: JSON.stringify({
type: 'doc',
+ attrs: { schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION },
content: [
{
type: 'heading',
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/__stories__/FormAdvancedTextFieldInput.stories.tsx b/packages/twenty-front/src/modules/advanced-text-editor/components/__stories__/FormAdvancedTextFieldInput.stories.tsx
similarity index 86%
rename from packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/__stories__/FormAdvancedTextFieldInput.stories.tsx
rename to packages/twenty-front/src/modules/advanced-text-editor/components/__stories__/FormAdvancedTextFieldInput.stories.tsx
index d5fdeaa8cfd..788108588df 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/__stories__/FormAdvancedTextFieldInput.stories.tsx
+++ b/packages/twenty-front/src/modules/advanced-text-editor/components/__stories__/FormAdvancedTextFieldInput.stories.tsx
@@ -1,8 +1,10 @@
-import { FormAdvancedTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormAdvancedTextFieldInput';
-import { WorkflowVariablePicker } from '@/workflow/workflow-variables/components/WorkflowVariablePicker';
+import { FormAdvancedTextFieldInput } from '@/advanced-text-editor/components/FormAdvancedTextFieldInput';
+import { type AdvancedTextEditorProfile } from '@/advanced-text-editor/types/AdvancedTextEditorProfile';
+import { buildFullRichTextWithVariableTagExtensions } from '@/advanced-text-editor/utils/buildFullRichTextExtensions';
import { type Meta, type StoryObj } from '@storybook/react-vite';
import { graphql, HttpResponse } from 'msw';
import { expect, fn, userEvent, within } from 'storybook/test';
+import { TIPTAP_DOCUMENT_SCHEMA_VERSION } from 'twenty-shared/utils';
import { ComponentDecorator, RouterDecorator } from 'twenty-ui/testing';
import { ObjectMetadataItemsDecorator } from '~/testing/decorators/ObjectMetadataItemsDecorator';
import { SnackBarDecorator } from '~/testing/decorators/SnackBarDecorator';
@@ -12,17 +14,33 @@ import { WorkspaceDecorator } from '~/testing/decorators/WorkspaceDecorator';
import { graphqlMocks } from '~/testing/graphqlMocks';
import { getWorkflowNodeIdMock } from '~/testing/mock-data/workflow';
+const STORY_FORM_EDITOR_PROFILE = {
+ chrome: 'field',
+ minHeight: 340,
+ enableFullScreen: true,
+ buildExtensions: buildFullRichTextWithVariableTagExtensions,
+} satisfies AdvancedTextEditorProfile;
+
+const StoryVariablePicker = ({
+ onVariableSelect,
+}: {
+ onVariableSelect: (variableName: string) => void;
+}) => (
+ <button onClick={() => onVariableSelect('{{firstName}}')}>Variable</button>
+);
+
const DEFAULT_PROPS = {
label: 'Advanced Text Field',
placeholder: 'Enter your content...',
defaultValue: '',
onChange: fn(),
readonly: false,
- preset: 'workflowEmailBody' as const,
+ profile: STORY_FORM_EDITOR_PROFILE,
};
const RICH_CONTENT_VALUE = JSON.stringify({
type: 'doc',
+ attrs: { schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION },
content: [
{
type: 'heading',
@@ -68,8 +86,7 @@ const RICH_CONTENT_VALUE = JSON.stringify({
});
const meta: Meta<typeof FormAdvancedTextFieldInput> = {
- title:
- 'Modules/ObjectRecord/RecordField/FormTypes/FormAdvancedTextFieldInput',
+ title: 'Modules/AdvancedTextEditor/FormAdvancedTextFieldInput',
component: FormAdvancedTextFieldInput,
parameters: {
msw: {
@@ -204,7 +221,7 @@ export const WithVariablePicker: Story = {
args: {
...DEFAULT_PROPS,
label: 'Field with Variable Picker',
- VariablePicker: WorkflowVariablePicker,
+ VariablePicker: StoryVariablePicker,
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
@@ -235,6 +252,7 @@ export const WithLongContent: Story = {
label: 'Field with Long Content',
defaultValue: JSON.stringify({
type: 'doc',
+ attrs: { schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION },
content: Array.from({ length: 20 }, (_, i) => ({
type: 'paragraph',
content: [
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/constants/AdvancedTextEditorBlockCatalog.ts b/packages/twenty-front/src/modules/advanced-text-editor/constants/AdvancedTextEditorBlockCatalog.ts
new file mode 100644
index 00000000000..38e65ce4409
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/constants/AdvancedTextEditorBlockCatalog.ts
@@ -0,0 +1,274 @@
+import {
+ createColumnBlockContent,
+ createParagraphBlockContent,
+} from '@/advanced-text-editor/constants/AdvancedTextEditorBlockContent';
+import { getAdvancedTextEditorContainerAppearanceSettings } from '@/advanced-text-editor/constants/getAdvancedTextEditorContainerAppearanceSettings';
+import { getAdvancedTextEditorTypographySettings } from '@/advanced-text-editor/constants/getAdvancedTextEditorTypographySettings';
+import { ButtonNode } from '@/advanced-text-editor/extensions/blocks/ButtonNode';
+import { ColumnNode } from '@/advanced-text-editor/extensions/blocks/ColumnNode';
+import { ColumnsNode } from '@/advanced-text-editor/extensions/blocks/ColumnsNode';
+import { DividerNode } from '@/advanced-text-editor/extensions/blocks/DividerNode';
+import { HtmlNode } from '@/advanced-text-editor/extensions/blocks/HtmlNode';
+import { SectionNode } from '@/advanced-text-editor/extensions/blocks/SectionNode';
+import {
+ type AdvancedTextEditorBlockDefinition,
+ type AdvancedTextEditorBlockNodeType,
+} from '@/advanced-text-editor/types/AdvancedTextEditorBlockCatalog';
+import { msg } from '@lingui/core/macro';
+import { TIPTAP_NODE_TYPES } from 'twenty-shared/utils';
+import {
+ IconBox,
+ IconClick,
+ IconCode,
+ IconColumns,
+ IconMinus,
+ IconPhoto,
+} from 'twenty-ui/icon';
+
+export const ADVANCED_TEXT_EDITOR_BLOCK_CATALOG = {
+ [TIPTAP_NODE_TYPES.SECTION]: {
+ label: msg`Section`,
+ icon: IconBox,
+ extension: SectionNode,
+ insertionRecipes: [
+ {
+ id: 'section',
+ nodeType: TIPTAP_NODE_TYPES.SECTION,
+ title: msg`Section`,
+ description: msg`Styled container for document content`,
+ keywords: [msg`section`, msg`container`, msg`block`, msg`background`],
+ createContent: () => ({
+ type: TIPTAP_NODE_TYPES.SECTION,
+ content: [createParagraphBlockContent()],
+ }),
+ },
+ ],
+ settingsFields: [
+ ...getAdvancedTextEditorTypographySettings(),
+ ...getAdvancedTextEditorContainerAppearanceSettings(),
+ ],
+ },
+ [TIPTAP_NODE_TYPES.COLUMNS]: {
+ label: msg`Columns`,
+ icon: IconColumns,
+ extension: ColumnsNode,
+ insertionRecipes: [
+ {
+ id: 'columns2',
+ nodeType: TIPTAP_NODE_TYPES.COLUMNS,
+ title: msg`2 Columns`,
+ description: msg`Two columns side by side`,
+ keywords: [msg`columns`, msg`two`, msg`layout`, msg`row`],
+ createContent: () => ({
+ type: TIPTAP_NODE_TYPES.COLUMNS,
+ content: [createColumnBlockContent(), createColumnBlockContent()],
+ }),
+ },
+ {
+ id: 'columns3',
+ nodeType: TIPTAP_NODE_TYPES.COLUMNS,
+ title: msg`3 Columns`,
+ description: msg`Three columns side by side`,
+ keywords: [msg`columns`, msg`three`, msg`layout`, msg`row`],
+ createContent: () => ({
+ type: TIPTAP_NODE_TYPES.COLUMNS,
+ content: [
+ createColumnBlockContent(),
+ createColumnBlockContent(),
+ createColumnBlockContent(),
+ ],
+ }),
+ },
+ ],
+ settingsFields: [
+ ...getAdvancedTextEditorTypographySettings(),
+ ...getAdvancedTextEditorContainerAppearanceSettings(),
+ ],
+ },
+ [TIPTAP_NODE_TYPES.COLUMN]: {
+ label: msg`Column`,
+ icon: IconColumns,
+ extension: ColumnNode,
+ insertionRecipes: [],
+ settingsFields: [
+ ...getAdvancedTextEditorTypographySettings(),
+ {
+ label: msg`Width`,
+ kind: 'style',
+ property: 'width',
+ input: 'size',
+ placeholder: '50%',
+ },
+ ...getAdvancedTextEditorContainerAppearanceSettings(),
+ ],
+ },
+ [TIPTAP_NODE_TYPES.BUTTON]: {
+ label: msg`Button`,
+ icon: IconClick,
+ extension: ButtonNode,
+ insertionRecipes: [
+ {
+ id: 'button',
+ nodeType: TIPTAP_NODE_TYPES.BUTTON,
+ title: msg`Button`,
+ description: msg`Call-to-action button`,
+ keywords: [msg`button`, msg`cta`, msg`link`, msg`action`],
+ createContent: (translate) => ({
+ type: TIPTAP_NODE_TYPES.BUTTON,
+ content: [
+ {
+ type: TIPTAP_NODE_TYPES.TEXT,
+ text: translate(msg`Click here`),
+ },
+ ],
+ }),
+ },
+ ],
+ settingsFields: [
+ {
+ label: msg`Alignment`,
+ kind: 'attribute',
+ property: 'align',
+ input: 'alignment',
+ },
+ {
+ label: msg`Link URL`,
+ kind: 'attribute',
+ property: 'href',
+ input: 'text',
+ placeholder: 'https://',
+ },
+ {
+ label: msg`Background`,
+ kind: 'style',
+ property: 'backgroundColor',
+ input: 'color',
+ },
+ {
+ label: msg`Text color`,
+ kind: 'style',
+ property: 'color',
+ input: 'color',
+ },
+ {
+ label: msg`Padding`,
+ kind: 'style',
+ property: 'padding',
+ input: 'box',
+ placeholder: '10',
+ },
+ {
+ label: msg`Corner radius`,
+ kind: 'style',
+ property: 'borderRadius',
+ input: 'box',
+ placeholder: '6',
+ },
+ ],
+ },
+ [TIPTAP_NODE_TYPES.DIVIDER]: {
+ label: msg`Divider`,
+ icon: IconMinus,
+ extension: DividerNode,
+ insertionRecipes: [
+ {
+ id: 'divider',
+ nodeType: TIPTAP_NODE_TYPES.DIVIDER,
+ title: msg`Divider`,
+ description: msg`Horizontal separator line`,
+ keywords: [msg`divider`, msg`separator`, msg`line`, msg`hr`],
+ createContent: () => ({ type: TIPTAP_NODE_TYPES.DIVIDER }),
+ },
+ ],
+ settingsFields: [
+ {
+ label: msg`Thickness`,
+ kind: 'style',
+ property: 'borderTopWidth',
+ input: 'size',
+ placeholder: '1',
+ },
+ {
+ label: msg`Color`,
+ kind: 'style',
+ property: 'borderTopColor',
+ input: 'color',
+ },
+ {
+ label: msg`Margin`,
+ kind: 'style',
+ property: 'margin',
+ input: 'box',
+ placeholder: '16',
+ },
+ ],
+ },
+ [TIPTAP_NODE_TYPES.HTML]: {
+ label: msg`HTML`,
+ icon: IconCode,
+ extension: HtmlNode,
+ insertionRecipes: [
+ {
+ id: 'html',
+ nodeType: TIPTAP_NODE_TYPES.HTML,
+ title: msg`HTML`,
+ description: msg`Raw HTML embedded in the document`,
+ keywords: [msg`html`, msg`embed`, msg`code`, msg`custom`],
+ createContent: () => ({ type: TIPTAP_NODE_TYPES.HTML }),
+ },
+ ],
+ settingsFields: [
+ {
+ label: msg`HTML`,
+ kind: 'attribute',
+ property: 'html',
+ input: 'textarea',
+ placeholder: '<p>Hello</p>',
+ },
+ ],
+ },
+ [TIPTAP_NODE_TYPES.IMAGE]: {
+ label: msg`Image`,
+ icon: IconPhoto,
+ extension: null,
+ insertionRecipes: [],
+ settingsFields: [
+ {
+ label: msg`Alignment`,
+ kind: 'attribute',
+ property: 'align',
+ input: 'alignment',
+ },
+ {
+ label: msg`Link URL`,
+ kind: 'attribute',
+ property: 'href',
+ input: 'text',
+ placeholder: 'https://',
+ },
+ {
+ label: msg`Source`,
+ kind: 'attribute',
+ property: 'src',
+ input: 'text',
+ placeholder: 'https://',
+ },
+ {
+ label: msg`Alt text`,
+ kind: 'attribute',
+ property: 'alt',
+ input: 'text',
+ },
+ {
+ label: msg`Width`,
+ kind: 'attribute',
+ property: 'width',
+ input: 'text',
+ placeholder: 'auto',
+ },
+ ],
+ },
+} as const satisfies Record<
+ AdvancedTextEditorBlockNodeType,
+ AdvancedTextEditorBlockDefinition
+>;
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/constants/AdvancedTextEditorBlockContent.ts b/packages/twenty-front/src/modules/advanced-text-editor/constants/AdvancedTextEditorBlockContent.ts
new file mode 100644
index 00000000000..f3b42c735fb
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/constants/AdvancedTextEditorBlockContent.ts
@@ -0,0 +1,13 @@
+import { type JSONContent } from '@tiptap/core';
+import { TIPTAP_NODE_TYPES } from 'twenty-shared/utils';
+
+export function createParagraphBlockContent(): JSONContent {
+ return { type: TIPTAP_NODE_TYPES.PARAGRAPH };
+}
+
+export function createColumnBlockContent(): JSONContent {
+ return {
+ type: TIPTAP_NODE_TYPES.COLUMN,
+ content: [createParagraphBlockContent()],
+ };
+}
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/constants/AdvancedTextEditorBlockExtensions.ts b/packages/twenty-front/src/modules/advanced-text-editor/constants/AdvancedTextEditorBlockExtensions.ts
new file mode 100644
index 00000000000..cb3a9864e71
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/constants/AdvancedTextEditorBlockExtensions.ts
@@ -0,0 +1,7 @@
+import { ADVANCED_TEXT_EDITOR_BLOCK_CATALOG } from '@/advanced-text-editor/constants/AdvancedTextEditorBlockCatalog';
+import { type AnyExtension } from '@tiptap/core';
+
+export const ADVANCED_TEXT_EDITOR_BLOCK_EXTENSIONS: AnyExtension[] =
+ Object.values(ADVANCED_TEXT_EDITOR_BLOCK_CATALOG).flatMap(({ extension }) =>
+ extension === null ? [] : [extension],
+ );
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/constants/AdvancedTextEditorBlockInsertionRecipes.ts b/packages/twenty-front/src/modules/advanced-text-editor/constants/AdvancedTextEditorBlockInsertionRecipes.ts
new file mode 100644
index 00000000000..9e45a368272
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/constants/AdvancedTextEditorBlockInsertionRecipes.ts
@@ -0,0 +1,8 @@
+import { ADVANCED_TEXT_EDITOR_BLOCK_CATALOG } from '@/advanced-text-editor/constants/AdvancedTextEditorBlockCatalog';
+import { type AdvancedTextEditorBlockInsertionItem } from '@/advanced-text-editor/types/AdvancedTextEditorBlockCatalog';
+
+export const ADVANCED_TEXT_EDITOR_BLOCK_INSERTION_RECIPES: AdvancedTextEditorBlockInsertionItem[] =
+ Object.values(ADVANCED_TEXT_EDITOR_BLOCK_CATALOG).flatMap(
+ ({ icon, insertionRecipes }) =>
+ insertionRecipes.map((recipe) => ({ ...recipe, icon })),
+ );
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/constants/AdvancedTextEditorBlockSlashCommands.ts b/packages/twenty-front/src/modules/advanced-text-editor/constants/AdvancedTextEditorBlockSlashCommands.ts
new file mode 100644
index 00000000000..051ebd6f8ce
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/constants/AdvancedTextEditorBlockSlashCommands.ts
@@ -0,0 +1,26 @@
+import { ADVANCED_TEXT_EDITOR_BLOCK_INSERTION_RECIPES } from '@/advanced-text-editor/constants/AdvancedTextEditorBlockInsertionRecipes';
+import { type SlashCommandConfig } from '@/advanced-text-editor/extensions/slash-command/types/SlashCommandConfig';
+import { i18n } from '@lingui/core';
+import { isDefined } from 'twenty-shared/utils';
+
+export const ADVANCED_TEXT_EDITOR_BLOCK_SLASH_COMMANDS: SlashCommandConfig[] =
+ ADVANCED_TEXT_EDITOR_BLOCK_INSERTION_RECIPES.map((recipe) => ({
+ id: recipe.id,
+ title: recipe.title,
+ description: recipe.description,
+ icon: recipe.icon,
+ keywords: [...recipe.keywords],
+ getIsActive: (editor) => editor.isActive(recipe.nodeType),
+ getIsVisible: (editor) =>
+ isDefined(editor.schema.nodes[recipe.nodeType]) &&
+ editor
+ .can()
+ .insertContent(recipe.createContent((message) => i18n._(message))),
+ getOnSelect: (editor, range) => () =>
+ editor
+ .chain()
+ .focus()
+ .deleteRange(range)
+ .insertContent(recipe.createContent((message) => i18n._(message)))
+ .run(),
+ }));
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/constants/AdvancedTextEditorCapabilityExtensions.ts b/packages/twenty-front/src/modules/advanced-text-editor/constants/AdvancedTextEditorCapabilityExtensions.ts
deleted file mode 100644
index dc571c9d5d0..00000000000
--- a/packages/twenty-front/src/modules/advanced-text-editor/constants/AdvancedTextEditorCapabilityExtensions.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { CampaignVariableTag } from '@/advanced-text-editor/extensions/campaign-variables/CampaignVariableTag';
-import { ButtonNode } from '@/advanced-text-editor/extensions/blocks/ButtonNode';
-import { HtmlNode } from '@/advanced-text-editor/extensions/blocks/HtmlNode';
-import { ColumnNode } from '@/advanced-text-editor/extensions/blocks/ColumnNode';
-import { ColumnsNode } from '@/advanced-text-editor/extensions/blocks/ColumnsNode';
-import { DividerNode } from '@/advanced-text-editor/extensions/blocks/DividerNode';
-import { SectionNode } from '@/advanced-text-editor/extensions/blocks/SectionNode';
-import { ResizableImage } from '@/advanced-text-editor/extensions/resizable-image/ResizableImage';
-import { UploadImageExtension } from '@/advanced-text-editor/extensions/resizable-image/UploadImageExtension';
-import { SlashCommand } from '@/advanced-text-editor/extensions/slash-command/SlashCommand';
-import { type AdvancedTextEditorCapability } from '@/advanced-text-editor/types/AdvancedTextEditorCapability';
-import { type UploadedImage } from '@/advanced-text-editor/types/UploadedImage';
-import { MentionSuggestion } from '@/mention/extensions/MentionSuggestion';
-import { MentionTag } from '@/mention/extensions/MentionTag';
-import { VariableTag } from '@/workflow/workflow-variables/utils/variableTag';
-import { type AnyExtension } from '@tiptap/core';
-import { Bold } from '@tiptap/extension-bold';
-import { Heading } from '@tiptap/extension-heading';
-import { Italic } from '@tiptap/extension-italic';
-import { Link } from '@tiptap/extension-link';
-import { ListKit } from '@tiptap/extension-list';
-import { Strike } from '@tiptap/extension-strike';
-import { Underline } from '@tiptap/extension-underline';
-
-export type AdvancedTextEditorExtensionContext = {
- onImageUpload?: (file: File) => Promise<UploadedImage>;
- onImageUploadError?: (error: Error, file: File) => void;
-};
-
-type AdvancedTextEditorExtensionFactory = (
- context: AdvancedTextEditorExtensionContext,
-) => AnyExtension[];
-
-export const ADVANCED_TEXT_EDITOR_CAPABILITY_EXTENSIONS: Record<
- AdvancedTextEditorCapability,
- AdvancedTextEditorExtensionFactory
-> = {
- basicMarks: () => [Bold, Italic, Strike, Underline],
- headings: () => [
- Heading.configure({
- levels: [1, 2, 3],
- }),
- ],
- lists: () => [ListKit],
- links: () => [
- Link.configure({
- openOnClick: false,
- }),
- ],
- images: ({ onImageUpload, onImageUploadError }) => [
- ResizableImage,
- UploadImageExtension.configure({
- onImageUpload,
- onImageUploadError,
- }),
- ],
- variables: () => [VariableTag],
- campaignVariables: () => [CampaignVariableTag],
- mentions: () => [MentionTag, MentionSuggestion],
- slashCommand: () => [SlashCommand],
- blocks: () => [
- SectionNode,
- ColumnsNode,
- ColumnNode,
- ButtonNode,
- DividerNode,
- HtmlNode,
- ],
-};
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/constants/AdvancedTextEditorPresets.ts b/packages/twenty-front/src/modules/advanced-text-editor/constants/AdvancedTextEditorPresets.ts
deleted file mode 100644
index 910580fdfa9..00000000000
--- a/packages/twenty-front/src/modules/advanced-text-editor/constants/AdvancedTextEditorPresets.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { EMAIL_DOCUMENT_CAPABILITIES } from '@/advanced-text-editor/constants/EmailDocumentCapabilities';
-import { FULL_RICH_TEXT_CAPABILITIES } from '@/advanced-text-editor/constants/FullRichTextCapabilities';
-import { type AdvancedTextEditorPreset } from '@/advanced-text-editor/types/AdvancedTextEditorPreset';
-
-// One entry per surface that renders the TipTap editor today. Add a surface
-// here rather than passing sizing and content-type props at the call site, so
-// the editor's shape per context stays reviewable in one place.
-export const ADVANCED_TEXT_EDITOR_PRESETS = {
- // The campaign body owns its whole tab, so it fills the widget instead of
- // sitting in a bordered box. Stored as TipTap JSON so the server can render
- // it to email-safe HTML at send time, like the workflow email node.
- campaignBody: {
- contentType: 'json',
- chrome: 'canvas',
- minHeight: 0,
- enableFullScreen: false,
- capabilities: [...EMAIL_DOCUMENT_CAPABILITIES, 'campaignVariables'],
- },
- inlineEmailBody: {
- contentType: 'html',
- chrome: 'field',
- minHeight: 120,
- enableFullScreen: true,
- capabilities: FULL_RICH_TEXT_CAPABILITIES,
- },
- workflowEmailBody: {
- contentType: 'json',
- chrome: 'field',
- minHeight: 340,
- enableFullScreen: true,
- capabilities: FULL_RICH_TEXT_CAPABILITIES,
- },
- // The RICH_TEXT form input. Its stored value is still BlockNote JSON; only
- // the editing surface is TipTap today.
- recordRichTextField: {
- contentType: 'json',
- chrome: 'field',
- minHeight: 340,
- enableFullScreen: true,
- capabilities: FULL_RICH_TEXT_CAPABILITIES,
- },
- aiInstructions: {
- contentType: 'markdown',
- chrome: 'field',
- minHeight: 120,
- enableFullScreen: true,
- capabilities: FULL_RICH_TEXT_CAPABILITIES,
- },
- aiChat: {
- contentType: 'json',
- chrome: 'document',
- minHeight: 0,
- enableFullScreen: false,
- capabilities: ['mentions'],
- },
-} as const satisfies Record<string, AdvancedTextEditorPreset>;
-
-export type AdvancedTextEditorPresetName =
- keyof typeof ADVANCED_TEXT_EDITOR_PRESETS;
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/constants/EmailDocumentCapabilities.ts b/packages/twenty-front/src/modules/advanced-text-editor/constants/EmailDocumentCapabilities.ts
deleted file mode 100644
index f13ae10ba9b..00000000000
--- a/packages/twenty-front/src/modules/advanced-text-editor/constants/EmailDocumentCapabilities.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { type AdvancedTextEditorCapability } from '@/advanced-text-editor/types/AdvancedTextEditorCapability';
-
-export const EMAIL_DOCUMENT_CAPABILITIES = [
- 'basicMarks',
- 'headings',
- 'lists',
- 'links',
- 'images',
- 'slashCommand',
- 'blocks',
-] as const satisfies readonly AdvancedTextEditorCapability[];
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/constants/FullRichTextCapabilities.ts b/packages/twenty-front/src/modules/advanced-text-editor/constants/FullRichTextCapabilities.ts
deleted file mode 100644
index dba06e47161..00000000000
--- a/packages/twenty-front/src/modules/advanced-text-editor/constants/FullRichTextCapabilities.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { type AdvancedTextEditorCapability } from '@/advanced-text-editor/types/AdvancedTextEditorCapability';
-
-export const FULL_RICH_TEXT_CAPABILITIES: readonly AdvancedTextEditorCapability[] =
- [
- 'basicMarks',
- 'headings',
- 'lists',
- 'links',
- 'images',
- 'variables',
- 'slashCommand',
- ];
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/constants/__tests__/AdvancedTextEditorBlockCatalog.test.ts b/packages/twenty-front/src/modules/advanced-text-editor/constants/__tests__/AdvancedTextEditorBlockCatalog.test.ts
new file mode 100644
index 00000000000..b481b8afe64
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/constants/__tests__/AdvancedTextEditorBlockCatalog.test.ts
@@ -0,0 +1,55 @@
+import { ADVANCED_TEXT_EDITOR_BLOCK_CATALOG } from '@/advanced-text-editor/constants/AdvancedTextEditorBlockCatalog';
+import { ADVANCED_TEXT_EDITOR_BLOCK_EXTENSIONS } from '@/advanced-text-editor/constants/AdvancedTextEditorBlockExtensions';
+import { ADVANCED_TEXT_EDITOR_BLOCK_INSERTION_RECIPES } from '@/advanced-text-editor/constants/AdvancedTextEditorBlockInsertionRecipes';
+import { ADVANCED_TEXT_EDITOR_BLOCK_SLASH_COMMANDS } from '@/advanced-text-editor/constants/AdvancedTextEditorBlockSlashCommands';
+import { ADVANCED_TEXT_EDITOR_BLOCK_NODE_TYPES } from '@/advanced-text-editor/types/AdvancedTextEditorBlockCatalog';
+import { DEFAULT_SLASH_COMMANDS } from '@/advanced-text-editor/extensions/slash-command/DefaultSlashCommands';
+
+describe('ADVANCED_TEXT_EDITOR_BLOCK_CATALOG', () => {
+ it('defines every shared block exactly once', () => {
+ expect(Object.keys(ADVANCED_TEXT_EDITOR_BLOCK_CATALOG).sort()).toEqual(
+ [...ADVANCED_TEXT_EDITOR_BLOCK_NODE_TYPES].sort(),
+ );
+ });
+
+ it('derives the extension bundle from catalog entries', () => {
+ const catalogExtensionNames = Object.values(
+ ADVANCED_TEXT_EDITOR_BLOCK_CATALOG,
+ ).flatMap(({ extension }) => (extension === null ? [] : [extension.name]));
+
+ expect(
+ ADVANCED_TEXT_EDITOR_BLOCK_EXTENSIONS.map(({ name }) => name),
+ ).toEqual(catalogExtensionNames);
+ });
+
+ it('creates content matching every insertion recipe node type', () => {
+ for (const recipe of ADVANCED_TEXT_EDITOR_BLOCK_INSERTION_RECIPES) {
+ expect(recipe.createContent(() => 'Click here').type).toBe(
+ recipe.nodeType,
+ );
+ }
+ });
+
+ it('uses the same recipes for insert controls and slash commands', () => {
+ const recipeIds = ADVANCED_TEXT_EDITOR_BLOCK_INSERTION_RECIPES.map(
+ ({ id }) => id,
+ );
+
+ expect(new Set(recipeIds).size).toBe(recipeIds.length);
+ expect(
+ ADVANCED_TEXT_EDITOR_BLOCK_SLASH_COMMANDS.map(({ id }) => id),
+ ).toEqual(recipeIds);
+ });
+
+ it('keeps document blocks above list commands in the slash menu', () => {
+ expect(DEFAULT_SLASH_COMMANDS.map(({ id }) => id)).toEqual([
+ 'paragraph',
+ 'h1',
+ 'h2',
+ 'h3',
+ ...ADVANCED_TEXT_EDITOR_BLOCK_INSERTION_RECIPES.map(({ id }) => id),
+ 'bulletList',
+ 'orderedList',
+ ]);
+ });
+});
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/constants/getAdvancedTextEditorContainerAppearanceSettings.ts b/packages/twenty-front/src/modules/advanced-text-editor/constants/getAdvancedTextEditorContainerAppearanceSettings.ts
new file mode 100644
index 00000000000..1f691d33ade
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/constants/getAdvancedTextEditorContainerAppearanceSettings.ts
@@ -0,0 +1,40 @@
+import { type AdvancedTextEditorBlockSetting } from '@/advanced-text-editor/types/AdvancedTextEditorBlockCatalog';
+import { msg } from '@lingui/core/macro';
+
+export function getAdvancedTextEditorContainerAppearanceSettings() {
+ return [
+ {
+ label: msg`Background`,
+ kind: 'style',
+ property: 'backgroundColor',
+ input: 'color',
+ },
+ {
+ label: msg`Padding`,
+ kind: 'style',
+ property: 'padding',
+ input: 'box',
+ placeholder: '12',
+ },
+ {
+ label: msg`Corner radius`,
+ kind: 'style',
+ property: 'borderRadius',
+ input: 'box',
+ placeholder: '8',
+ },
+ {
+ label: msg`Border`,
+ kind: 'style',
+ property: 'borderWidth',
+ input: 'size',
+ placeholder: '0',
+ },
+ {
+ label: msg`Border color`,
+ kind: 'style',
+ property: 'borderColor',
+ input: 'color',
+ },
+ ] as const satisfies readonly AdvancedTextEditorBlockSetting[];
+}
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/constants/getAdvancedTextEditorTypographySettings.ts b/packages/twenty-front/src/modules/advanced-text-editor/constants/getAdvancedTextEditorTypographySettings.ts
new file mode 100644
index 00000000000..25119135cf0
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/constants/getAdvancedTextEditorTypographySettings.ts
@@ -0,0 +1,40 @@
+import { type AdvancedTextEditorBlockSetting } from '@/advanced-text-editor/types/AdvancedTextEditorBlockCatalog';
+import { msg } from '@lingui/core/macro';
+
+export function getAdvancedTextEditorTypographySettings() {
+ return [
+ {
+ label: msg`Text color`,
+ kind: 'style',
+ property: 'color',
+ input: 'color',
+ },
+ {
+ label: msg`Font size`,
+ kind: 'style',
+ property: 'fontSize',
+ input: 'size',
+ placeholder: '14',
+ },
+ {
+ label: msg`Line height`,
+ kind: 'style',
+ property: 'lineHeight',
+ input: 'text',
+ placeholder: '1.5',
+ },
+ {
+ label: msg`Letter spacing`,
+ kind: 'style',
+ property: 'letterSpacing',
+ input: 'size',
+ placeholder: '0',
+ },
+ {
+ label: msg`Alignment`,
+ kind: 'style',
+ property: 'textAlign',
+ input: 'alignment',
+ },
+ ] as const satisfies readonly AdvancedTextEditorBlockSetting[];
+}
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/extensions/campaign-variables/CampaignVariableChip.tsx b/packages/twenty-front/src/modules/advanced-text-editor/extensions/campaign-variables/CampaignVariableChip.tsx
deleted file mode 100644
index 705d2fd5f56..00000000000
--- a/packages/twenty-front/src/modules/advanced-text-editor/extensions/campaign-variables/CampaignVariableChip.tsx
+++ /dev/null
@@ -1,13 +0,0 @@
-import { NodeViewWrapper, type NodeViewProps } from '@tiptap/react';
-
-type CampaignVariableChipProps = Pick<NodeViewProps, 'node'>;
-
-export const CampaignVariableChip = ({ node }: CampaignVariableChipProps) => {
- const variable =
- typeof node.attrs.variable === 'string' ? node.attrs.variable : '';
- return (
- <NodeViewWrapper as="span" data-drag-handle>
- <span className="variable-tag">{variable}</span>
- </NodeViewWrapper>
- );
-};
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/extensions/campaign-variables/CampaignVariableTag.ts b/packages/twenty-front/src/modules/advanced-text-editor/extensions/campaign-variables/CampaignVariableTag.ts
deleted file mode 100644
index c8172311fa5..00000000000
--- a/packages/twenty-front/src/modules/advanced-text-editor/extensions/campaign-variables/CampaignVariableTag.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { ReactNodeViewRenderer } from '@tiptap/react';
-
-import { CampaignVariableChip } from '@/advanced-text-editor/extensions/campaign-variables/CampaignVariableChip';
-import { VariableTag } from '@/workflow/workflow-variables/utils/variableTag';
-
-export const CampaignVariableTag = VariableTag.extend({
- addNodeView() {
- return ReactNodeViewRenderer(CampaignVariableChip);
- },
-});
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/extensions/slash-command/DefaultSlashCommands.ts b/packages/twenty-front/src/modules/advanced-text-editor/extensions/slash-command/DefaultSlashCommands.ts
index 9d22bd8befd..263db2568f1 100644
--- a/packages/twenty-front/src/modules/advanced-text-editor/extensions/slash-command/DefaultSlashCommands.ts
+++ b/packages/twenty-front/src/modules/advanced-text-editor/extensions/slash-command/DefaultSlashCommands.ts
@@ -1,42 +1,16 @@
-import { type MessageDescriptor } from '@lingui/core';
+import { ADVANCED_TEXT_EDITOR_BLOCK_SLASH_COMMANDS } from '@/advanced-text-editor/constants/AdvancedTextEditorBlockSlashCommands';
+import { type SlashCommandConfig } from '@/advanced-text-editor/extensions/slash-command/types/SlashCommandConfig';
import { msg } from '@lingui/core/macro';
-import { type Editor, type Range } from '@tiptap/core';
-import { isDefined, TIPTAP_NODE_TYPES } from 'twenty-shared/utils';
import {
- type IconComponent,
- IconBox,
- IconClick,
- IconCode,
- IconColumns,
IconH1,
IconH2,
IconH3,
IconList,
IconListNumbers,
- IconMinus,
IconPilcrow,
} from 'twenty-ui/icon';
-const hasSchemaNode = (editor: Editor, nodeName: string) =>
- isDefined(editor.schema.nodes[nodeName]);
-
-const columnJson = () => ({
- type: TIPTAP_NODE_TYPES.COLUMN,
- content: [{ type: TIPTAP_NODE_TYPES.PARAGRAPH }],
-});
-
-export type SlashCommandConfig = {
- id: string;
- title: MessageDescriptor;
- description: MessageDescriptor;
- icon: IconComponent;
- keywords: MessageDescriptor[];
- getIsActive: (editor: Editor) => boolean;
- getIsVisible: (editor: Editor) => boolean;
- getOnSelect: (editor: Editor, range: Range) => () => void;
-};
-
-export const DEFAULT_SLASH_COMMANDS: SlashCommandConfig[] = [
+const TEXT_SLASH_COMMANDS: SlashCommandConfig[] = [
{
id: 'paragraph',
title: msg`Text`,
@@ -45,9 +19,8 @@ export const DEFAULT_SLASH_COMMANDS: SlashCommandConfig[] = [
keywords: [msg`paragraph`, msg`text`, msg`p`],
getIsActive: (editor) => editor.isActive('paragraph'),
getIsVisible: (editor) => editor.can().setParagraph?.() ?? false,
- getOnSelect: (editor, range) => () => {
- return editor.chain().focus().deleteRange(range).setParagraph().run();
- },
+ getOnSelect: (editor, range) => () =>
+ editor.chain().focus().deleteRange(range).setParagraph().run(),
},
{
id: 'h1',
@@ -82,114 +55,9 @@ export const DEFAULT_SLASH_COMMANDS: SlashCommandConfig[] = [
getOnSelect: (editor, range) => () =>
editor.chain().focus().deleteRange(range).setHeading({ level: 3 }).run(),
},
- {
- id: 'section',
- title: msg`Section`,
- description: msg`Styled container for email content`,
- icon: IconBox,
- keywords: [msg`section`, msg`container`, msg`block`, msg`background`],
- getIsActive: (editor) => editor.isActive(TIPTAP_NODE_TYPES.SECTION),
- getIsVisible: (editor) => hasSchemaNode(editor, TIPTAP_NODE_TYPES.SECTION),
- getOnSelect: (editor, range) => () =>
- editor
- .chain()
- .focus()
- .deleteRange(range)
- .insertContent({
- type: TIPTAP_NODE_TYPES.SECTION,
- content: [{ type: TIPTAP_NODE_TYPES.PARAGRAPH }],
- })
- .run(),
- },
- {
- id: 'emailColumns2',
- title: msg`2 Columns`,
- description: msg`Two columns side by side`,
- icon: IconColumns,
- keywords: [msg`columns`, msg`two`, msg`layout`, msg`row`],
- getIsActive: (editor) => editor.isActive(TIPTAP_NODE_TYPES.COLUMNS),
- getIsVisible: (editor) => hasSchemaNode(editor, TIPTAP_NODE_TYPES.COLUMNS),
- getOnSelect: (editor, range) => () =>
- editor
- .chain()
- .focus()
- .deleteRange(range)
- .insertContent({
- type: TIPTAP_NODE_TYPES.COLUMNS,
- content: [columnJson(), columnJson()],
- })
- .run(),
- },
- {
- id: 'emailColumns3',
- title: msg`3 Columns`,
- description: msg`Three columns side by side`,
- icon: IconColumns,
- keywords: [msg`columns`, msg`three`, msg`layout`, msg`row`],
- getIsActive: (editor) => editor.isActive(TIPTAP_NODE_TYPES.COLUMNS),
- getIsVisible: (editor) => hasSchemaNode(editor, TIPTAP_NODE_TYPES.COLUMNS),
- getOnSelect: (editor, range) => () =>
- editor
- .chain()
- .focus()
- .deleteRange(range)
- .insertContent({
- type: TIPTAP_NODE_TYPES.COLUMNS,
- content: [columnJson(), columnJson(), columnJson()],
- })
- .run(),
- },
- {
- id: 'button',
- title: msg`Button`,
- description: msg`Call-to-action button`,
- icon: IconClick,
- keywords: [msg`button`, msg`cta`, msg`link`, msg`action`],
- getIsActive: (editor) => editor.isActive(TIPTAP_NODE_TYPES.BUTTON),
- getIsVisible: (editor) => hasSchemaNode(editor, TIPTAP_NODE_TYPES.BUTTON),
- getOnSelect: (editor, range) => () =>
- editor
- .chain()
- .focus()
- .deleteRange(range)
- .insertContent({
- type: TIPTAP_NODE_TYPES.BUTTON,
- content: [{ type: TIPTAP_NODE_TYPES.TEXT, text: 'Click here' }],
- })
- .run(),
- },
- {
- id: 'html',
- title: msg`HTML`,
- description: msg`Raw HTML embedded in the email`,
- icon: IconCode,
- keywords: [msg`html`, msg`embed`, msg`code`, msg`custom`],
- getIsActive: (editor) => editor.isActive(TIPTAP_NODE_TYPES.HTML),
- getIsVisible: (editor) => hasSchemaNode(editor, TIPTAP_NODE_TYPES.HTML),
- getOnSelect: (editor, range) => () =>
- editor
- .chain()
- .focus()
- .deleteRange(range)
- .insertContent({ type: TIPTAP_NODE_TYPES.HTML })
- .run(),
- },
- {
- id: 'divider',
- title: msg`Divider`,
- description: msg`Horizontal separator line`,
- icon: IconMinus,
- keywords: [msg`divider`, msg`separator`, msg`line`, msg`hr`],
- getIsActive: (editor) => editor.isActive(TIPTAP_NODE_TYPES.DIVIDER),
- getIsVisible: (editor) => hasSchemaNode(editor, TIPTAP_NODE_TYPES.DIVIDER),
- getOnSelect: (editor, range) => () =>
- editor
- .chain()
- .focus()
- .deleteRange(range)
- .insertContent({ type: TIPTAP_NODE_TYPES.DIVIDER })
- .run(),
- },
+];
+
+const LIST_SLASH_COMMANDS: SlashCommandConfig[] = [
{
id: 'bulletList',
title: msg`Bullet List`,
@@ -213,3 +81,9 @@ export const DEFAULT_SLASH_COMMANDS: SlashCommandConfig[] = [
editor.chain().focus().deleteRange(range).toggleOrderedList().run(),
},
];
+
+export const DEFAULT_SLASH_COMMANDS: SlashCommandConfig[] = [
+ ...TEXT_SLASH_COMMANDS,
+ ...ADVANCED_TEXT_EDITOR_BLOCK_SLASH_COMMANDS,
+ ...LIST_SLASH_COMMANDS,
+];
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/extensions/slash-command/SlashCommand.ts b/packages/twenty-front/src/modules/advanced-text-editor/extensions/slash-command/SlashCommand.ts
index b6745454d02..1777fd3e825 100644
--- a/packages/twenty-front/src/modules/advanced-text-editor/extensions/slash-command/SlashCommand.ts
+++ b/packages/twenty-front/src/modules/advanced-text-editor/extensions/slash-command/SlashCommand.ts
@@ -3,14 +3,12 @@ import { Extension, type Editor, type Range } from '@tiptap/core';
import Suggestion, { type SuggestionOptions } from '@tiptap/suggestion';
import { type IconComponent } from 'twenty-ui/icon';
-import {
- DEFAULT_SLASH_COMMANDS,
- type SlashCommandConfig,
-} from '@/advanced-text-editor/extensions/slash-command/DefaultSlashCommands';
+import { DEFAULT_SLASH_COMMANDS } from '@/advanced-text-editor/extensions/slash-command/DefaultSlashCommands';
import {
SlashCommandMenu,
type SlashCommandMenuProps,
} from '@/advanced-text-editor/extensions/slash-command/SlashCommandMenu';
+import { type SlashCommandConfig } from '@/advanced-text-editor/extensions/slash-command/types/SlashCommandConfig';
import { createSuggestionRenderLifecycle } from '@/ui/suggestion/components/createSuggestionRenderLifecycle';
export type SlashCommandItem = {
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/extensions/slash-command/types/SlashCommandConfig.ts b/packages/twenty-front/src/modules/advanced-text-editor/extensions/slash-command/types/SlashCommandConfig.ts
new file mode 100644
index 00000000000..8e5b8ebb5f0
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/extensions/slash-command/types/SlashCommandConfig.ts
@@ -0,0 +1,14 @@
+import { type MessageDescriptor } from '@lingui/core';
+import { type Editor, type Range } from '@tiptap/core';
+import { type IconComponent } from 'twenty-ui/icon';
+
+export type SlashCommandConfig = {
+ id: string;
+ title: MessageDescriptor;
+ description: MessageDescriptor;
+ icon: IconComponent;
+ keywords: MessageDescriptor[];
+ getIsActive: (editor: Editor) => boolean;
+ getIsVisible: (editor: Editor) => boolean;
+ getOnSelect: (editor: Editor, range: Range) => () => void;
+};
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/extensions/variable-tag/VariableChip.tsx b/packages/twenty-front/src/modules/advanced-text-editor/extensions/variable-tag/VariableChip.tsx
new file mode 100644
index 00000000000..f78d92391ff
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/extensions/variable-tag/VariableChip.tsx
@@ -0,0 +1,31 @@
+import { BaseChip } from '@/ui/input/components/BaseChip';
+import { styled } from '@linaria/react';
+import { t } from '@lingui/core/macro';
+import { NodeViewWrapper, type NodeViewProps } from '@tiptap/react';
+import { themeCssVariables } from 'twenty-ui/theme-constants';
+
+const StyledWrapper = styled.span`
+ display: inline-block;
+ padding-inline: ${themeCssVariables.spacing[0.5]};
+`;
+
+type VariableChipProps = Pick<NodeViewProps, 'deleteNode' | 'editor'> & {
+ label: string;
+ title?: string;
+};
+
+export const VariableChip = ({
+ deleteNode,
+ editor,
+ label,
+ title,
+}: VariableChipProps) => (
+ <NodeViewWrapper as={StyledWrapper} style={{ whiteSpace: 'nowrap' }}>
+ <BaseChip
+ label={label}
+ title={title}
+ onRemove={editor.isEditable ? deleteNode : undefined}
+ removeAriaLabel={t`Remove variable`}
+ />
+ </NodeViewWrapper>
+);
diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/variableTag.ts b/packages/twenty-front/src/modules/advanced-text-editor/extensions/variable-tag/VariableTag.ts
similarity index 87%
rename from packages/twenty-front/src/modules/workflow/workflow-variables/utils/variableTag.ts
rename to packages/twenty-front/src/modules/advanced-text-editor/extensions/variable-tag/VariableTag.ts
index d8ca152391e..fbdc7e38d38 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/variableTag.ts
+++ b/packages/twenty-front/src/modules/advanced-text-editor/extensions/variable-tag/VariableTag.ts
@@ -1,4 +1,4 @@
-import { WorkflowTextEditorVariableChip } from '@/workflow/workflow-variables/components/WorkflowTextEditorVariableChip';
+import { VariableTagChip } from '@/advanced-text-editor/extensions/variable-tag/VariableTagChip';
import { Node } from '@tiptap/core';
import { mergeAttributes, ReactNodeViewRenderer } from '@tiptap/react';
import { extractRawVariableNamePart } from 'twenty-shared/workflow';
@@ -17,6 +17,10 @@ export const VariableTag = Node.create({
inline: true,
atom: true,
+ addNodeView() {
+ return ReactNodeViewRenderer(VariableTagChip);
+ },
+
addAttributes: () => ({
variable: {
default: null,
@@ -45,10 +49,6 @@ export const VariableTag = Node.create({
];
},
- addNodeView: () => {
- return ReactNodeViewRenderer(WorkflowTextEditorVariableChip);
- },
-
renderText: ({ node }) => {
return node.attrs.variable;
},
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/extensions/variable-tag/VariableTagChip.tsx b/packages/twenty-front/src/modules/advanced-text-editor/extensions/variable-tag/VariableTagChip.tsx
new file mode 100644
index 00000000000..9677d81c83d
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/extensions/variable-tag/VariableTagChip.tsx
@@ -0,0 +1,27 @@
+import { VariableChip } from '@/advanced-text-editor/extensions/variable-tag/VariableChip';
+import { type NodeViewProps } from '@tiptap/react';
+import { extractRawVariableNamePart } from 'twenty-shared/workflow';
+
+type VariableTagChipProps = NodeViewProps;
+
+export const VariableTagChip = ({
+ deleteNode,
+ editor,
+ node,
+}: VariableTagChipProps) => {
+ const variable =
+ typeof node.attrs.variable === 'string' ? node.attrs.variable : '';
+ const label = extractRawVariableNamePart({
+ rawVariableName: variable,
+ part: 'selectedField',
+ });
+
+ return (
+ <VariableChip
+ deleteNode={deleteNode}
+ editor={editor}
+ label={label}
+ title={variable}
+ />
+ );
+};
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/hooks/useAdvancedTextEditor.ts b/packages/twenty-front/src/modules/advanced-text-editor/hooks/useAdvancedTextEditor.ts
index e54adc353c5..90b91d47bf3 100644
--- a/packages/twenty-front/src/modules/advanced-text-editor/hooks/useAdvancedTextEditor.ts
+++ b/packages/twenty-front/src/modules/advanced-text-editor/hooks/useAdvancedTextEditor.ts
@@ -1,18 +1,14 @@
-import {
- ADVANCED_TEXT_EDITOR_PRESETS,
- type AdvancedTextEditorPresetName,
-} from '@/advanced-text-editor/constants/AdvancedTextEditorPresets';
+import { type AdvancedTextEditorProfile } from '@/advanced-text-editor/types/AdvancedTextEditorProfile';
import { type UploadedImage } from '@/advanced-text-editor/types/UploadedImage';
import { buildAdvancedTextEditorExtensions } from '@/advanced-text-editor/utils/buildAdvancedTextEditorExtensions';
-import { getInitialAdvancedTextEditorContent } from '@/workflow/workflow-variables/utils/getInitialAdvancedTextEditorContent';
+import { deserializeAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/deserializeAdvancedTextEditorDocument';
import { type Content } from '@tiptap/core';
import { type Editor, type EditorOptions, useEditor } from '@tiptap/react';
-import { marked } from 'marked';
import { type DependencyList, useMemo } from 'react';
import { isDefined } from 'twenty-shared/utils';
type UseAdvancedTextEditorProps = {
- preset: AdvancedTextEditorPresetName;
+ profile: AdvancedTextEditorProfile;
placeholder: string | undefined;
readonly: boolean | undefined;
defaultValue: string | undefined | null;
@@ -27,7 +23,7 @@ type UseAdvancedTextEditorProps = {
export const useAdvancedTextEditor = (
{
- preset,
+ profile,
placeholder,
readonly,
defaultValue,
@@ -41,12 +37,10 @@ export const useAdvancedTextEditor = (
}: UseAdvancedTextEditorProps,
dependencies?: DependencyList,
) => {
- const { contentType, capabilities } = ADVANCED_TEXT_EDITOR_PRESETS[preset];
-
const extensions = useMemo(
() =>
buildAdvancedTextEditorExtensions({
- capabilities,
+ profile,
context: {
onImageUpload,
onImageUploadError,
@@ -54,7 +48,7 @@ export const useAdvancedTextEditor = (
placeholder,
readonly,
}),
- [capabilities, placeholder, onImageUpload, onImageUploadError, readonly],
+ [profile, placeholder, onImageUpload, onImageUploadError, readonly],
);
const getEditorContent = (): Content | undefined => {
@@ -66,16 +60,10 @@ export const useAdvancedTextEditor = (
return undefined;
}
- if (contentType === 'markdown') {
- // Convert markdown to HTML, then TipTap will parse the HTML
- return marked.parse(defaultValue, { async: false }) as string;
- }
-
- if (contentType === 'html') {
- return defaultValue;
- }
-
- return getInitialAdvancedTextEditorContent(defaultValue);
+ return deserializeAdvancedTextEditorDocument({
+ serializedDocument: defaultValue,
+ parseLegacyDocument: profile.parseLegacyDocument,
+ });
};
const editor = useEditor(
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorBlockCatalog.ts b/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorBlockCatalog.ts
new file mode 100644
index 00000000000..8fe8c320e5e
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorBlockCatalog.ts
@@ -0,0 +1,63 @@
+import { type MessageDescriptor } from '@lingui/core';
+import { type AnyExtension, type JSONContent } from '@tiptap/core';
+import { TIPTAP_NODE_TYPES, type TipTapNodeType } from 'twenty-shared/utils';
+import { type IconComponent } from 'twenty-ui/icon';
+
+export const ADVANCED_TEXT_EDITOR_BLOCK_NODE_TYPES = [
+ TIPTAP_NODE_TYPES.SECTION,
+ TIPTAP_NODE_TYPES.COLUMNS,
+ TIPTAP_NODE_TYPES.COLUMN,
+ TIPTAP_NODE_TYPES.BUTTON,
+ TIPTAP_NODE_TYPES.DIVIDER,
+ TIPTAP_NODE_TYPES.HTML,
+ TIPTAP_NODE_TYPES.IMAGE,
+] as const satisfies readonly TipTapNodeType[];
+
+export type AdvancedTextEditorBlockNodeType =
+ (typeof ADVANCED_TEXT_EDITOR_BLOCK_NODE_TYPES)[number];
+
+export type AdvancedTextEditorSettingInput =
+ | 'text'
+ | 'color'
+ | 'box'
+ | 'size'
+ | 'alignment'
+ | 'textarea';
+
+export type AdvancedTextEditorBlockSetting = {
+ label: MessageDescriptor;
+ kind: 'style' | 'attribute';
+ property: string;
+ input: AdvancedTextEditorSettingInput;
+ placeholder?: string;
+};
+
+export type AdvancedTextEditorBlockInsertionRecipe = {
+ id: string;
+ nodeType: AdvancedTextEditorBlockNodeType;
+ title: MessageDescriptor;
+ description: MessageDescriptor;
+ keywords: readonly MessageDescriptor[];
+ createContent: (
+ translate: (message: MessageDescriptor) => string,
+ ) => JSONContent;
+};
+
+export type AdvancedTextEditorBlockDefinition = {
+ label: MessageDescriptor;
+ icon: IconComponent;
+ extension: AnyExtension | null;
+ insertionRecipes: readonly AdvancedTextEditorBlockInsertionRecipe[];
+ settingsFields: readonly AdvancedTextEditorBlockSetting[];
+};
+
+export type AdvancedTextEditorBlockInsertionItem =
+ AdvancedTextEditorBlockInsertionRecipe &
+ Pick<AdvancedTextEditorBlockDefinition, 'icon'>;
+
+export const isAdvancedTextEditorBlockNodeType = (
+ nodeType: string,
+): nodeType is AdvancedTextEditorBlockNodeType =>
+ ADVANCED_TEXT_EDITOR_BLOCK_NODE_TYPES.some(
+ (blockNodeType) => blockNodeType === nodeType,
+ );
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorCapability.ts b/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorCapability.ts
deleted file mode 100644
index e49dea8baa6..00000000000
--- a/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorCapability.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-export type AdvancedTextEditorCapability =
- | 'basicMarks'
- | 'headings'
- | 'lists'
- | 'links'
- | 'images'
- | 'variables'
- | 'campaignVariables'
- | 'mentions'
- | 'slashCommand'
- | 'blocks';
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorComponentProps.ts b/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorComponentProps.ts
new file mode 100644
index 00000000000..336bebab3b6
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorComponentProps.ts
@@ -0,0 +1,7 @@
+import { type Editor } from '@tiptap/core';
+
+export type AdvancedTextEditorComponentProps = {
+ readonly: boolean | undefined;
+ editor: Editor;
+ minHeight: number;
+};
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorContentType.ts b/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorContentType.ts
deleted file mode 100644
index ebb6f005336..00000000000
--- a/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorContentType.ts
+++ /dev/null
@@ -1 +0,0 @@
-export type AdvancedTextEditorContentType = 'json' | 'html' | 'markdown';
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorExtensionContext.ts b/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorExtensionContext.ts
new file mode 100644
index 00000000000..483626d8bca
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorExtensionContext.ts
@@ -0,0 +1,6 @@
+import { type UploadedImage } from '@/advanced-text-editor/types/UploadedImage';
+
+export type AdvancedTextEditorExtensionContext = {
+ onImageUpload?: (file: File) => Promise<UploadedImage>;
+ onImageUploadError?: (error: Error, file: File) => void;
+};
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorLegacyDocumentParser.ts b/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorLegacyDocumentParser.ts
new file mode 100644
index 00000000000..f06687779bf
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorLegacyDocumentParser.ts
@@ -0,0 +1,5 @@
+import { type Content } from '@tiptap/core';
+
+export type AdvancedTextEditorLegacyDocumentParser = (
+ serializedDocument: string,
+) => Content;
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorPreset.ts b/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorPreset.ts
deleted file mode 100644
index 269be2ccfcc..00000000000
--- a/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorPreset.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { type AdvancedTextEditorCapability } from '@/advanced-text-editor/types/AdvancedTextEditorCapability';
-import { type AdvancedTextEditorContentType } from '@/advanced-text-editor/types/AdvancedTextEditorContentType';
-
-// 'field' keeps the bordered form-field chrome. 'document' drops the border so
-// the editor fills whatever container it is given and reads as page content
-export type AdvancedTextEditorChrome = 'field' | 'document' | 'canvas';
-
-export type AdvancedTextEditorPreset = {
- contentType: AdvancedTextEditorContentType;
- chrome: AdvancedTextEditorChrome;
- minHeight: number;
- enableFullScreen: boolean;
- capabilities: readonly AdvancedTextEditorCapability[];
-};
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorProfile.ts b/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorProfile.ts
new file mode 100644
index 00000000000..76c33c9a604
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/types/AdvancedTextEditorProfile.ts
@@ -0,0 +1,16 @@
+import { type AdvancedTextEditorExtensionContext } from '@/advanced-text-editor/types/AdvancedTextEditorExtensionContext';
+import { type AdvancedTextEditorLegacyDocumentParser } from '@/advanced-text-editor/types/AdvancedTextEditorLegacyDocumentParser';
+import { type AnyExtension } from '@tiptap/core';
+
+export type AdvancedTextEditorChrome = 'field' | 'document';
+
+export type AdvancedTextEditorProfile = {
+ chrome: AdvancedTextEditorChrome;
+ minHeight: number;
+ enableFullScreen: boolean;
+ buildExtensions: (
+ context: AdvancedTextEditorExtensionContext,
+ ) => AnyExtension[];
+ documentExtension?: AnyExtension;
+ parseLegacyDocument?: AdvancedTextEditorLegacyDocumentParser;
+};
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/utils/__tests__/advancedTextEditorDocument.test.ts b/packages/twenty-front/src/modules/advanced-text-editor/utils/__tests__/advancedTextEditorDocument.test.ts
new file mode 100644
index 00000000000..afe23ae4f81
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/utils/__tests__/advancedTextEditorDocument.test.ts
@@ -0,0 +1,137 @@
+import { deserializeAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/deserializeAdvancedTextEditorDocument';
+import { getInitialEditorContent } from '@/advanced-text-editor/utils/getInitialEditorContent';
+import { parseLegacyHtmlOrPlainTextDocument } from '@/advanced-text-editor/utils/parseLegacyHtmlOrPlainTextDocument';
+import { parseLegacyPlainTextDocument } from '@/advanced-text-editor/utils/parseLegacyPlainTextDocument';
+import { serializeAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializeAdvancedTextEditorDocument';
+import { serializePlainTextAsAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializePlainTextAsAdvancedTextEditorDocument';
+import { type Editor } from '@tiptap/core';
+import { TIPTAP_DOCUMENT_SCHEMA_VERSION } from 'twenty-shared/utils';
+
+describe('advanced text editor document persistence', () => {
+ const content = [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'Hello' }],
+ },
+ ];
+
+ it('serializes every editor profile as a versioned TipTap document', () => {
+ const editor = {
+ getJSON: () => ({ type: 'doc', content }),
+ } as Editor;
+
+ expect(JSON.parse(serializeAdvancedTextEditorDocument(editor))).toEqual({
+ type: 'doc',
+ attrs: { schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION },
+ content,
+ });
+ });
+
+ it('deserializes the canonical document without a profile codec', () => {
+ const serializedDocument = JSON.stringify({
+ type: 'doc',
+ attrs: { schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION },
+ content,
+ });
+
+ expect(
+ deserializeAdvancedTextEditorDocument({ serializedDocument }),
+ ).toEqual(JSON.parse(serializedDocument));
+ });
+
+ it('delegates non-canonical values to the profile legacy parser', () => {
+ expect(
+ deserializeAdvancedTextEditorDocument({
+ serializedDocument: 'Line one\nLine two',
+ parseLegacyDocument: parseLegacyPlainTextDocument,
+ }),
+ ).toEqual({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: 'Line one' },
+ { type: 'hardBreak' },
+ { type: 'text', text: 'Line two' },
+ ],
+ },
+ ],
+ });
+ });
+
+ it('uses the schema version to distinguish canonical documents from legacy text', () => {
+ const versionlessDocument = JSON.stringify({ type: 'doc', content });
+
+ expect(
+ deserializeAdvancedTextEditorDocument({
+ serializedDocument: versionlessDocument,
+ parseLegacyDocument: parseLegacyPlainTextDocument,
+ }),
+ ).toEqual(parseLegacyPlainTextDocument(versionlessDocument));
+ });
+
+ it('does not reinterpret non-canonical content without a legacy parser', () => {
+ expect(
+ deserializeAdvancedTextEditorDocument({
+ serializedDocument: JSON.stringify({ type: 'doc', content }),
+ }),
+ ).toEqual(getInitialEditorContent(''));
+ });
+
+ it('recognizes structured and self-closing legacy HTML fragments', () => {
+ const documents = [
+ '<p>Hello</p>',
+ '<br/>Hello',
+ '<img src="https://example.com/image.png"/>',
+ '<!-- greeting --><div>Hello</div>',
+ ];
+
+ for (const document of documents) {
+ expect(parseLegacyHtmlOrPlainTextDocument(document)).toBe(document);
+ }
+ });
+
+ it('keeps a leading tag-like token as legacy plain text', () => {
+ const document = '<support> {{contact.name}}';
+
+ expect(parseLegacyHtmlOrPlainTextDocument(document)).toEqual(
+ getInitialEditorContent(document),
+ );
+ });
+
+ it('normalizes legacy plain-text line endings', () => {
+ expect(
+ parseLegacyPlainTextDocument('Line one\r\nLine two\rLine three'),
+ ).toEqual({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: 'Line one' },
+ { type: 'hardBreak' },
+ { type: 'text', text: 'Line two' },
+ { type: 'hardBreak' },
+ { type: 'text', text: 'Line three' },
+ ],
+ },
+ ],
+ });
+ });
+
+ it('creates canonical documents for plain-text entry points', () => {
+ expect(
+ JSON.parse(serializePlainTextAsAdvancedTextEditorDocument('Ask Twenty')),
+ ).toEqual({
+ type: 'doc',
+ attrs: { schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION },
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'Ask Twenty' }],
+ },
+ ],
+ });
+ });
+});
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/utils/__tests__/buildAdvancedTextEditorExtensions.test.ts b/packages/twenty-front/src/modules/advanced-text-editor/utils/__tests__/buildAdvancedTextEditorExtensions.test.ts
index 480b4e26b53..08ca9fbb092 100644
--- a/packages/twenty-front/src/modules/advanced-text-editor/utils/__tests__/buildAdvancedTextEditorExtensions.test.ts
+++ b/packages/twenty-front/src/modules/advanced-text-editor/utils/__tests__/buildAdvancedTextEditorExtensions.test.ts
@@ -1,5 +1,8 @@
-import { ADVANCED_TEXT_EDITOR_PRESETS } from '@/advanced-text-editor/constants/AdvancedTextEditorPresets';
+import { VariableTag } from '@/advanced-text-editor/extensions/variable-tag/VariableTag';
+import { type AdvancedTextEditorProfile } from '@/advanced-text-editor/types/AdvancedTextEditorProfile';
import { buildAdvancedTextEditorExtensions } from '@/advanced-text-editor/utils/buildAdvancedTextEditorExtensions';
+import { buildFullRichTextExtensions } from '@/advanced-text-editor/utils/buildFullRichTextExtensions';
+import { Document } from '@tiptap/extension-document';
const getExtensionNames = (
extensions: ReturnType<typeof buildAdvancedTextEditorExtensions>,
@@ -8,7 +11,7 @@ const getExtensionNames = (
describe('buildAdvancedTextEditorExtensions', () => {
it('should always include core extensions', () => {
const extensions = buildAdvancedTextEditorExtensions({
- capabilities: [],
+ profile: createProfile(),
context: {},
placeholder: undefined,
readonly: false,
@@ -27,9 +30,14 @@ describe('buildAdvancedTextEditorExtensions', () => {
);
});
- it('should build the structured email extension set for campaign bodies', () => {
+ it('should compose the extension set provided by the surface profile', () => {
const extensions = buildAdvancedTextEditorExtensions({
- capabilities: ADVANCED_TEXT_EDITOR_PRESETS.campaignBody.capabilities,
+ profile: createProfile({
+ buildExtensions: (context) => [
+ ...buildFullRichTextExtensions(context),
+ VariableTag,
+ ],
+ }),
context: {},
placeholder: undefined,
readonly: false,
@@ -48,19 +56,14 @@ describe('buildAdvancedTextEditorExtensions', () => {
'uploadImage',
'variableTag',
'slash-command',
- 'section',
- 'columns',
- 'column',
- 'button',
- 'divider',
- 'html',
]),
);
});
- it('should only add mention extensions on top of core for the aiChat preset', () => {
+ it('should allow a surface profile to replace the document extension', () => {
+ const SurfaceDocument = Document.extend({ name: 'surfaceDocument' });
const extensions = buildAdvancedTextEditorExtensions({
- capabilities: ADVANCED_TEXT_EDITOR_PRESETS.aiChat.capabilities,
+ profile: createProfile({ documentExtension: SurfaceDocument }),
context: {},
placeholder: undefined,
readonly: false,
@@ -68,19 +71,15 @@ describe('buildAdvancedTextEditorExtensions', () => {
const extensionNames = getExtensionNames(extensions);
- expect(extensionNames).toEqual(
- expect.arrayContaining(['mentionTag', 'mention-suggestion']),
- );
- expect(extensionNames).not.toEqual(expect.arrayContaining(['bold']));
- expect(extensionNames).not.toEqual(expect.arrayContaining(['heading']));
- expect(extensionNames).not.toEqual(
- expect.arrayContaining(['slash-command']),
- );
+ expect(extensionNames).toContain('surfaceDocument');
+ expect(extensionNames).not.toContain('doc');
});
it('should drop the slash command when readonly', () => {
const extensions = buildAdvancedTextEditorExtensions({
- capabilities: ['slashCommand'],
+ profile: createProfile({
+ buildExtensions: (context) => buildFullRichTextExtensions(context),
+ }),
context: {},
placeholder: undefined,
readonly: true,
@@ -95,7 +94,9 @@ describe('buildAdvancedTextEditorExtensions', () => {
const onImageUpload = jest.fn();
const extensions = buildAdvancedTextEditorExtensions({
- capabilities: ['images'],
+ profile: createProfile({
+ buildExtensions: (context) => buildFullRichTextExtensions(context),
+ }),
context: { onImageUpload },
placeholder: undefined,
readonly: false,
@@ -108,3 +109,13 @@ describe('buildAdvancedTextEditorExtensions', () => {
expect(uploadImageExtension?.options.onImageUpload).toBe(onImageUpload);
});
});
+
+const createProfile = (
+ overrides: Partial<AdvancedTextEditorProfile> = {},
+): AdvancedTextEditorProfile => ({
+ chrome: 'document',
+ minHeight: 0,
+ enableFullScreen: false,
+ buildExtensions: () => [],
+ ...overrides,
+});
diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/__tests__/getInitialEditorContent.test.ts b/packages/twenty-front/src/modules/advanced-text-editor/utils/__tests__/getInitialEditorContent.test.ts
similarity index 98%
rename from packages/twenty-front/src/modules/workflow/workflow-variables/utils/__tests__/getInitialEditorContent.test.ts
rename to packages/twenty-front/src/modules/advanced-text-editor/utils/__tests__/getInitialEditorContent.test.ts
index 3a6dba8ab1a..608ff9c83ed 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/__tests__/getInitialEditorContent.test.ts
+++ b/packages/twenty-front/src/modules/advanced-text-editor/utils/__tests__/getInitialEditorContent.test.ts
@@ -1,4 +1,4 @@
-import { getInitialEditorContent } from '@/workflow/workflow-variables/utils/getInitialEditorContent';
+import { getInitialEditorContent } from '@/advanced-text-editor/utils/getInitialEditorContent';
describe('getInitialEditorContent', () => {
it('should handle single line text', () => {
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/utils/__tests__/serializeAdvancedTextEditorContent.test.ts b/packages/twenty-front/src/modules/advanced-text-editor/utils/__tests__/serializeAdvancedTextEditorContent.test.ts
deleted file mode 100644
index d2331e8cb0e..00000000000
--- a/packages/twenty-front/src/modules/advanced-text-editor/utils/__tests__/serializeAdvancedTextEditorContent.test.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { serializeAdvancedTextEditorContent } from '@/advanced-text-editor/utils/serializeAdvancedTextEditorContent';
-import { Editor } from '@tiptap/core';
-import { Document } from '@tiptap/extension-document';
-import { Paragraph } from '@tiptap/extension-paragraph';
-import { Text } from '@tiptap/extension-text';
-
-describe('serializeAdvancedTextEditorContent', () => {
- const editor = new Editor({
- extensions: [Document, Paragraph, Text],
- content: '<p>Hello</p>',
- });
-
- afterAll(() => {
- editor.destroy();
- });
-
- it('should serialize to a JSON string for json content', () => {
- const serialized = serializeAdvancedTextEditorContent({
- editor,
- contentType: 'json',
- });
-
- expect(JSON.parse(serialized)).toMatchObject({
- type: 'doc',
- content: [
- {
- type: 'paragraph',
- content: [{ type: 'text', text: 'Hello' }],
- },
- ],
- });
- });
-
- it('should serialize to HTML for html content', () => {
- expect(
- serializeAdvancedTextEditorContent({ editor, contentType: 'html' }),
- ).toBe('<p>Hello</p>');
- });
-
- it('should serialize to HTML for markdown content', () => {
- expect(
- serializeAdvancedTextEditorContent({ editor, contentType: 'markdown' }),
- ).toBe('<p>Hello</p>');
- });
-});
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/utils/buildAdvancedTextEditorExtensions.ts b/packages/twenty-front/src/modules/advanced-text-editor/utils/buildAdvancedTextEditorExtensions.ts
index c9cde2aa452..54dca4c712f 100644
--- a/packages/twenty-front/src/modules/advanced-text-editor/utils/buildAdvancedTextEditorExtensions.ts
+++ b/packages/twenty-front/src/modules/advanced-text-editor/utils/buildAdvancedTextEditorExtensions.ts
@@ -1,37 +1,31 @@
-import {
- ADVANCED_TEXT_EDITOR_CAPABILITY_EXTENSIONS,
- type AdvancedTextEditorExtensionContext,
-} from '@/advanced-text-editor/constants/AdvancedTextEditorCapabilityExtensions';
import { buildAdvancedTextEditorCoreExtensions } from '@/advanced-text-editor/constants/AdvancedTextEditorCoreExtensions';
-import { ThemedDocument } from '@/advanced-text-editor/extensions/blocks/ThemedDocument';
-import { type AdvancedTextEditorCapability } from '@/advanced-text-editor/types/AdvancedTextEditorCapability';
+import { type AdvancedTextEditorExtensionContext } from '@/advanced-text-editor/types/AdvancedTextEditorExtensionContext';
+import { type AdvancedTextEditorProfile } from '@/advanced-text-editor/types/AdvancedTextEditorProfile';
import { type AnyExtension } from '@tiptap/core';
export const buildAdvancedTextEditorExtensions = ({
- capabilities,
+ profile,
context,
placeholder,
readonly,
}: {
- capabilities: readonly AdvancedTextEditorCapability[];
+ profile: AdvancedTextEditorProfile;
context: AdvancedTextEditorExtensionContext;
placeholder: string | undefined;
readonly: boolean | undefined;
}): AnyExtension[] => {
const coreExtensions = buildAdvancedTextEditorCoreExtensions({ placeholder });
+ const profileExtensions = profile.buildExtensions(context);
+ const { documentExtension } = profile;
return [
- ...(capabilities.includes('blocks')
+ ...(documentExtension
? coreExtensions.map((extension) =>
- extension.name === 'doc' ? ThemedDocument : extension,
+ extension.name === 'doc' ? documentExtension : extension,
)
: coreExtensions),
- ...capabilities
- .filter(
- (capability) => !(readonly === true && capability === 'slashCommand'),
- )
- .flatMap((capability) =>
- ADVANCED_TEXT_EDITOR_CAPABILITY_EXTENSIONS[capability](context),
- ),
+ ...profileExtensions.filter(
+ (extension) => !(readonly === true && extension.name === 'slash-command'),
+ ),
];
};
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/utils/buildFullRichTextExtensions.ts b/packages/twenty-front/src/modules/advanced-text-editor/utils/buildFullRichTextExtensions.ts
new file mode 100644
index 00000000000..69da554e9ae
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/utils/buildFullRichTextExtensions.ts
@@ -0,0 +1,32 @@
+import { ResizableImage } from '@/advanced-text-editor/extensions/resizable-image/ResizableImage';
+import { UploadImageExtension } from '@/advanced-text-editor/extensions/resizable-image/UploadImageExtension';
+import { SlashCommand } from '@/advanced-text-editor/extensions/slash-command/SlashCommand';
+import { VariableTag } from '@/advanced-text-editor/extensions/variable-tag/VariableTag';
+import { type AdvancedTextEditorExtensionContext } from '@/advanced-text-editor/types/AdvancedTextEditorExtensionContext';
+import { type AnyExtension } from '@tiptap/core';
+import { Bold } from '@tiptap/extension-bold';
+import { Heading } from '@tiptap/extension-heading';
+import { Italic } from '@tiptap/extension-italic';
+import { Link } from '@tiptap/extension-link';
+import { ListKit } from '@tiptap/extension-list';
+import { Strike } from '@tiptap/extension-strike';
+import { Underline } from '@tiptap/extension-underline';
+
+export const buildFullRichTextExtensions = (
+ context: AdvancedTextEditorExtensionContext,
+): AnyExtension[] => [
+ Bold,
+ Italic,
+ Strike,
+ Underline,
+ Heading.configure({ levels: [1, 2, 3] }),
+ ListKit,
+ Link.configure({ openOnClick: false }),
+ ResizableImage,
+ UploadImageExtension.configure(context),
+ SlashCommand,
+];
+
+export const buildFullRichTextWithVariableTagExtensions = (
+ context: AdvancedTextEditorExtensionContext,
+): AnyExtension[] => [...buildFullRichTextExtensions(context), VariableTag];
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/utils/deserializeAdvancedTextEditorDocument.ts b/packages/twenty-front/src/modules/advanced-text-editor/utils/deserializeAdvancedTextEditorDocument.ts
new file mode 100644
index 00000000000..99c0e6b0794
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/utils/deserializeAdvancedTextEditorDocument.ts
@@ -0,0 +1,26 @@
+import { type AdvancedTextEditorLegacyDocumentParser } from '@/advanced-text-editor/types/AdvancedTextEditorLegacyDocumentParser';
+import { getInitialEditorContent } from '@/advanced-text-editor/utils/getInitialEditorContent';
+import { type Content } from '@tiptap/core';
+import { parseCanonicalTipTapJsonDocument } from 'twenty-shared/utils';
+
+export const deserializeAdvancedTextEditorDocument = ({
+ serializedDocument,
+ parseLegacyDocument,
+}: {
+ serializedDocument: string;
+ parseLegacyDocument?: AdvancedTextEditorLegacyDocumentParser;
+}): Content => {
+ if (serializedDocument.trim() === '') {
+ return getInitialEditorContent('');
+ }
+
+ const document = parseCanonicalTipTapJsonDocument(serializedDocument);
+
+ if (document !== undefined) {
+ return document;
+ }
+
+ return (
+ parseLegacyDocument?.(serializedDocument) ?? getInitialEditorContent('')
+ );
+};
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/utils/getBlockSelectionTarget.ts b/packages/twenty-front/src/modules/advanced-text-editor/utils/getBlockSelectionTarget.ts
index c1c33de1e23..bca42186afe 100644
--- a/packages/twenty-front/src/modules/advanced-text-editor/utils/getBlockSelectionTarget.ts
+++ b/packages/twenty-front/src/modules/advanced-text-editor/utils/getBlockSelectionTarget.ts
@@ -1,19 +1,12 @@
+import {
+ isAdvancedTextEditorBlockNodeType,
+ type AdvancedTextEditorBlockNodeType,
+} from '@/advanced-text-editor/types/AdvancedTextEditorBlockCatalog';
import { type Editor } from '@tiptap/core';
import { NodeSelection } from '@tiptap/pm/state';
-import { TIPTAP_NODE_TYPES } from 'twenty-shared/utils';
-
-const INSPECTABLE_NODE_TYPES: readonly string[] = [
- TIPTAP_NODE_TYPES.SECTION,
- TIPTAP_NODE_TYPES.COLUMNS,
- TIPTAP_NODE_TYPES.COLUMN,
- TIPTAP_NODE_TYPES.BUTTON,
- TIPTAP_NODE_TYPES.DIVIDER,
- TIPTAP_NODE_TYPES.HTML,
- TIPTAP_NODE_TYPES.IMAGE,
-];
export type BlockSelectionTarget = {
- nodeType: string;
+ nodeType: AdvancedTextEditorBlockNodeType;
pos: number;
attrs: Record<string, unknown>;
};
@@ -25,7 +18,7 @@ export const getBlockSelectionTarget = (
if (
selection instanceof NodeSelection &&
- INSPECTABLE_NODE_TYPES.includes(selection.node.type.name)
+ isAdvancedTextEditorBlockNodeType(selection.node.type.name)
) {
return {
nodeType: selection.node.type.name,
@@ -37,7 +30,7 @@ export const getBlockSelectionTarget = (
const { $from } = selection;
for (let depth = $from.depth; depth > 0; depth--) {
const node = $from.node(depth);
- if (INSPECTABLE_NODE_TYPES.includes(node.type.name)) {
+ if (isAdvancedTextEditorBlockNodeType(node.type.name)) {
return {
nodeType: node.type.name,
pos: $from.before(depth),
diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/getInitialEditorContent.ts b/packages/twenty-front/src/modules/advanced-text-editor/utils/getInitialEditorContent.ts
similarity index 91%
rename from packages/twenty-front/src/modules/workflow/workflow-variables/utils/getInitialEditorContent.ts
rename to packages/twenty-front/src/modules/advanced-text-editor/utils/getInitialEditorContent.ts
index 9cac48ecbfb..87e73041653 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/getInitialEditorContent.ts
+++ b/packages/twenty-front/src/modules/advanced-text-editor/utils/getInitialEditorContent.ts
@@ -1,6 +1,6 @@
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
import { isNonEmptyString } from '@sniptt/guards';
import type { JSONContent } from '@tiptap/react';
+import { isStandaloneVariableString } from 'twenty-shared/workflow';
export const CAPTURE_VARIABLE_TAG_REGEX = /({{[^{}]+}})/;
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/utils/parseLegacyHtmlDocument.ts b/packages/twenty-front/src/modules/advanced-text-editor/utils/parseLegacyHtmlDocument.ts
new file mode 100644
index 00000000000..93954279fb0
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/utils/parseLegacyHtmlDocument.ts
@@ -0,0 +1,4 @@
+import { type Content } from '@tiptap/core';
+
+export const parseLegacyHtmlDocument = (serializedDocument: string): Content =>
+ serializedDocument;
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/utils/parseLegacyHtmlOrPlainTextDocument.ts b/packages/twenty-front/src/modules/advanced-text-editor/utils/parseLegacyHtmlOrPlainTextDocument.ts
new file mode 100644
index 00000000000..1743178b316
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/utils/parseLegacyHtmlOrPlainTextDocument.ts
@@ -0,0 +1,52 @@
+import { getInitialEditorContent } from '@/advanced-text-editor/utils/getInitialEditorContent';
+import { type Content } from '@tiptap/core';
+
+const HTML_VOID_TAG_NAMES = new Set([
+ 'area',
+ 'base',
+ 'br',
+ 'col',
+ 'embed',
+ 'hr',
+ 'img',
+ 'input',
+ 'link',
+ 'meta',
+ 'param',
+ 'source',
+ 'track',
+ 'wbr',
+]);
+
+const hasLeadingHtmlTag = (serializedDocument: string): boolean => {
+ const documentWithoutLeadingComments = serializedDocument
+ .trim()
+ .replace(/^(?:<!--[\s\S]*?-->\s*)*/, '');
+
+ if (/^<!doctype\s+html(?:\s[^>]*)?>/i.test(documentWithoutLeadingComments)) {
+ return true;
+ }
+
+ const openingTagMatch = /^<([a-z][a-z0-9-]*)(?:\s[^<>]*?)?\s*(\/?)>/i.exec(
+ documentWithoutLeadingComments,
+ );
+
+ if (openingTagMatch === null) {
+ return false;
+ }
+
+ const tagName = openingTagMatch[1].toLowerCase();
+
+ return (
+ openingTagMatch[2] === '/' ||
+ HTML_VOID_TAG_NAMES.has(tagName) ||
+ new RegExp(`</${tagName}\\s*>`, 'i').test(documentWithoutLeadingComments)
+ );
+};
+
+export const parseLegacyHtmlOrPlainTextDocument = (
+ serializedDocument: string,
+): Content =>
+ hasLeadingHtmlTag(serializedDocument)
+ ? serializedDocument
+ : getInitialEditorContent(serializedDocument);
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/utils/parseLegacyMarkdownDocument.ts b/packages/twenty-front/src/modules/advanced-text-editor/utils/parseLegacyMarkdownDocument.ts
new file mode 100644
index 00000000000..132280749c2
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/utils/parseLegacyMarkdownDocument.ts
@@ -0,0 +1,6 @@
+import { type Content } from '@tiptap/core';
+import { marked } from 'marked';
+
+export const parseLegacyMarkdownDocument = (
+ serializedDocument: string,
+): Content => marked.parse(serializedDocument, { async: false }) as string;
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/utils/parseLegacyPlainTextDocument.ts b/packages/twenty-front/src/modules/advanced-text-editor/utils/parseLegacyPlainTextDocument.ts
new file mode 100644
index 00000000000..57b12b6f828
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/utils/parseLegacyPlainTextDocument.ts
@@ -0,0 +1,18 @@
+import { type JSONContent } from '@tiptap/core';
+
+export const parseLegacyPlainTextDocument = (
+ serializedDocument: string,
+): JSONContent => {
+ const content = serializedDocument
+ .replace(/\r\n?/g, '\n')
+ .split('\n')
+ .flatMap((line, index, lines) => [
+ ...(line === '' ? [] : [{ type: 'text', text: line }]),
+ ...(index === lines.length - 1 ? [] : [{ type: 'hardBreak' }]),
+ ]);
+
+ return {
+ type: 'doc',
+ content: [{ type: 'paragraph', content }],
+ };
+};
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/utils/serializeAdvancedTextEditorContent.ts b/packages/twenty-front/src/modules/advanced-text-editor/utils/serializeAdvancedTextEditorContent.ts
deleted file mode 100644
index 4e31ef504eb..00000000000
--- a/packages/twenty-front/src/modules/advanced-text-editor/utils/serializeAdvancedTextEditorContent.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { type AdvancedTextEditorContentType } from '@/advanced-text-editor/types/AdvancedTextEditorContentType';
-import { type Editor } from '@tiptap/core';
-
-export const serializeAdvancedTextEditorContent = ({
- editor,
- contentType,
-}: {
- editor: Editor;
- contentType: AdvancedTextEditorContentType;
-}): string => {
- if (contentType === 'html' || contentType === 'markdown') {
- return editor.getHTML();
- }
-
- return JSON.stringify(editor.getJSON());
-};
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/utils/serializeAdvancedTextEditorDocument.ts b/packages/twenty-front/src/modules/advanced-text-editor/utils/serializeAdvancedTextEditorDocument.ts
new file mode 100644
index 00000000000..49c9c4f296d
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/utils/serializeAdvancedTextEditorDocument.ts
@@ -0,0 +1,14 @@
+import { type Editor } from '@tiptap/core';
+import { TIPTAP_DOCUMENT_SCHEMA_VERSION } from 'twenty-shared/utils';
+
+export const serializeAdvancedTextEditorDocument = (editor: Editor): string => {
+ const document = editor.getJSON();
+
+ return JSON.stringify({
+ ...document,
+ attrs: {
+ ...document.attrs,
+ schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION,
+ },
+ });
+};
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/utils/serializePlainTextAsAdvancedTextEditorDocument.ts b/packages/twenty-front/src/modules/advanced-text-editor/utils/serializePlainTextAsAdvancedTextEditorDocument.ts
new file mode 100644
index 00000000000..74cd22044d8
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/utils/serializePlainTextAsAdvancedTextEditorDocument.ts
@@ -0,0 +1,10 @@
+import { parseLegacyPlainTextDocument } from '@/advanced-text-editor/utils/parseLegacyPlainTextDocument';
+import { TIPTAP_DOCUMENT_SCHEMA_VERSION } from 'twenty-shared/utils';
+
+export const serializePlainTextAsAdvancedTextEditorDocument = (
+ text: string,
+): string =>
+ JSON.stringify({
+ ...parseLegacyPlainTextDocument(text),
+ attrs: { schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION },
+ });
diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatPrepromptEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatPrepromptEffect.tsx
index 88060d153d9..640b7474f29 100644
--- a/packages/twenty-front/src/modules/ai/components/AgentChatPrepromptEffect.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AgentChatPrepromptEffect.tsx
@@ -1,6 +1,7 @@
import { useEffect } from 'react';
import { isDefined } from 'twenty-shared/utils';
+import { serializePlainTextAsAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializePlainTextAsAdvancedTextEditorDocument';
import { AGENT_CHAT_RESTORE_EDITOR_CONTENT_EVENT_NAME } from '@/ai/constants/AgentChatRestoreEditorContentEventName';
import { agentChatPrepromptState } from '@/ai/states/agentChatPrepromptState';
import { dispatchAgentChatSendMessageEvent } from '@/ai/utils/dispatchAgentChatSendMessageEvent';
@@ -27,7 +28,7 @@ export const AgentChatPrepromptEffect = () => {
});
} else {
dispatchBrowserEvent(AGENT_CHAT_RESTORE_EDITOR_CONTENT_EVENT_NAME, {
- content: text,
+ content: serializePlainTextAsAdvancedTextEditorDocument(text),
});
}
diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx
index faec0f4a98f..d2be244cd9a 100644
--- a/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx
@@ -1,6 +1,10 @@
import { useAtomValue, useStore } from 'jotai';
import { useEffect } from 'react';
-import { isDefined, isValidUuid } from 'twenty-shared/utils';
+import {
+ isDefined,
+ isValidUuid,
+ tipTapDocumentToMarkdown,
+} from 'twenty-shared/utils';
import {
AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
@@ -105,7 +109,7 @@ export const AgentChatThreadInitializationEffect = () => {
store.get(agentChatDraftsByThreadIdState.atom)[firstThread.id] ?? '';
setCurrentAiChatThread(firstThread.id);
- setAgentChatInput(draftForThread);
+ setAgentChatInput(tipTapDocumentToMarkdown(draftForThread));
const firstThreadFamilyKey = { threadId: firstThread.id };
@@ -136,9 +140,11 @@ export const AgentChatThreadInitializationEffect = () => {
store.set(hasTriggeredCreateForDraftState.atom, false);
setCurrentAiChatThread(AGENT_CHAT_NEW_THREAD_DRAFT_KEY);
setAgentChatInput(
- store.get(agentChatDraftsByThreadIdState.atom)[
- AGENT_CHAT_NEW_THREAD_DRAFT_KEY
- ] ?? '',
+ tipTapDocumentToMarkdown(
+ store.get(agentChatDraftsByThreadIdState.atom)[
+ AGENT_CHAT_NEW_THREAD_DRAFT_KEY
+ ] ?? '',
+ ),
);
}
}, [
diff --git a/packages/twenty-front/src/modules/ai/constants/AiChatEditorProfile.ts b/packages/twenty-front/src/modules/ai/constants/AiChatEditorProfile.ts
new file mode 100644
index 00000000000..ead175d3fe0
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/constants/AiChatEditorProfile.ts
@@ -0,0 +1,10 @@
+import { type AdvancedTextEditorProfile } from '@/advanced-text-editor/types/AdvancedTextEditorProfile';
+import { MentionSuggestion } from '@/mention/extensions/MentionSuggestion';
+import { MentionTag } from '@/mention/extensions/MentionTag';
+
+export const AI_CHAT_EDITOR_PROFILE = {
+ chrome: 'document',
+ minHeight: 0,
+ enableFullScreen: false,
+ buildExtensions: () => [MentionTag, MentionSuggestion],
+} satisfies AdvancedTextEditorProfile;
diff --git a/packages/twenty-front/src/modules/ai/constants/AiInstructionsEditorProfile.ts b/packages/twenty-front/src/modules/ai/constants/AiInstructionsEditorProfile.ts
new file mode 100644
index 00000000000..07b87ae3cf6
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/constants/AiInstructionsEditorProfile.ts
@@ -0,0 +1,11 @@
+import { type AdvancedTextEditorProfile } from '@/advanced-text-editor/types/AdvancedTextEditorProfile';
+import { buildFullRichTextWithVariableTagExtensions } from '@/advanced-text-editor/utils/buildFullRichTextExtensions';
+import { parseLegacyMarkdownDocument } from '@/advanced-text-editor/utils/parseLegacyMarkdownDocument';
+
+export const AI_INSTRUCTIONS_EDITOR_PROFILE = {
+ chrome: 'field',
+ minHeight: 120,
+ enableFullScreen: true,
+ parseLegacyDocument: parseLegacyMarkdownDocument,
+ buildExtensions: buildFullRichTextWithVariableTagExtensions,
+} satisfies AdvancedTextEditorProfile;
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts
index 2e5eaa6ae32..157f63f15f8 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts
@@ -4,7 +4,11 @@ import { t } from '@lingui/core/macro';
import { useStore } from 'jotai';
import { useCallback } from 'react';
import { type ExtendedUIMessage } from 'twenty-shared/ai';
-import { isDefined, isValidUuid } from 'twenty-shared/utils';
+import {
+ isDefined,
+ isValidUuid,
+ tipTapDocumentToMarkdown,
+} from 'twenty-shared/utils';
import { v4 } from 'uuid';
import { AGENT_CHAT_INSTANCE_ID } from '@/ai/constants/AgentChatInstanceId';
@@ -61,14 +65,11 @@ export const useAgentChat = (
const draftKey =
store.get(currentAiChatThreadState.atom) ??
AGENT_CHAT_NEW_THREAD_DRAFT_KEY;
- const contentToSend =
- draftKey === AGENT_CHAT_NEW_THREAD_DRAFT_KEY
- ? (
- store.get(agentChatDraftsByThreadIdState.atom)[
- AGENT_CHAT_NEW_THREAD_DRAFT_KEY
- ] ?? store.get(agentChatInputState.atom)
- ).trim()
- : store.get(agentChatInputState.atom).trim();
+ const serializedContentToSend =
+ store.get(agentChatDraftsByThreadIdState.atom)[draftKey] ?? '';
+ const contentToSend = tipTapDocumentToMarkdown(
+ serializedContentToSend,
+ ).trim();
if (contentToSend === '') {
return;
@@ -210,7 +211,7 @@ export const useAgentChat = (
setAgentChatInput(contentToSend);
setAgentChatDraftsByThreadId((prev) => ({
...prev,
- [restoredDraftKey]: contentToSend,
+ [restoredDraftKey]: serializedContentToSend,
...(draftKey === AGENT_CHAT_NEW_THREAD_DRAFT_KEY
? { [AGENT_CHAT_NEW_THREAD_DRAFT_KEY]: '' }
: {}),
@@ -233,7 +234,7 @@ export const useAgentChat = (
);
dispatchBrowserEvent(AGENT_CHAT_RESTORE_EDITOR_CONTENT_EVENT_NAME, {
- content: contentToSend,
+ content: serializedContentToSend,
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts
index 5870da4bde0..a319a8debd8 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts
@@ -3,6 +3,9 @@ import { useCallback } from 'react';
import { isDefined } from 'twenty-shared/utils';
import { useAdvancedTextEditor } from '@/advanced-text-editor/hooks/useAdvancedTextEditor';
+import { deserializeAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/deserializeAdvancedTextEditorDocument';
+import { serializeAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializeAdvancedTextEditorDocument';
+import { AI_CHAT_EDITOR_PROFILE } from '@/ai/constants/AiChatEditorProfile';
import { AGENT_CHAT_RESTORE_EDITOR_CONTENT_EVENT_NAME } from '@/ai/constants/AgentChatRestoreEditorContentEventName';
import { AI_CHAT_INPUT_ID } from '@/ai/constants/AiChatInputId';
import {
@@ -24,16 +27,6 @@ import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomState
import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
import { turnIntoEmptyStringIfWhitespacesOnly } from '~/utils/string/turnIntoEmptyStringIfWhitespacesOnly';
-const textToTiptapContent = (text: string) => ({
- type: 'doc',
- content: [
- {
- type: 'paragraph',
- content: text ? [{ type: 'text', text }] : [],
- },
- ],
-});
-
export const useAiChatEditor = () => {
const setAgentChatInput = useSetAtomState(agentChatInputState);
const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);
@@ -46,14 +39,11 @@ export const useAiChatEditor = () => {
const draftKey = currentAiChatThread ?? AGENT_CHAT_NEW_THREAD_DRAFT_KEY;
const initialDraft = agentChatDraftsByThreadId[draftKey] ?? '';
- const initialContent = textToTiptapContent(initialDraft);
-
const editor = useAdvancedTextEditor({
- preset: 'aiChat',
+ profile: AI_CHAT_EDITOR_PROFILE,
placeholder: t`Ask, search or make anything...`,
readonly: false,
- defaultValue: undefined,
- content: initialContent,
+ defaultValue: initialDraft,
editorProps: {
handleKeyDown: (view, event) => {
if (event.key === 'Enter' && !event.shiftKey) {
@@ -78,8 +68,14 @@ export const useAiChatEditor = () => {
const text = turnIntoEmptyStringIfWhitespacesOnly(
currentEditor.getText({ blockSeparator: '\n' }),
);
+ const serializedDraft =
+ text === '' ? '' : serializeAdvancedTextEditorDocument(currentEditor);
+
setAgentChatInput(text);
- setAgentChatDraftsByThreadId((prev) => ({ ...prev, [draftKey]: text }));
+ setAgentChatDraftsByThreadId((prev) => ({
+ ...prev,
+ [draftKey]: serializedDraft,
+ }));
if (draftKey === AGENT_CHAT_NEW_THREAD_DRAFT_KEY && text.trim() !== '') {
dispatchAgentChatEnsureThreadForDraftEvent();
}
@@ -117,7 +113,11 @@ export const useAiChatEditor = () => {
const handleRestoreEditorContent = useCallback(
(detail?: { content: string }) => {
if (isDefined(detail?.content)) {
- editor?.commands.setContent(textToTiptapContent(detail.content));
+ editor?.commands.setContent(
+ deserializeAdvancedTextEditorDocument({
+ serializedDocument: detail.content,
+ }),
+ );
}
},
[editor],
diff --git a/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.ts b/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.ts
index fd9bc024db3..9f17ec0b027 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.ts
@@ -15,6 +15,7 @@ import { threadIdCreatedFromDraftState } from '@/ai/states/threadIdCreatedFromDr
import { useUpdateMetadataStoreDraft } from '@/metadata-store/hooks/useUpdateMetadataStoreDraft';
import { type FlatAgentChatThread } from '@/metadata-store/types/FlatAgentChatThread';
import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
+import { tipTapDocumentToMarkdown } from 'twenty-shared/utils';
import { useMutation } from '@apollo/client/react';
import { CreateChatThreadDocument } from '~/generated-metadata/graphql';
@@ -72,15 +73,10 @@ export const useCreateAgentChatThread = () => {
store.set(shouldFocusChatEditorState.atom, true);
store.set(skipMessagesSkeletonUntilLoadedState.atom, true);
store.set(threadIdCreatedFromDraftState.atom, newThreadId);
- } else {
- setAgentChatDraftsByThreadId((previousDrafts) => ({
- ...previousDrafts,
- [previousDraftKey]: store.get(agentChatInputState.atom),
- }));
}
setCurrentAiChatThread(newThreadId);
- setAgentChatInput(newDraft);
+ setAgentChatInput(tipTapDocumentToMarkdown(newDraft));
},
onError: () => {
setIsCreatingChatThread(false);
diff --git a/packages/twenty-front/src/modules/ai/hooks/useDeleteChatThread.ts b/packages/twenty-front/src/modules/ai/hooks/useDeleteChatThread.ts
index 65b8bc7bbe5..e6f35a4f5c7 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useDeleteChatThread.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useDeleteChatThread.ts
@@ -14,6 +14,7 @@ import { useUpdateMetadataStoreDraft } from '@/metadata-store/hooks/useUpdateMet
import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';
import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
import { DeleteChatThreadDocument } from '~/generated-metadata/graphql';
+import { tipTapDocumentToMarkdown } from 'twenty-shared/utils';
export const useDeleteChatThread = () => {
const { removeFromDraft, applyChanges } = useUpdateMetadataStoreDraft();
@@ -48,11 +49,15 @@ export const useDeleteChatThread = () => {
const nextThreadId = remaining[0].id;
setCurrentAiChatThread(nextThreadId);
- setAgentChatInput(draftsByThreadId[nextThreadId] ?? '');
+ setAgentChatInput(
+ tipTapDocumentToMarkdown(draftsByThreadId[nextThreadId] ?? ''),
+ );
} else {
setCurrentAiChatThread(AGENT_CHAT_NEW_THREAD_DRAFT_KEY);
setAgentChatInput(
- draftsByThreadId[AGENT_CHAT_NEW_THREAD_DRAFT_KEY] ?? '',
+ tipTapDocumentToMarkdown(
+ draftsByThreadId[AGENT_CHAT_NEW_THREAD_DRAFT_KEY] ?? '',
+ ),
);
}
} catch (error) {
diff --git a/packages/twenty-front/src/modules/ai/hooks/useEnsureAgentChatThreadExistsForDraft.ts b/packages/twenty-front/src/modules/ai/hooks/useEnsureAgentChatThreadExistsForDraft.ts
index 3bf9d6a007a..e3e1c4ed735 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useEnsureAgentChatThreadExistsForDraft.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useEnsureAgentChatThreadExistsForDraft.ts
@@ -10,6 +10,7 @@ import { hasTriggeredCreateForDraftState } from '@/ai/states/hasTriggeredCreateF
import { isCreatingChatThreadState } from '@/ai/states/isCreatingChatThreadState';
import { pendingCreateFromDraftPromiseState } from '@/ai/states/pendingCreateFromDraftPromiseState';
import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
+import { tipTapDocumentToMarkdown } from 'twenty-shared/utils';
export const useEnsureAgentChatThreadExistsForDraft = (
createChatThread: () => Promise<any>,
@@ -32,7 +33,7 @@ export const useEnsureAgentChatThreadExistsForDraft = (
AGENT_CHAT_NEW_THREAD_DRAFT_KEY
] ?? '';
- if (draft.trim() === '') {
+ if (tipTapDocumentToMarkdown(draft).trim() === '') {
return;
}
diff --git a/packages/twenty-front/src/modules/ai/hooks/useOpenAskAiPageWithPreprompt.ts b/packages/twenty-front/src/modules/ai/hooks/useOpenAskAiPageWithPreprompt.ts
index 6ad2c30ab31..628b69c2c8f 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useOpenAskAiPageWithPreprompt.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useOpenAskAiPageWithPreprompt.ts
@@ -1,6 +1,7 @@
import { isDefined } from 'twenty-shared/utils';
import { useSwitchToNewAiChat } from '@/ai/hooks/useSwitchToNewAiChat';
+import { serializePlainTextAsAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializePlainTextAsAdvancedTextEditorDocument';
import {
AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
agentChatDraftsByThreadIdState,
@@ -48,7 +49,8 @@ export const useOpenAskAiPageWithPreprompt = () => {
setAgentChatDraftsByThreadId((prev) => ({
...prev,
- [AGENT_CHAT_NEW_THREAD_DRAFT_KEY]: text,
+ [AGENT_CHAT_NEW_THREAD_DRAFT_KEY]:
+ serializePlainTextAsAdvancedTextEditorDocument(text),
}));
setAgentChatPreprompt({ text, mode });
};
diff --git a/packages/twenty-front/src/modules/ai/hooks/useSwitchAgentChatThreadWithDraft.ts b/packages/twenty-front/src/modules/ai/hooks/useSwitchAgentChatThreadWithDraft.ts
index d7d7835c5fa..234b9f578cf 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useSwitchAgentChatThreadWithDraft.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useSwitchAgentChatThreadWithDraft.ts
@@ -4,34 +4,24 @@ import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';
import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
import { useStore } from 'jotai';
-import { isDefined } from 'twenty-shared/utils';
+import { tipTapDocumentToMarkdown } from 'twenty-shared/utils';
export const useSwitchAgentChatThreadWithDraft = () => {
const [currentAiChatThread, setCurrentAiChatThread] = useAtomState(
currentAiChatThreadState,
);
const setAgentChatInput = useSetAtomState(agentChatInputState);
- const setAgentChatDraftsByThreadId = useSetAtomState(
- agentChatDraftsByThreadIdState,
- );
const store = useStore();
const switchThreadWithDraft = (toThreadId: string) => {
const isSameThread = toThreadId === currentAiChatThread;
- if (isDefined(currentAiChatThread)) {
- setAgentChatDraftsByThreadId((prev) => ({
- ...prev,
- [currentAiChatThread]: store.get(agentChatInputState.atom),
- }));
- }
-
setCurrentAiChatThread(toThreadId);
if (!isSameThread) {
const destinationDraft =
store.get(agentChatDraftsByThreadIdState.atom)[toThreadId] ?? '';
- setAgentChatInput(destinationDraft);
+ setAgentChatInput(tipTapDocumentToMarkdown(destinationDraft));
}
};
diff --git a/packages/twenty-front/src/modules/ai/states/agentChatDraftsByThreadIdState.ts b/packages/twenty-front/src/modules/ai/states/agentChatDraftsByThreadIdState.ts
index 3a51c77f4ac..12db203824e 100644
--- a/packages/twenty-front/src/modules/ai/states/agentChatDraftsByThreadIdState.ts
+++ b/packages/twenty-front/src/modules/ai/states/agentChatDraftsByThreadIdState.ts
@@ -1,3 +1,4 @@
+import { isAgentChatDraftsByThreadId } from '@/ai/utils/isAgentChatDraftsByThreadId';
import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
export const AGENT_CHAT_NEW_THREAD_DRAFT_KEY = '__new__';
@@ -11,4 +12,5 @@ export const agentChatDraftsByThreadIdState = createAtomState<
defaultValue: {},
useLocalStorage: true,
localStorageOptions: { getOnInit: true },
+ validateInitFn: isAgentChatDraftsByThreadId,
});
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/isAgentChatDraftsByThreadId.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/isAgentChatDraftsByThreadId.test.ts
new file mode 100644
index 00000000000..fd8bc46c982
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/isAgentChatDraftsByThreadId.test.ts
@@ -0,0 +1,23 @@
+import { serializePlainTextAsAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializePlainTextAsAdvancedTextEditorDocument';
+import { isAgentChatDraftsByThreadId } from '@/ai/utils/isAgentChatDraftsByThreadId';
+
+describe('isAgentChatDraftsByThreadId', () => {
+ it('accepts empty and canonical drafts', () => {
+ expect(
+ isAgentChatDraftsByThreadId({
+ empty: '',
+ draft: serializePlainTextAsAdvancedTextEditorDocument('Hello'),
+ }),
+ ).toBe(true);
+ });
+
+ it('rejects legacy and malformed drafts', () => {
+ expect(
+ isAgentChatDraftsByThreadId({
+ draft: JSON.stringify({ type: 'doc', content: [] }),
+ }),
+ ).toBe(false);
+ expect(isAgentChatDraftsByThreadId({ draft: 'Hello' })).toBe(false);
+ expect(isAgentChatDraftsByThreadId([])).toBe(false);
+ });
+});
diff --git a/packages/twenty-front/src/modules/ai/utils/formatChatReference.ts b/packages/twenty-front/src/modules/ai/utils/formatChatReference.ts
index 272f69d8130..debbb46bc61 100644
--- a/packages/twenty-front/src/modules/ai/utils/formatChatReference.ts
+++ b/packages/twenty-front/src/modules/ai/utils/formatChatReference.ts
@@ -1,8 +1,14 @@
import { type ChatReferenceIdentity } from '@/ai/types/ChatReferenceIdentity';
import { getChatReferenceCloseTag } from '@/ai/utils/getChatReferenceCloseTag';
import { getChatReferenceIdentitySegment } from '@/ai/utils/getChatReferenceIdentitySegment';
+import { formatRecordReference } from 'twenty-shared/ai';
export const formatChatReference = (
reference: ChatReferenceIdentity & { displayName: string },
-): string =>
- `[[${reference.kind}:${getChatReferenceIdentitySegment(reference)}:${reference.displayName}${getChatReferenceCloseTag(reference.kind)}`;
+): string => {
+ if (reference.kind === 'record') {
+ return formatRecordReference(reference);
+ }
+
+ return `[[${reference.kind}:${getChatReferenceIdentitySegment(reference)}:${reference.displayName}${getChatReferenceCloseTag(reference.kind)}`;
+};
diff --git a/packages/twenty-front/src/modules/ai/utils/formatRecordReference.ts b/packages/twenty-front/src/modules/ai/utils/formatRecordReference.ts
index 457f37e00f0..04ac9e55ace 100644
--- a/packages/twenty-front/src/modules/ai/utils/formatRecordReference.ts
+++ b/packages/twenty-front/src/modules/ai/utils/formatRecordReference.ts
@@ -1,17 +1 @@
-import { formatChatReference } from '@/ai/utils/formatChatReference';
-
-export const formatRecordReference = ({
- objectNameSingular,
- recordId,
- displayName,
-}: {
- objectNameSingular: string;
- recordId: string;
- displayName: string;
-}): string =>
- formatChatReference({
- kind: 'record',
- objectNameSingular,
- recordId,
- displayName,
- });
+export { formatRecordReference } from 'twenty-shared/ai';
diff --git a/packages/twenty-front/src/modules/ai/utils/isAgentChatDraftsByThreadId.ts b/packages/twenty-front/src/modules/ai/utils/isAgentChatDraftsByThreadId.ts
new file mode 100644
index 00000000000..2ae454394ce
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/isAgentChatDraftsByThreadId.ts
@@ -0,0 +1,15 @@
+import { parseCanonicalTipTapJsonDocument } from 'twenty-shared/utils';
+
+export const isAgentChatDraftsByThreadId = (
+ value: unknown,
+): value is Record<string, string> => {
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
+ return false;
+ }
+
+ return Object.values(value).every(
+ (draft) =>
+ typeof draft === 'string' &&
+ (draft === '' || parseCanonicalTipTapJsonDocument(draft) !== undefined),
+ );
+};
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormAddressFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormAddressFieldInput.tsx
index 2d1aa28505d..65565664a44 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormAddressFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormAddressFieldInput.tsx
@@ -1,5 +1,5 @@
import { FormCountrySelectInput } from '@/object-record/record-field/ui/form-types/components/FormCountrySelectInput';
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormNestedFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormNestedFieldInputContainer';
import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
import { type VariablePickerComponent } from '@/object-record/record-field/ui/form-types/types/VariablePickerComponent';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormArrayFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormArrayFieldInput.tsx
index 1a9a4e52603..1d5a68dfb90 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormArrayFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormArrayFieldInput.tsx
@@ -1,4 +1,4 @@
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormFieldInputInnerContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputInnerContainer';
import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputRowContainer';
import { FormFieldPlaceholder } from '@/object-record/record-field/ui/form-types/components/FormFieldPlaceholder';
@@ -21,7 +21,7 @@ import { usePushFocusItemToFocusStack } from '@/ui/utilities/focus/hooks/usePush
import { useRemoveFocusItemFromFocusStackById } from '@/ui/utilities/focus/hooks/useRemoveFocusItemFromFocusStackById';
import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentType';
import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
+import { isStandaloneVariableString } from 'twenty-shared/workflow';
import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
import { isNonEmptyArray } from '@sniptt/guards';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormBooleanFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormBooleanFieldInput.tsx
index 76fb7fe342f..a0036dd2067 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormBooleanFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormBooleanFieldInput.tsx
@@ -1,4 +1,4 @@
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormFieldInputInnerContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputInnerContainer';
import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputRowContainer';
import { VariableChipStandalone } from '@/object-record/record-field/ui/form-types/components/VariableChipStandalone';
@@ -7,7 +7,7 @@ import { InputLabel } from '@/ui/input/components/InputLabel';
import { Select } from '@/ui/input/components/Select';
import { GenericDropdownContentWidth } from '@/ui/layout/dropdown/constants/GenericDropdownContentWidth';
import { useRemoveFocusItemFromFocusStackById } from '@/ui/utilities/focus/hooks/useRemoveFocusItemFromFocusStackById';
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
+import { isStandaloneVariableString } from 'twenty-shared/workflow';
import { useLingui } from '@lingui/react/macro';
import { useContext, useId, useState } from 'react';
import { isDefined } from 'twenty-shared/utils';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormBooleanFieldToggleInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormBooleanFieldToggleInput.tsx
index 59ad6576fa4..a0841c927a8 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormBooleanFieldToggleInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormBooleanFieldToggleInput.tsx
@@ -1,4 +1,4 @@
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormFieldInputInnerContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputInnerContainer';
import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputRowContainer';
import { InputHint } from '@/ui/input/components/InputHint';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormCallingCodeSelectInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormCallingCodeSelectInput.tsx
index 42f3d6fbe0c..bbca952b345 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormCallingCodeSelectInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormCallingCodeSelectInput.tsx
@@ -3,7 +3,7 @@ import { useMemo } from 'react';
import { FormSelectFieldInput } from '@/object-record/record-field/ui/form-types/components/FormSelectFieldInput';
import { type VariablePickerComponent } from '@/object-record/record-field/ui/form-types/types/VariablePickerComponent';
import { useCountries } from '@/ui/input/components/internal/hooks/useCountries';
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
+import { isStandaloneVariableString } from 'twenty-shared/workflow';
import { t } from '@lingui/core/macro';
import { IconCircleOff, type IconComponentProps } from 'twenty-ui/icon';
import { type SelectOption } from 'twenty-ui/input';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormCurrencyFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormCurrencyFieldInput.tsx
index 19becd6dcf1..299a7d61cf4 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormCurrencyFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormCurrencyFieldInput.tsx
@@ -1,4 +1,4 @@
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormNestedFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormNestedFieldInputContainer';
import { FormNumberFieldInput } from '@/object-record/record-field/ui/form-types/components/FormNumberFieldInput';
import { FormSelectFieldInput } from '@/object-record/record-field/ui/form-types/components/FormSelectFieldInput';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormDateFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormDateFieldInput.tsx
index 04e858bfc79..aa46feed04f 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormDateFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormDateFieldInput.tsx
@@ -1,4 +1,4 @@
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormFieldInputInnerContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputInnerContainer';
import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputRowContainer';
import { VariableChipStandalone } from '@/object-record/record-field/ui/form-types/components/VariableChipStandalone';
@@ -17,7 +17,7 @@ import { OverlayContainer } from '@/ui/layout/overlay/components/OverlayContaine
import { useHotkeysOnFocusedElement } from '@/ui/utilities/hotkey/hooks/useHotkeysOnFocusedElement';
import { useListenClickOutside } from '@/ui/utilities/pointer-event/hooks/useListenClickOutside';
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
+import { isStandaloneVariableString } from 'twenty-shared/workflow';
import {
FloatingPortal,
autoUpdate,
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormDateTimeFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormDateTimeFieldInput.tsx
index dae7b3d5da0..035a08fae1d 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormDateTimeFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormDateTimeFieldInput.tsx
@@ -1,4 +1,4 @@
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormFieldInputInnerContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputInnerContainer';
import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputRowContainer';
import { VariableChipStandalone } from '@/object-record/record-field/ui/form-types/components/VariableChipStandalone';
@@ -19,7 +19,7 @@ import { useHotkeysOnFocusedElement } from '@/ui/utilities/hotkey/hooks/useHotke
import { ParentClickOutsideIdContext } from '@/ui/utilities/pointer-event/contexts/ParentClickOutsideIdContext';
import { useListenClickOutside } from '@/ui/utilities/pointer-event/hooks/useListenClickOutside';
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
+import { isStandaloneVariableString } from 'twenty-shared/workflow';
import {
FloatingPortal,
autoUpdate,
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormEmailsFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormEmailsFieldInput.tsx
index 6918dd33c2c..3035054fc58 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormEmailsFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormEmailsFieldInput.tsx
@@ -1,4 +1,4 @@
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormNestedFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormNestedFieldInputContainer';
import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
import { type VariablePickerComponent } from '@/object-record/record-field/ui/form-types/types/VariablePickerComponent';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormFieldPlaceholder.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormFieldPlaceholder.tsx
index 1a8e1ec5c2c..b7ec010f759 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormFieldPlaceholder.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormFieldPlaceholder.tsx
@@ -1,4 +1,4 @@
-import { FORM_FIELD_PLACEHOLDER_STYLES } from '@/object-record/record-field/ui/form-types/constants/FormFieldPlaceholderStyles';
+import { FORM_FIELD_PLACEHOLDER_STYLES } from '@/ui/input/constants/FormFieldPlaceholderStyles';
import { styled } from '@linaria/react';
const StyledPlaceholder = styled.div`
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormFilesFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormFilesFieldInput.tsx
index 9910380d59a..73d02ed194f 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormFilesFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormFilesFieldInput.tsx
@@ -1,4 +1,4 @@
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormFieldInputInnerContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputInnerContainer';
import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputRowContainer';
import { TextVariableEditor } from '@/object-record/record-field/ui/form-types/components/TextVariableEditor';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormFullNameFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormFullNameFieldInput.tsx
index 2b263d66ba0..6c47b5df7c0 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormFullNameFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormFullNameFieldInput.tsx
@@ -1,5 +1,5 @@
import { t } from '@lingui/core/macro';
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormNestedFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormNestedFieldInputContainer';
import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
import { type VariablePickerComponent } from '@/object-record/record-field/ui/form-types/types/VariablePickerComponent';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormLinksFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormLinksFieldInput.tsx
index 1fd703792eb..5b3833a5ce1 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormLinksFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormLinksFieldInput.tsx
@@ -1,5 +1,5 @@
import { t } from '@lingui/core/macro';
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormNestedFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormNestedFieldInputContainer';
import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
import { type VariablePickerComponent } from '@/object-record/record-field/ui/form-types/types/VariablePickerComponent';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMorphRelationToOneFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMorphRelationToOneFieldInput.tsx
index 96042b9b79f..2207a225107 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMorphRelationToOneFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMorphRelationToOneFieldInput.tsx
@@ -1,7 +1,7 @@
import { useObjectMetadataItems } from '@/object-metadata/hooks/useObjectMetadataItems';
import { type FieldMetadataItemRelation } from '@/object-metadata/types/FieldMetadataItemRelation';
import { useObjectPermissions } from '@/object-record/hooks/useObjectPermissions';
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormFieldInputInnerContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputInnerContainer';
import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputRowContainer';
import { FormFieldPlaceholder } from '@/object-record/record-field/ui/form-types/components/FormFieldPlaceholder';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMultiRecordFieldChips.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMultiRecordFieldChips.tsx
index 8da9f570d6d..1e23c325d7f 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMultiRecordFieldChips.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMultiRecordFieldChips.tsx
@@ -4,7 +4,7 @@ import { VariableChipStandalone } from '@/object-record/record-field/ui/form-typ
import { type FormMultiRecordPickerDraftValue } from '@/object-record/record-field/ui/form-types/utils/getFormMultiRecordPickerDraftValue';
import { type ObjectRecord } from '@/object-record/types/ObjectRecord';
import { ExpandableList } from '@/ui/layout/expandable-list/components/ExpandableList';
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
+import { isStandaloneVariableString } from 'twenty-shared/workflow';
import { styled } from '@linaria/react';
import { t } from '@lingui/core/macro';
import { isNonEmptyArray } from '@sniptt/guards';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMultiRecordPicker.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMultiRecordPicker.tsx
index ae5d2843b74..a7d69940aae 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMultiRecordPicker.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMultiRecordPicker.tsx
@@ -1,5 +1,5 @@
import { useFindManyRecords } from '@/object-record/hooks/useFindManyRecords';
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormFieldInputInnerContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputInnerContainer';
import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputRowContainer';
import { FormMultiRecordFieldChips } from '@/object-record/record-field/ui/form-types/components/FormMultiRecordFieldChips';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMultiSelectFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMultiSelectFieldInput.tsx
index 164039561b2..476d0a5ed74 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMultiSelectFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMultiSelectFieldInput.tsx
@@ -1,7 +1,7 @@
import { styled } from '@linaria/react';
import { t } from '@lingui/core/macro';
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormFieldInputInnerContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputInnerContainer';
import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputRowContainer';
import { FormFieldPlaceholder } from '@/object-record/record-field/ui/form-types/components/FormFieldPlaceholder';
@@ -18,7 +18,7 @@ import { OverlayContainer } from '@/ui/layout/overlay/components/OverlayContaine
import { usePushFocusItemToFocusStack } from '@/ui/utilities/focus/hooks/usePushFocusItemToFocusStack';
import { useRemoveFocusItemFromFocusStackById } from '@/ui/utilities/focus/hooks/useRemoveFocusItemFromFocusStackById';
import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentType';
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
+import { isStandaloneVariableString } from 'twenty-shared/workflow';
import { isArray } from '@sniptt/guards';
import { useContext, useId, useState } from 'react';
import { isDefined } from 'twenty-shared/utils';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMultiTextFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMultiTextFieldInput.tsx
index ab31cb4ccac..596d9e28c0e 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMultiTextFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMultiTextFieldInput.tsx
@@ -1,4 +1,4 @@
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormFieldInputInnerContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputInnerContainer';
import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputRowContainer';
import { TextVariableEditor } from '@/object-record/record-field/ui/form-types/components/TextVariableEditor';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormNumberFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormNumberFieldInput.tsx
index 979732eafdc..354f9f627a3 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormNumberFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormNumberFieldInput.tsx
@@ -1,4 +1,4 @@
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormFieldInputInnerContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputInnerContainer';
import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputRowContainer';
import { VariableChipStandalone } from '@/object-record/record-field/ui/form-types/components/VariableChipStandalone';
@@ -6,7 +6,7 @@ import { type VariablePickerComponent } from '@/object-record/record-field/ui/fo
import { TextInput } from '@/ui/field/input/components/TextInput';
import { InputHint } from '@/ui/input/components/InputHint';
import { InputLabel } from '@/ui/input/components/InputLabel';
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
+import { isStandaloneVariableString } from 'twenty-shared/workflow';
import { t } from '@lingui/core/macro';
import isEmpty from 'lodash.isempty';
import { useId, useState } from 'react';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormPhoneFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormPhoneFieldInput.tsx
index a2f189472b9..285de416328 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormPhoneFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormPhoneFieldInput.tsx
@@ -2,7 +2,7 @@ import {
FormCallingCodeSelectInput,
type FormCallingCodeSelectInputUpdatedValue,
} from '@/object-record/record-field/ui/form-types/components/FormCallingCodeSelectInput';
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormNestedFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormNestedFieldInputContainer';
import { FormNumberFieldInput } from '@/object-record/record-field/ui/form-types/components/FormNumberFieldInput';
import { type VariablePickerComponent } from '@/object-record/record-field/ui/form-types/types/VariablePickerComponent';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormRawJsonFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormRawJsonFieldInput.tsx
index 68ba71af116..423f7d7fc59 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormRawJsonFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormRawJsonFieldInput.tsx
@@ -1,5 +1,5 @@
import { t } from '@lingui/core/macro';
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormFieldInputInnerContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputInnerContainer';
import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputRowContainer';
import { TextVariableEditor } from '@/object-record/record-field/ui/form-types/components/TextVariableEditor';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormRichTextFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormRichTextFieldInput.tsx
index c3b30ded0ec..1283cf9f6a8 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormRichTextFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormRichTextFieldInput.tsx
@@ -1,6 +1,8 @@
-import { FormAdvancedTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormAdvancedTextFieldInput';
+import { FormAdvancedTextFieldInput } from '@/advanced-text-editor/components/FormAdvancedTextFieldInput';
+import { RECORD_RICH_TEXT_EDITOR_PROFILE } from '@/object-record/record-field/ui/form-types/constants/RecordRichTextEditorProfile';
import { type VariablePickerComponent } from '@/object-record/record-field/ui/form-types/types/VariablePickerComponent';
import { type FieldRichTextValue } from '@/object-record/record-field/ui/types/FieldMetadata';
+import { convertTipTapDocumentToBlockNote } from '@/object-record/record-field/ui/form-types/utils/convertTipTapDocumentToBlockNote';
type FormRichTextFieldInputProps = {
label?: string;
@@ -14,18 +16,6 @@ type FormRichTextFieldInputProps = {
VariablePicker?: VariablePickerComponent;
};
-const mapTipTapToBlockNote = (tiptapJson: string): string => {
- try {
- const json = JSON.parse(tiptapJson);
- if (json.type === 'doc' && Array.isArray(json.content)) {
- return JSON.stringify(json.content);
- }
- return tiptapJson;
- } catch {
- return tiptapJson;
- }
-};
-
export const FormRichTextFieldInput = ({
label,
error,
@@ -38,7 +28,9 @@ export const FormRichTextFieldInput = ({
}: FormRichTextFieldInputProps) => {
const handleChange = (value: string) => {
onChange({
- blocknote: mapTipTapToBlockNote(value),
+ // RICH_TEXT still exposes the legacy BlockNote array contract. Keep the
+ // compatibility projection here until that field is migrated to TipTap.
+ blocknote: convertTipTapDocumentToBlockNote(value),
markdown: null,
});
};
@@ -53,7 +45,7 @@ export const FormRichTextFieldInput = ({
onChange={handleChange}
readonly={readonly}
VariablePicker={VariablePicker}
- preset="recordRichTextField"
+ profile={RECORD_RICH_TEXT_EDITOR_PROFILE}
/>
);
};
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormSelectFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormSelectFieldInput.tsx
index 06477fce6dc..eb15c89d35b 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormSelectFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormSelectFieldInput.tsx
@@ -1,5 +1,5 @@
import { t } from '@lingui/core/macro';
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormFieldInputInnerContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputInnerContainer';
import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputRowContainer';
import { VariableChipStandalone } from '@/object-record/record-field/ui/form-types/components/VariableChipStandalone';
@@ -10,7 +10,7 @@ import { type CallToActionButton, Select } from '@/ui/input/components/Select';
import { GenericDropdownContentWidth } from '@/ui/layout/dropdown/constants/GenericDropdownContentWidth';
import { useRemoveFocusItemFromFocusStackById } from '@/ui/utilities/focus/hooks/useRemoveFocusItemFromFocusStackById';
import { useHotkeysOnFocusedElement } from '@/ui/utilities/hotkey/hooks/useHotkeysOnFocusedElement';
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
+import { isStandaloneVariableString } from 'twenty-shared/workflow';
import { useContext, useId, useState } from 'react';
import { Key } from 'ts-key-enum';
import { isNonEmptyString } from '@sniptt/guards';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormSingleRecordFieldChip.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormSingleRecordFieldChip.tsx
index 92b74e28f02..06bb1e2cbcf 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormSingleRecordFieldChip.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormSingleRecordFieldChip.tsx
@@ -6,7 +6,7 @@ import {
} from '@/object-record/record-field/ui/form-types/types/RecordPickerValue';
import { VariableChipStandalone } from '@/object-record/record-field/ui/form-types/components/VariableChipStandalone';
import { type ObjectRecord } from '@/object-record/types/ObjectRecord';
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
+import { isStandaloneVariableString } from 'twenty-shared/workflow';
import { styled } from '@linaria/react';
import { t } from '@lingui/core/macro';
import { isDefined } from 'twenty-shared/utils';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormSingleRecordPicker.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormSingleRecordPicker.tsx
index 82ae2379286..0c4a182f490 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormSingleRecordPicker.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormSingleRecordPicker.tsx
@@ -1,5 +1,5 @@
import { useFindOneRecord } from '@/object-record/hooks/useFindOneRecord';
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormFieldInputInnerContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputInnerContainer';
import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputRowContainer';
import { FormSingleRecordFieldChip } from '@/object-record/record-field/ui/form-types/components/FormSingleRecordFieldChip';
@@ -17,7 +17,7 @@ import { Dropdown } from '@/ui/layout/dropdown/components/Dropdown';
import { GenericDropdownContentWidth } from '@/ui/layout/dropdown/constants/GenericDropdownContentWidth';
import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';
import { useSetAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useSetAtomComponentState';
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
+import { isStandaloneVariableString } from 'twenty-shared/workflow';
import { styled } from '@linaria/react';
import { t } from '@lingui/core/macro';
import { useCallback, useContext, useId } from 'react';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormTextFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormTextFieldInput.tsx
index 536c8982769..6bead74630f 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormTextFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormTextFieldInput.tsx
@@ -1,5 +1,5 @@
import { t } from '@lingui/core/macro';
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormFieldInputInnerContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputInnerContainer';
import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputRowContainer';
import { TextVariableEditor } from '@/object-record/record-field/ui/form-types/components/TextVariableEditor';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormUuidFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormUuidFieldInput.tsx
index 577ebf70187..69886bf2b38 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormUuidFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormUuidFieldInput.tsx
@@ -1,11 +1,11 @@
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormFieldInputInnerContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputInnerContainer';
import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputRowContainer';
import { VariableChipStandalone } from '@/object-record/record-field/ui/form-types/components/VariableChipStandalone';
import { type VariablePickerComponent } from '@/object-record/record-field/ui/form-types/types/VariablePickerComponent';
import { TextInput } from '@/ui/field/input/components/TextInput';
import { InputLabel } from '@/ui/input/components/InputLabel';
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
+import { isStandaloneVariableString } from 'twenty-shared/workflow';
import { t } from '@lingui/core/macro';
import { useId, useState } from 'react';
import { isDefined } from 'twenty-shared/utils';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormWorkspaceMemberFilterValueInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormWorkspaceMemberFilterValueInput.tsx
index 146a4ad874b..a0bdc0136a3 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormWorkspaceMemberFilterValueInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormWorkspaceMemberFilterValueInput.tsx
@@ -16,7 +16,7 @@ import { type JsonValue } from 'type-fest';
import { MAX_WORKSPACE_MEMBERS_TO_DISPLAY } from '@/object-record/object-filter-dropdown/components/ObjectFilterDropdownActorSelect';
import { CURRENT_WORKSPACE_MEMBER_SELECTABLE_ITEM_ID } from '@/object-record/object-filter-dropdown/constants/CurrentWorkspaceMemberSelectableItemId';
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormFieldInputInnerContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputInnerContainer';
import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputRowContainer';
import { FormWorkspaceMemberFilterValueInputDropdownContent } from '@/object-record/record-field/ui/form-types/components/FormWorkspaceMemberFilterValueInputDropdownContent';
@@ -31,7 +31,7 @@ import { useRecordsForSelect } from '@/object-record/select/hooks/useRecordsForS
import { type SelectableItem } from '@/object-record/select/types/SelectableItem';
import { InputLabel } from '@/ui/input/components/InputLabel';
import { Dropdown } from '@/ui/layout/dropdown/components/Dropdown';
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
+import { isStandaloneVariableString } from 'twenty-shared/workflow';
const StyledFormSelectContainerWrapper = styled.div<{ readonly?: boolean }>`
cursor: ${({ readonly }) => (readonly ? 'default' : 'pointer')};
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/TextVariableEditor.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/TextVariableEditor.tsx
index de2d05ee06f..b3052f51e5f 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/TextVariableEditor.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/TextVariableEditor.tsx
@@ -1,4 +1,4 @@
-import { FORM_FIELD_PLACEHOLDER_STYLES } from '@/object-record/record-field/ui/form-types/constants/FormFieldPlaceholderStyles';
+import { FORM_FIELD_PLACEHOLDER_STYLES } from '@/ui/input/constants/FormFieldPlaceholderStyles';
import { styled } from '@linaria/react';
import { EditorContent, type Editor } from '@tiptap/react';
import { themeCssVariables } from 'twenty-ui/theme-constants';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/VariableChip.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/VariableChip.tsx
index 2ebd71b5115..a12948fbd17 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/VariableChip.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/VariableChip.tsx
@@ -1,4 +1,4 @@
-import { BaseChip } from '@/object-record/record-field/ui/form-types/components/BaseChip';
+import { BaseChip } from '@/ui/input/components/BaseChip';
import { useSearchVariable } from '@/workflow/workflow-variables/hooks/useSearchVariable';
import { useLingui } from '@lingui/react/macro';
import { useContext } from 'react';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/constants/RecordRichTextEditorProfile.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/constants/RecordRichTextEditorProfile.ts
new file mode 100644
index 00000000000..67dbc85413f
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/constants/RecordRichTextEditorProfile.ts
@@ -0,0 +1,15 @@
+import { type AdvancedTextEditorProfile } from '@/advanced-text-editor/types/AdvancedTextEditorProfile';
+import { buildFullRichTextExtensions } from '@/advanced-text-editor/utils/buildFullRichTextExtensions';
+import { parseLegacyRecordRichTextDocument } from '@/object-record/record-field/ui/form-types/utils/parseLegacyRecordRichTextDocument';
+import { WorkflowVariableTag } from '@/workflow/workflow-variables/extensions/WorkflowVariableTag';
+
+export const RECORD_RICH_TEXT_EDITOR_PROFILE = {
+ chrome: 'field',
+ minHeight: 340,
+ enableFullScreen: true,
+ parseLegacyDocument: parseLegacyRecordRichTextDocument,
+ buildExtensions: (context) => [
+ ...buildFullRichTextExtensions(context),
+ WorkflowVariableTag,
+ ],
+} satisfies AdvancedTextEditorProfile;
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/hooks/useMultiItemFieldEditor.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/hooks/useMultiItemFieldEditor.ts
index 6b99770a568..f84b9aea3ea 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/hooks/useMultiItemFieldEditor.ts
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/hooks/useMultiItemFieldEditor.ts
@@ -1,7 +1,6 @@
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
import { getMultiItemFieldEditorContent } from '@/workflow/workflow-variables/utils/getMultiItemFieldEditorContent';
+import { WorkflowVariableTag } from '@/workflow/workflow-variables/extensions/WorkflowVariableTag';
import { TextTag } from '@/workflow/workflow-variables/utils/textTag';
-import { VariableTag } from '@/workflow/workflow-variables/utils/variableTag';
import { Extension } from '@tiptap/core';
import Document from '@tiptap/extension-document';
import Paragraph from '@tiptap/extension-paragraph';
@@ -11,6 +10,7 @@ import { UndoRedo } from '@tiptap/extensions/undo-redo';
import { Plugin, PluginKey } from '@tiptap/pm/state';
import { type Editor, useEditor } from '@tiptap/react';
import { isDefined } from 'twenty-shared/utils';
+import { isStandaloneVariableString } from 'twenty-shared/workflow';
type UseMultiItemFieldEditorProps = {
placeholder: string | undefined;
@@ -137,7 +137,7 @@ export const useMultiItemFieldEditor = ({
Placeholder.configure({
placeholder,
}),
- VariableTag,
+ WorkflowVariableTag,
TextTag,
CommaToTagExtension,
UndoRedo,
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/hooks/useTextVariableEditor.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/hooks/useTextVariableEditor.ts
index 9ca1599af3d..83813b8a241 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/hooks/useTextVariableEditor.ts
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/hooks/useTextVariableEditor.ts
@@ -1,5 +1,5 @@
-import { getInitialEditorContent } from '@/workflow/workflow-variables/utils/getInitialEditorContent';
-import { VariableTag } from '@/workflow/workflow-variables/utils/variableTag';
+import { getInitialEditorContent } from '@/advanced-text-editor/utils/getInitialEditorContent';
+import { WorkflowVariableTag } from '@/workflow/workflow-variables/extensions/WorkflowVariableTag';
import Document from '@tiptap/extension-document';
import HardBreak from '@tiptap/extension-hard-break';
import Paragraph from '@tiptap/extension-paragraph';
@@ -48,7 +48,7 @@ export const useTextVariableEditor = ({
Placeholder.configure({
placeholder,
}),
- VariableTag,
+ WorkflowVariableTag,
...(multiline
? [
HardBreak.configure({
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/types/VariablePickerComponent.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/types/VariablePickerComponent.ts
index f4807aa4592..5449c21f363 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/types/VariablePickerComponent.ts
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/types/VariablePickerComponent.ts
@@ -1,9 +1 @@
-export type VariablePickerComponent = React.FC<{
- instanceId: string;
- disabled?: boolean;
- multiline?: boolean;
- onVariableSelect: (variableName: string) => void;
- shouldDisplayRecordObjects?: boolean;
- shouldDisplayRecordFields?: boolean;
- objectNameSingularsToSelect?: string[];
-}>;
+export type { VariablePickerComponent } from '@/ui/input/types/VariablePickerComponent';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/utils/__tests__/recordRichTextDocumentCompatibility.test.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/utils/__tests__/recordRichTextDocumentCompatibility.test.ts
new file mode 100644
index 00000000000..71929f97b26
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/utils/__tests__/recordRichTextDocumentCompatibility.test.ts
@@ -0,0 +1,72 @@
+import { convertTipTapDocumentToBlockNote } from '@/object-record/record-field/ui/form-types/utils/convertTipTapDocumentToBlockNote';
+import { parseLegacyRecordRichTextDocument } from '@/object-record/record-field/ui/form-types/utils/parseLegacyRecordRichTextDocument';
+
+describe('record rich-text document compatibility', () => {
+ it('projects canonical documents to the legacy content-array shape', () => {
+ const content = [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'Hello' }],
+ },
+ ];
+
+ expect(
+ JSON.parse(
+ convertTipTapDocumentToBlockNote(
+ JSON.stringify({
+ type: 'doc',
+ attrs: { schemaVersion: 1 },
+ content,
+ }),
+ ),
+ ),
+ ).toEqual(content);
+ });
+
+ it('preserves unknown legacy values at the write boundary', () => {
+ expect(convertTipTapDocumentToBlockNote('legacy markdown')).toBe(
+ 'legacy markdown',
+ );
+ });
+
+ it('reads the legacy content-array shape', () => {
+ const content = [{ type: 'paragraph', content: [] }];
+
+ expect(parseLegacyRecordRichTextDocument(JSON.stringify(content))).toEqual({
+ type: 'doc',
+ content,
+ });
+ });
+
+ it('normalizes permissive legacy BlockNote string content', () => {
+ const content = [
+ { type: 'paragraph', content: 'Legacy BlockNote plain content' },
+ ];
+
+ expect(parseLegacyRecordRichTextDocument(JSON.stringify(content))).toEqual({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'Legacy BlockNote plain content' }],
+ },
+ ],
+ });
+ });
+
+ it('does not pass malformed legacy blocks to the editor', () => {
+ const serializedDocument = JSON.stringify([
+ { type: 'paragraph', marks: 'invalid' },
+ ]);
+
+ expect(parseLegacyRecordRichTextDocument(serializedDocument)).toEqual({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: serializedDocument }],
+ },
+ ],
+ });
+ });
+});
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/utils/convertTipTapDocumentToBlockNote.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/utils/convertTipTapDocumentToBlockNote.ts
new file mode 100644
index 00000000000..4ec1c2193f0
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/utils/convertTipTapDocumentToBlockNote.ts
@@ -0,0 +1,11 @@
+import { parseTipTapJsonDocument } from 'twenty-shared/utils';
+
+export const convertTipTapDocumentToBlockNote = (
+ serializedDocument: string,
+): string => {
+ const document = parseTipTapJsonDocument(serializedDocument);
+
+ return document === undefined
+ ? serializedDocument
+ : JSON.stringify(document.content ?? []);
+};
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/utils/getFormMultiRecordPickerDraftValue.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/utils/getFormMultiRecordPickerDraftValue.ts
index ce075445c73..3bf5c98ba98 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/utils/getFormMultiRecordPickerDraftValue.ts
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/utils/getFormMultiRecordPickerDraftValue.ts
@@ -2,7 +2,7 @@ import {
type RecordId,
type Variable,
} from '@/object-record/record-field/ui/form-types/types/RecordPickerValue';
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
+import { isStandaloneVariableString } from 'twenty-shared/workflow';
import { isArray, isNonEmptyString, isString } from '@sniptt/guards';
import { isValidUuid } from 'twenty-shared/utils';
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/utils/parseLegacyRecordRichTextDocument.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/utils/parseLegacyRecordRichTextDocument.ts
new file mode 100644
index 00000000000..5856a478864
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/utils/parseLegacyRecordRichTextDocument.ts
@@ -0,0 +1,49 @@
+import { getInitialEditorContent } from '@/advanced-text-editor/utils/getInitialEditorContent';
+import { type Content } from '@tiptap/core';
+import { isTipTapNode, type TipTapNode } from 'twenty-shared/utils';
+
+const normalizeLegacyBlockContent = (value: unknown): unknown => {
+ if (Array.isArray(value)) {
+ return value.map(normalizeLegacyBlockContent);
+ }
+
+ if (typeof value !== 'object' || value === null || !('content' in value)) {
+ return value;
+ }
+
+ const content = value.content;
+
+ if (typeof content === 'string') {
+ return {
+ ...value,
+ content: [{ type: 'text', text: content }],
+ };
+ }
+
+ return Array.isArray(content)
+ ? { ...value, content: content.map(normalizeLegacyBlockContent) }
+ : value;
+};
+
+const isTipTapNodeArray = (value: unknown): value is TipTapNode[] =>
+ Array.isArray(value) && value.every(isTipTapNode);
+
+const tryParseJson = (value: string): unknown => {
+ try {
+ return JSON.parse(value);
+ } catch {
+ return undefined;
+ }
+};
+
+export const parseLegacyRecordRichTextDocument = (
+ serializedDocument: string,
+): Content => {
+ const blocks = normalizeLegacyBlockContent(tryParseJson(serializedDocument));
+
+ if (isTipTapNodeArray(blocks)) {
+ return { type: 'doc', content: blocks };
+ }
+
+ return getInitialEditorContent(serializedDocument);
+};
diff --git a/packages/twenty-front/src/modules/object-record/record-filter/hooks/useGetRecordFilterDisplayValue.ts b/packages/twenty-front/src/modules/object-record/record-filter/hooks/useGetRecordFilterDisplayValue.ts
index 1410f15ae8f..276cd63d246 100644
--- a/packages/twenty-front/src/modules/object-record/record-filter/hooks/useGetRecordFilterDisplayValue.ts
+++ b/packages/twenty-front/src/modules/object-record/record-filter/hooks/useGetRecordFilterDisplayValue.ts
@@ -10,7 +10,7 @@ import { RecordFilterOperand } from '@/object-record/record-filter/types/RecordF
import { isRecordFilterConsideredEmpty } from '@/object-record/record-filter/utils/isRecordFilterConsideredEmpty';
import { useUserTimezone } from '@/ui/input/components/internal/date/hooks/useUserTimezone';
import { getTimezoneAbbreviationForZonedDateTime } from '@/ui/input/components/internal/date/utils/getTimeZoneAbbreviationForZonedDateTime';
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
+import { isStandaloneVariableString } from 'twenty-shared/workflow';
import { type Nullable } from 'twenty-shared/types';
import {
diff --git a/packages/twenty-front/src/modules/side-panel/pages/email-block-settings/components/EmailBlockSettingsFieldInput.tsx b/packages/twenty-front/src/modules/side-panel/pages/email-block-settings/components/EmailBlockSettingsFieldInput.tsx
index 7e72b2ec7cc..c2bf0634a1e 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/email-block-settings/components/EmailBlockSettingsFieldInput.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/email-block-settings/components/EmailBlockSettingsFieldInput.tsx
@@ -1,6 +1,6 @@
import { useLingui } from '@lingui/react/macro';
-import { type MessageDescriptor } from '@lingui/core';
+import { type AdvancedTextEditorBlockSetting } from '@/advanced-text-editor/types/AdvancedTextEditorBlockCatalog';
import { EmailAlignmentInput } from '@/side-panel/pages/email-block-settings/components/EmailAlignmentInput';
import { EmailColorInput } from '@/side-panel/pages/email-block-settings/components/EmailColorInput';
import { EmailSizeInput } from '@/side-panel/pages/email-block-settings/components/EmailSizeInput';
@@ -8,20 +8,11 @@ import { StyledEmailFieldLabel } from '@/side-panel/pages/email-block-settings/c
import { TextArea } from '@/ui/input/components/TextArea';
import { TextInput } from '@/ui/input/components/TextInput';
-export type EmailStyleFieldKind =
- | 'text'
- | 'color'
- | 'box'
- | 'size'
- | 'alignment'
- | 'textarea';
-
type EmailBlockSettingsFieldInputProps = {
- field: {
- label: MessageDescriptor;
- input: EmailStyleFieldKind;
- placeholder?: string;
- };
+ field: Pick<
+ AdvancedTextEditorBlockSetting,
+ 'label' | 'input' | 'placeholder'
+ >;
value: string;
onChange: (value: string) => void;
};
diff --git a/packages/twenty-front/src/modules/side-panel/pages/email-block-settings/components/SidePanelEmailBlockSettingsPage.tsx b/packages/twenty-front/src/modules/side-panel/pages/email-block-settings/components/SidePanelEmailBlockSettingsPage.tsx
index 021c7424a76..6263d09690a 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/email-block-settings/components/SidePanelEmailBlockSettingsPage.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/email-block-settings/components/SidePanelEmailBlockSettingsPage.tsx
@@ -11,7 +11,9 @@ import { IconTrash } from 'twenty-ui/icon';
import { LightIconButton } from 'twenty-ui/input';
import { themeCssVariables } from 'twenty-ui/theme-constants';
-import { activeEmailEditorState } from '@/advanced-text-editor/states/activeEmailEditorState';
+import { activeEmailEditorState } from '@/activities/emails/states/activeEmailEditorState';
+import { ADVANCED_TEXT_EDITOR_BLOCK_CATALOG } from '@/advanced-text-editor/constants/AdvancedTextEditorBlockCatalog';
+import { type AdvancedTextEditorBlockSetting } from '@/advanced-text-editor/types/AdvancedTextEditorBlockCatalog';
import { getBlockSelectionTarget } from '@/advanced-text-editor/utils/getBlockSelectionTarget';
import { getBlockStyle } from '@/advanced-text-editor/utils/getBlockStyle';
import { EmailBlockSettingsFieldInput } from '@/side-panel/pages/email-block-settings/components/EmailBlockSettingsFieldInput';
@@ -20,8 +22,6 @@ import {
type CssBoxSides,
} from '@/side-panel/pages/email-block-settings/components/EmailBoxSidesInput';
import { EmailPageStyleSection } from '@/side-panel/pages/email-block-settings/components/EmailPageStyleSection';
-import { EMAIL_BLOCK_SETTINGS_FIELDS } from '@/side-panel/pages/email-block-settings/constants/EmailBlockSettingsFields';
-import { getEmailBlockLabel } from '@/side-panel/pages/email-block-settings/utils/getEmailBlockLabel';
import { getEffectiveSectionStyleValue } from '@/side-panel/pages/email-block-settings/utils/getEffectiveSectionStyleValue';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
@@ -81,7 +81,8 @@ const EmailBlockSettingsContent = ({ editor }: { editor: Editor }) => {
return <EmailPageStyleSection editor={editor} />;
}
- const fields = EMAIL_BLOCK_SETTINGS_FIELDS[target.nodeType] ?? [];
+ const blockDefinition = ADVANCED_TEXT_EDITOR_BLOCK_CATALOG[target.nodeType];
+ const fields = blockDefinition.settingsFields;
const styles = getBlockStyle(target.attrs.style);
const canvasTheme = resolveCanvasTheme(editor.state.doc.attrs.canvasTheme);
@@ -122,7 +123,10 @@ const EmailBlockSettingsContent = ({ editor }: { editor: Editor }) => {
.run();
};
- const handleFieldChange = (field: (typeof fields)[number], value: string) => {
+ const handleFieldChange = (
+ field: AdvancedTextEditorBlockSetting,
+ value: string,
+ ) => {
if (field.kind === 'attribute') {
if (field.property === 'width') {
const trimmed = value.trim();
@@ -178,9 +182,7 @@ const EmailBlockSettingsContent = ({ editor }: { editor: Editor }) => {
return (
<StyledContainer>
<StyledBlockHeader>
- <StyledBlockTitle>
- {getEmailBlockLabel(target.nodeType)}
- </StyledBlockTitle>
+ <StyledBlockTitle>{i18n._(blockDefinition.label)}</StyledBlockTitle>
<LightIconButton
Icon={IconTrash}
size="small"
diff --git a/packages/twenty-front/src/modules/side-panel/pages/email-block-settings/constants/EmailBlockSettingsFields.ts b/packages/twenty-front/src/modules/side-panel/pages/email-block-settings/constants/EmailBlockSettingsFields.ts
deleted file mode 100644
index 47acc5c9927..00000000000
--- a/packages/twenty-front/src/modules/side-panel/pages/email-block-settings/constants/EmailBlockSettingsFields.ts
+++ /dev/null
@@ -1,340 +0,0 @@
-/* oxlint-disable twenty/no-hardcoded-colors --
- placeholders show literal inline CSS examples for email content, where
- theme variables do not exist */
-import { type MessageDescriptor } from '@lingui/core';
-import { msg } from '@lingui/core/macro';
-import { TIPTAP_NODE_TYPES } from 'twenty-shared/utils';
-
-import { type EmailStyleFieldKind } from '@/side-panel/pages/email-block-settings/components/EmailBlockSettingsFieldInput';
-
-export type EmailBlockSettingsField = {
- label: MessageDescriptor;
- kind: 'style' | 'attribute';
- property: string;
- input: EmailStyleFieldKind;
- placeholder?: string;
-};
-
-export const EMAIL_BLOCK_SETTINGS_FIELDS: Record<
- string,
- EmailBlockSettingsField[]
-> = {
- [TIPTAP_NODE_TYPES.SECTION]: [
- {
- label: msg`Text color`,
- kind: 'style',
- property: 'color',
- input: 'color',
- },
- {
- label: msg`Font size`,
- kind: 'style',
- property: 'fontSize',
- input: 'size',
- placeholder: '14',
- },
- {
- label: msg`Line height`,
- kind: 'style',
- property: 'lineHeight',
- input: 'text',
- placeholder: '1.5',
- },
- {
- label: msg`Letter spacing`,
- kind: 'style',
- property: 'letterSpacing',
- input: 'size',
- placeholder: '0',
- },
- {
- label: msg`Alignment`,
- kind: 'style',
- property: 'textAlign',
- input: 'alignment',
- },
- {
- label: msg`Background`,
- kind: 'style',
- property: 'backgroundColor',
- input: 'color',
- },
- {
- label: msg`Padding`,
- kind: 'style',
- property: 'padding',
- input: 'box',
- placeholder: '12',
- },
- {
- label: msg`Corner radius`,
- kind: 'style',
- property: 'borderRadius',
- input: 'box',
- placeholder: '8',
- },
- {
- label: msg`Border`,
- kind: 'style',
- property: 'borderWidth',
- input: 'size',
- placeholder: '0',
- },
- {
- label: msg`Border color`,
- kind: 'style',
- property: 'borderColor',
- input: 'color',
- },
- ],
- [TIPTAP_NODE_TYPES.COLUMNS]: [
- {
- label: msg`Text color`,
- kind: 'style',
- property: 'color',
- input: 'color',
- },
- {
- label: msg`Font size`,
- kind: 'style',
- property: 'fontSize',
- input: 'size',
- placeholder: '14',
- },
- {
- label: msg`Line height`,
- kind: 'style',
- property: 'lineHeight',
- input: 'text',
- placeholder: '1.5',
- },
- {
- label: msg`Letter spacing`,
- kind: 'style',
- property: 'letterSpacing',
- input: 'size',
- placeholder: '0',
- },
- {
- label: msg`Alignment`,
- kind: 'style',
- property: 'textAlign',
- input: 'alignment',
- },
- {
- label: msg`Background`,
- kind: 'style',
- property: 'backgroundColor',
- input: 'color',
- },
- {
- label: msg`Padding`,
- kind: 'style',
- property: 'padding',
- input: 'box',
- placeholder: '12',
- },
- {
- label: msg`Corner radius`,
- kind: 'style',
- property: 'borderRadius',
- input: 'box',
- placeholder: '8',
- },
- {
- label: msg`Border`,
- kind: 'style',
- property: 'borderWidth',
- input: 'size',
- placeholder: '0',
- },
- {
- label: msg`Border color`,
- kind: 'style',
- property: 'borderColor',
- input: 'color',
- },
- ],
- [TIPTAP_NODE_TYPES.COLUMN]: [
- {
- label: msg`Text color`,
- kind: 'style',
- property: 'color',
- input: 'color',
- },
- {
- label: msg`Font size`,
- kind: 'style',
- property: 'fontSize',
- input: 'size',
- placeholder: '14',
- },
- {
- label: msg`Line height`,
- kind: 'style',
- property: 'lineHeight',
- input: 'text',
- placeholder: '1.5',
- },
- {
- label: msg`Letter spacing`,
- kind: 'style',
- property: 'letterSpacing',
- input: 'size',
- placeholder: '0',
- },
- {
- label: msg`Alignment`,
- kind: 'style',
- property: 'textAlign',
- input: 'alignment',
- },
- {
- label: msg`Width`,
- kind: 'style',
- property: 'width',
- input: 'size',
- placeholder: '50%',
- },
- {
- label: msg`Background`,
- kind: 'style',
- property: 'backgroundColor',
- input: 'color',
- },
- {
- label: msg`Padding`,
- kind: 'style',
- property: 'padding',
- input: 'box',
- placeholder: '12',
- },
- {
- label: msg`Corner radius`,
- kind: 'style',
- property: 'borderRadius',
- input: 'box',
- placeholder: '8',
- },
- {
- label: msg`Border`,
- kind: 'style',
- property: 'borderWidth',
- input: 'size',
- placeholder: '0',
- },
- {
- label: msg`Border color`,
- kind: 'style',
- property: 'borderColor',
- input: 'color',
- },
- ],
- [TIPTAP_NODE_TYPES.BUTTON]: [
- {
- label: msg`Alignment`,
- kind: 'attribute',
- property: 'align',
- input: 'alignment',
- },
- {
- label: msg`Link URL`,
- kind: 'attribute',
- property: 'href',
- input: 'text',
- placeholder: 'https://',
- },
- {
- label: msg`Background`,
- kind: 'style',
- property: 'backgroundColor',
- input: 'color',
- },
- {
- label: msg`Text color`,
- kind: 'style',
- property: 'color',
- input: 'color',
- },
- {
- label: msg`Padding`,
- kind: 'style',
- property: 'padding',
- input: 'box',
- placeholder: '10',
- },
- {
- label: msg`Corner radius`,
- kind: 'style',
- property: 'borderRadius',
- input: 'box',
- placeholder: '6',
- },
- ],
- [TIPTAP_NODE_TYPES.IMAGE]: [
- {
- label: msg`Alignment`,
- kind: 'attribute',
- property: 'align',
- input: 'alignment',
- },
- {
- label: msg`Link URL`,
- kind: 'attribute',
- property: 'href',
- input: 'text',
- placeholder: 'https://',
- },
- {
- label: msg`Source`,
- kind: 'attribute',
- property: 'src',
- input: 'text',
- placeholder: 'https://',
- },
- {
- label: msg`Alt text`,
- kind: 'attribute',
- property: 'alt',
- input: 'text',
- },
- {
- label: msg`Width`,
- kind: 'attribute',
- property: 'width',
- input: 'text',
- placeholder: 'auto',
- },
- ],
- [TIPTAP_NODE_TYPES.HTML]: [
- {
- label: msg`HTML`,
- kind: 'attribute',
- property: 'html',
- input: 'textarea',
- placeholder: '<p>Hello</p>',
- },
- ],
- [TIPTAP_NODE_TYPES.DIVIDER]: [
- {
- label: msg`Thickness`,
- kind: 'style',
- property: 'borderTopWidth',
- input: 'size',
- placeholder: '1',
- },
- {
- label: msg`Color`,
- kind: 'style',
- property: 'borderTopColor',
- input: 'color',
- },
- {
- label: msg`Margin`,
- kind: 'style',
- property: 'margin',
- input: 'box',
- placeholder: '16',
- },
- ],
-};
diff --git a/packages/twenty-front/src/modules/side-panel/pages/email-block-settings/types/EmailThemeField.ts b/packages/twenty-front/src/modules/side-panel/pages/email-block-settings/types/EmailThemeField.ts
index af94655b7c6..dd99f4a3875 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/email-block-settings/types/EmailThemeField.ts
+++ b/packages/twenty-front/src/modules/side-panel/pages/email-block-settings/types/EmailThemeField.ts
@@ -1,11 +1,11 @@
import { type MessageDescriptor } from '@lingui/core';
import { type CanvasTheme } from 'twenty-shared/utils';
-import { type EmailStyleFieldKind } from '@/side-panel/pages/email-block-settings/components/EmailBlockSettingsFieldInput';
+import { type AdvancedTextEditorSettingInput } from '@/advanced-text-editor/types/AdvancedTextEditorBlockCatalog';
export type EmailThemeField = {
label: MessageDescriptor;
property: keyof CanvasTheme;
- input: EmailStyleFieldKind;
+ input: AdvancedTextEditorSettingInput;
placeholder?: string;
};
diff --git a/packages/twenty-front/src/modules/side-panel/pages/email-block-settings/utils/getEmailBlockLabel.ts b/packages/twenty-front/src/modules/side-panel/pages/email-block-settings/utils/getEmailBlockLabel.ts
deleted file mode 100644
index 661d04c836b..00000000000
--- a/packages/twenty-front/src/modules/side-panel/pages/email-block-settings/utils/getEmailBlockLabel.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { t } from '@lingui/core/macro';
-import { TIPTAP_NODE_TYPES } from 'twenty-shared/utils';
-
-export const getEmailBlockLabel = (nodeType: string): string => {
- switch (nodeType) {
- case TIPTAP_NODE_TYPES.SECTION:
- return t`Section`;
- case TIPTAP_NODE_TYPES.COLUMNS:
- return t`Columns`;
- case TIPTAP_NODE_TYPES.COLUMN:
- return t`Column`;
- case TIPTAP_NODE_TYPES.BUTTON:
- return t`Button`;
- case TIPTAP_NODE_TYPES.DIVIDER:
- return t`Divider`;
- case TIPTAP_NODE_TYPES.HTML:
- return t`HTML`;
- case TIPTAP_NODE_TYPES.IMAGE:
- return t`Image`;
- default:
- return nodeType;
- }
-};
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/BaseChip.tsx b/packages/twenty-front/src/modules/ui/input/components/BaseChip.tsx
similarity index 100%
rename from packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/BaseChip.tsx
rename to packages/twenty-front/src/modules/ui/input/components/BaseChip.tsx
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormFieldInputContainer.tsx b/packages/twenty-front/src/modules/ui/input/components/FormFieldInputContainer.tsx
similarity index 100%
rename from packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormFieldInputContainer.tsx
rename to packages/twenty-front/src/modules/ui/input/components/FormFieldInputContainer.tsx
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/constants/FormFieldPlaceholderStyles.ts b/packages/twenty-front/src/modules/ui/input/constants/FormFieldPlaceholderStyles.ts
similarity index 100%
rename from packages/twenty-front/src/modules/object-record/record-field/ui/form-types/constants/FormFieldPlaceholderStyles.ts
rename to packages/twenty-front/src/modules/ui/input/constants/FormFieldPlaceholderStyles.ts
diff --git a/packages/twenty-front/src/modules/ui/input/types/VariablePickerComponent.ts b/packages/twenty-front/src/modules/ui/input/types/VariablePickerComponent.ts
new file mode 100644
index 00000000000..75583977bf7
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/input/types/VariablePickerComponent.ts
@@ -0,0 +1,11 @@
+import { type FC } from 'react';
+
+export type VariablePickerComponent = FC<{
+ instanceId: string;
+ disabled?: boolean;
+ multiline?: boolean;
+ onVariableSelect: (variableName: string) => void;
+ shouldDisplayRecordObjects?: boolean;
+ shouldDisplayRecordFields?: boolean;
+ objectNameSingularsToSelect?: string[];
+}>;
diff --git a/packages/twenty-front/src/modules/workflow/utils/__tests__/isStandaloneVariableString.test.ts b/packages/twenty-front/src/modules/workflow/utils/__tests__/isStandaloneVariableString.test.ts
deleted file mode 100644
index 68d2f72db71..00000000000
--- a/packages/twenty-front/src/modules/workflow/utils/__tests__/isStandaloneVariableString.test.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
-
-it('returns false if the provided value is not a string', () => {
- expect(isStandaloneVariableString(42)).toBe(false);
-});
-
-it('returns true if the provided value is a valid variable definition string', () => {
- expect(isStandaloneVariableString('{{ test.a.b.c }}')).toBe(true);
-});
-
-it('returns false if the provided value starts with blank spaces', () => {
- expect(isStandaloneVariableString(' {{ test.a.b.c }}')).toBe(false);
-});
-
-it('returns false if the provided value ends with blank spaces', () => {
- expect(isStandaloneVariableString('{{ test.a.b.c }} ')).toBe(false);
-});
diff --git a/packages/twenty-front/src/modules/workflow/utils/isStandaloneVariableString.ts b/packages/twenty-front/src/modules/workflow/utils/isStandaloneVariableString.ts
deleted file mode 100644
index 829c3bd8971..00000000000
--- a/packages/twenty-front/src/modules/workflow/utils/isStandaloneVariableString.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { isString } from '@sniptt/guards';
-
-const STANDALONE_VARIABLE_REGEX = /^{{[^{}]+}}$/;
-
-export const isStandaloneVariableString = (value: unknown): value is string => {
- return isString(value) && STANDALONE_VARIABLE_REGEX.test(value);
-};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowOutputSchemaBuilder.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowOutputSchemaBuilder.tsx
index 84c645f28b3..14cb2f77fc2 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowOutputSchemaBuilder.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowOutputSchemaBuilder.tsx
@@ -1,4 +1,4 @@
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
import { type OutputSchemaField } from '@/ai/constants/OutputFieldTypeOptions';
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/code-action/components/WorkflowEditActionCodeFieldLeaf.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/code-action/components/WorkflowEditActionCodeFieldLeaf.tsx
index 48c0f716a99..80237aa4896 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/code-action/components/WorkflowEditActionCodeFieldLeaf.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/code-action/components/WorkflowEditActionCodeFieldLeaf.tsx
@@ -8,7 +8,6 @@ import { FormSingleRecordPicker } from '@/object-record/record-field/ui/form-typ
import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
import { type VariablePickerComponent } from '@/object-record/record-field/ui/form-types/types/VariablePickerComponent';
import { type FieldArrayValue } from '@/object-record/record-field/ui/types/FieldMetadata';
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
import { getWorkflowCodeFieldsEnumSelectOptions } from '@/workflow/workflow-steps/workflow-actions/code-action/utils/getWorkflowCodeFieldsEnumSelectOptions';
import { getWorkflowCodeFieldsLeafKind } from '@/workflow/workflow-steps/workflow-actions/code-action/utils/getWorkflowCodeFieldsLeafKind';
import { t } from '@lingui/core/macro';
@@ -21,7 +20,10 @@ import {
isString,
} from '@sniptt/guards';
import { isDefined } from 'twenty-shared/utils';
-import { type InputSchemaProperty } from 'twenty-shared/workflow';
+import {
+ type InputSchemaProperty,
+ isStandaloneVariableString,
+} from 'twenty-shared/workflow';
type WorkflowEditActionCodeFieldLeafProps = {
label: string;
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowEditActionEmailBase.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowEditActionEmailBase.tsx
index a4bbc7f6fcf..0af7417067d 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowEditActionEmailBase.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowEditActionEmailBase.tsx
@@ -1,7 +1,6 @@
import { type ConnectedAccount } from '@/accounts/types/ConnectedAccount';
import { getMissingDraftEmailScopes } from '@/accounts/utils/hasMissingDraftEmailScopes';
-import { WorkflowSendEmailAttachments } from '@/advanced-text-editor/components/WorkflowSendEmailAttachments';
-import { FormAdvancedTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormAdvancedTextFieldInput';
+import { FormAdvancedTextFieldInput } from '@/advanced-text-editor/components/FormAdvancedTextFieldInput';
import { FormMultiTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormMultiTextFieldInput';
import { FormSelectFieldInput } from '@/object-record/record-field/ui/form-types/components/FormSelectFieldInput';
import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
@@ -19,9 +18,11 @@ import { WORKFLOW_STEP_CONNECTED_ACCOUNT_HANDLE } from '@/workflow/graphql/queri
import { useWorkflowWithCurrentVersion } from '@/workflow/hooks/useWorkflowWithCurrentVersion';
import { workflowVisualizerWorkflowIdComponentState } from '@/workflow/states/workflowVisualizerWorkflowIdComponentState';
import { type WorkflowEmailAction } from '@/workflow/types/WorkflowEmailAction';
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
+import { isStandaloneVariableString } from 'twenty-shared/workflow';
import { WorkflowStepBody } from '@/workflow/workflow-steps/components/WorkflowStepBody';
import { WorkflowStepFooter } from '@/workflow/workflow-steps/components/WorkflowStepFooter';
+import { WorkflowSendEmailAttachments } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowSendEmailAttachments';
+import { WORKFLOW_EMAIL_BODY_EDITOR_PROFILE } from '@/workflow/workflow-steps/workflow-actions/constants/WorkflowEmailBodyEditorProfile';
import { useEmailForm } from '@/workflow/workflow-steps/workflow-actions/hooks/useEmailForm';
import { WorkflowVariablePicker } from '@/workflow/workflow-variables/components/WorkflowVariablePicker';
import { useQuery } from '@apollo/client/react';
@@ -371,7 +372,7 @@ export const WorkflowEditActionEmailBase = ({
children: t`Email Editor`,
},
]}
- preset="workflowEmailBody"
+ profile={WORKFLOW_EMAIL_BODY_EDITOR_PROFILE}
/>
<WorkflowSendEmailAttachments
label={t`Attachments`}
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/components/WorkflowSendEmailAttachments.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowSendEmailAttachments.tsx
similarity index 98%
rename from packages/twenty-front/src/modules/advanced-text-editor/components/WorkflowSendEmailAttachments.tsx
rename to packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowSendEmailAttachments.tsx
index 95bf4356c35..97c8980a01a 100644
--- a/packages/twenty-front/src/modules/advanced-text-editor/components/WorkflowSendEmailAttachments.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowSendEmailAttachments.tsx
@@ -1,4 +1,4 @@
-import { useUploadWorkflowFile } from '@/advanced-text-editor/hooks/useUploadWorkflowFile';
+import { useUploadWorkflowFile } from '@/workflow/workflow-steps/workflow-actions/hooks/useUploadWorkflowFile';
import { AttachmentChip } from '@/file/components/AttachmentChip';
import { useFileUpload } from '@/file-upload/hooks/useFileUpload';
import { VariableChip } from '@/object-record/record-field/ui/form-types/components/VariableChip';
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/WorkflowEmailBodyEditorProfile.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/WorkflowEmailBodyEditorProfile.ts
new file mode 100644
index 00000000000..1cf82fcda1b
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/WorkflowEmailBodyEditorProfile.ts
@@ -0,0 +1,15 @@
+import { type AdvancedTextEditorProfile } from '@/advanced-text-editor/types/AdvancedTextEditorProfile';
+import { buildFullRichTextExtensions } from '@/advanced-text-editor/utils/buildFullRichTextExtensions';
+import { parseLegacyWorkflowEmailBodyDocument } from '@/workflow/workflow-steps/workflow-actions/utils/parseLegacyWorkflowEmailBodyDocument';
+import { WorkflowVariableTag } from '@/workflow/workflow-variables/extensions/WorkflowVariableTag';
+
+export const WORKFLOW_EMAIL_BODY_EDITOR_PROFILE = {
+ chrome: 'field',
+ minHeight: 340,
+ enableFullScreen: true,
+ parseLegacyDocument: parseLegacyWorkflowEmailBodyDocument,
+ buildExtensions: (context) => [
+ ...buildFullRichTextExtensions(context),
+ WorkflowVariableTag,
+ ],
+} satisfies AdvancedTextEditorProfile;
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/find-records-action/components/WorkflowEditActionFindRecords.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/find-records-action/components/WorkflowEditActionFindRecords.tsx
index 9f880b6b0e9..417c8817e8f 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/find-records-action/components/WorkflowEditActionFindRecords.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/find-records-action/components/WorkflowEditActionFindRecords.tsx
@@ -33,7 +33,7 @@ import { WorkflowFindRecordsFilters } from '@/workflow/workflow-steps/workflow-a
import { WorkflowFindRecordsFiltersEffect } from '@/workflow/workflow-steps/workflow-actions/find-records-action/components/WorkflowFindRecordsFiltersEffect';
import { WorkflowFindRecordsSorts } from '@/workflow/workflow-steps/workflow-actions/find-records-action/components/WorkflowFindRecordsSorts';
import { WorkflowObjectDropdownContent } from '@/workflow/workflow-steps/workflow-actions/find-records-action/components/WorkflowObjectDropdownContent';
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
+import { isStandaloneVariableString } from 'twenty-shared/workflow';
import { WorkflowVariablePicker } from '@/workflow/workflow-variables/components/WorkflowVariablePicker';
import { themeCssVariables } from 'twenty-ui/theme-constants';
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowEditActionFormBuilder.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowEditActionFormBuilder.tsx
index 11d68846fed..b9d8336357f 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowEditActionFormBuilder.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowEditActionFormBuilder.tsx
@@ -1,4 +1,4 @@
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormFieldInputInnerContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputInnerContainer';
import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputRowContainer';
import { FormFieldPlaceholder } from '@/object-record/record-field/ui/form-types/components/FormFieldPlaceholder';
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowEditActionFormFieldSettings.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowEditActionFormFieldSettings.tsx
index 1bb0e6b68ba..52a524af60c 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowEditActionFormFieldSettings.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowEditActionFormFieldSettings.tsx
@@ -1,4 +1,4 @@
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormSelectFieldInput } from '@/object-record/record-field/ui/form-types/components/FormSelectFieldInput';
import { InputLabel } from '@/ui/input/components/InputLabel';
import { WorkflowFormFieldSettingsByType } from '@/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFieldSettingsByType';
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFieldSettingsDate.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFieldSettingsDate.tsx
index 9569b9998b7..10b685d87ad 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFieldSettingsDate.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFieldSettingsDate.tsx
@@ -1,4 +1,4 @@
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
import { InputLabel } from '@/ui/input/components/InputLabel';
import { type WorkflowFormActionField } from '@/workflow/workflow-steps/workflow-actions/form-action/types/WorkflowFormActionField';
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFieldSettingsNumber.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFieldSettingsNumber.tsx
index ca91d644afd..ca67f1b726a 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFieldSettingsNumber.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFieldSettingsNumber.tsx
@@ -1,4 +1,4 @@
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
import { InputLabel } from '@/ui/input/components/InputLabel';
import { type WorkflowFormActionField } from '@/workflow/workflow-steps/workflow-actions/form-action/types/WorkflowFormActionField';
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFieldSettingsRecordPicker.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFieldSettingsRecordPicker.tsx
index a0a9c1c81ae..e97ead8492b 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFieldSettingsRecordPicker.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFieldSettingsRecordPicker.tsx
@@ -1,6 +1,6 @@
import { useFilteredObjectMetadataItems } from '@/object-metadata/hooks/useFilteredObjectMetadataItems';
import { useObjectMetadataSelectHelpers } from '@/object-metadata/hooks/useObjectMetadataSelectHelpers';
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
import { InputLabel } from '@/ui/input/components/InputLabel';
import { Select } from '@/ui/input/components/Select';
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFieldSettingsSelect.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFieldSettingsSelect.tsx
index ce6cf6ffcb4..0ec11b8172b 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFieldSettingsSelect.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFieldSettingsSelect.tsx
@@ -1,6 +1,6 @@
import { useFilteredObjectMetadataItems } from '@/object-metadata/hooks/useFilteredObjectMetadataItems';
import { isHiddenSystemField } from '@/object-metadata/utils/isHiddenSystemField';
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormSelectFieldInput } from '@/object-record/record-field/ui/form-types/components/FormSelectFieldInput';
import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
import { InputLabel } from '@/ui/input/components/InputLabel';
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFieldSettingsText.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFieldSettingsText.tsx
index 2b6125ee237..57ff9b98f06 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFieldSettingsText.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFieldSettingsText.tsx
@@ -1,4 +1,4 @@
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
import { InputLabel } from '@/ui/input/components/InputLabel';
import { type WorkflowFormActionField } from '@/workflow/workflow-steps/workflow-actions/form-action/types/WorkflowFormActionField';
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/hooks/useUploadWorkflowFile.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/hooks/useUploadWorkflowFile.ts
similarity index 100%
rename from packages/twenty-front/src/modules/advanced-text-editor/hooks/useUploadWorkflowFile.ts
rename to packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/hooks/useUploadWorkflowFile.ts
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/http-request-action/components/BodyInput.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/http-request-action/components/BodyInput.tsx
index b2e15807719..5a05bfa0b55 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/http-request-action/components/BodyInput.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/http-request-action/components/BodyInput.tsx
@@ -1,5 +1,5 @@
import { t } from '@lingui/core/macro';
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormRawJsonFieldInput } from '@/object-record/record-field/ui/form-types/components/FormRawJsonFieldInput';
import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
import { InputLabel } from '@/ui/input/components/InputLabel';
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/http-request-action/components/HttpRequestTestVariableInput.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/http-request-action/components/HttpRequestTestVariableInput.tsx
index 4731e634cf7..c9d70fa6963 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/http-request-action/components/HttpRequestTestVariableInput.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/http-request-action/components/HttpRequestTestVariableInput.tsx
@@ -1,4 +1,4 @@
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
import { type WorkflowStep } from '@/workflow/types/Workflow';
import { getWorkflowVariablesUsedInStep } from '@/workflow/workflow-steps/utils/getWorkflowVariablesUsedInStep';
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/http-request-action/components/KeyValuePairInput.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/http-request-action/components/KeyValuePairInput.tsx
index efa8c36d4fc..1d450527c9f 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/http-request-action/components/KeyValuePairInput.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/http-request-action/components/KeyValuePairInput.tsx
@@ -1,4 +1,4 @@
-import { FormFieldInputContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputContainer';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
import { InputLabel } from '@/ui/input/components/InputLabel';
import { AUTO_SET_HEADER_KEYS } from '@/workflow/workflow-steps/workflow-actions/http-request-action/constants/AutoSetHeaderKeys';
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/iterator-action/components/WorkflowEditActionIterator.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/iterator-action/components/WorkflowEditActionIterator.tsx
index c3a126581cd..262a44a2edc 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/iterator-action/components/WorkflowEditActionIterator.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/iterator-action/components/WorkflowEditActionIterator.tsx
@@ -2,7 +2,7 @@ import { FormArrayFieldInput } from '@/object-record/record-field/ui/form-types/
import { FormBooleanFieldToggleInput } from '@/object-record/record-field/ui/form-types/components/FormBooleanFieldToggleInput';
import { type FieldArrayValue } from '@/object-record/record-field/ui/types/FieldMetadata';
import { type WorkflowIteratorAction } from '@/workflow/types/Workflow';
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
+import { isStandaloneVariableString } from 'twenty-shared/workflow';
import { WorkflowStepBody } from '@/workflow/workflow-steps/components/WorkflowStepBody';
import { WorkflowStepFooter } from '@/workflow/workflow-steps/components/WorkflowStepFooter';
import { WorkflowVariablePicker } from '@/workflow/workflow-variables/components/WorkflowVariablePicker';
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/__tests__/parseLegacyWorkflowEmailBodyDocument.test.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/__tests__/parseLegacyWorkflowEmailBodyDocument.test.ts
new file mode 100644
index 00000000000..d0ed7097ac8
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/__tests__/parseLegacyWorkflowEmailBodyDocument.test.ts
@@ -0,0 +1,37 @@
+import { parseLegacyWorkflowEmailBodyDocument } from '@/workflow/workflow-steps/workflow-actions/utils/parseLegacyWorkflowEmailBodyDocument';
+
+describe('parseLegacyWorkflowEmailBodyDocument', () => {
+ it('preserves versionless TipTap documents stored by workflow email actions', () => {
+ const document = {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'Hello' }],
+ },
+ ],
+ };
+
+ expect(
+ parseLegacyWorkflowEmailBodyDocument(JSON.stringify(document)),
+ ).toEqual(document);
+ });
+
+ it('preserves HTML stored by workflow email actions', () => {
+ expect(parseLegacyWorkflowEmailBodyDocument('<p>Hello</p>')).toBe(
+ '<p>Hello</p>',
+ );
+ });
+
+ it('converts plain text stored by workflow email actions', () => {
+ expect(parseLegacyWorkflowEmailBodyDocument('Hello')).toEqual({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'Hello' }],
+ },
+ ],
+ });
+ });
+});
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/parseLegacyWorkflowEmailBodyDocument.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/parseLegacyWorkflowEmailBodyDocument.ts
new file mode 100644
index 00000000000..4944b93ee65
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/parseLegacyWorkflowEmailBodyDocument.ts
@@ -0,0 +1,14 @@
+import { type AdvancedTextEditorLegacyDocumentParser } from '@/advanced-text-editor/types/AdvancedTextEditorLegacyDocumentParser';
+import { parseLegacyHtmlOrPlainTextDocument } from '@/advanced-text-editor/utils/parseLegacyHtmlOrPlainTextDocument';
+import { parseTipTapJsonDocument } from 'twenty-shared/utils';
+
+export const parseLegacyWorkflowEmailBodyDocument: AdvancedTextEditorLegacyDocumentParser =
+ (serializedDocument) => {
+ const document = parseTipTapJsonDocument(serializedDocument);
+
+ if (document !== undefined && document.attrs?.schemaVersion === undefined) {
+ return document;
+ }
+
+ return parseLegacyHtmlOrPlainTextDocument(serializedDocument);
+ };
diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/components/WorkflowTextEditorTextChip.tsx b/packages/twenty-front/src/modules/workflow/workflow-variables/components/WorkflowTextEditorTextChip.tsx
index 644a4d5908a..65e36e62df4 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-variables/components/WorkflowTextEditorTextChip.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/components/WorkflowTextEditorTextChip.tsx
@@ -1,4 +1,4 @@
-import { BaseChip } from '@/object-record/record-field/ui/form-types/components/BaseChip';
+import { BaseChip } from '@/ui/input/components/BaseChip';
import { styled } from '@linaria/react';
import { NodeViewWrapper, type NodeViewProps } from '@tiptap/react';
import { themeCssVariables } from 'twenty-ui/theme-constants';
diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/extensions/WorkflowVariableTag.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/extensions/WorkflowVariableTag.ts
new file mode 100644
index 00000000000..5c3c1932894
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/extensions/WorkflowVariableTag.ts
@@ -0,0 +1,9 @@
+import { VariableTag } from '@/advanced-text-editor/extensions/variable-tag/VariableTag';
+import { WorkflowTextEditorVariableChip } from '@/workflow/workflow-variables/components/WorkflowTextEditorVariableChip';
+import { ReactNodeViewRenderer } from '@tiptap/react';
+
+export const WorkflowVariableTag = VariableTag.extend({
+ addNodeView() {
+ return ReactNodeViewRenderer(WorkflowTextEditorVariableChip);
+ },
+});
diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/__tests__/getInitialAdvancedTextEditorContent.test.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/__tests__/getInitialAdvancedTextEditorContent.test.ts
deleted file mode 100644
index 6af659d296d..00000000000
--- a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/__tests__/getInitialAdvancedTextEditorContent.test.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { getInitialAdvancedTextEditorContent } from '@/workflow/workflow-variables/utils/getInitialAdvancedTextEditorContent';
-
-describe('getInitialAdvancedTextEditorContent', () => {
- it('should return an empty document when the content is blank', () => {
- expect(getInitialAdvancedTextEditorContent(' ')).toEqual({
- type: 'doc',
- content: [{ type: 'paragraph', content: [] }],
- });
- });
-
- it('should return the parsed document when the content is TipTap JSON', () => {
- const document = {
- type: 'doc',
- content: [
- { type: 'paragraph', content: [{ type: 'text', text: 'Hello' }] },
- ],
- };
-
- expect(
- getInitialAdvancedTextEditorContent(JSON.stringify(document)),
- ).toEqual(document);
- });
-
- it('should wrap a BlockNote array in a document', () => {
- const blocks = [{ type: 'paragraph', content: [] }];
-
- expect(getInitialAdvancedTextEditorContent(JSON.stringify(blocks))).toEqual(
- {
- type: 'doc',
- content: blocks,
- },
- );
- });
-
- it('should hand legacy HTML back untouched so TipTap parses it', () => {
- const html = '<p>Hi <strong>there</strong></p><p>Bye</p>';
-
- expect(getInitialAdvancedTextEditorContent(html)).toBe(html);
- });
-
- it('should hand legacy HTML back untouched when it is indented', () => {
- const html = '\n <h1 class="title">Title</h1>';
-
- expect(getInitialAdvancedTextEditorContent(html)).toBe(html);
- });
-
- it('should still convert plain text with variables into variable tags', () => {
- expect(getInitialAdvancedTextEditorContent('Hi {{firstName}}')).toEqual({
- type: 'doc',
- content: [
- {
- type: 'paragraph',
- content: [
- { type: 'text', text: 'Hi ' },
- { type: 'variableTag', attrs: { variable: '{{firstName}}' } },
- ],
- },
- ],
- });
- });
-
- it('should not treat plain text that merely contains angle brackets as HTML', () => {
- const text = 'Reply to a <b>bold</b> claim';
-
- expect(getInitialAdvancedTextEditorContent(text)).toEqual({
- type: 'doc',
- content: [{ type: 'paragraph', content: [{ type: 'text', text }] }],
- });
- });
-});
diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/getInitialAdvancedTextEditorContent.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/getInitialAdvancedTextEditorContent.ts
deleted file mode 100644
index 2d00b1b318e..00000000000
--- a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/getInitialAdvancedTextEditorContent.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { getInitialEditorContent } from '@/workflow/workflow-variables/utils/getInitialEditorContent';
-import type { JSONContent } from '@tiptap/react';
-
-// Campaign bodies were stored as the editor's own HTML before they moved to
-// JSON. TipTap parses an HTML string natively, so hand it through untouched
-// rather than letting the plain-text fallback render the markup as literal
-// text. Requiring a leading tag keeps plain-text bodies, which need the
-// variable-tag conversion below, out of this branch.
-const LEADING_HTML_TAG_PATTERN = /^<[a-z][a-z0-9]*(\s[^>]*)?>/i;
-
-// Previous format of the email body was plain text,
-// but from now on we will save it as JSON.
-// So it will fail to parse the content, that's why we have this fallback.
-export const getInitialAdvancedTextEditorContent = (
- rawContent: string,
-): JSONContent | string => {
- // Handle empty or null content
- if (!rawContent || rawContent.trim() === '') {
- return {
- type: 'doc',
- content: [
- {
- type: 'paragraph',
- content: [],
- },
- ],
- };
- }
-
- try {
- const json = JSON.parse(rawContent);
-
- // Handle BlockNote array format (wrap in doc structure for TipTap)
- if (Array.isArray(json)) {
- return {
- type: 'doc',
- content: json,
- };
- }
-
- return json;
- } catch {
- if (LEADING_HTML_TAG_PATTERN.test(rawContent.trim())) {
- return rawContent;
- }
-
- return getInitialEditorContent(rawContent);
- }
-};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/getMultiItemFieldEditorContent.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/getMultiItemFieldEditorContent.ts
index f025e553324..80a33d98d2b 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/getMultiItemFieldEditorContent.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/getMultiItemFieldEditorContent.ts
@@ -1,4 +1,4 @@
-import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
+import { isStandaloneVariableString } from 'twenty-shared/workflow';
import type { JSONContent } from '@tiptap/react';
export const getMultiItemFieldEditorContent = (
diff --git a/packages/twenty-front/src/pages/settings/ai/SettingsAiPrompts.tsx b/packages/twenty-front/src/pages/settings/ai/SettingsAiPrompts.tsx
index 3609a84a9b5..3b14d745747 100644
--- a/packages/twenty-front/src/pages/settings/ai/SettingsAiPrompts.tsx
+++ b/packages/twenty-front/src/pages/settings/ai/SettingsAiPrompts.tsx
@@ -1,7 +1,8 @@
import { styled } from '@linaria/react';
import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
-import { FormAdvancedTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormAdvancedTextFieldInput';
+import { FormAdvancedTextFieldInput } from '@/advanced-text-editor/components/FormAdvancedTextFieldInput';
+import { AI_INSTRUCTIONS_EDITOR_PROFILE } from '@/ai/constants/AiInstructionsEditorProfile';
import { SettingsPageContainer } from '@/settings/components/SettingsPageContainer';
import { SettingsPageLayout } from '@/settings/components/layout/SettingsPageLayout';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
@@ -135,7 +136,7 @@ export const SettingsAiPrompts = () => {
label={section.title}
readonly={true}
defaultValue={section.content}
- preset="aiInstructions"
+ profile={AI_INSTRUCTIONS_EDITOR_PROFILE}
onChange={() => {}}
enableFullScreen={true}
fullScreenBreadcrumbs={[
@@ -164,7 +165,7 @@ export const SettingsAiPrompts = () => {
label={t`User Information`}
readonly={true}
defaultValue={userContextPreview}
- preset="aiInstructions"
+ profile={AI_INSTRUCTIONS_EDITOR_PROFILE}
onChange={() => {}}
enableFullScreen={false}
minHeight={80}
diff --git a/packages/twenty-front/src/pages/settings/ai/SettingsSkillForm.tsx b/packages/twenty-front/src/pages/settings/ai/SettingsSkillForm.tsx
index b9737a41cea..cc95d329df2 100644
--- a/packages/twenty-front/src/pages/settings/ai/SettingsSkillForm.tsx
+++ b/packages/twenty-front/src/pages/settings/ai/SettingsSkillForm.tsx
@@ -3,7 +3,8 @@ import { styled } from '@linaria/react';
import { useParams } from 'react-router-dom';
import { useDebouncedCallback } from 'use-debounce';
-import { FormAdvancedTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormAdvancedTextFieldInput';
+import { FormAdvancedTextFieldInput } from '@/advanced-text-editor/components/FormAdvancedTextFieldInput';
+import { AI_INSTRUCTIONS_EDITOR_PROFILE } from '@/ai/constants/AiInstructionsEditorProfile';
import { AdvancedSettingsWrapper } from '@/settings/components/AdvancedSettingsWrapper';
import { SaveAndCancelButtons } from '@/settings/components/SaveAndCancelButtons/SaveAndCancelButtons';
import { SettingsEditableTitle } from '@/settings/components/SettingsEditableTitle';
@@ -491,7 +492,7 @@ export const SettingsSkillForm = ({ mode }: { mode: 'create' | 'edit' }) => {
label={t`Instructions`}
readonly={isReadonlyMode}
defaultValue={formValues.content}
- preset="aiInstructions"
+ profile={AI_INSTRUCTIONS_EDITOR_PROFILE}
onChange={(content: string) =>
handleFieldChange('content', content)
}
diff --git a/packages/twenty-front/src/pages/settings/ai/components/SettingsAiOverviewTab.tsx b/packages/twenty-front/src/pages/settings/ai/components/SettingsAiOverviewTab.tsx
index 89ce27ae216..db54f1ef056 100644
--- a/packages/twenty-front/src/pages/settings/ai/components/SettingsAiOverviewTab.tsx
+++ b/packages/twenty-front/src/pages/settings/ai/components/SettingsAiOverviewTab.tsx
@@ -1,5 +1,6 @@
import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
-import { FormAdvancedTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormAdvancedTextFieldInput';
+import { FormAdvancedTextFieldInput } from '@/advanced-text-editor/components/FormAdvancedTextFieldInput';
+import { AI_INSTRUCTIONS_EDITOR_PROFILE } from '@/ai/constants/AiInstructionsEditorProfile';
import { SettingsCard } from '@/settings/components/SettingsCard';
import { SettingsStatsGrid } from '@/settings/components/SettingsStatsGrid';
import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';
@@ -137,7 +138,7 @@ export const SettingsAiOverviewTab = () => {
key={originalInstructions}
readonly={false}
defaultValue={workspaceInstructions}
- preset="aiInstructions"
+ profile={AI_INSTRUCTIONS_EDITOR_PROFILE}
onChange={(value) => {
setWorkspaceInstructions(value);
autoSave(value);
diff --git a/packages/twenty-server/src/engine/core-modules/email/types/compiled-outbound-email-content.type.ts b/packages/twenty-server/src/engine/core-modules/email/types/compiled-outbound-email-content.type.ts
new file mode 100644
index 00000000000..0144a4254af
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/email/types/compiled-outbound-email-content.type.ts
@@ -0,0 +1,4 @@
+export type CompiledOutboundEmailContent = {
+ html: string;
+ plainText: string;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/utils/__tests__/render-rich-text-to-html.util.spec.ts b/packages/twenty-server/src/engine/core-modules/email/utils/__tests__/compile-outbound-email-content.util.spec.ts
similarity index 67%
rename from packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/utils/__tests__/render-rich-text-to-html.util.spec.ts
rename to packages/twenty-server/src/engine/core-modules/email/utils/__tests__/compile-outbound-email-content.util.spec.ts
index e28e5c6de28..36237127aad 100644
--- a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/utils/__tests__/render-rich-text-to-html.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/email/utils/__tests__/compile-outbound-email-content.util.spec.ts
@@ -1,11 +1,16 @@
-import { renderRichTextToHtml } from 'src/engine/core-modules/tool/tools/email-tool/utils/render-rich-text-to-html.util';
+import { type EmailDocument } from 'twenty-shared/utils';
-describe('renderRichTextToHtml', () => {
+import { compileOutboundEmailContent } from 'src/engine/core-modules/email/utils/compile-outbound-email-content.util';
+
+const compileDocument = async (document: EmailDocument): Promise<string> =>
+ (await compileOutboundEmailContent(document)).html;
+
+describe('compileOutboundEmailContent', () => {
beforeAll(() => {
jest.useRealTimers();
});
it('should render an email section with its inline styles', async () => {
- const html = await renderRichTextToHtml({
+ const html = await compileDocument({
type: 'doc',
content: [
{
@@ -26,15 +31,41 @@ describe('renderRichTextToHtml', () => {
expect(html).toContain('padding:24px');
});
+ it('should preserve the rendered email document preamble', async () => {
+ const html = await compileDocument({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'Standards mode' }],
+ },
+ ],
+ });
+
+ expect(
+ html.startsWith(
+ '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"',
+ ),
+ ).toBe(true);
+ expect(html).toContain(
+ '<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">',
+ );
+ expect(html).toContain(
+ '<meta name="x-apple-disable-message-reformatting">',
+ );
+ });
+
it('should render columns as a table row with one cell per column', async () => {
- const html = await renderRichTextToHtml({
+ const html = await compileDocument({
type: 'doc',
content: [
{
type: 'columns',
+ attrs: { style: {} },
content: [
{
type: 'column',
+ attrs: { style: {} },
content: [
{
type: 'paragraph',
@@ -44,6 +75,7 @@ describe('renderRichTextToHtml', () => {
},
{
type: 'column',
+ attrs: { style: {} },
content: [
{
type: 'paragraph',
@@ -62,7 +94,7 @@ describe('renderRichTextToHtml', () => {
});
it('should render a button as a styled link', async () => {
- const html = await renderRichTextToHtml({
+ const html = await compileDocument({
type: 'doc',
content: [
{
@@ -82,7 +114,7 @@ describe('renderRichTextToHtml', () => {
});
it('should render a divider as an hr with its styles', async () => {
- const html = await renderRichTextToHtml({
+ const html = await compileDocument({
type: 'doc',
content: [
{
@@ -97,7 +129,7 @@ describe('renderRichTextToHtml', () => {
});
it('should wrap themed documents in a styled page and centered container', async () => {
- const html = await renderRichTextToHtml({
+ const html = await compileDocument({
type: 'doc',
attrs: {
canvasTheme: {
@@ -125,7 +157,7 @@ describe('renderRichTextToHtml', () => {
});
it('should keep the bare body for documents without a theme', async () => {
- const html = await renderRichTextToHtml({
+ const html = await compileDocument({
type: 'doc',
content: [
{
@@ -139,8 +171,8 @@ describe('renderRichTextToHtml', () => {
expect(html).not.toContain('max-width:600px');
});
- it('should embed raw HTML blocks verbatim', async () => {
- const html = await renderRichTextToHtml({
+ it('should embed safe raw HTML blocks', async () => {
+ const html = await compileDocument({
type: 'doc',
content: [
{
@@ -157,7 +189,7 @@ describe('renderRichTextToHtml', () => {
});
it('should wrap linked images in an anchor', async () => {
- const html = await renderRichTextToHtml({
+ const html = await compileDocument({
type: 'doc',
content: [
{
@@ -176,25 +208,56 @@ describe('renderRichTextToHtml', () => {
expect(html).toContain('alt="Banner"');
});
- it('should render nothing for unknown node types', async () => {
- const html = await renderRichTextToHtml({
+ it('should reject unknown structured nodes before rendering', async () => {
+ await expect(
+ compileOutboundEmailContent({
+ type: 'doc',
+ content: [
+ {
+ type: 'someFutureNode',
+ content: [{ type: 'text', text: 'lost' }],
+ },
+ ],
+ } as unknown as EmailDocument),
+ ).rejects.toThrow('Invalid outbound email document');
+ });
+
+ it('should sanitize structured and legacy HTML with the same policy', async () => {
+ const structured = await compileDocument({
type: 'doc',
content: [
- { type: 'someFutureNode', content: [{ type: 'text', text: 'lost' }] },
{
- type: 'paragraph',
- content: [{ type: 'text', text: 'still rendered' }],
+ type: 'html',
+ attrs: {
+ html: '<a href="javascript:alert(1)" onclick="alert(1)">Open</a><script>alert(1)</script>',
+ },
},
],
});
+ const legacy = await compileOutboundEmailContent(
+ '<a href="javascript:alert(1)" onclick="alert(1)">Open</a><script>alert(1)</script>',
+ );
+
+ for (const html of [structured, legacy.html]) {
+ expect(html).toContain('Open');
+ expect(html).not.toContain('javascript:');
+ expect(html).not.toContain('onclick');
+ expect(html).not.toContain('<script');
+ }
+ });
- expect(html).not.toContain('lost');
- expect(html).toContain('still rendered');
+ it('should derive plain text from the sanitized HTML', async () => {
+ await expect(
+ compileOutboundEmailContent('<p>Hello <strong>Ada</strong></p>'),
+ ).resolves.toEqual({
+ html: '<p>Hello <strong>Ada</strong></p>',
+ plainText: 'Hello Ada',
+ });
});
describe('unsafe URL schemes', () => {
it('should drop javascript: hrefs from buttons, links and images', async () => {
- const html = await renderRichTextToHtml({
+ const html = await compileDocument({
type: 'doc',
content: [
{
@@ -226,7 +289,7 @@ describe('renderRichTextToHtml', () => {
});
it('should keep http, mailto and variable-bearing URLs', async () => {
- const html = await renderRichTextToHtml({
+ const html = await compileDocument({
type: 'doc',
content: [
{
diff --git a/packages/twenty-server/src/engine/core-modules/email/utils/__tests__/resolve-email-document-bindings.util.spec.ts b/packages/twenty-server/src/engine/core-modules/email/utils/__tests__/resolve-email-document-bindings.util.spec.ts
new file mode 100644
index 00000000000..70b975716a8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/email/utils/__tests__/resolve-email-document-bindings.util.spec.ts
@@ -0,0 +1,181 @@
+import { type EmailDocument } from 'twenty-shared/utils';
+
+import { resolveEmailDocumentBindings } from 'src/engine/core-modules/email/utils/resolve-email-document-bindings.util';
+
+describe('resolveEmailDocumentBindings', () => {
+ it('should resolve every authored string slot without mutating the source', () => {
+ const source = {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: 'Hello {{name}}: {{message}}' },
+ {
+ type: 'variableTag',
+ attrs: { variable: '{{message}}' },
+ marks: [
+ { type: 'bold' },
+ {
+ type: 'link',
+ attrs: { href: 'https://example.com/{{id}}' },
+ },
+ ],
+ },
+ {
+ type: 'text',
+ text: 'link',
+ marks: [
+ {
+ type: 'link',
+ attrs: { href: 'https://example.com/{{id}}' },
+ },
+ ],
+ },
+ ],
+ },
+ {
+ type: 'image',
+ attrs: {
+ src: 'https://example.com/{{id}}.png',
+ href: 'https://example.com/{{id}}',
+ alt: 'Portrait of {{name}}',
+ },
+ },
+ {
+ type: 'html',
+ attrs: { html: '<p>{{name}}</p>' },
+ },
+ ],
+ } satisfies EmailDocument;
+ const snapshot = structuredClone(source);
+ const values: Record<string, string> = {
+ '{{name}}': 'Ada',
+ '{{message}}': 'first\nsecond',
+ '{{id}}': 'person-1',
+ };
+
+ const resolved = resolveEmailDocumentBindings(source, (value) =>
+ Object.entries(values).reduce(
+ (result, [binding, replacement]) =>
+ result.split(binding).join(replacement),
+ value,
+ ),
+ );
+
+ expect(source).toEqual(snapshot);
+ expect(resolved).toEqual({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: 'Hello Ada: first' },
+ { type: 'hardBreak' },
+ { type: 'text', text: 'second' },
+ {
+ type: 'text',
+ text: 'first',
+ marks: [
+ { type: 'bold' },
+ {
+ type: 'link',
+ attrs: { href: 'https://example.com/person-1' },
+ },
+ ],
+ },
+ {
+ type: 'hardBreak',
+ marks: [
+ { type: 'bold' },
+ {
+ type: 'link',
+ attrs: { href: 'https://example.com/person-1' },
+ },
+ ],
+ },
+ {
+ type: 'text',
+ text: 'second',
+ marks: [
+ { type: 'bold' },
+ {
+ type: 'link',
+ attrs: { href: 'https://example.com/person-1' },
+ },
+ ],
+ },
+ {
+ type: 'text',
+ text: 'link',
+ marks: [
+ {
+ type: 'link',
+ attrs: { href: 'https://example.com/person-1' },
+ },
+ ],
+ },
+ ],
+ },
+ {
+ type: 'image',
+ attrs: {
+ src: 'https://example.com/person-1.png',
+ href: 'https://example.com/person-1',
+ alt: 'Portrait of Ada',
+ },
+ },
+ { type: 'html', attrs: { html: '<p>Ada</p>' } },
+ ],
+ });
+ });
+
+ it('should keep resolved values inert', () => {
+ const source = {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'variableTag', attrs: { variable: '{{message}}' } },
+ ],
+ },
+ ],
+ } satisfies EmailDocument;
+ const values: Record<string, string> = {
+ '{{message}}': '{{secret}}',
+ '{{secret}}': 'leaked',
+ };
+
+ const resolved = resolveEmailDocumentBindings(source, (value) =>
+ value.replace(/\{\{[^{}]+\}\}/g, (binding) => values[binding] ?? ''),
+ );
+
+ expect(resolved.content?.[0].content).toEqual([
+ { type: 'text', text: '{{secret}}' },
+ ]);
+ });
+
+ it('should preserve unresolved variable placeholders and omit empty text', () => {
+ const source = {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'variableTag', attrs: { variable: null } },
+ { type: 'text', text: '{{empty}}' },
+ ],
+ },
+ ],
+ } satisfies EmailDocument;
+
+ const resolved = resolveEmailDocumentBindings(source, (value) =>
+ value.replace('{{empty}}', ''),
+ );
+
+ expect(resolved.content?.[0].content).toEqual([
+ { type: 'variableTag', attrs: { variable: null } },
+ ]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/email/utils/__tests__/sanitize-outbound-email-html.util.spec.ts b/packages/twenty-server/src/engine/core-modules/email/utils/__tests__/sanitize-outbound-email-html.util.spec.ts
new file mode 100644
index 00000000000..4c626a8c98e
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/email/utils/__tests__/sanitize-outbound-email-html.util.spec.ts
@@ -0,0 +1,92 @@
+import {
+ sanitizeOutboundEmailHtml,
+ sanitizeOutboundEmailSubject,
+} from 'src/engine/core-modules/email/utils/sanitize-outbound-email-html.util';
+
+describe('outbound email sanitization', () => {
+ beforeAll(() => {
+ jest.useRealTimers();
+ });
+
+ it('should preserve full documents preceded by comments', async () => {
+ const doctype =
+ '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
+ const sanitized = await sanitizeOutboundEmailHtml(
+ `<!-- generated -->${doctype}<html><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta name="x-apple-disable-message-reformatting"><style>.hero { color: red; }</style></head><body><p class="hero">Hello</p></body></html>`,
+ );
+
+ expect(sanitized.startsWith(`${doctype}<html>`)).toBe(true);
+ expect(sanitized).toContain('<head>');
+ expect(sanitized).toContain(
+ '<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">',
+ );
+ expect(sanitized).toContain(
+ '<meta name="x-apple-disable-message-reformatting">',
+ );
+ expect(sanitized).toContain('.hero { color: red; }');
+ expect(sanitized).toContain('<body>');
+ });
+
+ it('should preserve doctypes with repeated whitespace before the HTML name', async () => {
+ const doctype = '<!DOCTYPE \n\t html>';
+ const sanitized = await sanitizeOutboundEmailHtml(
+ `${doctype}<html><body>Hello</body></html>`,
+ );
+
+ expect(sanitized.startsWith(`${doctype}<html>`)).toBe(true);
+ });
+
+ it('should preserve quoted greater-than signs in doctypes', async () => {
+ const doctype = '<!DOCTYPE html SYSTEM "about:legacy-compat?x=>">';
+ const sanitized = await sanitizeOutboundEmailHtml(
+ `${doctype}<html><body>Hello</body></html>`,
+ );
+
+ expect(sanitized.startsWith(`${doctype}<html>`)).toBe(true);
+ });
+
+ it('should reject active meta directives', async () => {
+ const sanitized = await sanitizeOutboundEmailHtml(
+ '<!doctype html><html><head><meta http-equiv="refresh" content="0;url=https://evil.test"></head><body>Hello</body></html>',
+ );
+
+ expect(sanitized).not.toContain('http-equiv="refresh"');
+ });
+
+ it('should scan repeated leading comments without regex backtracking', async () => {
+ const comments = '<!---->'.repeat(2_000);
+
+ const sanitized = await sanitizeOutboundEmailHtml(
+ `${comments}<html><body><p>Hello</p></body></html>`,
+ );
+
+ expect(sanitized).toContain('<html>');
+ expect(sanitized).toContain('<p>Hello</p>');
+ });
+
+ it('should not mistake similarly prefixed elements for an HTML document', async () => {
+ await expect(
+ sanitizeOutboundEmailHtml('<html-preview>Hello</html-preview>'),
+ ).resolves.toBe('Hello');
+ });
+
+ it('should always sanitize subjects as plain text', async () => {
+ await expect(
+ sanitizeOutboundEmailSubject(
+ '<html><body><strong>Hello</strong><script>alert(1)</script></body></html>',
+ ),
+ ).resolves.toBe('Hello');
+ });
+
+ it('should preserve plain-text subject characters without entity encoding', async () => {
+ await expect(
+ sanitizeOutboundEmailSubject('Price < 100 & ready'),
+ ).resolves.toBe('Price < 100 & ready');
+ });
+
+ it('should collapse header control characters', async () => {
+ await expect(
+ sanitizeOutboundEmailSubject('Hello\r\nBcc: [email protected]'),
+ ).resolves.toBe('Hello Bcc: [email protected]');
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/email/utils/compile-outbound-email-content.util.ts b/packages/twenty-server/src/engine/core-modules/email/utils/compile-outbound-email-content.util.ts
new file mode 100644
index 00000000000..1d3311b4140
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/email/utils/compile-outbound-email-content.util.ts
@@ -0,0 +1,41 @@
+import {
+ type JSONContent,
+ reactMarkupFromJSON,
+ render,
+ toPlainText,
+} from 'twenty-emails';
+import {
+ type EmailDocument,
+ isEmailDocumentShape,
+ parseEmailDocument,
+ parseJson,
+} from 'twenty-shared/utils';
+
+import { type CompiledOutboundEmailContent } from 'src/engine/core-modules/email/types/compiled-outbound-email-content.type';
+import { sanitizeOutboundEmailHtml } from 'src/engine/core-modules/email/utils/sanitize-outbound-email-html.util';
+
+const renderContent = async (body: string | EmailDocument): Promise<string> => {
+ const parsedBody = typeof body === 'string' ? parseJson<unknown>(body) : body;
+ const parseResult = parseEmailDocument(parsedBody);
+
+ if (parseResult.success) {
+ return render(reactMarkupFromJSON(parseResult.document as JSONContent));
+ }
+
+ if (typeof body !== 'string' || isEmailDocumentShape(parsedBody)) {
+ throw new Error(`Invalid outbound email document: ${parseResult.error}`);
+ }
+
+ return body;
+};
+
+export const compileOutboundEmailContent = async (
+ body: string | EmailDocument,
+): Promise<CompiledOutboundEmailContent> => {
+ const html = await sanitizeOutboundEmailHtml(await renderContent(body));
+
+ return {
+ html,
+ plainText: toPlainText(html),
+ };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/email/utils/resolve-email-document-bindings.util.ts b/packages/twenty-server/src/engine/core-modules/email/utils/resolve-email-document-bindings.util.ts
new file mode 100644
index 00000000000..f2366a00c61
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/email/utils/resolve-email-document-bindings.util.ts
@@ -0,0 +1,88 @@
+import {
+ type EmailDocument,
+ type EmailDocumentNode,
+ type EmailDocumentStringContext,
+ TIPTAP_NODE_TYPES,
+ transformEmailDocumentStrings,
+} from 'twenty-shared/utils';
+
+const textToInlineNodes = (
+ text: string,
+ marks?: EmailDocumentNode['marks'],
+): EmailDocumentNode[] =>
+ text.split('\n').flatMap((line, index, lines) => [
+ ...(line === ''
+ ? []
+ : [
+ {
+ type: TIPTAP_NODE_TYPES.TEXT,
+ text: line,
+ ...(marks && { marks }),
+ } satisfies EmailDocumentNode,
+ ]),
+ ...(index < lines.length - 1
+ ? [
+ {
+ type: TIPTAP_NODE_TYPES.HARD_BREAK,
+ ...(marks && { marks }),
+ } satisfies EmailDocumentNode,
+ ]
+ : []),
+ ]);
+
+const resolveNode = (
+ node: EmailDocumentNode,
+ resolve: (value: string, context: EmailDocumentStringContext) => string,
+): EmailDocumentNode[] => {
+ if (node.type === TIPTAP_NODE_TYPES.VARIABLE_TAG) {
+ const variable = node.attrs?.variable;
+
+ if (typeof variable !== 'string') {
+ return [node];
+ }
+
+ const resolvedNode = transformEmailDocumentStrings(
+ {
+ type: TIPTAP_NODE_TYPES.TEXT,
+ marks: node.marks,
+ },
+ resolve,
+ );
+
+ return textToInlineNodes(resolve(variable, 'text'), resolvedNode.marks);
+ }
+
+ if (node.type === TIPTAP_NODE_TYPES.TEXT && typeof node.text === 'string') {
+ const resolvedNode = transformEmailDocumentStrings(node, (value, context) =>
+ context === 'text' ? value : resolve(value, context),
+ );
+
+ return textToInlineNodes(resolve(node.text, 'text'), resolvedNode.marks);
+ }
+
+ const { content, ...nodeWithoutContent } = node;
+ const resolvedNode = transformEmailDocumentStrings(
+ nodeWithoutContent,
+ resolve,
+ );
+
+ return [
+ {
+ ...resolvedNode,
+ ...(content && {
+ content: content.flatMap((childNode) =>
+ resolveNode(childNode, resolve),
+ ),
+ }),
+ },
+ ];
+};
+
+export const resolveEmailDocumentBindings = (
+ document: EmailDocument,
+ resolve: (value: string, context: EmailDocumentStringContext) => string,
+): EmailDocument => {
+ const [resolvedDocument] = resolveNode(document, resolve);
+
+ return resolvedDocument as EmailDocument;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/email/utils/sanitize-outbound-email-html.util.ts b/packages/twenty-server/src/engine/core-modules/email/utils/sanitize-outbound-email-html.util.ts
new file mode 100644
index 00000000000..df0960cbaec
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/email/utils/sanitize-outbound-email-html.util.ts
@@ -0,0 +1,159 @@
+import DOMPurify from 'dompurify';
+
+let purifierPromise: Promise<ReturnType<typeof DOMPurify>> | undefined;
+
+const MAX_DOCTYPE_LENGTH = 512;
+const SUBJECT_CONTROL_CHARACTERS_PATTERN =
+ /[\u0000-\u001f\u007f\u0080-\u009f]+/g;
+
+const isWhitespace = (character: string | undefined): boolean =>
+ character !== undefined && /\s/u.test(character);
+
+type HtmlDocumentPreamble = {
+ isWholeDocument: boolean;
+ doctype?: string;
+};
+
+const findDoctypeEnd = (html: string, start: number): number | undefined => {
+ const searchEnd = Math.min(html.length, start + MAX_DOCTYPE_LENGTH);
+ let quote: '"' | "'" | undefined;
+
+ for (let cursor = start + '<!doctype'.length; cursor < searchEnd; cursor++) {
+ const character = html[cursor];
+
+ if (quote !== undefined) {
+ if (character === quote) {
+ quote = undefined;
+ }
+
+ continue;
+ }
+
+ if (character === '"' || character === "'") {
+ quote = character;
+ } else if (character === '>') {
+ return cursor;
+ }
+ }
+
+ return undefined;
+};
+
+const isHtmlDoctype = (doctype: string): boolean => {
+ let cursor = '<!doctype'.length;
+
+ if (!isWhitespace(doctype[cursor])) {
+ return false;
+ }
+
+ while (isWhitespace(doctype[cursor])) {
+ cursor += 1;
+ }
+
+ return (
+ doctype.slice(cursor, cursor + 'html'.length).toLowerCase() === 'html' &&
+ (doctype[cursor + 'html'.length] === '>' ||
+ isWhitespace(doctype[cursor + 'html'.length]))
+ );
+};
+
+const inspectHtmlDocumentPreamble = (html: string): HtmlDocumentPreamble => {
+ let cursor = 0;
+
+ while (cursor < html.length) {
+ while (isWhitespace(html[cursor])) {
+ cursor += 1;
+ }
+
+ if (!html.startsWith('<!--', cursor)) {
+ break;
+ }
+
+ const commentEnd = html.indexOf('-->', cursor + 4);
+
+ if (commentEnd === -1) {
+ return { isWholeDocument: false };
+ }
+
+ cursor = commentEnd + 3;
+ }
+
+ const normalizedStart = html.slice(cursor, cursor + 10).toLowerCase();
+
+ const startsWithDoctype =
+ normalizedStart.startsWith('<!doctype') &&
+ (html[cursor + 9] === '>' || isWhitespace(html[cursor + 9]));
+
+ if (startsWithDoctype) {
+ const doctypeEnd = findDoctypeEnd(html, cursor);
+ const doctype =
+ doctypeEnd !== undefined ? html.slice(cursor, doctypeEnd + 1) : undefined;
+
+ return {
+ isWholeDocument: true,
+ ...(doctype !== undefined && isHtmlDoctype(doctype) && { doctype }),
+ };
+ }
+
+ return {
+ isWholeDocument:
+ normalizedStart.startsWith('<html') &&
+ (html[cursor + 5] === '>' || isWhitespace(html[cursor + 5])),
+ };
+};
+
+const getPurifier = (): Promise<ReturnType<typeof DOMPurify>> => {
+ purifierPromise ??= import('jsdom').then(({ JSDOM }) => {
+ const purifier = DOMPurify(new JSDOM('').window);
+
+ purifier.addHook('uponSanitizeAttribute', (node, attribute) => {
+ if (
+ node.nodeName === 'META' &&
+ attribute.attrName === 'http-equiv' &&
+ attribute.attrValue.trim().toLowerCase() !== 'content-type'
+ ) {
+ attribute.keepAttr = false;
+ }
+ });
+
+ return purifier;
+ });
+
+ return purifierPromise;
+};
+
+export const sanitizeOutboundEmailHtml = async (
+ html: string,
+): Promise<string> => {
+ const preamble = inspectHtmlDocumentPreamble(html);
+ const sanitizedHtml = (await getPurifier()).sanitize(html, {
+ WHOLE_DOCUMENT: preamble.isWholeDocument,
+ ...(preamble.isWholeDocument && {
+ ADD_TAGS: ['meta'],
+ ADD_ATTR: ['charset', 'content', 'http-equiv', 'name'],
+ }),
+ });
+
+ // DOMPurify intentionally removes document types and comments. Restore the
+ // inert doctype so email clients stay in standards mode; conditional comments
+ // remain stripped because preserving arbitrary commented markup would create
+ // a sanitizer bypass for raw HTML blocks and legacy bodies.
+ return preamble.doctype === undefined
+ ? sanitizedHtml
+ : `${preamble.doctype}${sanitizedHtml}`;
+};
+
+export const sanitizeOutboundEmailSubject = async (
+ subject: string,
+): Promise<string> => {
+ const sanitizedSubject = (await getPurifier()).sanitize(subject, {
+ ALLOWED_ATTR: [],
+ ALLOWED_TAGS: [],
+ RETURN_DOM_FRAGMENT: true,
+ });
+
+ return (sanitizedSubject.textContent ?? '').replace(
+ SUBJECT_CONTROL_CHARACTERS_PATTERN,
+ ' ',
+ );
+};
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/tools/__tests__/load-skill.tool.spec.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/tools/__tests__/load-skill.tool.spec.ts
new file mode 100644
index 00000000000..8d2961f5883
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/tools/__tests__/load-skill.tool.spec.ts
@@ -0,0 +1,38 @@
+import { createLoadSkillTool } from 'src/engine/core-modules/tool-provider/tools/load-skill.tool';
+import { type FlatSkill } from 'src/engine/metadata-modules/flat-skill/types/flat-skill.type';
+
+describe('createLoadSkillTool', () => {
+ it('projects canonical skill documents to Markdown', async () => {
+ const tool = createLoadSkillTool(
+ async () => [
+ {
+ name: 'sales-playbook',
+ label: 'Sales playbook',
+ content: JSON.stringify({
+ type: 'doc',
+ attrs: { schemaVersion: 1 },
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'Qualify the account.' }],
+ },
+ ],
+ }),
+ } as FlatSkill,
+ ],
+ async () => [],
+ );
+
+ await expect(
+ tool.execute({ skillNames: ['sales-playbook'] }),
+ ).resolves.toMatchObject({
+ skills: [
+ {
+ name: 'sales-playbook',
+ label: 'Sales playbook',
+ content: 'Qualify the account.',
+ },
+ ],
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/tools/load-skill.tool.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/tools/load-skill.tool.ts
index b3340d996c9..4853133b43c 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/tools/load-skill.tool.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/tools/load-skill.tool.ts
@@ -1,4 +1,5 @@
import { z } from 'zod';
+import { tipTapDocumentToMarkdown } from 'twenty-shared/utils';
import { type FlatSkill } from 'src/engine/metadata-modules/flat-skill/types/flat-skill.type';
@@ -56,7 +57,7 @@ export const createLoadSkillTool = (
skills: skills.map((skill) => ({
name: skill.name,
label: skill.label,
- content: skill.content,
+ content: tipTapDocumentToMarkdown(skill.content),
})),
message: `Loaded ${skills.map((skill) => skill.label).join(', ')}.`,
};
diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-composer.service.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-composer.service.ts
index 4cf37b50147..1bb4315fa37 100644
--- a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-composer.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-composer.service.ts
@@ -2,8 +2,6 @@ import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { isNonEmptyString } from '@sniptt/guards';
-import DOMPurify from 'dompurify';
-import { toPlainText } from 'twenty-emails';
import { MAX_EMAIL_RECIPIENTS } from 'twenty-shared/constants';
import {
ConnectedAccountProvider,
@@ -15,6 +13,8 @@ import { z } from 'zod';
import { FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
import { FileService } from 'src/engine/core-modules/file/services/file.service';
+import { compileOutboundEmailContent } from 'src/engine/core-modules/email/utils/compile-outbound-email-content.util';
+import { sanitizeOutboundEmailSubject } from 'src/engine/core-modules/email/utils/sanitize-outbound-email-html.util';
import { EMAIL_ATTACHMENT_FILE_FOLDERS } from 'src/engine/core-modules/tool/tools/email-tool/constants/email-attachment-file-folders.const';
import {
EmailToolException,
@@ -23,7 +23,6 @@ import {
import { type ComposeEmailParams } from 'src/engine/core-modules/tool/tools/email-tool/types/compose-email-params.type';
import { EmailComposerResult } from 'src/engine/core-modules/tool/tools/email-tool/types/email-composer-result.type';
import { parseCommaSeparatedEmails } from 'src/engine/core-modules/tool/tools/email-tool/utils/parse-comma-separated-emails.util';
-import { renderEmailBodyToHtml } from 'src/engine/core-modules/tool/tools/email-tool/utils/render-email-body.util';
import { selectConnectedAccountIdForCaller } from 'src/engine/core-modules/tool/tools/email-tool/utils/select-connected-account-id-for-caller.util';
import { type ToolExecutionContext } from 'src/engine/core-modules/tool/types/tool-execution-context.type';
import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
@@ -418,14 +417,9 @@ export class EmailComposerService {
const attachments = await this.getAttachments(files || [], workspaceId);
- const { JSDOM } = await import('jsdom');
- const window = new JSDOM('').window;
- const purify = DOMPurify(window);
-
- const htmlBody = await renderEmailBodyToHtml(body ?? '');
- const sanitizedHtmlBody = purify.sanitize(htmlBody);
- const plainTextBody = toPlainText(sanitizedHtmlBody);
- const sanitizedSubject = purify.sanitize(subject || '');
+ const { html: sanitizedHtmlBody, plainText: plainTextBody } =
+ await compileOutboundEmailContent(body ?? '');
+ const sanitizedSubject = await sanitizeOutboundEmailSubject(subject || '');
const { threadExternalId, references } =
isDefined(inReplyTo) && isDefined(messageChannel)
diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/utils/__tests__/render-email-body.util.spec.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/utils/__tests__/render-email-body.util.spec.ts
deleted file mode 100644
index 17f08172ccd..00000000000
--- a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/utils/__tests__/render-email-body.util.spec.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { renderEmailBodyToHtml } from 'src/engine/core-modules/tool/tools/email-tool/utils/render-email-body.util';
-
-jest.mock(
- 'src/engine/core-modules/tool/tools/email-tool/utils/render-rich-text-to-html.util',
- () => ({
- renderRichTextToHtml: jest.fn().mockResolvedValue('<p>rendered html</p>'),
- }),
-);
-
-const { renderRichTextToHtml } = jest.requireMock(
- 'src/engine/core-modules/tool/tools/email-tool/utils/render-rich-text-to-html.util',
-);
-
-describe('renderEmailBodyToHtml', () => {
- afterEach(() => {
- jest.clearAllMocks();
- });
-
- it('should pass an HTML string through untouched', async () => {
- const html = '<p>Hello <strong>there</strong></p>';
-
- await expect(renderEmailBodyToHtml(html)).resolves.toBe(html);
- expect(renderRichTextToHtml).not.toHaveBeenCalled();
- });
-
- it('should render an email document through the shared renderer', async () => {
- const document = {
- type: 'doc' as const,
- content: [
- {
- type: 'paragraph',
- content: [{ type: 'text', text: 'Hello' }],
- },
- ],
- };
-
- await expect(renderEmailBodyToHtml(document)).resolves.toBe(
- '<p>rendered html</p>',
- );
- expect(renderRichTextToHtml).toHaveBeenCalledWith(document);
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/utils/render-email-body.util.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/utils/render-email-body.util.ts
deleted file mode 100644
index 781d56e0ea1..00000000000
--- a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/utils/render-email-body.util.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import DOMPurify from 'dompurify';
-import { type JSONContent } from 'twenty-emails';
-import {
- type EmailDocument,
- type EmailDocumentNode,
- transformEmailDocumentStrings,
-} from 'twenty-shared/utils';
-
-import { renderRichTextToHtml } from 'src/engine/core-modules/tool/tools/email-tool/utils/render-rich-text-to-html.util';
-
-let purifyInstance: ReturnType<typeof DOMPurify> | null = null;
-
-const getPurify = async () => {
- if (purifyInstance === null) {
- const { JSDOM } = await import('jsdom');
-
- purifyInstance = DOMPurify(new JSDOM('').window);
- }
-
- return purifyInstance;
-};
-
-export const renderEmailBodyToHtml = async (
- body: string | EmailDocument,
-): Promise<string> => {
- if (typeof body === 'string') {
- return body;
- }
-
- const purify = await getPurify();
-
- const sanitizedBody = transformEmailDocumentStrings(
- body as EmailDocumentNode,
- (value, context) => (context === 'html' ? purify.sanitize(value) : value),
- );
-
- return renderRichTextToHtml(sanitizedBody as JSONContent);
-};
diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/utils/render-rich-text-to-html.util.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/utils/render-rich-text-to-html.util.ts
deleted file mode 100644
index 8a074702f29..00000000000
--- a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/utils/render-rich-text-to-html.util.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { type JSONContent, reactMarkupFromJSON, render } from 'twenty-emails';
-
-export const renderRichTextToHtml = async (
- jsonContent: JSONContent,
-): Promise<string> => {
- const reactMarkup = reactMarkupFromJSON(jsonContent);
-
- return render(reactMarkup);
-};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
index 362a4453e20..7c51128857b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
@@ -14,7 +14,11 @@ import {
import { type RunAgentMessage } from 'twenty-shared/application';
import { AUTO_SELECT_SMART_MODEL_ID } from 'twenty-shared/constants';
import { type ActorMetadata } from 'twenty-shared/types';
-import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+import {
+ isDefined,
+ isNonEmptyArray,
+ tipTapDocumentToMarkdown,
+} from 'twenty-shared/utils';
import { type Repository } from 'typeorm';
import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
@@ -354,7 +358,7 @@ export class AgentAsyncExecutorService {
let hasNoMoreAvailableCredits = false;
const textResponse = await generateText({
- system: `${baseSystemPrompt}\n\n${agent ? agent.prompt : ''}${toolCatalogSection}`,
+ system: `${baseSystemPrompt}\n\n${agent ? tipTapDocumentToMarkdown(agent.prompt) : ''}${toolCatalogSection}`,
tools,
model: registeredModel.model,
messages: messages.map(
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/system-prompt-builder.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/system-prompt-builder.service.spec.ts
index 26d17be3b0b..80699400de2 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/system-prompt-builder.service.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/system-prompt-builder.service.spec.ts
@@ -71,4 +71,37 @@ describe('SystemPromptBuilderService', () => {
expect(result.endsWith('\n')).toBe(false);
});
});
+
+ describe('buildWorkspaceInstructionsSection', () => {
+ it('projects canonical TipTap JSON to Markdown', () => {
+ const result = buildService().buildWorkspaceInstructionsSection(
+ JSON.stringify({
+ type: 'doc',
+ attrs: { schemaVersion: 1 },
+ content: [
+ {
+ type: 'heading',
+ attrs: { level: 2 },
+ content: [{ type: 'text', text: 'Sales rules' }],
+ },
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'Be concise.' }],
+ },
+ ],
+ }),
+ );
+
+ expect(result).toContain('## Sales rules\n\nBe concise.');
+ expect(result).not.toContain('"type":"doc"');
+ });
+
+ it('omits an empty canonical document', () => {
+ expect(
+ buildService().buildWorkspaceInstructionsSection(
+ JSON.stringify({ type: 'doc', attrs: { schemaVersion: 1 } }),
+ ),
+ ).toBe('');
+ });
+ });
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/system-prompt-builder.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/system-prompt-builder.service.ts
index 780e12fff31..a6fa33d2ca0 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/system-prompt-builder.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/system-prompt-builder.service.ts
@@ -1,7 +1,10 @@
import { Injectable } from '@nestjs/common';
import { isNonEmptyString } from '@sniptt/guards';
-import { getValidTimeZoneOrUndefined } from 'twenty-shared/utils';
+import {
+ getValidTimeZoneOrUndefined,
+ tipTapDocumentToMarkdown,
+} from 'twenty-shared/utils';
import { COMMON_PRELOAD_TOOLS } from 'src/engine/core-modules/tool-provider/constants/common-preload-tools.const';
import { ToolRegistryService } from 'src/engine/core-modules/tool-provider/services/tool-registry.service';
@@ -75,11 +78,11 @@ export class SystemPromptBuilderService {
estimatedTokenCount: estimateTokenCount(responseFormatContent),
});
- if (workspaceInstructions) {
- const workspaceSection = this.buildWorkspaceInstructionsSection(
- workspaceInstructions,
- );
+ const workspaceSection = this.buildWorkspaceInstructionsSection(
+ workspaceInstructions ?? '',
+ );
+ if (isNonEmptyString(workspaceSection)) {
sections.push({
title: 'Workspace Instructions',
content: workspaceSection,
@@ -146,8 +149,12 @@ export class SystemPromptBuilderService {
CHAT_SYSTEM_PROMPTS.RESPONSE_FORMAT,
];
- if (workspaceInstructions) {
- parts.push(this.buildWorkspaceInstructionsSection(workspaceInstructions));
+ const workspaceInstructionsSection = this.buildWorkspaceInstructionsSection(
+ workspaceInstructions ?? '',
+ );
+
+ if (isNonEmptyString(workspaceInstructionsSection)) {
+ parts.push(workspaceInstructionsSection);
}
if (userContext) {
@@ -170,12 +177,18 @@ export class SystemPromptBuilderService {
}
buildWorkspaceInstructionsSection(instructions: string): string {
+ const projectedInstructions = tipTapDocumentToMarkdown(instructions).trim();
+
+ if (!isNonEmptyString(projectedInstructions)) {
+ return '';
+ }
+
return `
## Workspace Instructions
The following are custom instructions provided by the workspace administrator:
-${instructions}`;
+${projectedInstructions}`;
}
buildUserContextSection(userContext: UserContext): string {
diff --git a/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts b/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts
index 2bb87755f43..d56a9001778 100644
--- a/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts
@@ -53,7 +53,7 @@ import { MessageSuppressionService } from 'src/modules/emailing/services/message
import { MessageCampaignWorkspaceEntity } from 'src/modules/emailing/standard-objects/message-campaign.workspace-entity';
import { MessageListMemberWorkspaceEntity } from 'src/modules/emailing/standard-objects/message-list-member.workspace-entity';
import { collectCampaignVariableNamesFromTemplates } from 'src/modules/emailing/utils/collect-campaign-variable-names-from-templates.util';
-import { renderCampaignBodyToHtml } from 'src/modules/emailing/utils/render-campaign-body.util';
+import { compileCampaignEmailContent } from 'src/modules/emailing/utils/compile-campaign-email-content.util';
import { renderCampaignTemplate } from 'src/modules/emailing/utils/render-campaign-template.util';
import { sendableDraftCampaignSchema } from 'src/modules/emailing/zod-schemas/sendable-draft-campaign.zod-schema';
import { MessageDirection } from 'src/modules/messaging/common/enums/message-direction.enum';
@@ -61,7 +61,6 @@ import { MessageChannelMessageAssociationWorkspaceEntity } from 'src/modules/mes
import { MessageParticipantWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-participant.workspace-entity';
import { MessageThreadWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-thread.workspace-entity';
import { MessageWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message.workspace-entity';
-import { createHtmlToTextConverter } from 'src/modules/messaging/message-import-manager/utils/create-html-to-text-converter.util';
import { PersonWorkspaceEntity } from 'src/modules/person/standard-objects/person.workspace-entity';
import {
MessageParticipantRole,
@@ -115,8 +114,6 @@ const toRawRecipient = (person: {
@Injectable()
export class MessageCampaignService {
private readonly logger = new Logger(MessageCampaignService.name);
- private readonly htmlToText = createHtmlToTextConverter();
-
constructor(
@InjectWorkspaceScopedRepository(EmailingDomainEntity)
private readonly emailingDomainRepository: WorkspaceScopedRepository<EmailingDomainEntity>,
@@ -267,7 +264,7 @@ export class MessageCampaignService {
const renderedSubject = renderCampaignTemplate(subject, variables, {
escapeValues: false,
});
- const renderedHtml = await renderCampaignBodyToHtml(html, variables);
+ const compiledContent = await compileCampaignEmailContent(html, variables);
return this.emailingDomainSenderService.sendEmail(
workspaceId,
@@ -276,8 +273,8 @@ export class MessageCampaignService {
from: fromAddress,
to: [toAddress],
subject: renderedSubject,
- text: this.htmlToText(renderedHtml),
- html: renderedHtml,
+ text: compiledContent.plainText,
+ html: compiledContent.html,
unsubscribeTopicId,
},
);
@@ -452,11 +449,10 @@ export class MessageCampaignService {
escapeValues: false,
},
);
- const html = await renderCampaignBodyToHtml(
+ const compiledContent = await compileCampaignEmailContent(
campaign.bodyTemplate ?? '',
variables,
);
- const text = this.htmlToText(html);
const fromAddress = campaign.fromAddress?.primaryEmail ?? '';
const unsubscribeTopicId = campaign.unsubscribeTopicId ?? undefined;
@@ -482,8 +478,8 @@ export class MessageCampaignService {
from: fromAddress,
to: [recipientEmail],
subject,
- text,
- html,
+ text: compiledContent.plainText,
+ html: compiledContent.html,
unsubscribeTopicId,
},
);
@@ -526,7 +522,7 @@ export class MessageCampaignService {
deliveryStatus: CAMPAIGN_MESSAGE_DELIVERY_STATUS.SENT,
headerMessageId: result.messageId,
subject,
- text,
+ text: compiledContent.plainText,
});
await this.emailBillingService.billSentEmails({
@@ -655,8 +651,9 @@ export class MessageCampaignService {
const now = new Date();
// The stored message keeps the unresolved template, so placeholders stay
// visible on the campaign's message records.
- const text = this.htmlToText(
- await renderCampaignBodyToHtml(bodyTemplate, null),
+ const { plainText: text } = await compileCampaignEmailContent(
+ bodyTemplate,
+ null,
);
const rows = recipients.map((recipient) => ({
recipient,
diff --git a/packages/twenty-server/src/modules/emailing/utils/__tests__/compile-campaign-email-content.util.spec.ts b/packages/twenty-server/src/modules/emailing/utils/__tests__/compile-campaign-email-content.util.spec.ts
new file mode 100644
index 00000000000..e7bcf84e386
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/utils/__tests__/compile-campaign-email-content.util.spec.ts
@@ -0,0 +1,303 @@
+import { EMAIL_DOCUMENT_SCHEMA_VERSION } from 'twenty-shared/utils';
+
+import {
+ EmailingDomainException,
+ EmailingDomainExceptionCode,
+} from 'src/engine/core-modules/emailing-domain/exceptions/emailing-domain.exception';
+import { compileCampaignEmailContent } from 'src/modules/emailing/utils/compile-campaign-email-content.util';
+
+jest.mock(
+ 'src/engine/core-modules/email/utils/compile-outbound-email-content.util',
+ () => ({
+ compileOutboundEmailContent: jest.fn().mockResolvedValue({
+ html: '<p>rendered html</p>',
+ plainText: 'rendered html',
+ }),
+ }),
+);
+
+const { compileOutboundEmailContent } = jest.requireMock(
+ 'src/engine/core-modules/email/utils/compile-outbound-email-content.util',
+);
+
+const VARIABLES = {
+ firstName: 'Ada',
+ lastName: 'Lovelace',
+ fullName: 'Ada Lovelace',
+ email: '[email protected]',
+ personId: 'person-123',
+};
+
+const serializeDocument = (content?: unknown[]) =>
+ JSON.stringify({
+ type: 'doc',
+ attrs: { schemaVersion: EMAIL_DOCUMENT_SCHEMA_VERSION },
+ ...(content === undefined ? {} : { content }),
+ });
+
+const buildDocument = (text: string) =>
+ serializeDocument([{ type: 'paragraph', content: [{ type: 'text', text }] }]);
+
+const compiledDocument = () => compileOutboundEmailContent.mock.calls[0][0];
+
+describe('compileCampaignEmailContent', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('should render a TipTap document through the email renderer', async () => {
+ const content = await compileCampaignEmailContent(
+ buildDocument('Hello there'),
+ VARIABLES,
+ );
+
+ expect(content).toEqual({
+ html: '<p>rendered html</p>',
+ plainText: 'rendered html',
+ });
+ expect(compiledDocument()).toEqual({
+ type: 'doc',
+ attrs: { schemaVersion: EMAIL_DOCUMENT_SCHEMA_VERSION },
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'Hello there' }],
+ },
+ ],
+ });
+ });
+
+ it('should substitute variables inside text nodes', async () => {
+ await compileCampaignEmailContent(
+ buildDocument('Hi {{firstName}}, from {{fullName}}'),
+ VARIABLES,
+ );
+
+ expect(compiledDocument().content[0].content[0].text).toBe(
+ 'Hi Ada, from Ada Lovelace',
+ );
+ });
+
+ it('should substitute variables carried by variable chip attributes', async () => {
+ await compileCampaignEmailContent(
+ serializeDocument([
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: 'Dear ' },
+ { type: 'variableTag', attrs: { variable: '{{firstName}}' } },
+ ],
+ },
+ ]),
+ VARIABLES,
+ );
+
+ expect(compiledDocument().content[0].content[1]).toEqual({
+ type: 'text',
+ text: 'Ada',
+ });
+ });
+
+ it('should substitute variables inside button and link URLs', async () => {
+ await compileCampaignEmailContent(
+ serializeDocument([
+ {
+ type: 'button',
+ attrs: { href: 'https://example.com/p/{{personId}}' },
+ content: [{ type: 'text', text: 'Open' }],
+ },
+ {
+ type: 'paragraph',
+ content: [
+ {
+ type: 'text',
+ text: 'here',
+ marks: [
+ {
+ type: 'link',
+ attrs: { href: 'https://example.com/u/{{personId}}' },
+ },
+ ],
+ },
+ ],
+ },
+ ]),
+ VARIABLES,
+ );
+
+ expect(compiledDocument().content[0].attrs.href).toBe(
+ 'https://example.com/p/person-123',
+ );
+ expect(compiledDocument().content[1].content[0].marks[0].attrs.href).toBe(
+ 'https://example.com/u/person-123',
+ );
+ });
+
+ it('should substitute variables inside image link URLs', async () => {
+ await compileCampaignEmailContent(
+ serializeDocument([
+ {
+ type: 'image',
+ attrs: {
+ src: 'https://example.com/{{personId}}/banner.png',
+ href: 'https://example.com/promo/{{personId}}',
+ alt: 'Banner for {{firstName}}',
+ },
+ },
+ ]),
+ VARIABLES,
+ );
+
+ expect(compiledDocument().content[0].attrs.href).toBe(
+ 'https://example.com/promo/person-123',
+ );
+ expect(compiledDocument().content[0].attrs.src).toBe(
+ 'https://example.com/person-123/banner.png',
+ );
+ expect(compiledDocument().content[0].attrs.alt).toBe('Banner for Ada');
+ });
+
+ it('should substitute variables inside raw HTML blocks with escaping', async () => {
+ await compileCampaignEmailContent(
+ serializeDocument([
+ {
+ type: 'html',
+ attrs: {
+ html: '<a href="https://example.com/p/{{personId}}">Hi {{firstName}}</a>',
+ },
+ },
+ ]),
+ { ...VARIABLES, firstName: '<b>Ada</b>' },
+ );
+
+ expect(compiledDocument().content[0].attrs.html).toBe(
+ '<a href="https://example.com/p/person-123">Hi &lt;b&gt;Ada&lt;/b&gt;</a>',
+ );
+ });
+
+ it('should substitute variables nested under marks and lists', async () => {
+ const document = serializeDocument([
+ {
+ type: 'bulletList',
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ {
+ type: 'text',
+ text: 'Dear {{firstName}}',
+ marks: [{ type: 'bold' }],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ]);
+
+ await compileCampaignEmailContent(document, VARIABLES);
+
+ const textNode =
+ compiledDocument().content[0].content[0].content[0].content[0];
+
+ expect(textNode.text).toBe('Dear Ada');
+ expect(textNode.marks).toEqual([{ type: 'bold' }]);
+ });
+
+ it('should replace unknown variables with an empty string', async () => {
+ await compileCampaignEmailContent(
+ buildDocument('Hi {{unknown}}!'),
+ VARIABLES,
+ );
+
+ expect(compiledDocument().content[0].content[0].text).toBe('Hi !');
+ });
+
+ it('should leave a value containing markup for the renderer to escape', async () => {
+ await compileCampaignEmailContent(buildDocument('{{firstName}}'), {
+ ...VARIABLES,
+ firstName: '<script>alert(1)</script>',
+ });
+
+ expect(compiledDocument().content[0].content[0].text).toBe(
+ '<script>alert(1)</script>',
+ );
+ });
+
+ it('should keep placeholders in place when no variables are given', async () => {
+ await compileCampaignEmailContent(buildDocument('Hi {{firstName}}'), null);
+
+ expect(compiledDocument().content[0].content[0].text).toBe(
+ 'Hi {{firstName}}',
+ );
+ });
+
+ it('should render an empty body as empty without calling the renderer', async () => {
+ expect(await compileCampaignEmailContent('', VARIABLES)).toEqual({
+ html: '',
+ plainText: '',
+ });
+ expect(await compileCampaignEmailContent(' ', VARIABLES)).toEqual({
+ html: '',
+ plainText: '',
+ });
+ expect(compileOutboundEmailContent).not.toHaveBeenCalled();
+ });
+
+ it('should reject a body that is not JSON', async () => {
+ await expect(
+ compileCampaignEmailContent('<p>Hi {{firstName}}</p>', VARIABLES),
+ ).rejects.toThrow('not a renderable email document');
+ });
+
+ it('should reject a JSON value that is not a document', async () => {
+ await expect(
+ compileCampaignEmailContent('{"foo":"bar"}', VARIABLES),
+ ).rejects.toMatchObject({
+ code: EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_NOT_SENDABLE,
+ });
+
+ await expect(
+ compileCampaignEmailContent('{"foo":"bar"}', VARIABLES),
+ ).rejects.toBeInstanceOf(EmailingDomainException);
+ });
+
+ it('should reject a document with a non-array content', async () => {
+ await expect(
+ compileCampaignEmailContent(
+ JSON.stringify({
+ type: 'doc',
+ attrs: { schemaVersion: EMAIL_DOCUMENT_SCHEMA_VERSION },
+ content: 'not an array',
+ }),
+ VARIABLES,
+ ),
+ ).rejects.toThrow('not a renderable email document');
+ });
+
+ it('should render a document with no content at all', async () => {
+ const content = await compileCampaignEmailContent(
+ serializeDocument(),
+ VARIABLES,
+ );
+
+ expect(content.html).toBe('<p>rendered html</p>');
+ expect(compiledDocument()).toEqual({
+ type: 'doc',
+ attrs: { schemaVersion: EMAIL_DOCUMENT_SCHEMA_VERSION },
+ });
+ });
+
+ it('should reject a versionless document', async () => {
+ await expect(
+ compileCampaignEmailContent(
+ JSON.stringify({ type: 'doc', content: [] }),
+ VARIABLES,
+ ),
+ ).rejects.toThrow('not a renderable email document');
+ });
+});
diff --git a/packages/twenty-server/src/modules/emailing/utils/__tests__/render-campaign-body.util.spec.ts b/packages/twenty-server/src/modules/emailing/utils/__tests__/render-campaign-body.util.spec.ts
deleted file mode 100644
index 3da3ce07840..00000000000
--- a/packages/twenty-server/src/modules/emailing/utils/__tests__/render-campaign-body.util.spec.ts
+++ /dev/null
@@ -1,264 +0,0 @@
-import { renderCampaignBodyToHtml } from 'src/modules/emailing/utils/render-campaign-body.util';
-
-jest.mock(
- 'src/engine/core-modules/tool/tools/email-tool/utils/render-rich-text-to-html.util',
- () => ({
- renderRichTextToHtml: jest.fn().mockResolvedValue('<p>rendered html</p>'),
- }),
-);
-
-const { renderRichTextToHtml } = jest.requireMock(
- 'src/engine/core-modules/tool/tools/email-tool/utils/render-rich-text-to-html.util',
-);
-
-const VARIABLES = {
- firstName: 'Ada',
- lastName: 'Lovelace',
- fullName: 'Ada Lovelace',
- email: '[email protected]',
- personId: 'person-123',
-};
-
-const buildDocument = (text: string) =>
- JSON.stringify({
- type: 'doc',
- content: [{ type: 'paragraph', content: [{ type: 'text', text }] }],
- });
-
-const renderedDocument = () => renderRichTextToHtml.mock.calls[0][0];
-
-describe('renderCampaignBodyToHtml', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- });
-
- it('should render a TipTap document through the email renderer', async () => {
- const html = await renderCampaignBodyToHtml(
- buildDocument('Hello there'),
- VARIABLES,
- );
-
- expect(html).toBe('<p>rendered html</p>');
- expect(renderedDocument()).toEqual({
- type: 'doc',
- content: [
- {
- type: 'paragraph',
- content: [{ type: 'text', text: 'Hello there' }],
- },
- ],
- });
- });
-
- it('should substitute variables inside text nodes', async () => {
- await renderCampaignBodyToHtml(
- buildDocument('Hi {{firstName}}, from {{fullName}}'),
- VARIABLES,
- );
-
- expect(renderedDocument().content[0].content[0].text).toBe(
- 'Hi Ada, from Ada Lovelace',
- );
- });
-
- it('should substitute variables carried by variable chip attributes', async () => {
- await renderCampaignBodyToHtml(
- JSON.stringify({
- type: 'doc',
- content: [
- {
- type: 'paragraph',
- content: [
- { type: 'text', text: 'Dear ' },
- { type: 'variableTag', attrs: { variable: '{{firstName}}' } },
- ],
- },
- ],
- }),
- VARIABLES,
- );
-
- expect(renderedDocument().content[0].content[1].attrs.variable).toBe('Ada');
- });
-
- it('should substitute variables inside button and link URLs', async () => {
- await renderCampaignBodyToHtml(
- JSON.stringify({
- type: 'doc',
- content: [
- {
- type: 'button',
- attrs: { href: 'https://example.com/p/{{personId}}' },
- content: [{ type: 'text', text: 'Open' }],
- },
- {
- type: 'paragraph',
- content: [
- {
- type: 'text',
- text: 'here',
- marks: [
- {
- type: 'link',
- attrs: { href: 'https://example.com/u/{{personId}}' },
- },
- ],
- },
- ],
- },
- ],
- }),
- VARIABLES,
- );
-
- expect(renderedDocument().content[0].attrs.href).toBe(
- 'https://example.com/p/person-123',
- );
- expect(renderedDocument().content[1].content[0].marks[0].attrs.href).toBe(
- 'https://example.com/u/person-123',
- );
- });
-
- it('should substitute variables inside image link URLs', async () => {
- await renderCampaignBodyToHtml(
- JSON.stringify({
- type: 'doc',
- content: [
- {
- type: 'image',
- attrs: {
- src: 'https://example.com/{{personId}}/banner.png',
- href: 'https://example.com/promo/{{personId}}',
- alt: 'Banner for {{firstName}}',
- },
- },
- ],
- }),
- VARIABLES,
- );
-
- expect(renderedDocument().content[0].attrs.href).toBe(
- 'https://example.com/promo/person-123',
- );
- expect(renderedDocument().content[0].attrs.src).toBe(
- 'https://example.com/person-123/banner.png',
- );
- expect(renderedDocument().content[0].attrs.alt).toBe('Banner for Ada');
- });
-
- it('should substitute variables inside raw HTML blocks with escaping', async () => {
- await renderCampaignBodyToHtml(
- JSON.stringify({
- type: 'doc',
- content: [
- {
- type: 'html',
- attrs: {
- html: '<a href="https://example.com/p/{{personId}}">Hi {{firstName}}</a>',
- },
- },
- ],
- }),
- { ...VARIABLES, firstName: '<b>Ada</b>' },
- );
-
- expect(renderedDocument().content[0].attrs.html).toBe(
- '<a href="https://example.com/p/person-123">Hi &lt;b&gt;Ada&lt;/b&gt;</a>',
- );
- });
-
- it('should substitute variables nested under marks and lists', async () => {
- const document = JSON.stringify({
- type: 'doc',
- content: [
- {
- type: 'bulletList',
- content: [
- {
- type: 'listItem',
- content: [
- {
- type: 'paragraph',
- content: [
- {
- type: 'text',
- text: 'Dear {{firstName}}',
- marks: [{ type: 'bold' }],
- },
- ],
- },
- ],
- },
- ],
- },
- ],
- });
-
- await renderCampaignBodyToHtml(document, VARIABLES);
-
- const textNode =
- renderedDocument().content[0].content[0].content[0].content[0];
-
- expect(textNode.text).toBe('Dear Ada');
- expect(textNode.marks).toEqual([{ type: 'bold' }]);
- });
-
- it('should replace unknown variables with an empty string', async () => {
- await renderCampaignBodyToHtml(buildDocument('Hi {{unknown}}!'), VARIABLES);
-
- expect(renderedDocument().content[0].content[0].text).toBe('Hi !');
- });
-
- it('should leave a value containing markup for the renderer to escape', async () => {
- await renderCampaignBodyToHtml(buildDocument('{{firstName}}'), {
- ...VARIABLES,
- firstName: '<script>alert(1)</script>',
- });
-
- expect(renderedDocument().content[0].content[0].text).toBe(
- '<script>alert(1)</script>',
- );
- });
-
- it('should keep placeholders in place when no variables are given', async () => {
- await renderCampaignBodyToHtml(buildDocument('Hi {{firstName}}'), null);
-
- expect(renderedDocument().content[0].content[0].text).toBe(
- 'Hi {{firstName}}',
- );
- });
-
- it('should render an empty body as empty without calling the renderer', async () => {
- expect(await renderCampaignBodyToHtml('', VARIABLES)).toBe('');
- expect(await renderCampaignBodyToHtml(' ', VARIABLES)).toBe('');
- expect(renderRichTextToHtml).not.toHaveBeenCalled();
- });
-
- it('should reject a body that is not JSON', async () => {
- await expect(
- renderCampaignBodyToHtml('<p>Hi {{firstName}}</p>', VARIABLES),
- ).rejects.toThrow('not a renderable email document');
- });
-
- it('should reject a JSON value that is not a document', async () => {
- await expect(
- renderCampaignBodyToHtml('{"foo":"bar"}', VARIABLES),
- ).rejects.toThrow('not a renderable email document');
- });
-
- it('should reject a document with a non-array content', async () => {
- await expect(
- renderCampaignBodyToHtml(
- '{"type":"doc","content":"not an array"}',
- VARIABLES,
- ),
- ).rejects.toThrow('not a renderable email document');
- });
-
- it('should render a document with no content at all', async () => {
- const html = await renderCampaignBodyToHtml('{"type":"doc"}', VARIABLES);
-
- expect(html).toBe('<p>rendered html</p>');
- expect(renderedDocument()).toEqual({ type: 'doc' });
- });
-});
diff --git a/packages/twenty-server/src/modules/emailing/utils/compile-campaign-email-content.util.ts b/packages/twenty-server/src/modules/emailing/utils/compile-campaign-email-content.util.ts
new file mode 100644
index 00000000000..6f77e07af3a
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/utils/compile-campaign-email-content.util.ts
@@ -0,0 +1,46 @@
+import { msg } from '@lingui/core/macro';
+import {
+ isDefined,
+ parseCanonicalEmailDocument,
+ parseJson,
+} from 'twenty-shared/utils';
+
+import { type CompiledOutboundEmailContent } from 'src/engine/core-modules/email/types/compiled-outbound-email-content.type';
+import { compileOutboundEmailContent } from 'src/engine/core-modules/email/utils/compile-outbound-email-content.util';
+import { resolveEmailDocumentBindings } from 'src/engine/core-modules/email/utils/resolve-email-document-bindings.util';
+import {
+ EmailingDomainException,
+ EmailingDomainExceptionCode,
+} from 'src/engine/core-modules/emailing-domain/exceptions/emailing-domain.exception';
+import { renderCampaignTemplate } from 'src/modules/emailing/utils/render-campaign-template.util';
+
+export const compileCampaignEmailContent = async (
+ bodyTemplate: string,
+ variables: Record<string, string> | null,
+): Promise<CompiledOutboundEmailContent> => {
+ if (bodyTemplate.trim() === '') {
+ return { html: '', plainText: '' };
+ }
+
+ const parseResult = parseCanonicalEmailDocument(
+ parseJson<unknown>(bodyTemplate),
+ );
+
+ if (!parseResult.success) {
+ throw new EmailingDomainException(
+ `Campaign bodyTemplate is not a renderable email document: ${parseResult.error}`,
+ EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_NOT_SENDABLE,
+ { userFriendlyMessage: msg`This campaign's email content is invalid.` },
+ );
+ }
+
+ return compileOutboundEmailContent(
+ isDefined(variables)
+ ? resolveEmailDocumentBindings(parseResult.document, (value, context) =>
+ renderCampaignTemplate(value, variables, {
+ escapeValues: context === 'html',
+ }),
+ )
+ : parseResult.document,
+ );
+};
diff --git a/packages/twenty-server/src/modules/emailing/utils/render-campaign-body.util.ts b/packages/twenty-server/src/modules/emailing/utils/render-campaign-body.util.ts
deleted file mode 100644
index d1aeef1ff27..00000000000
--- a/packages/twenty-server/src/modules/emailing/utils/render-campaign-body.util.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import {
- isDefined,
- parseJson,
- parseEmailDocument,
- transformEmailDocumentStrings,
-} from 'twenty-shared/utils';
-
-import { renderEmailBodyToHtml } from 'src/engine/core-modules/tool/tools/email-tool/utils/render-email-body.util';
-import { renderCampaignTemplate } from 'src/modules/emailing/utils/render-campaign-template.util';
-
-export const renderCampaignBodyToHtml = async (
- bodyTemplate: string,
- variables: Record<string, string> | null,
-): Promise<string> => {
- if (bodyTemplate.trim() === '') {
- return '';
- }
-
- const parseResult = parseEmailDocument(parseJson<unknown>(bodyTemplate));
-
- if (!parseResult.success) {
- throw new Error('Campaign bodyTemplate is not a renderable email document');
- }
-
- // Values are substituted into text nodes rather than into the serialized
- // JSON, so a value containing quotes or braces cannot corrupt the document.
- // react-email escapes them when it renders.
- return renderEmailBodyToHtml(
- isDefined(variables)
- ? transformEmailDocumentStrings(parseResult.document, (value, context) =>
- renderCampaignTemplate(value, variables, {
- escapeValues: context === 'html',
- }),
- )
- : parseResult.document,
- );
-};
diff --git a/packages/twenty-server/src/modules/emailing/zod-schemas/__tests__/sendable-draft-campaign.zod-schema.spec.ts b/packages/twenty-server/src/modules/emailing/zod-schemas/__tests__/sendable-draft-campaign.zod-schema.spec.ts
index 0e85ad10392..22ad0e837ec 100644
--- a/packages/twenty-server/src/modules/emailing/zod-schemas/__tests__/sendable-draft-campaign.zod-schema.spec.ts
+++ b/packages/twenty-server/src/modules/emailing/zod-schemas/__tests__/sendable-draft-campaign.zod-schema.spec.ts
@@ -1,4 +1,5 @@
import { MessageCampaignStatus } from 'twenty-shared/types';
+import { EMAIL_DOCUMENT_SCHEMA_VERSION } from 'twenty-shared/utils';
import { sendableDraftCampaignSchema } from 'src/modules/emailing/zod-schemas/sendable-draft-campaign.zod-schema';
describe('sendableDraftCampaignSchema', () => {
@@ -7,6 +8,7 @@ describe('sendableDraftCampaignSchema', () => {
subject: 'Monthly newsletter',
bodyTemplate: JSON.stringify({
type: 'doc',
+ attrs: { schemaVersion: EMAIL_DOCUMENT_SCHEMA_VERSION },
content: [
{ type: 'paragraph', content: [{ type: 'text', text: 'Hello' }] },
],
@@ -75,12 +77,13 @@ describe('sendableDraftCampaignSchema', () => {
).toBe(false);
});
- it('should accept a body holding a valid TipTap document', () => {
+ it('should accept a body holding a canonical TipTap document', () => {
expect(
sendableDraftCampaignSchema.safeParse({
...sendableDraftCampaign,
bodyTemplate: JSON.stringify({
type: 'doc',
+ attrs: { schemaVersion: EMAIL_DOCUMENT_SCHEMA_VERSION },
content: [
{
type: 'paragraph',
@@ -92,6 +95,23 @@ describe('sendableDraftCampaignSchema', () => {
).toBe(true);
});
+ it('should reject a versionless TipTap document', () => {
+ expect(
+ sendableDraftCampaignSchema.safeParse({
+ ...sendableDraftCampaign,
+ bodyTemplate: JSON.stringify({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'Legacy body' }],
+ },
+ ],
+ }),
+ }).success,
+ ).toBe(false);
+ });
+
it('should reject a body that is not an email document', () => {
expect(
sendableDraftCampaignSchema.safeParse({
@@ -116,6 +136,7 @@ describe('sendableDraftCampaignSchema', () => {
...sendableDraftCampaign,
bodyTemplate: JSON.stringify({
type: 'doc',
+ attrs: { schemaVersion: EMAIL_DOCUMENT_SCHEMA_VERSION },
content: [{ type: 'paragraph', content: [{ text: 'no type' }] }],
}),
}).success,
@@ -128,7 +149,7 @@ describe('sendableDraftCampaignSchema', () => {
...sendableDraftCampaign,
bodyTemplate: JSON.stringify({
type: 'doc',
- attrs: { schemaVersion: 1 },
+ attrs: { schemaVersion: EMAIL_DOCUMENT_SCHEMA_VERSION },
content: [
{
type: 'section',
@@ -157,6 +178,7 @@ describe('sendableDraftCampaignSchema', () => {
...sendableDraftCampaign,
bodyTemplate: JSON.stringify({
type: 'doc',
+ attrs: { schemaVersion: EMAIL_DOCUMENT_SCHEMA_VERSION },
content: [{ type: 'countdownTimer', attrs: {} }],
}),
}).success,
diff --git a/packages/twenty-server/src/modules/emailing/zod-schemas/sendable-draft-campaign.zod-schema.ts b/packages/twenty-server/src/modules/emailing/zod-schemas/sendable-draft-campaign.zod-schema.ts
index a0a3897b602..d83e59c1a7d 100644
--- a/packages/twenty-server/src/modules/emailing/zod-schemas/sendable-draft-campaign.zod-schema.ts
+++ b/packages/twenty-server/src/modules/emailing/zod-schemas/sendable-draft-campaign.zod-schema.ts
@@ -1,9 +1,9 @@
import { MessageCampaignStatus } from 'twenty-shared/types';
-import { emailDocumentSchema, parseJson } from 'twenty-shared/utils';
+import { parseCanonicalEmailDocument, parseJson } from 'twenty-shared/utils';
import { z } from 'zod';
const isSendableBodyTemplate = (bodyTemplate: string): boolean =>
- emailDocumentSchema.safeParse(parseJson<unknown>(bodyTemplate)).success;
+ parseCanonicalEmailDocument(parseJson<unknown>(bodyTemplate)).success;
export const sendableDraftCampaignSchema = z.object({
status: z.literal(MessageCampaignStatus.DRAFT),
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/draft-email.workflow-action.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/draft-email.workflow-action.spec.ts
index 238289f9a0b..4f52e0a0630 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/draft-email.workflow-action.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/draft-email.workflow-action.spec.ts
@@ -11,13 +11,6 @@ import { type WorkflowActionSettings } from 'src/modules/workflow/workflow-execu
import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
import { WorkflowRunStepLogWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run-step-log.workspace-service';
-jest.mock(
- 'src/engine/core-modules/tool/tools/email-tool/utils/render-rich-text-to-html.util',
- () => ({
- renderRichTextToHtml: jest.fn().mockResolvedValue('<p>rendered html</p>'),
- }),
-);
-
const baseSettings: WorkflowActionSettings = {
outputSchema: {},
errorHandlingOptions: {
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/send-email.workflow-action.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/send-email.workflow-action.spec.ts
index dcbfe8ea844..b7f376efd60 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/send-email.workflow-action.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/send-email.workflow-action.spec.ts
@@ -11,17 +11,6 @@ import { type WorkflowActionSettings } from 'src/modules/workflow/workflow-execu
import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
import { WorkflowRunStepLogWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run-step-log.workspace-service';
-jest.mock(
- 'src/engine/core-modules/tool/tools/email-tool/utils/render-rich-text-to-html.util',
- () => ({
- renderRichTextToHtml: jest.fn().mockResolvedValue('<p>rendered html</p>'),
- }),
-);
-
-const { renderRichTextToHtml } = jest.requireMock(
- 'src/engine/core-modules/tool/tools/email-tool/utils/render-rich-text-to-html.util',
-);
-
const baseSettings: WorkflowActionSettings = {
outputSchema: {},
errorHandlingOptions: {
@@ -117,8 +106,13 @@ describe('SendEmailWorkflowAction', () => {
},
});
+ const executedBodyDocument = () =>
+ JSON.parse(
+ mockSendEmailTool.execute.mock.calls[0][0].body as string,
+ ) as Record<string, unknown>;
+
describe('email body handling', () => {
- it('should render TipTap JSON body to HTML', async () => {
+ it('should prepare TipTap JSON for the shared email compiler', async () => {
const tipTapBody = JSON.stringify({
type: 'doc',
content: [
@@ -131,14 +125,10 @@ describe('SendEmailWorkflowAction', () => {
await executeWithBody(tipTapBody);
- expect(renderRichTextToHtml).toHaveBeenCalledWith(JSON.parse(tipTapBody));
- expect(mockSendEmailTool.execute).toHaveBeenCalledWith(
- expect.objectContaining({ body: '<p>rendered html</p>' }),
- expect.any(Object),
- );
+ expect(executedBodyDocument()).toEqual(JSON.parse(tipTapBody));
});
- it('should resolve variableTag nodes inside TipTap JSON before rendering', async () => {
+ it('should resolve variableTag nodes inside TipTap JSON before compilation', async () => {
const tipTapBodyWithVariable = JSON.stringify({
type: 'doc',
content: [
@@ -156,7 +146,7 @@ describe('SendEmailWorkflowAction', () => {
await executeWithBody(tipTapBodyWithVariable);
- expect(renderRichTextToHtml).toHaveBeenCalledWith({
+ expect(executedBodyDocument()).toEqual({
type: 'doc',
content: [
{
@@ -192,7 +182,7 @@ describe('SendEmailWorkflowAction', () => {
}),
);
- expect(renderRichTextToHtml).toHaveBeenCalledWith({
+ expect(executedBodyDocument()).toEqual({
type: 'doc',
content: [
{
@@ -233,7 +223,7 @@ describe('SendEmailWorkflowAction', () => {
},
});
- expect(renderRichTextToHtml).toHaveBeenCalledWith({
+ expect(executedBodyDocument()).toEqual({
type: 'doc',
content: [
{
@@ -244,25 +234,44 @@ describe('SendEmailWorkflowAction', () => {
});
});
- it('should not resolve an already-rendered email body a second time', async () => {
- renderRichTextToHtml.mockResolvedValueOnce('<p>{{trigger.email}}</p>');
-
- await executeWithBody(
- JSON.stringify({
- type: 'doc',
- content: [
- {
- type: 'paragraph',
- content: [{ type: 'text', text: '{{trigger.name}}' }],
- },
- ],
- }),
- );
+ it('should keep placeholders from resolved values inert', async () => {
+ await action.execute({
+ currentStepId: 'step-1',
+ steps: [
+ buildSendEmailStep({
+ ...emailInput,
+ body: JSON.stringify({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: '{{trigger.name}}' }],
+ },
+ ],
+ }),
+ }),
+ ],
+ context: {
+ trigger: {
+ name: '{{trigger.email}}',
+ email: '[email protected]',
+ },
+ },
+ runInfo: {
+ workspaceId: 'workspace-1',
+ workflowRunId: 'run-1',
+ },
+ });
- expect(mockSendEmailTool.execute).toHaveBeenCalledWith(
- expect.objectContaining({ body: '<p>{{trigger.email}}</p>' }),
- expect.any(Object),
- );
+ expect(executedBodyDocument()).toEqual({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: '{{trigger.email}}' }],
+ },
+ ],
+ });
});
it('should reject an invalid structured email document', async () => {
@@ -281,7 +290,6 @@ describe('SendEmailWorkflowAction', () => {
it('should pass plain text body through without rendering', async () => {
await executeWithBody('{{trigger.name}}\n{{trigger.email}}');
- expect(renderRichTextToHtml).not.toHaveBeenCalled();
expect(mockSendEmailTool.execute).toHaveBeenCalledWith(
expect.objectContaining({ body: 'John\[email protected]' }),
expect.any(Object),
@@ -291,7 +299,6 @@ describe('SendEmailWorkflowAction', () => {
it('should treat non-TipTap JSON as plain text', async () => {
await executeWithBody('{"key":"value"}');
- expect(renderRichTextToHtml).not.toHaveBeenCalled();
expect(mockSendEmailTool.execute).toHaveBeenCalledWith(
expect.objectContaining({ body: '{"key":"value"}' }),
expect.any(Object),
@@ -301,14 +308,12 @@ describe('SendEmailWorkflowAction', () => {
it('should handle empty string body without crashing', async () => {
await executeWithBody('');
- expect(renderRichTextToHtml).not.toHaveBeenCalled();
expect(mockSendEmailTool.execute).toHaveBeenCalled();
});
it('should handle undefined body without crashing', async () => {
await executeWithBody(undefined);
- expect(renderRichTextToHtml).not.toHaveBeenCalled();
expect(mockSendEmailTool.execute).toHaveBeenCalled();
});
});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/__tests__/resolve-email-body.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/__tests__/resolve-email-body.util.spec.ts
index 705ad1daecd..2ea2fefe896 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/__tests__/resolve-email-body.util.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/__tests__/resolve-email-body.util.spec.ts
@@ -1,23 +1,6 @@
import { resolveEmailBody } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/resolve-email-body.util';
-jest.mock(
- 'src/engine/core-modules/tool/tools/email-tool/utils/render-email-body.util',
- () => ({
- renderEmailBodyToHtml: jest.fn().mockResolvedValue('<p>rendered html</p>'),
- }),
-);
-
-const { renderEmailBodyToHtml } = jest.requireMock(
- 'src/engine/core-modules/tool/tools/email-tool/utils/render-email-body.util',
-);
-
-const renderedDocument = () => renderEmailBodyToHtml.mock.calls[0][0];
-
describe('resolveEmailBody', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- });
-
it('should resolve only authored placeholders in structured documents', async () => {
const body = JSON.stringify({
type: 'doc',
@@ -35,7 +18,7 @@ describe('resolveEmailBody', () => {
],
});
- await resolveEmailBody(body, {
+ const resolvedBody = await resolveEmailBody(body, {
trigger: {
name: 'Ada',
message: '{{trigger.secret}}',
@@ -43,7 +26,7 @@ describe('resolveEmailBody', () => {
},
});
- expect(renderedDocument().content[0].content).toEqual([
+ expect(JSON.parse(resolvedBody).content[0].content).toEqual([
{ type: 'text', text: 'Hello Ada: ' },
{ type: 'text', text: '{{trigger.secret}}' },
]);
@@ -65,11 +48,11 @@ describe('resolveEmailBody', () => {
],
});
- await resolveEmailBody(body, {
+ const resolvedBody = await resolveEmailBody(body, {
trigger: { message: 'first\n\nthird' },
});
- expect(renderedDocument().content[0].content).toEqual([
+ expect(JSON.parse(resolvedBody).content[0].content).toEqual([
{ type: 'text', text: 'first' },
{ type: 'hardBreak' },
{ type: 'hardBreak' },
@@ -88,11 +71,11 @@ describe('resolveEmailBody', () => {
],
});
- await resolveEmailBody(body, {
+ const resolvedBody = await resolveEmailBody(body, {
trigger: { message: '<b>{{trigger.secret}}</b>', secret: 'hidden' },
});
- expect(renderedDocument().content[0].attrs.html).toBe(
+ expect(JSON.parse(resolvedBody).content[0].attrs.html).toBe(
'<p>&lt;b&gt;{{trigger.secret}}&lt;/b&gt;</p>',
);
});
@@ -103,7 +86,5 @@ describe('resolveEmailBody', () => {
trigger: { name: 'Ada' },
}),
).resolves.toBe('<p>Hello Ada</p>');
-
- expect(renderEmailBodyToHtml).not.toHaveBeenCalled();
});
});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/resolve-email-body.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/resolve-email-body.util.ts
index 00d67e65f6a..fcb99bdfca0 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/resolve-email-body.util.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/resolve-email-body.util.ts
@@ -1,79 +1,19 @@
import {
- type EmailDocument,
- type EmailDocumentNode,
- parseJson,
+ isEmailDocumentShape,
parseEmailDocument,
- TIPTAP_NODE_TYPES,
- transformEmailDocumentStrings,
+ parseJson,
} from 'twenty-shared/utils';
-import { renderEmailBodyToHtml } from 'src/engine/core-modules/tool/tools/email-tool/utils/render-email-body.util';
+import { resolveEmailDocumentBindings } from 'src/engine/core-modules/email/utils/resolve-email-document-bindings.util';
import { resolveWorkflowEmailTemplateString } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/resolve-workflow-email-template-string.util';
-const textToInlineNodes = (text: string): EmailDocumentNode[] =>
- text.split('\n').flatMap((line, index, lines) => [
- ...(line === ''
- ? []
- : [
- {
- type: TIPTAP_NODE_TYPES.TEXT,
- text: line,
- } satisfies EmailDocumentNode,
- ]),
- ...(index < lines.length - 1
- ? [{ type: TIPTAP_NODE_TYPES.HARD_BREAK } satisfies EmailDocumentNode]
- : []),
- ]);
-
-const resolveDocumentNode = (
- node: EmailDocumentNode,
- context: Record<string, unknown>,
-): EmailDocumentNode[] => {
- if (node.type === TIPTAP_NODE_TYPES.VARIABLE_TAG) {
- const variable = node.attrs?.variable;
-
- return textToInlineNodes(
- typeof variable === 'string'
- ? resolveWorkflowEmailTemplateString(variable, context, {
- escapeValues: false,
- })
- : '',
- );
- }
-
- const { content, ...nodeWithoutContent } = node;
- const resolvedNode = transformEmailDocumentStrings(
- nodeWithoutContent,
- (value, stringContext) =>
- resolveWorkflowEmailTemplateString(value, context, {
- escapeValues: stringContext === 'html',
- }),
- );
-
- return [
- {
- ...resolvedNode,
- ...(content && {
- content: content.flatMap((childNode) =>
- resolveDocumentNode(childNode, context),
- ),
- }),
- },
- ];
-};
-
export const resolveEmailBody = async (
body: string,
context: Record<string, unknown>,
): Promise<string> => {
const unresolvedDocument = parseJson<unknown>(body);
- const isDocument =
- typeof unresolvedDocument === 'object' &&
- unresolvedDocument !== null &&
- 'type' in unresolvedDocument &&
- unresolvedDocument.type === 'doc';
- if (!isDocument) {
+ if (!isEmailDocumentShape(unresolvedDocument)) {
return resolveWorkflowEmailTemplateString(body, context, {
escapeValues: false,
});
@@ -85,7 +25,11 @@ export const resolveEmailBody = async (
throw new Error(`Invalid workflow email document: ${parseResult.error}`);
}
- const [resolvedDocument] = resolveDocumentNode(parseResult.document, context);
-
- return renderEmailBodyToHtml(resolvedDocument as EmailDocument);
+ return JSON.stringify(
+ resolveEmailDocumentBindings(parseResult.document, (value, stringContext) =>
+ resolveWorkflowEmailTemplateString(value, context, {
+ escapeValues: stringContext === 'html',
+ }),
+ ),
+ );
};
diff --git a/packages/twenty-shared/src/ai/index.ts b/packages/twenty-shared/src/ai/index.ts
index e3c287309ea..de5765782ce 100644
--- a/packages/twenty-shared/src/ai/index.ts
+++ b/packages/twenty-shared/src/ai/index.ts
@@ -51,6 +51,7 @@ export type {
export type { ExtendedUIMessagePart } from './types/ExtendedUIMessagePart';
export type { ModelConfiguration } from './types/model-configuration.type';
export type { NavigateAppToolOutput } from './types/NavigateAppToolOutput';
+export { formatRecordReference } from './utils/format-record-reference.util';
export { inferAiSdkPackage } from './utils/infer-ai-sdk-package.util';
export { isAiSdkPackage } from './utils/is-ai-sdk-package.util';
export { isDataResidency } from './utils/is-data-residency.util';
diff --git a/packages/twenty-shared/src/ai/utils/__tests__/format-record-reference.util.spec.ts b/packages/twenty-shared/src/ai/utils/__tests__/format-record-reference.util.spec.ts
new file mode 100644
index 00000000000..ca99a3c31dc
--- /dev/null
+++ b/packages/twenty-shared/src/ai/utils/__tests__/format-record-reference.util.spec.ts
@@ -0,0 +1,13 @@
+import { formatRecordReference } from '@/ai/utils/format-record-reference.util';
+
+describe('formatRecordReference', () => {
+ it('formats a record reference without altering its display name', () => {
+ expect(
+ formatRecordReference({
+ objectNameSingular: 'company',
+ recordId: 'record-id',
+ displayName: '[test] ]] [test]',
+ }),
+ ).toBe('[[record:company:record-id:[test] ]] [test][[/record]]');
+ });
+});
diff --git a/packages/twenty-shared/src/ai/utils/format-record-reference.util.ts b/packages/twenty-shared/src/ai/utils/format-record-reference.util.ts
new file mode 100644
index 00000000000..84adc538a73
--- /dev/null
+++ b/packages/twenty-shared/src/ai/utils/format-record-reference.util.ts
@@ -0,0 +1,10 @@
+export const formatRecordReference = ({
+ objectNameSingular,
+ recordId,
+ displayName,
+}: {
+ objectNameSingular: string;
+ recordId: string;
+ displayName: string;
+}): string =>
+ `[[record:${objectNameSingular}:${recordId}:${displayName}[[/record]]`;
diff --git a/packages/twenty-shared/src/utils/index.ts b/packages/twenty-shared/src/utils/index.ts
index 69595031c0d..93957fb215c 100644
--- a/packages/twenty-shared/src/utils/index.ts
+++ b/packages/twenty-shared/src/utils/index.ts
@@ -199,16 +199,42 @@ export { uncapitalize } from './strings/uncapitalize';
export { getSubdomainSlugFromDisplayName } from './subdomain/getSubdomainSlugFromDisplayName';
export type { CanvasTheme } from './tiptap/canvas-theme';
export { CANVAS_THEME_DEFAULTS } from './tiptap/canvas-theme';
+export type { EmailDocumentMarkType } from './tiptap/email-document-mark-catalog';
+export {
+ EMAIL_DOCUMENT_MARK_CATALOG,
+ isEmailDocumentMarkType,
+} from './tiptap/email-document-mark-catalog';
+export type {
+ EmailDocumentNodeType,
+ RenderedEmailDocumentNodeType,
+} from './tiptap/email-document-node-catalog';
+export {
+ EMAIL_DOCUMENT_NODE_CATALOG,
+ isEmailDocumentNodeType,
+ isRenderedEmailDocumentNodeType,
+} from './tiptap/email-document-node-catalog';
export type { EmailDocumentNode } from './tiptap/email-document-node';
export { EMAIL_DOCUMENT_SCHEMA_VERSION } from './tiptap/email-document-schema-version';
export type { EmailDocument } from './tiptap/email-document-schema';
export { emailDocumentSchema } from './tiptap/email-document-schema';
export type { EmailDocumentStringContext } from './tiptap/email-document-string-context';
export { isCanvasTheme } from './tiptap/is-canvas-theme';
+export { isEmailDocumentShape } from './tiptap/is-email-document-shape';
export type { CampaignVariableDefinition } from './tiptap/list-campaign-variables-for-fields';
export { listCampaignVariablesForFields } from './tiptap/list-campaign-variables-for-fields';
-export { parseEmailDocument } from './tiptap/parse-email-document';
+export {
+ parseEmailDocument,
+ parseCanonicalEmailDocument,
+} from './tiptap/parse-email-document';
+export {
+ isTipTapNode,
+ parseTipTapJsonDocument,
+ parseCanonicalTipTapJsonDocument,
+} from './tiptap/parse-tiptap-json-document';
export { resolveCanvasTheme } from './tiptap/resolve-canvas-theme';
+export { TIPTAP_DOCUMENT_SCHEMA_VERSION } from './tiptap/tiptap-document-schema-version';
+export { tipTapDocumentToMarkdown } from './tiptap/tiptap-document-to-markdown';
+export type { TipTapDocument } from './tiptap/tiptap-document';
export type {
TipTapMarkType,
LinkMarkAttributes,
@@ -218,6 +244,7 @@ export { TIPTAP_MARK_TYPES } from './tiptap/tiptap-mark-types';
export { TIPTAP_MARKS_RENDER_ORDER } from './tiptap/tiptap-marks-render-order';
export type { TipTapNodeType } from './tiptap/tiptap-node-types';
export { TIPTAP_NODE_TYPES } from './tiptap/tiptap-node-types';
+export type { TipTapNode } from './tiptap/tiptap-node';
export { transformEmailDocumentStrings } from './tiptap/transform-email-document-strings';
export type { StringPropertyKeys } from './trim-and-remove-duplicated-whitespaces-from-object-string-properties';
export { trimAndRemoveDuplicatedWhitespacesFromObjectStringProperties } from './trim-and-remove-duplicated-whitespaces-from-object-string-properties';
diff --git a/packages/twenty-shared/src/utils/tiptap/__tests__/email-document-node-catalog.test.ts b/packages/twenty-shared/src/utils/tiptap/__tests__/email-document-node-catalog.test.ts
new file mode 100644
index 00000000000..79a4f6d93b2
--- /dev/null
+++ b/packages/twenty-shared/src/utils/tiptap/__tests__/email-document-node-catalog.test.ts
@@ -0,0 +1,33 @@
+import {
+ EMAIL_DOCUMENT_NODE_CATALOG,
+ isEmailDocumentNodeType,
+ isRenderedEmailDocumentNodeType,
+} from '../email-document-node-catalog';
+import { TIPTAP_NODE_TYPES } from '../tiptap-node-types';
+
+describe('EMAIL_DOCUMENT_NODE_CATALOG', () => {
+ it('explicitly selects reusable TipTap nodes supported by email', () => {
+ expect(isEmailDocumentNodeType(TIPTAP_NODE_TYPES.SECTION)).toBe(true);
+ expect(isEmailDocumentNodeType(TIPTAP_NODE_TYPES.COLUMNS)).toBe(true);
+ expect(isEmailDocumentNodeType(TIPTAP_NODE_TYPES.HTML)).toBe(true);
+ });
+
+ it('distinguishes nodes rendered by their parent from renderer entries', () => {
+ expect(isRenderedEmailDocumentNodeType('paragraph')).toBe(true);
+ expect(isRenderedEmailDocumentNodeType('column')).toBe(false);
+ expect(isRenderedEmailDocumentNodeType('doc')).toBe(false);
+ });
+
+ it('rejects node types outside the email document vocabulary', () => {
+ expect(isEmailDocumentNodeType('mentionTag')).toBe(false);
+ });
+
+ it('keeps renderer behavior in the email capability catalog', () => {
+ expect(
+ EMAIL_DOCUMENT_NODE_CATALOG[TIPTAP_NODE_TYPES.COLUMN].renderMode,
+ ).toBe('parent');
+ expect(
+ EMAIL_DOCUMENT_NODE_CATALOG[TIPTAP_NODE_TYPES.SECTION].renderMode,
+ ).toBe('node');
+ });
+});
diff --git a/packages/twenty-shared/src/utils/tiptap/__tests__/email-document-schema.test.ts b/packages/twenty-shared/src/utils/tiptap/__tests__/email-document-schema.test.ts
index 6e416e24781..1f20bd73283 100644
--- a/packages/twenty-shared/src/utils/tiptap/__tests__/email-document-schema.test.ts
+++ b/packages/twenty-shared/src/utils/tiptap/__tests__/email-document-schema.test.ts
@@ -1,5 +1,8 @@
import { EMAIL_DOCUMENT_SCHEMA_VERSION } from '../email-document-schema-version';
-import { parseEmailDocument } from '../parse-email-document';
+import {
+ parseCanonicalEmailDocument,
+ parseEmailDocument,
+} from '../parse-email-document';
const paragraph = (text: string) => ({
type: 'paragraph',
@@ -111,6 +114,25 @@ describe('parseEmailDocument', () => {
expect(result.success).toBe(true);
});
+ it('should require the current schema version at canonical boundaries', () => {
+ expect(
+ parseCanonicalEmailDocument({
+ type: 'doc',
+ attrs: { schemaVersion: EMAIL_DOCUMENT_SCHEMA_VERSION },
+ content: [paragraph('Current body')],
+ }).success,
+ ).toBe(true);
+ expect(
+ parseCanonicalEmailDocument({
+ type: 'doc',
+ content: [paragraph('Legacy body')],
+ }),
+ ).toEqual({
+ success: false,
+ error: `attrs.schemaVersion: Expected ${EMAIL_DOCUMENT_SCHEMA_VERSION}`,
+ });
+ });
+
it('should accept an empty document', () => {
expect(parseEmailDocument({ type: 'doc' }).success).toBe(true);
});
diff --git a/packages/twenty-shared/src/utils/tiptap/__tests__/tiptap-document.test.ts b/packages/twenty-shared/src/utils/tiptap/__tests__/tiptap-document.test.ts
new file mode 100644
index 00000000000..c031c32462b
--- /dev/null
+++ b/packages/twenty-shared/src/utils/tiptap/__tests__/tiptap-document.test.ts
@@ -0,0 +1,206 @@
+import {
+ parseCanonicalTipTapJsonDocument,
+ parseTipTapJsonDocument,
+} from '../parse-tiptap-json-document';
+import { TIPTAP_DOCUMENT_SCHEMA_VERSION } from '../tiptap-document-schema-version';
+import { tipTapDocumentToMarkdown } from '../tiptap-document-to-markdown';
+
+const document = {
+ type: 'doc' as const,
+ attrs: { schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION },
+ content: [
+ {
+ type: 'heading',
+ attrs: { level: 2 },
+ content: [{ type: 'text', text: 'Overview' }],
+ },
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: 'Hello ' },
+ {
+ type: 'text',
+ text: 'Ada',
+ marks: [
+ { type: 'bold' as const },
+ {
+ type: 'link' as const,
+ attrs: { href: 'https://example.com' },
+ },
+ ],
+ },
+ { type: 'text', text: ' ' },
+ {
+ type: 'mentionTag',
+ attrs: {
+ objectNameSingular: 'person',
+ recordId: 'person-id',
+ label: 'Ada Lovelace',
+ },
+ },
+ ],
+ },
+ {
+ type: 'bulletList',
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'First' }],
+ },
+ ],
+ },
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'Second' }],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+};
+
+describe('TipTap document primitives', () => {
+ it('parses a structurally valid document without filtering extensions', () => {
+ expect(parseTipTapJsonDocument(JSON.stringify(document))).toEqual(document);
+ });
+
+ it('parses only documents with the current canonical schema version', () => {
+ expect(parseCanonicalTipTapJsonDocument(JSON.stringify(document))).toEqual(
+ document,
+ );
+ expect(
+ parseCanonicalTipTapJsonDocument(
+ JSON.stringify({ type: 'doc', content: [] }),
+ ),
+ ).toBeUndefined();
+ expect(
+ parseCanonicalTipTapJsonDocument(
+ JSON.stringify({
+ type: 'doc',
+ attrs: { schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION + 1 },
+ content: [],
+ }),
+ ),
+ ).toBeUndefined();
+ });
+
+ it('rejects malformed nested nodes and marks', () => {
+ expect(
+ parseTipTapJsonDocument(
+ JSON.stringify({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', marks: [{ attrs: {} }] }],
+ },
+ ],
+ }),
+ ),
+ ).toBeUndefined();
+ });
+
+ it('projects canonical documents to Markdown at text boundaries', () => {
+ expect(tipTapDocumentToMarkdown(document)).toBe(
+ [
+ '## Overview',
+ '',
+ 'Hello [**Ada**](https://example.com) [[record:person:person-id:Ada Lovelace[[/record]]',
+ '',
+ '- First',
+ '- Second',
+ ].join('\n'),
+ );
+ });
+
+ it('preserves nested list hierarchy in Markdown projections', () => {
+ expect(
+ tipTapDocumentToMarkdown({
+ type: 'doc',
+ content: [
+ {
+ type: 'bulletList',
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'Parent' }],
+ },
+ {
+ type: 'orderedList',
+ attrs: { start: 3 },
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'Child' }],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ }),
+ ).toBe(['- Parent', '', ' 3. Child'].join('\n'));
+ });
+
+ it('escapes literal Markdown text and link destinations', () => {
+ expect(
+ tipTapDocumentToMarkdown({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: '1. Literal *stars* [brackets] ' },
+ {
+ type: 'text',
+ text: 'linked',
+ marks: [
+ {
+ type: 'link',
+ attrs: { href: 'https://example.com/a_(b c)' },
+ },
+ ],
+ },
+ ],
+ },
+ {
+ type: 'image',
+ attrs: {
+ alt: '[diagram]',
+ src: 'https://example.com/a(b c).png',
+ },
+ },
+ ],
+ }),
+ ).toBe(
+ [
+ '1\\. Literal \\*stars\\* \\[brackets\\] [linked](https://example.com/a_%28b%20c%29)',
+ '',
+ '![\\[diagram\\]](https://example.com/a%28b%20c%29.png)',
+ ].join('\n'),
+ );
+ });
+
+ it('passes legacy text through unchanged', () => {
+ expect(tipTapDocumentToMarkdown('Legacy **Markdown**')).toBe(
+ 'Legacy **Markdown**',
+ );
+ });
+});
diff --git a/packages/twenty-shared/src/utils/tiptap/__tests__/transform-email-document-strings.test.ts b/packages/twenty-shared/src/utils/tiptap/__tests__/transform-email-document-strings.test.ts
index 0c4fb0dfa65..5201df94a04 100644
--- a/packages/twenty-shared/src/utils/tiptap/__tests__/transform-email-document-strings.test.ts
+++ b/packages/twenty-shared/src/utils/tiptap/__tests__/transform-email-document-strings.test.ts
@@ -27,6 +27,7 @@ describe('transformEmailDocumentStrings', () => {
title: '{{name}}',
},
},
+ { type: 'button', attrs: { href: '/people/{{id}}' } },
{ type: 'html', attrs: { html: '<p>{{name}}</p>' } },
],
},
@@ -52,7 +53,8 @@ describe('transformEmailDocumentStrings', () => {
alt: '[text]{{name}}',
title: '[text]{{name}}',
});
- expect(document.content?.[2].attrs?.html).toBe('[html]<p>{{name}}</p>');
+ expect(document.content?.[2].attrs?.href).toBe('[url]/people/{{id}}');
+ expect(document.content?.[3].attrs?.html).toBe('[html]<p>{{name}}</p>');
expect(contexts).toContain('html');
expect(contexts).toContain('text');
expect(contexts).toContain('url');
diff --git a/packages/twenty-shared/src/utils/tiptap/email-document-mark-catalog.ts b/packages/twenty-shared/src/utils/tiptap/email-document-mark-catalog.ts
new file mode 100644
index 00000000000..170ffd231c4
--- /dev/null
+++ b/packages/twenty-shared/src/utils/tiptap/email-document-mark-catalog.ts
@@ -0,0 +1,27 @@
+import { type EmailDocumentStringContext } from './email-document-string-context';
+import { TIPTAP_MARK_TYPES, type TipTapMarkType } from './tiptap-mark-types';
+
+type EmailDocumentMarkDefinition = {
+ stringAttributes: Readonly<
+ Partial<Record<string, EmailDocumentStringContext>>
+ >;
+};
+
+export const EMAIL_DOCUMENT_MARK_CATALOG = {
+ [TIPTAP_MARK_TYPES.BOLD]: { stringAttributes: {} },
+ [TIPTAP_MARK_TYPES.ITALIC]: { stringAttributes: {} },
+ [TIPTAP_MARK_TYPES.UNDERLINE]: { stringAttributes: {} },
+ [TIPTAP_MARK_TYPES.STRIKE]: { stringAttributes: {} },
+ [TIPTAP_MARK_TYPES.LINK]: {
+ stringAttributes: { href: 'url' },
+ },
+} as const satisfies Partial<
+ Record<TipTapMarkType, EmailDocumentMarkDefinition>
+>;
+
+export type EmailDocumentMarkType = keyof typeof EMAIL_DOCUMENT_MARK_CATALOG;
+
+export const isEmailDocumentMarkType = (
+ markType: string,
+): markType is EmailDocumentMarkType =>
+ Object.prototype.hasOwnProperty.call(EMAIL_DOCUMENT_MARK_CATALOG, markType);
diff --git a/packages/twenty-shared/src/utils/tiptap/email-document-node-catalog.ts b/packages/twenty-shared/src/utils/tiptap/email-document-node-catalog.ts
new file mode 100644
index 00000000000..a0780bbab90
--- /dev/null
+++ b/packages/twenty-shared/src/utils/tiptap/email-document-node-catalog.ts
@@ -0,0 +1,102 @@
+import { type EmailDocumentStringContext } from './email-document-string-context';
+import { TIPTAP_NODE_TYPES, type TipTapNodeType } from './tiptap-node-types';
+
+type EmailDocumentNodeDefinition = {
+ renderMode: 'children' | 'node' | 'parent';
+ stringAttributes: Readonly<
+ Partial<Record<string, EmailDocumentStringContext>>
+ >;
+};
+
+export const EMAIL_DOCUMENT_NODE_CATALOG = {
+ [TIPTAP_NODE_TYPES.DOCUMENT]: {
+ renderMode: 'children',
+ stringAttributes: {},
+ },
+ [TIPTAP_NODE_TYPES.PARAGRAPH]: {
+ renderMode: 'node',
+ stringAttributes: {},
+ },
+ [TIPTAP_NODE_TYPES.TEXT]: {
+ renderMode: 'node',
+ stringAttributes: {},
+ },
+ [TIPTAP_NODE_TYPES.HEADING]: {
+ renderMode: 'node',
+ stringAttributes: {},
+ },
+ [TIPTAP_NODE_TYPES.VARIABLE_TAG]: {
+ renderMode: 'node',
+ stringAttributes: { variable: 'text' },
+ },
+ [TIPTAP_NODE_TYPES.IMAGE]: {
+ renderMode: 'node',
+ stringAttributes: {
+ src: 'url',
+ href: 'url',
+ alt: 'text',
+ title: 'text',
+ },
+ },
+ [TIPTAP_NODE_TYPES.BULLET_LIST]: {
+ renderMode: 'node',
+ stringAttributes: {},
+ },
+ [TIPTAP_NODE_TYPES.ORDERED_LIST]: {
+ renderMode: 'node',
+ stringAttributes: {},
+ },
+ [TIPTAP_NODE_TYPES.LIST_ITEM]: {
+ renderMode: 'node',
+ stringAttributes: {},
+ },
+ [TIPTAP_NODE_TYPES.HARD_BREAK]: {
+ renderMode: 'node',
+ stringAttributes: {},
+ },
+ [TIPTAP_NODE_TYPES.SECTION]: {
+ renderMode: 'node',
+ stringAttributes: {},
+ },
+ [TIPTAP_NODE_TYPES.COLUMNS]: {
+ renderMode: 'node',
+ stringAttributes: {},
+ },
+ [TIPTAP_NODE_TYPES.COLUMN]: {
+ renderMode: 'parent',
+ stringAttributes: {},
+ },
+ [TIPTAP_NODE_TYPES.BUTTON]: {
+ renderMode: 'node',
+ stringAttributes: { href: 'url' },
+ },
+ [TIPTAP_NODE_TYPES.DIVIDER]: {
+ renderMode: 'node',
+ stringAttributes: {},
+ },
+ [TIPTAP_NODE_TYPES.HTML]: {
+ renderMode: 'node',
+ stringAttributes: { html: 'html' },
+ },
+} as const satisfies Partial<
+ Record<TipTapNodeType, EmailDocumentNodeDefinition>
+>;
+
+export type EmailDocumentNodeType = keyof typeof EMAIL_DOCUMENT_NODE_CATALOG;
+
+export type RenderedEmailDocumentNodeType = {
+ [TNodeType in EmailDocumentNodeType]: (typeof EMAIL_DOCUMENT_NODE_CATALOG)[TNodeType]['renderMode'] extends 'node'
+ ? TNodeType
+ : never;
+}[EmailDocumentNodeType];
+
+export const isEmailDocumentNodeType = (
+ nodeType: string,
+): nodeType is EmailDocumentNodeType =>
+ Object.prototype.hasOwnProperty.call(EMAIL_DOCUMENT_NODE_CATALOG, nodeType);
+
+export const isRenderedEmailDocumentNodeType = (
+ nodeType: string,
+): nodeType is RenderedEmailDocumentNodeType =>
+ isEmailDocumentNodeType(nodeType) &&
+ EMAIL_DOCUMENT_NODE_CATALOG[nodeType].renderMode === 'node';
diff --git a/packages/twenty-shared/src/utils/tiptap/email-document-schema-version.ts b/packages/twenty-shared/src/utils/tiptap/email-document-schema-version.ts
index a33033066d0..0a55f4e009f 100644
--- a/packages/twenty-shared/src/utils/tiptap/email-document-schema-version.ts
+++ b/packages/twenty-shared/src/utils/tiptap/email-document-schema-version.ts
@@ -1 +1,3 @@
-export const EMAIL_DOCUMENT_SCHEMA_VERSION = 1;
+import { TIPTAP_DOCUMENT_SCHEMA_VERSION } from './tiptap-document-schema-version';
+
+export const EMAIL_DOCUMENT_SCHEMA_VERSION = TIPTAP_DOCUMENT_SCHEMA_VERSION;
diff --git a/packages/twenty-shared/src/utils/tiptap/email-document-schema.ts b/packages/twenty-shared/src/utils/tiptap/email-document-schema.ts
index 233fc0e1797..af04866dbe2 100644
--- a/packages/twenty-shared/src/utils/tiptap/email-document-schema.ts
+++ b/packages/twenty-shared/src/utils/tiptap/email-document-schema.ts
@@ -167,7 +167,7 @@ const canvasThemeAttributeSchema = z.looseObject({
});
export const emailDocumentSchema = z.looseObject({
- type: z.literal('doc'),
+ type: z.literal(TIPTAP_NODE_TYPES.DOCUMENT),
attrs: z
.looseObject({
schemaVersion: z
diff --git a/packages/twenty-shared/src/utils/tiptap/is-email-document-shape.ts b/packages/twenty-shared/src/utils/tiptap/is-email-document-shape.ts
new file mode 100644
index 00000000000..839c2f30194
--- /dev/null
+++ b/packages/twenty-shared/src/utils/tiptap/is-email-document-shape.ts
@@ -0,0 +1,7 @@
+export const isEmailDocumentShape = (
+ value: unknown,
+): value is { type: 'doc' } =>
+ typeof value === 'object' &&
+ value !== null &&
+ 'type' in value &&
+ value.type === 'doc';
diff --git a/packages/twenty-shared/src/utils/tiptap/parse-email-document.ts b/packages/twenty-shared/src/utils/tiptap/parse-email-document.ts
index 090703744fb..6319328fcb8 100644
--- a/packages/twenty-shared/src/utils/tiptap/parse-email-document.ts
+++ b/packages/twenty-shared/src/utils/tiptap/parse-email-document.ts
@@ -2,12 +2,15 @@ import {
type EmailDocument,
emailDocumentSchema,
} from './email-document-schema';
+import { EMAIL_DOCUMENT_SCHEMA_VERSION } from './email-document-schema-version';
+
+type ParseEmailDocumentResult =
+ | { success: true; document: EmailDocument }
+ | { success: false; error: string };
export const parseEmailDocument = (
value: unknown,
-):
- | { success: true; document: EmailDocument }
- | { success: false; error: string } => {
+): ParseEmailDocumentResult => {
const result = emailDocumentSchema.safeParse(value);
if (result.success) {
@@ -21,3 +24,22 @@ export const parseEmailDocument = (
return { success: false, error: issues };
};
+
+export const parseCanonicalEmailDocument = (
+ value: unknown,
+): ParseEmailDocumentResult => {
+ const result = parseEmailDocument(value);
+
+ if (!result.success) {
+ return result;
+ }
+
+ if (result.document.attrs?.schemaVersion !== EMAIL_DOCUMENT_SCHEMA_VERSION) {
+ return {
+ success: false,
+ error: `attrs.schemaVersion: Expected ${EMAIL_DOCUMENT_SCHEMA_VERSION}`,
+ };
+ }
+
+ return result;
+};
diff --git a/packages/twenty-shared/src/utils/tiptap/parse-tiptap-json-document.ts b/packages/twenty-shared/src/utils/tiptap/parse-tiptap-json-document.ts
new file mode 100644
index 00000000000..4cb7d62b29f
--- /dev/null
+++ b/packages/twenty-shared/src/utils/tiptap/parse-tiptap-json-document.ts
@@ -0,0 +1,60 @@
+import { type TipTapDocument } from './tiptap-document';
+import { TIPTAP_DOCUMENT_SCHEMA_VERSION } from './tiptap-document-schema-version';
+import { type TipTapMark } from './tiptap-mark-types';
+import { type TipTapNode } from './tiptap-node';
+import { TIPTAP_NODE_TYPES } from './tiptap-node-types';
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+const isTipTapMark = (value: unknown): value is TipTapMark => {
+ if (!isRecord(value)) {
+ return false;
+ }
+
+ return (
+ typeof value.type === 'string' &&
+ (value.attrs === undefined || isRecord(value.attrs))
+ );
+};
+
+export const isTipTapNode = (value: unknown): value is TipTapNode => {
+ if (!isRecord(value)) {
+ return false;
+ }
+
+ return (
+ typeof value.type === 'string' &&
+ (value.attrs === undefined || isRecord(value.attrs)) &&
+ (value.text === undefined || typeof value.text === 'string') &&
+ (value.content === undefined ||
+ (Array.isArray(value.content) && value.content.every(isTipTapNode))) &&
+ (value.marks === undefined ||
+ (Array.isArray(value.marks) && value.marks.every(isTipTapMark)))
+ );
+};
+
+const isTipTapDocument = (value: unknown): value is TipTapDocument =>
+ isTipTapNode(value) && value.type === TIPTAP_NODE_TYPES.DOCUMENT;
+
+export const parseTipTapJsonDocument = (
+ serializedDocument: string,
+): TipTapDocument | undefined => {
+ try {
+ const parsedDocument: unknown = JSON.parse(serializedDocument);
+
+ return isTipTapDocument(parsedDocument) ? parsedDocument : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+export const parseCanonicalTipTapJsonDocument = (
+ serializedDocument: string,
+): TipTapDocument | undefined => {
+ const document = parseTipTapJsonDocument(serializedDocument);
+
+ return document?.attrs?.schemaVersion === TIPTAP_DOCUMENT_SCHEMA_VERSION
+ ? document
+ : undefined;
+};
diff --git a/packages/twenty-shared/src/utils/tiptap/tiptap-document-schema-version.ts b/packages/twenty-shared/src/utils/tiptap/tiptap-document-schema-version.ts
new file mode 100644
index 00000000000..91359966c9f
--- /dev/null
+++ b/packages/twenty-shared/src/utils/tiptap/tiptap-document-schema-version.ts
@@ -0,0 +1 @@
+export const TIPTAP_DOCUMENT_SCHEMA_VERSION = 1;
diff --git a/packages/twenty-shared/src/utils/tiptap/tiptap-document-to-markdown.ts b/packages/twenty-shared/src/utils/tiptap/tiptap-document-to-markdown.ts
new file mode 100644
index 00000000000..bdb7797b6d9
--- /dev/null
+++ b/packages/twenty-shared/src/utils/tiptap/tiptap-document-to-markdown.ts
@@ -0,0 +1,172 @@
+import { formatRecordReference } from '@/ai/utils/format-record-reference.util';
+
+import { parseTipTapJsonDocument } from './parse-tiptap-json-document';
+import { type TipTapDocument } from './tiptap-document';
+import { type TipTapMark, TIPTAP_MARK_TYPES } from './tiptap-mark-types';
+import { TIPTAP_MARKS_RENDER_ORDER } from './tiptap-marks-render-order';
+import { type TipTapNode } from './tiptap-node';
+import { TIPTAP_NODE_TYPES } from './tiptap-node-types';
+
+const renderChildren = (node: TipTapNode): string =>
+ (node.content ?? []).map(renderTipTapNodeToMarkdown).join('');
+
+const escapeMarkdownText = (text: string): string =>
+ text
+ .replace(/([\\`*_[\]{}<>~|#&])/g, '\\$1')
+ .replace(/^(\s{0,3})>(?=\s|$)/gm, '$1\\>')
+ .replace(/^(\s{0,3})-(?=-{2}|\s|$)/gm, '$1\\-')
+ .replace(/^(\s{0,3})\+(?=\s|$)/gm, '$1\\+')
+ .replace(/^(\s{0,3}\d+)([.)])(?=\s|$)/gm, '$1\\$2');
+
+const MARKDOWN_DESTINATION_CHARACTER_ESCAPES: Readonly<Record<string, string>> =
+ {
+ '\\': '%5C',
+ '(': '%28',
+ ')': '%29',
+ '<': '%3C',
+ '>': '%3E',
+ };
+
+const escapeMarkdownDestination = (destination: string): string =>
+ destination.replace(/[\\()<>\s]/g, (character) =>
+ character in MARKDOWN_DESTINATION_CHARACTER_ESCAPES
+ ? MARKDOWN_DESTINATION_CHARACTER_ESCAPES[character]
+ : encodeURIComponent(character),
+ );
+
+const applyMark = (text: string, mark: TipTapMark): string => {
+ switch (mark.type) {
+ case TIPTAP_MARK_TYPES.BOLD:
+ return `**${text}**`;
+ case TIPTAP_MARK_TYPES.ITALIC:
+ return `_${text}_`;
+ case TIPTAP_MARK_TYPES.UNDERLINE:
+ return `<u>${text}</u>`;
+ case TIPTAP_MARK_TYPES.STRIKE:
+ return `~~${text}~~`;
+ case TIPTAP_MARK_TYPES.LINK: {
+ const href = mark.attrs?.href;
+
+ return typeof href === 'string'
+ ? `[${text}](${escapeMarkdownDestination(href)})`
+ : text;
+ }
+ default:
+ return text;
+ }
+};
+
+const renderMention = (node: TipTapNode): string => {
+ const objectName = node.attrs?.objectNameSingular;
+ const recordId = node.attrs?.recordId;
+ const label = node.attrs?.label;
+
+ if (typeof objectName === 'string' && typeof recordId === 'string') {
+ return formatRecordReference({
+ objectNameSingular: objectName,
+ recordId,
+ displayName: typeof label === 'string' ? label : '',
+ });
+ }
+
+ if (typeof label === 'string') {
+ return `@${label}`;
+ }
+
+ return '';
+};
+
+const renderListItem = (item: TipTapNode, marker: string): string => {
+ const [firstLine = '', ...continuationLines] = renderChildren(item)
+ .trim()
+ .split('\n');
+ const indentation = ' '.repeat(marker.length);
+ const indentedContinuation = continuationLines
+ .map((line) => (line === '' ? '' : `${indentation}${line}`))
+ .join('\n');
+
+ return `${marker}${firstLine}${
+ indentedContinuation === '' ? '' : `\n${indentedContinuation}`
+ }\n`;
+};
+
+const renderTipTapNodeToMarkdown = (node: TipTapNode): string => {
+ switch (node.type) {
+ case TIPTAP_NODE_TYPES.TEXT:
+ return [...(node.marks ?? [])]
+ .sort(
+ (firstMark, secondMark) =>
+ TIPTAP_MARKS_RENDER_ORDER.indexOf(firstMark.type) -
+ TIPTAP_MARKS_RENDER_ORDER.indexOf(secondMark.type),
+ )
+ .reduce(
+ (text, mark) => applyMark(text, mark),
+ escapeMarkdownText(node.text ?? ''),
+ );
+ case TIPTAP_NODE_TYPES.HARD_BREAK:
+ return '\n';
+ case TIPTAP_NODE_TYPES.VARIABLE_TAG:
+ return typeof node.attrs?.variable === 'string'
+ ? node.attrs.variable
+ : '';
+ case TIPTAP_NODE_TYPES.MENTION_TAG:
+ return renderMention(node);
+ case TIPTAP_NODE_TYPES.HEADING: {
+ const level =
+ typeof node.attrs?.level === 'number' ? node.attrs.level : 1;
+
+ return `${'#'.repeat(Math.min(Math.max(level, 1), 6))} ${renderChildren(node)}\n\n`;
+ }
+ case TIPTAP_NODE_TYPES.PARAGRAPH:
+ return `${renderChildren(node)}\n\n`;
+ case TIPTAP_NODE_TYPES.BULLET_LIST:
+ return `${(node.content ?? [])
+ .map((item) => renderListItem(item, '- '))
+ .join('')}\n`;
+ case TIPTAP_NODE_TYPES.ORDERED_LIST: {
+ const start =
+ typeof node.attrs?.start === 'number' ? node.attrs.start : 1;
+
+ return `${(node.content ?? [])
+ .map((item, index) => renderListItem(item, `${start + index}. `))
+ .join('')}\n`;
+ }
+ case TIPTAP_NODE_TYPES.IMAGE: {
+ const alt = typeof node.attrs?.alt === 'string' ? node.attrs.alt : '';
+ const src = typeof node.attrs?.src === 'string' ? node.attrs.src : '';
+
+ return src === ''
+ ? escapeMarkdownText(alt)
+ : `![${escapeMarkdownText(alt)}](${escapeMarkdownDestination(src)})\n\n`;
+ }
+ case TIPTAP_NODE_TYPES.BUTTON: {
+ const label = renderChildren(node);
+ const href = node.attrs?.href;
+
+ return `${
+ typeof href === 'string'
+ ? `[${label}](${escapeMarkdownDestination(href)})`
+ : label
+ }\n\n`;
+ }
+ case TIPTAP_NODE_TYPES.HTML:
+ return typeof node.attrs?.html === 'string' ? node.attrs.html : '';
+ case TIPTAP_NODE_TYPES.DIVIDER:
+ return '---\n\n';
+ default:
+ return renderChildren(node);
+ }
+};
+
+export const tipTapDocumentToMarkdown = (
+ document: string | TipTapDocument,
+): string => {
+ const parsedDocument =
+ typeof document === 'string' ? parseTipTapJsonDocument(document) : document;
+
+ if (parsedDocument === undefined) {
+ return typeof document === 'string' ? document : '';
+ }
+
+ return renderTipTapNodeToMarkdown(parsedDocument).trim();
+};
diff --git a/packages/twenty-shared/src/utils/tiptap/tiptap-document.ts b/packages/twenty-shared/src/utils/tiptap/tiptap-document.ts
new file mode 100644
index 00000000000..2f07453aa7a
--- /dev/null
+++ b/packages/twenty-shared/src/utils/tiptap/tiptap-document.ts
@@ -0,0 +1,5 @@
+import { type TipTapNode } from './tiptap-node';
+
+export type TipTapDocument = TipTapNode & {
+ type: 'doc';
+};
diff --git a/packages/twenty-shared/src/utils/tiptap/tiptap-node-types.ts b/packages/twenty-shared/src/utils/tiptap/tiptap-node-types.ts
index 1e048d8e3be..2381459a0cd 100644
--- a/packages/twenty-shared/src/utils/tiptap/tiptap-node-types.ts
+++ b/packages/twenty-shared/src/utils/tiptap/tiptap-node-types.ts
@@ -1,8 +1,10 @@
export const TIPTAP_NODE_TYPES = {
+ DOCUMENT: 'doc',
PARAGRAPH: 'paragraph',
TEXT: 'text',
HEADING: 'heading',
VARIABLE_TAG: 'variableTag',
+ MENTION_TAG: 'mentionTag',
IMAGE: 'image',
BULLET_LIST: 'bulletList',
ORDERED_LIST: 'orderedList',
diff --git a/packages/twenty-shared/src/utils/tiptap/tiptap-node.ts b/packages/twenty-shared/src/utils/tiptap/tiptap-node.ts
new file mode 100644
index 00000000000..6283a72d146
--- /dev/null
+++ b/packages/twenty-shared/src/utils/tiptap/tiptap-node.ts
@@ -0,0 +1,9 @@
+import { type TipTapMark } from './tiptap-mark-types';
+
+export type TipTapNode = {
+ type: string;
+ attrs?: Record<string, unknown>;
+ content?: TipTapNode[];
+ marks?: TipTapMark[];
+ text?: string;
+};
diff --git a/packages/twenty-shared/src/utils/tiptap/transform-email-document-strings.ts b/packages/twenty-shared/src/utils/tiptap/transform-email-document-strings.ts
index e804b2ef644..decb5a81e86 100644
--- a/packages/twenty-shared/src/utils/tiptap/transform-email-document-strings.ts
+++ b/packages/twenty-shared/src/utils/tiptap/transform-email-document-strings.ts
@@ -1,90 +1,84 @@
+import { isDefined } from '@/utils/validation';
+
+import {
+ EMAIL_DOCUMENT_MARK_CATALOG,
+ isEmailDocumentMarkType,
+} from './email-document-mark-catalog';
import { type EmailDocumentNode } from './email-document-node';
+import {
+ EMAIL_DOCUMENT_NODE_CATALOG,
+ isEmailDocumentNodeType,
+} from './email-document-node-catalog';
import { type EmailDocumentStringContext } from './email-document-string-context';
-import { TIPTAP_MARK_TYPES } from './tiptap-mark-types';
-import { TIPTAP_NODE_TYPES } from './tiptap-node-types';
type StringTransformer = (
value: string,
context: EmailDocumentStringContext,
) => string;
-const transformAttribute = (
+type StringAttributeContexts = Readonly<
+ Partial<Record<string, EmailDocumentStringContext>>
+>;
+
+const transformAttributes = (
attributes: Record<string, unknown> | undefined,
- attributeName: string,
- context: EmailDocumentStringContext,
+ stringAttributes: StringAttributeContexts,
transform: StringTransformer,
): Record<string, unknown> | undefined => {
- const value = attributes?.[attributeName];
-
- if (typeof value !== 'string') {
+ if (!isDefined(attributes)) {
return attributes;
}
- return {
- ...attributes,
- [attributeName]: transform(value, context),
- };
+ return Object.entries(stringAttributes).reduce(
+ (transformedAttributes, [attributeName, context]) => {
+ const value = transformedAttributes[attributeName];
+
+ return typeof value === 'string' && isDefined(context)
+ ? {
+ ...transformedAttributes,
+ [attributeName]: transform(value, context),
+ }
+ : transformedAttributes;
+ },
+ attributes,
+ );
};
export const transformEmailDocumentStrings = <TNode extends EmailDocumentNode>(
node: TNode,
transform: StringTransformer,
): TNode => {
- let attributes = node.attrs;
-
- if (node.type === TIPTAP_NODE_TYPES.VARIABLE_TAG) {
- attributes = transformAttribute(attributes, 'variable', 'text', transform);
- }
-
- if (node.type === TIPTAP_NODE_TYPES.BUTTON) {
- attributes = transformAttribute(attributes, 'href', 'url', transform);
- }
-
- if (node.type === TIPTAP_NODE_TYPES.IMAGE) {
- for (const attributeName of ['src', 'href']) {
- attributes = transformAttribute(
- attributes,
- attributeName,
- 'url',
- transform,
- );
- }
-
- for (const attributeName of ['alt', 'title']) {
- attributes = transformAttribute(
- attributes,
- attributeName,
- 'text',
- transform,
- );
- }
- }
-
- if (node.type === TIPTAP_NODE_TYPES.HTML) {
- attributes = transformAttribute(attributes, 'html', 'html', transform);
- }
+ const nodeDefinition = isEmailDocumentNodeType(node.type)
+ ? EMAIL_DOCUMENT_NODE_CATALOG[node.type]
+ : undefined;
+ const attributes = transformAttributes(
+ node.attrs,
+ nodeDefinition?.stringAttributes ?? {},
+ transform,
+ );
const marks = node.marks?.map((mark) => {
if (
typeof mark !== 'object' ||
mark === null ||
!('type' in mark) ||
- mark.type !== TIPTAP_MARK_TYPES.LINK ||
- !('attrs' in mark) ||
- typeof mark.attrs !== 'object' ||
- mark.attrs === null
+ typeof mark.type !== 'string' ||
+ !isEmailDocumentMarkType(mark.type)
) {
return mark;
}
return {
...mark,
- attrs: transformAttribute(
- mark.attrs as Record<string, unknown>,
- 'href',
- 'url',
- transform,
- ),
+ ...('attrs' in mark &&
+ typeof mark.attrs === 'object' &&
+ mark.attrs !== null && {
+ attrs: transformAttributes(
+ mark.attrs as Record<string, unknown>,
+ EMAIL_DOCUMENT_MARK_CATALOG[mark.type].stringAttributes,
+ transform,
+ ),
+ }),
};
});
diff --git a/packages/twenty-shared/src/workflow/index.ts b/packages/twenty-shared/src/workflow/index.ts
index bf09afcaecc..0e29cb1c452 100644
--- a/packages/twenty-shared/src/workflow/index.ts
+++ b/packages/twenty-shared/src/workflow/index.ts
@@ -127,6 +127,7 @@ export { canObjectBeManagedByAutomation } from './utils/canObjectBeManagedByAuto
export { extractRawVariableNamePart } from './utils/extractRawVariableNameParts';
export { getFunctionInputFromInputSchema } from './utils/getFunctionInputFromInputSchema';
export { getWorkflowRunContext } from './utils/getWorkflowRunContext';
+export { isStandaloneVariableString } from './utils/isStandaloneVariableString';
export { parseBooleanFromStringValue } from './utils/parseBooleanFromStringValue';
export { parseDataFromContentType } from './utils/parseDataFromContentType';
export {
diff --git a/packages/twenty-shared/src/workflow/utils/__tests__/isStandaloneVariableString.test.ts b/packages/twenty-shared/src/workflow/utils/__tests__/isStandaloneVariableString.test.ts
new file mode 100644
index 00000000000..57b908481e1
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/utils/__tests__/isStandaloneVariableString.test.ts
@@ -0,0 +1,19 @@
+import { isStandaloneVariableString } from '@/workflow/utils/isStandaloneVariableString';
+
+describe('isStandaloneVariableString', () => {
+ it('rejects non-string values', () => {
+ expect(isStandaloneVariableString(42)).toBe(false);
+ });
+
+ it('accepts a standalone variable', () => {
+ expect(isStandaloneVariableString('{{ test.a.b.c }}')).toBe(true);
+ });
+
+ it('rejects leading text', () => {
+ expect(isStandaloneVariableString(' {{ test.a.b.c }}')).toBe(false);
+ });
+
+ it('rejects trailing text', () => {
+ expect(isStandaloneVariableString('{{ test.a.b.c }} ')).toBe(false);
+ });
+});
diff --git a/packages/twenty-shared/src/workflow/utils/isStandaloneVariableString.ts b/packages/twenty-shared/src/workflow/utils/isStandaloneVariableString.ts
new file mode 100644
index 00000000000..ae322dac668
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/utils/isStandaloneVariableString.ts
@@ -0,0 +1,2 @@
+export const isStandaloneVariableString = (value: unknown): value is string =>
+ typeof value === 'string' && /^{{[^{}]+}}$/.test(value);