Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(workflows): slim inline email template editor (#75989)

Harley Alexander6500c0c45455
diff --git a/frontend/src/layout/scenes/components/SceneTitleSection.tsx b/frontend/src/layout/scenes/components/SceneTitleSection.tsx
index 15fd79403063..fca45feca899 100644
--- a/frontend/src/layout/scenes/components/SceneTitleSection.tsx
+++ b/frontend/src/layout/scenes/components/SceneTitleSection.tsx
@@ -169,6 +169,10 @@ type SceneMainTitleProps = {
* Usually this is for 'new' resources, or "edit" mode
*/
forceEdit?: boolean
+ /**
+ * If true, the description is always rendered and the show/hide toggle is omitted
+ */
+ descriptionAlwaysVisible?: boolean
/**
* The number of milliseconds to debounce the name and description changes
* useful for renaming resources that update too fast
@@ -236,6 +240,7 @@ export function SceneTitleSection({
onDescriptionChange,
canEdit = false,
forceEdit = false,
+ descriptionAlwaysVisible = false,
renameDebounceMs,
saveOnBlur = false,
noBorder = false,
@@ -358,7 +363,7 @@ export function SceneTitleSection({
suffix={
<>
{nameSuffix}
- {hasDescription ? (
+ {hasDescription && !descriptionAlwaysVisible ? (
<ButtonPrimitive
className={cn(
'size-[var(--button-height-sm)] shrink-0',
@@ -402,7 +407,7 @@ export function SceneTitleSection({
</div>
{/* Border is handled by the outer container's border-b */}
</div>
- {hasDescription && (showDescription || forceEdit) && (
+ {hasDescription && (descriptionAlwaysVisible || showDescription || forceEdit) && (
<div className={cn('[&_svg]:size-6', noPadding ? cn('pl-4 pr-2', className) : '-mt-4')}>
<SceneDescription
description={effectiveDescription}
diff --git a/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx b/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx
index 1f4229f32eb9..e8a1dc4b24d9 100644
--- a/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx
+++ b/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx
@@ -1,20 +1,11 @@
import clsx from 'clsx'
import { BindLogic, useActions, useValues } from 'kea'
import { ChildFunctionProps, Form } from 'kea-forms'
-import { useCallback, useEffect, useRef, useState } from 'react'
+import { useEffect, useState } from 'react'
import EmailEditor, { EditorRef } from 'react-email-editor'
-import {
- IconChevronDown,
- IconChevronLeft,
- IconChevronRight,
- IconCollapse,
- IconExpand,
- IconExternal,
- IconPlus,
- IconX,
-} from '@posthog/icons'
-import { LemonButton, LemonLabel, LemonModal, LemonSelect, LemonTabs } from '@posthog/lemon-ui'
+import { IconCollapse, IconExpand, IconExternal, IconPlus, IconX } from '@posthog/icons'
+import { LemonButton, LemonCard, LemonLabel, LemonModal, LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'
import { CyclotronJobTemplateSuggestionsButton } from 'lib/components/CyclotronJob/CyclotronJobTemplateSuggestions'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
@@ -33,48 +24,6 @@ import { EMAIL_TYPE_SUPPORTED_FIELDS, EmailTemplaterLogicProps, emailTemplaterLo
export type EmailEditorMode = 'full' | 'preview'
-function EmailPreviewIframe({ html, title }: { html: string; title: string }): JSX.Element {
- const iframeRef = useRef<HTMLIFrameElement>(null)
- const observerRef = useRef<ResizeObserver | null>(null)
- const [height, setHeight] = useState<number | null>(null)
-
- const measure = useCallback(() => {
- const doc = iframeRef.current?.contentDocument
- if (doc?.documentElement) {
- setHeight(doc.documentElement.scrollHeight)
- }
- }, [])
-
- // Size the iframe to its document so the preview shows the whole email. The
- // ResizeObserver re-measures as images load; re-attached on every load since
- // srcDoc replaces the document.
- const onLoad = useCallback(() => {
- measure()
- const body = iframeRef.current?.contentDocument?.body
- if (body) {
- observerRef.current?.disconnect()
- observerRef.current = new ResizeObserver(measure)
- observerRef.current.observe(body)
- }
- }, [measure])
-
- useEffect(() => () => observerRef.current?.disconnect(), [])
-
- return (
- <iframe
- ref={iframeRef}
- srcDoc={html}
- // allow-same-origin without allow-scripts keeps the content inert (no JS runs)
- // while letting the parent read the document height
- sandbox="allow-same-origin"
- title={title}
- className="w-full"
- style={{ height: height ?? 150 }}
- onLoad={onLoad}
- />
- )
-}
-
function AddAdvancedFieldButtons(): JSX.Element | null {
const { hiddenAdvancedFields } = useValues(emailTemplaterLogic)
const { revealAdvancedField } = useActions(emailTemplaterLogic)
@@ -146,9 +95,8 @@ function DestinationEmailTemplaterForm({
mode: EmailEditorMode
fieldsHidden?: boolean
}): JSX.Element {
- const { logicProps, mergeTags, activeContentTab } = useValues(emailTemplaterLogic)
- const { setEmailEditorRef, onEmailEditorReady, setIsModalOpen, setActiveContentTab } =
- useActions(emailTemplaterLogic)
+ const { logicProps, mergeTags, activeContentTab, emailTemplate } = useValues(emailTemplaterLogic)
+ const { setEmailEditorRef, onEmailEditorReady } = useActions(emailTemplaterLogic)
return (
<>
@@ -191,15 +139,6 @@ function DestinationEmailTemplaterForm({
{mode === 'full' ? (
<>
- <LemonTabs
- activeKey={activeContentTab}
- onChange={(key) => setActiveContentTab(key as 'visual' | 'plaintext')}
- tabs={[
- { key: 'visual', label: 'Visual' },
- { key: 'plaintext', label: 'Plain text' },
- ]}
- className="px-2 shrink-0 border-b"
- />
<div className="relative flex flex-col flex-1">
<div
className={clsx(
@@ -243,14 +182,21 @@ function DestinationEmailTemplaterForm({
<LemonField name="html" className="flex relative flex-col">
{({ value }: ChildFunctionProps) => (
<>
- <div className="flex absolute inset-0 justify-center items-end p-2 opacity-0 transition-opacity hover:opacity-100">
+ <div
+ className={clsx(
+ 'flex absolute inset-0 justify-center items-end p-2 transition-opacity',
+ // Persistent start buttons while empty; hover-reveal once there is content
+ value ? 'opacity-0 hover:opacity-100' : 'opacity-100'
+ )}
+ >
<div className="absolute inset-0 opacity-50 bg-surface-primary" />
- <LemonButton type="primary" size="small" onClick={() => setIsModalOpen(true)}>
- Click to modify content
- </LemonButton>
+ {/* A plain-text-only email has no html, so content is judged on every shape */}
+ <EmailPreviewOverlayButtons
+ hasContent={!!value || !!emailTemplate.text || !!emailTemplate.design}
+ />
</div>
- <EmailPreviewIframe html={value} title="Email template preview" />
+ <iframe srcDoc={value} sandbox="" title="Email template preview" className="flex-1" />
</>
)}
</LemonField>
@@ -369,124 +315,56 @@ function LiquidSupportedText({
)
}
-const CARD_WIDTH = 192 // w-48
-const CARD_GAP = 12 // gap-3
-
-function TemplateSlider({
- templates,
- onSelect,
- onSaveAsTemplate,
-}: {
- templates: any[]
- onSelect: (template: any) => void
- onSaveAsTemplate?: () => void
-}): JSX.Element {
- const [expanded, setExpanded] = useState(false)
- const [page, setPage] = useState(0)
- const [pageSize, setPageSize] = useState(5)
- const containerRef = useRef<HTMLDivElement>(null)
-
- const updatePageSize = useCallback(() => {
- if (containerRef.current) {
- const width = containerRef.current.offsetWidth
- const count = Math.max(1, Math.floor((width + CARD_GAP) / (CARD_WIDTH + CARD_GAP)))
- setPageSize(count)
- }
- }, [])
-
- useEffect(() => {
- if (!expanded) {
- return
- }
- updatePageSize()
- const observer = new ResizeObserver(updatePageSize)
- if (containerRef.current) {
- observer.observe(containerRef.current)
- }
- return () => observer.disconnect()
- }, [expanded, updatePageSize])
-
- const totalPages = Math.ceil(templates.length / pageSize)
- const clampedPage = Math.min(page, totalPages - 1)
- const visibleTemplates = templates.slice(clampedPage * pageSize, (clampedPage + 1) * pageSize)
+export function TemplatePickerModal({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }): JSX.Element {
+ const { templates } = useValues(emailTemplaterLogic)
+ const { applyTemplate } = useActions(emailTemplaterLogic)
return (
- <div className="border-b">
- <div
- className="flex gap-2 items-center px-2 py-1 cursor-pointer select-none"
- onClick={() => setExpanded(!expanded)}
- >
- <IconChevronDown className={clsx('w-4 h-4 transition-transform', !expanded && '-rotate-90')} />
- <span className="flex-1 text-sm text-secondary">Start from a template (optional)</span>
- {onSaveAsTemplate && (
- <LemonButton
- size="xsmall"
- type="secondary"
- onClick={(e) => {
- e.stopPropagation()
- onSaveAsTemplate()
- }}
- >
- Save as new template
- </LemonButton>
- )}
- </div>
- {expanded && (
- <div ref={containerRef} className="flex items-center gap-1 px-1 pb-2">
- <LemonButton
- size="small"
- icon={<IconChevronLeft />}
- disabled={clampedPage === 0}
- onClick={() => setPage(clampedPage - 1)}
- />
- <div className="flex gap-3 flex-1 overflow-hidden" key={clampedPage}>
- {visibleTemplates.map((template, index) => (
- <div
- key={template.id}
- className="shrink-0 w-48 h-56 MessageTemplateSlider__SlideIn--animate"
- style={{ animationDelay: `${index * 50}ms` }}
- >
- <MessageTemplateCard
- template={template}
- index={clampedPage * pageSize + index}
- onClick={() => onSelect(template)}
- />
- </div>
- ))}
+ <LemonModal isOpen={isOpen} onClose={onClose} title="Choose a starting point" width={880}>
+ <div className="flex flex-wrap gap-3">
+ <LemonCard
+ className="w-48 h-56 flex flex-col gap-2 items-center justify-center cursor-pointer"
+ onClick={onClose}
+ data-attr="template-picker-blank"
+ >
+ <IconPlus className="text-2xl" />
+ <span>Blank template</span>
+ </LemonCard>
+ {templates.map((template, index) => (
+ <div key={template.id} className="w-48 h-56">
+ <MessageTemplateCard
+ template={template}
+ index={index}
+ onClick={() => {
+ applyTemplate(template)
+ onClose()
+ }}
+ />
</div>
- <LemonButton
- size="small"
- icon={<IconChevronRight />}
- disabled={clampedPage >= totalPages - 1}
- onClick={() => setPage(clampedPage + 1)}
- />
- </div>
- )}
- </div>
+ ))}
+ </div>
+ </LemonModal>
)
}
function NativeEmailTemplaterForm({
mode,
fieldsHidden,
- onSaveAsTemplate,
}: {
mode: EmailEditorMode
fieldsHidden?: boolean
- onSaveAsTemplate?: () => void
}): JSX.Element {
- const { unlayerEditorProjectId, logicProps, templates, mergeTags, activeContentTab, visibleFields } =
+ const { unlayerEditorProjectId, logicProps, templates, mergeTags, activeContentTab, visibleFields, emailTemplate } =
useValues(emailTemplaterLogic)
- const {
- setEmailEditorRef,
- onEmailEditorReady,
- setIsModalOpen,
- applyTemplate,
- setActiveContentTab,
- hideAdvancedField,
- } = useActions(emailTemplaterLogic)
+ const { setEmailEditorRef, onEmailEditorReady, setActiveContentTab, hideAdvancedField, revealAdvancedField } =
+ useActions(emailTemplaterLogic)
- const [previewTemplate, setPreviewTemplate] = useState<(typeof templates)[0] | null>(null)
+ // The template editor has only subject + preheader, so they share one row with the
+ // visual/plain-text switch to keep vertical space for the canvas.
+ const compactHeader = logicProps.type === 'native_email_template' && mode === 'full'
+ const preheaderVisible = visibleFields.some((field) => field.key === 'preheader')
+ // Preheaders see almost no use, so don't advertise the field unless this team already uses it.
+ const offerPreheader = templates.some((template) => !!template.content?.email?.preheader)
return (
<>
@@ -497,83 +375,128 @@ function NativeEmailTemplaterForm({
formKey="emailTemplate"
>
<div className={fieldsHidden ? 'h-0 overflow-hidden' : ''}>
- {visibleFields.map((field) => (
- <LemonField
- key={field.key}
- name={field.key}
- className="gap-1 pl-2 border-b shrink-0"
- // We will handle the error display ourselves
- renderError={() => null}
- showOptional={field.optional}
- >
- {({ value, onChange, error }: ChildFunctionProps) => (
- <div className="flex gap-2 items-center">
- <LemonLabel
- className={error ? 'text-danger' : ''}
- info={field.helpText}
- showOptional={field.optional}
- >
- {field.label}
- </LemonLabel>
- {field.key === 'from' ? (
- <NativeEmailIntegrationChoice value={value} onChange={onChange} />
- ) : field.key === 'to' ? (
- /**
- * In email inputs, "to" maps to { email: string; name: string; },
- * whereas other fields map directly to their string value
- */
- <LiquidSupportedText
- value={value?.email}
- onChange={(email) => onChange({ ...value, email })}
- globals={logicProps.variables}
- />
- ) : (
+ {compactHeader ? (
+ <div className="flex gap-2 items-center pl-2 pr-1 py-0.5 border-b shrink-0">
+ <LemonField name="subject" className="flex-2 min-w-40" renderError={() => null}>
+ {({ value, onChange, error }: ChildFunctionProps) => (
+ <div className="flex gap-2 items-center flex-1">
+ <LemonLabel className={error ? 'text-danger' : ''}>Subject</LemonLabel>
<LiquidSupportedText
value={value}
onChange={onChange}
globals={logicProps.variables}
/>
+ </div>
+ )}
+ </LemonField>
+ {preheaderVisible ? (
+ <LemonField name="preheader" className="flex-1 min-w-40" renderError={() => null}>
+ {({ value, onChange }: ChildFunctionProps) => (
+ <div className="flex gap-2 items-center flex-1">
+ <LemonLabel info="This is the preview text that appears below the subject line in an inbox.">
+ Preheader
+ </LemonLabel>
+ <LiquidSupportedText
+ value={value}
+ onChange={onChange}
+ globals={logicProps.variables}
+ />
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ icon={<IconX />}
+ onClick={() => {
+ onChange('')
+ hideAdvancedField('preheader')
+ }}
+ tooltip="Remove field"
+ />
+ </div>
)}
- {field.isAdvancedField && (
- <LemonButton
- size="xsmall"
- type="tertiary"
- icon={<IconX />}
- className="mr-2"
- onClick={() => {
- onChange('')
- hideAdvancedField(field.key)
- }}
- tooltip="Remove field"
- />
- )}
- </div>
- )}
- </LemonField>
- ))}
-
- <AddAdvancedFieldButtons />
-
- {mode === 'full' && templates.length > 0 && (
- <TemplateSlider
- templates={templates}
- onSelect={applyTemplate}
- onSaveAsTemplate={onSaveAsTemplate}
- />
+ </LemonField>
+ ) : offerPreheader ? (
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ icon={<IconPlus />}
+ onClick={() => revealAdvancedField('preheader')}
+ >
+ Preheader
+ </LemonButton>
+ ) : null}
+ <LemonSegmentedButton
+ size="small"
+ className="ml-2 shrink-0"
+ value={activeContentTab}
+ onChange={(tab) => setActiveContentTab(tab as 'visual' | 'plaintext')}
+ options={[
+ { value: 'visual', label: 'Visual' },
+ { value: 'plaintext', label: 'Plain text' },
+ ]}
+ />
+ </div>
+ ) : (
+ visibleFields.map((field) => (
+ <LemonField
+ key={field.key}
+ name={field.key}
+ className="gap-1 pl-2 border-b shrink-0"
+ // We will handle the error display ourselves
+ renderError={() => null}
+ showOptional={field.optional}
+ >
+ {({ value, onChange, error }: ChildFunctionProps) => (
+ <div className="flex gap-2 items-center">
+ <LemonLabel
+ className={error ? 'text-danger' : ''}
+ info={field.helpText}
+ showOptional={field.optional}
+ >
+ {field.label}
+ </LemonLabel>
+ {field.key === 'from' ? (
+ <NativeEmailIntegrationChoice value={value} onChange={onChange} />
+ ) : field.key === 'to' ? (
+ /**
+ * In email inputs, "to" maps to { email: string; name: string; },
+ * whereas other fields map directly to their string value
+ */
+ <LiquidSupportedText
+ value={value?.email}
+ onChange={(email) => onChange({ ...value, email })}
+ globals={logicProps.variables}
+ />
+ ) : (
+ <LiquidSupportedText
+ value={value}
+ onChange={onChange}
+ globals={logicProps.variables}
+ />
+ )}
+ {field.isAdvancedField && (
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ icon={<IconX />}
+ className="mr-2"
+ onClick={() => {
+ onChange('')
+ hideAdvancedField(field.key)
+ }}
+ tooltip="Remove field"
+ />
+ )}
+ </div>
+ )}
+ </LemonField>
+ ))
)}
+
+ {!compactHeader && <AddAdvancedFieldButtons />}
</div>
{mode === 'full' ? (
<>
- <LemonTabs
- activeKey={activeContentTab}
- onChange={(key) => setActiveContentTab(key as 'visual' | 'plaintext')}
- tabs={[
- { key: 'visual', label: 'Visual' },
- { key: 'plaintext', label: 'Plain text' },
- ]}
- className="px-2 shrink-0 border-b"
- />
<div className="relative flex flex-col flex-1">
<div
className={clsx(
@@ -632,21 +555,6 @@ function NativeEmailTemplaterForm({
</div>
{activeContentTab === 'plaintext' && <PlainTextEditor />}
</div>
- <LemonModal
- isOpen={!!previewTemplate}
- onClose={() => setPreviewTemplate(null)}
- title={`Preview: ${previewTemplate?.name}`}
- width="90vw"
- >
- <div className="h-[80vh] overflow-auto">
- <iframe
- srcDoc={previewTemplate?.content.email.html}
- sandbox=""
- title="Email template preview"
- className="w-full h-full border-0"
- />
- </div>
- </LemonModal>
</>
) : (
<LemonField name="html" className="flex relative flex-col">
@@ -654,17 +562,19 @@ function NativeEmailTemplaterForm({
<>
<div
className={clsx(
- 'flex absolute inset-0 justify-center items-center p-2 opacity-0 transition-opacity hover:opacity-100',
- value ? 'opacity-0' : 'opacity-100' // Hide if there is content
+ 'flex absolute inset-0 justify-center items-center p-2 transition-opacity',
+ // Persistent start buttons while empty; hover-reveal once there is content
+ value ? 'opacity-0 hover:opacity-100' : 'opacity-100'
)}
>
<div className="absolute inset-0 opacity-50 bg-surface-primary" />
- <LemonButton type="primary" size="small" onClick={() => setIsModalOpen(true)}>
- Click to modify content
- </LemonButton>
+ {/* A plain-text-only email has no html, so content is judged on every shape */}
+ <EmailPreviewOverlayButtons
+ hasContent={!!value || !!emailTemplate.text || !!emailTemplate.design}
+ />
</div>
- <EmailPreviewIframe html={value} title="Email template preview" />
+ <iframe srcDoc={value} sandbox="" title="Email template preview" className="flex-1" />
</>
)}
</LemonField>
@@ -674,15 +584,40 @@ function NativeEmailTemplaterForm({
)
}
-function EmailTemplaterForm({
- mode,
- fieldsHidden,
- onSaveAsTemplate,
-}: {
- mode: EmailEditorMode
- fieldsHidden?: boolean
- onSaveAsTemplate?: () => void
-}): JSX.Element {
+function EmailPreviewOverlayButtons({ hasContent }: { hasContent: boolean }): JSX.Element {
+ const { templates } = useValues(emailTemplaterLogic)
+ const { setIsModalOpen, setIsTemplatePickerOpen } = useActions(emailTemplaterLogic)
+
+ if (hasContent) {
+ return (
+ <LemonButton type="primary" size="small" onClick={() => setIsModalOpen(true)}>
+ Click to modify content
+ </LemonButton>
+ )
+ }
+
+ return (
+ <div className="flex gap-2 z-10">
+ <LemonButton type="primary" size="small" onClick={() => setIsModalOpen(true)}>
+ Start blank
+ </LemonButton>
+ {templates.length > 0 && (
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={() => {
+ setIsModalOpen(true)
+ setIsTemplatePickerOpen(true)
+ }}
+ >
+ Start from template
+ </LemonButton>
+ )}
+ </div>
+ )
+}
+
+function EmailTemplaterForm({ mode, fieldsHidden }: { mode: EmailEditorMode; fieldsHidden?: boolean }): JSX.Element {
const { logicProps } = useValues(emailTemplaterLogic)
switch (logicProps.type) {
@@ -690,9 +625,7 @@ function EmailTemplaterForm({
return <DestinationEmailTemplaterForm mode={mode} fieldsHidden={fieldsHidden} />
case 'native_email_template':
case 'native_email':
- return (
- <NativeEmailTemplaterForm mode={mode} fieldsHidden={fieldsHidden} onSaveAsTemplate={onSaveAsTemplate} />
- )
+ return <NativeEmailTemplaterForm mode={mode} fieldsHidden={fieldsHidden} />
}
}
@@ -764,15 +697,28 @@ function SaveTemplateModal({
}
function EmailTemplaterModal(): JSX.Element {
- const { isModalOpen, isEmailEditorReady, emailTemplateChanged, isSaveTemplateModalOpen } =
- useValues(emailTemplaterLogic)
- const { closeWithConfirmation, submitEmailTemplate, saveAsTemplate, setIsSaveTemplateModalOpen } =
- useActions(emailTemplaterLogic)
- const [fieldsHidden, setFieldsHidden] = useState(false)
+ const {
+ isModalOpen,
+ isEmailEditorReady,
+ emailTemplateChanged,
+ isSaveTemplateModalOpen,
+ isTemplatePickerOpen,
+ activeContentTab,
+ } = useValues(emailTemplaterLogic)
+ const {
+ closeWithConfirmation,
+ submitEmailTemplate,
+ saveAsTemplate,
+ setIsSaveTemplateModalOpen,
+ setIsTemplatePickerOpen,
+ setActiveContentTab,
+ } = useActions(emailTemplaterLogic)
+ // Fields start collapsed: in embedded contexts they duplicate the surrounding form.
+ const [fieldsHidden, setFieldsHidden] = useState(true)
useEffect(() => {
if (!isModalOpen) {
- setFieldsHidden(false)
+ setFieldsHidden(true)
}
}, [isModalOpen])
@@ -780,30 +726,46 @@ function EmailTemplaterModal(): JSX.Element {
<>
<LemonModal
isOpen={isModalOpen}
- width="90vw"
+ fullScreen
+ simple
+ title=""
onClose={() => closeWithConfirmation()}
hasUnsavedInput={emailTemplateChanged}
>
- <div className="h-[85vh] flex relative">
- <LemonButton
- type="tertiary"
- size="small"
- icon={fieldsHidden ? <IconExpand /> : <IconCollapse />}
- onClick={() => setFieldsHidden(!fieldsHidden)}
- className="absolute -top-1 right-10 z-10"
- >
- {fieldsHidden ? 'Show fields' : 'Hide fields'}
- </LemonButton>
+ {/* simple puts us directly in the modal's flex column, so flex-1 fills the screen;
+ a percentage height would collapse inside the default non-flex content wrapper. */}
+ <div className="flex-1 min-h-0 flex relative p-4">
+ {/* Aligned with the modal's close button (top-3 right-4), sitting just left of it */}
+ <div className="absolute top-3 right-14 z-10 flex items-center gap-2">
+ {/* The toggle label changes width; keeping it left of the right-anchored
+ tabs means the tabs never shift when it flips */}
+ <LemonButton
+ type="tertiary"
+ size="small"
+ icon={fieldsHidden ? <IconExpand /> : <IconCollapse />}
+ onClick={() => setFieldsHidden(!fieldsHidden)}
+ >
+ {fieldsHidden ? 'Show fields' : 'Hide fields'}
+ </LemonButton>
+ <LemonSegmentedButton
+ size="small"
+ value={activeContentTab}
+ onChange={(tab) => setActiveContentTab(tab as 'visual' | 'plaintext')}
+ options={[
+ { value: 'visual', label: 'Visual' },
+ { value: 'plaintext', label: 'Plain text' },
+ ]}
+ />
+ </div>
<div className="flex flex-col flex-1">
<div className="shrink-0">
<h2>Editing email template</h2>
</div>
- <EmailTemplaterForm
- mode="full"
- fieldsHidden={fieldsHidden}
- onSaveAsTemplate={() => setIsSaveTemplateModalOpen(true)}
- />
+ <EmailTemplaterForm mode="full" fieldsHidden={fieldsHidden} />
<div className="flex gap-2 items-center mt-2">
+ <LemonButton type="secondary" onClick={() => setIsSaveTemplateModalOpen(true)}>
+ Save as new template
+ </LemonButton>
<div className="flex-1" />
<LemonButton onClick={() => closeWithConfirmation()}>Discard changes</LemonButton>
<LemonButton
@@ -817,6 +779,23 @@ function EmailTemplaterModal(): JSX.Element {
</div>
</div>
</LemonModal>
+ <TemplatePickerModal isOpen={isTemplatePickerOpen} onClose={() => setIsTemplatePickerOpen(false)} />
+ <SaveTemplateModal
+ isOpen={isSaveTemplateModalOpen}
+ onClose={() => setIsSaveTemplateModalOpen(false)}
+ onSave={(name, description) => saveAsTemplate(name, description)}
+ />
+ </>
+ )
+}
+
+function EmailTemplaterInline(): JSX.Element {
+ const { isSaveTemplateModalOpen } = useValues(emailTemplaterLogic)
+ const { saveAsTemplate, setIsSaveTemplateModalOpen } = useActions(emailTemplaterLogic)
+
+ return (
+ <>
+ <EmailTemplaterForm mode="full" />
<SaveTemplateModal
isOpen={isSaveTemplateModalOpen}
onClose={() => setIsSaveTemplateModalOpen(false)}
@@ -830,8 +809,14 @@ export function EmailTemplater(props: EmailTemplaterLogicProps): JSX.Element {
return (
<BindLogic logic={emailTemplaterLogic} props={props}>
<div className="flex flex-col flex-1">
- <EmailTemplaterForm mode="preview" />
- <EmailTemplaterModal />
+ {props.layout === 'inline' ? (
+ <EmailTemplaterInline />
+ ) : (
+ <>
+ <EmailTemplaterForm mode="preview" />
+ <EmailTemplaterModal />
+ </>
+ )}
</div>
</BindLogic>
)
diff --git a/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.test.ts b/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.test.ts
index a71bbb47ba2f..f4f87b9fe426 100644
--- a/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.test.ts
+++ b/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.test.ts
@@ -4,10 +4,11 @@ import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import {
- emailTemplaterLogic,
EMAIL_TYPE_SUPPORTED_FIELDS,
+ EditorRef,
EmailTemplate,
EmailTemplaterLogicProps,
+ emailTemplaterLogic,
} from './emailTemplaterLogic'
const DEFAULT_EMAIL_TEMPLATE: EmailTemplate = {
@@ -31,7 +32,7 @@ function makeProps(overrides?: Partial<EmailTemplaterLogicProps>): EmailTemplate
const ADVANCED_FIELDS = EMAIL_TYPE_SUPPORTED_FIELDS.native_email.filter((f) => f.isAdvancedField)
const NON_ADVANCED_FIELDS = EMAIL_TYPE_SUPPORTED_FIELDS.native_email.filter((f) => !f.isAdvancedField)
-describe('emailTemplaterLogic - advanced fields', () => {
+describe('emailTemplaterLogic', () => {
let logic: ReturnType<typeof emailTemplaterLogic.build>
beforeEach(() => {
@@ -46,83 +47,221 @@ describe('emailTemplaterLogic - advanced fields', () => {
afterEach(() => {
logic?.unmount()
+ jest.useRealTimers()
})
- it('hides advanced fields by default', async () => {
- logic = emailTemplaterLogic(makeProps())
- logic.mount()
+ describe('advanced fields', () => {
+ it('hides advanced fields by default', async () => {
+ logic = emailTemplaterLogic(makeProps())
+ logic.mount()
- await expectLogic(logic).toMatchValues({
- visibleFields: NON_ADVANCED_FIELDS,
- hiddenAdvancedFields: ADVANCED_FIELDS,
+ await expectLogic(logic).toMatchValues({
+ visibleFields: NON_ADVANCED_FIELDS,
+ hiddenAdvancedFields: ADVANCED_FIELDS,
+ })
})
- })
- it('can reveal and then hide an advanced field', async () => {
- logic = emailTemplaterLogic(makeProps())
- logic.mount()
+ it('can reveal and then hide an advanced field', async () => {
+ logic = emailTemplaterLogic(makeProps())
+ logic.mount()
+
+ await expectLogic(logic, () => {
+ logic.actions.revealAdvancedField('replyTo')
+ }).toMatchValues({
+ revealedAdvancedFields: ['replyTo'],
+ visibleFields: expect.arrayContaining([expect.objectContaining({ key: 'replyTo' })]),
+ hiddenAdvancedFields: expect.arrayContaining([
+ expect.objectContaining({ key: 'cc' }),
+ expect.objectContaining({ key: 'bcc' }),
+ expect.objectContaining({ key: 'preheader' }),
+ ]),
+ })
- await expectLogic(logic, () => {
+ // Revealing the same field again should not duplicate it
logic.actions.revealAdvancedField('replyTo')
- }).toMatchValues({
- revealedAdvancedFields: ['replyTo'],
- visibleFields: expect.arrayContaining([expect.objectContaining({ key: 'replyTo' })]),
- hiddenAdvancedFields: expect.arrayContaining([
- expect.objectContaining({ key: 'cc' }),
- expect.objectContaining({ key: 'bcc' }),
- expect.objectContaining({ key: 'preheader' }),
- ]),
+ expect(logic.values.revealedAdvancedFields).toEqual(['replyTo'])
+
+ await expectLogic(logic, () => {
+ logic.actions.hideAdvancedField('replyTo')
+ }).toMatchValues({
+ visibleFields: NON_ADVANCED_FIELDS,
+ hiddenAdvancedFields: ADVANCED_FIELDS,
+ })
})
- // Revealing the same field again should not duplicate it
- logic.actions.revealAdvancedField('replyTo')
- expect(logic.values.revealedAdvancedFields).toEqual(['replyTo'])
+ it('auto-reveals advanced fields that have values on mount', async () => {
+ logic = emailTemplaterLogic(
+ makeProps({
+ value: { ...DEFAULT_EMAIL_TEMPLATE, replyTo: '[email protected]' },
+ })
+ )
+ logic.mount()
- await expectLogic(logic, () => {
- logic.actions.hideAdvancedField('replyTo')
- }).toMatchValues({
- visibleFields: NON_ADVANCED_FIELDS,
- hiddenAdvancedFields: ADVANCED_FIELDS,
+ await expectLogic(logic).toMatchValues({
+ revealedAdvancedFields: ['replyTo'],
+ visibleFields: expect.arrayContaining([expect.objectContaining({ key: 'replyTo' })]),
+ hiddenAdvancedFields: expect.arrayContaining([
+ expect.objectContaining({ key: 'cc' }),
+ expect.objectContaining({ key: 'bcc' }),
+ expect.objectContaining({ key: 'preheader' }),
+ ]),
+ })
})
- })
- it('auto-reveals advanced fields that have values on mount', async () => {
- logic = emailTemplaterLogic(
- makeProps({
+ it('auto-reveals advanced fields when props change with new values', async () => {
+ const initialProps = makeProps()
+ logic = emailTemplaterLogic(initialProps)
+ logic.mount()
+
+ await expectLogic(logic).toMatchValues({
+ revealedAdvancedFields: [],
+ })
+
+ // Simulate parent updating props with a replyTo value
+ const updatedProps = makeProps({
value: { ...DEFAULT_EMAIL_TEMPLATE, replyTo: '[email protected]' },
})
- )
- logic.mount()
-
- await expectLogic(logic).toMatchValues({
- revealedAdvancedFields: ['replyTo'],
- visibleFields: expect.arrayContaining([expect.objectContaining({ key: 'replyTo' })]),
- hiddenAdvancedFields: expect.arrayContaining([
- expect.objectContaining({ key: 'cc' }),
- expect.objectContaining({ key: 'bcc' }),
- expect.objectContaining({ key: 'preheader' }),
- ]),
+ emailTemplaterLogic(updatedProps)
+
+ await expectLogic(logic).toMatchValues({
+ revealedAdvancedFields: ['replyTo'],
+ visibleFields: expect.arrayContaining([expect.objectContaining({ key: 'replyTo' })]),
+ })
+ })
+ })
+
+ describe('modal content tab default', () => {
+ it.each([
+ {
+ description: 'a blank email opens on the visual tab',
+ value: { ...DEFAULT_EMAIL_TEMPLATE, html: '', text: '', design: null },
+ expectedTab: 'visual',
+ },
+ {
+ description: 'an email with html opens on the visual tab',
+ value: DEFAULT_EMAIL_TEMPLATE,
+ expectedTab: 'visual',
+ },
+ {
+ description: 'a plain-text-only email opens on the plain text tab',
+ value: { ...DEFAULT_EMAIL_TEMPLATE, html: '', design: null },
+ expectedTab: 'plaintext',
+ },
+ ])('$description', async ({ value, expectedTab }) => {
+ logic = emailTemplaterLogic(makeProps({ value }))
+ logic.mount()
+
+ logic.actions.setIsModalOpen(true)
+ await expectLogic(logic).toMatchValues({ activeContentTab: expectedTab })
})
})
- it('auto-reveals advanced fields when props change with new values', async () => {
- const initialProps = makeProps()
- logic = emailTemplaterLogic(initialProps)
- logic.mount()
+ describe('starting-point picker', () => {
+ it('closes the picker when the editor modal closes', async () => {
+ logic = emailTemplaterLogic(makeProps())
+ logic.mount()
- await expectLogic(logic).toMatchValues({
- revealedAdvancedFields: [],
+ logic.actions.setIsModalOpen(true)
+ logic.actions.setIsTemplatePickerOpen(true)
+ await expectLogic(logic).toMatchValues({ isTemplatePickerOpen: true })
+
+ logic.actions.setIsModalOpen(false)
+ await expectLogic(logic).toMatchValues({ isTemplatePickerOpen: false })
})
+ })
- // Simulate parent updating props with a replyTo value
- const updatedProps = makeProps({
- value: { ...DEFAULT_EMAIL_TEMPLATE, replyTo: '[email protected]' },
+ describe('inline layout live propagation', () => {
+ let onChange: jest.Mock
+ let loadDesign: jest.Mock
+ let editorListeners: Record<string, () => void>
+ let editorDesign: Record<string, any>
+
+ const DESIGN_STORED = { body: { id: 'stored', rows: [{ id: 'r1' }] } }
+ // What unlayer exports after normalizing DESIGN_STORED (it rewrites ids/defaults on load).
+ const DESIGN_NORMALIZED = { body: { id: 'stored', rows: [{ id: 'r1' }], values: { normalized: true } } }
+ const DESIGN_EDITED = { body: { id: 'edited', rows: [{ id: 'r2' }] } }
+
+ const fakeEditorRef = (): EditorRef =>
+ ({
+ editor: {
+ loadDesign,
+ addEventListener: (event: string, callback: () => void) => {
+ editorListeners[event] = callback
+ },
+ exportHtml: (callback: (data: any) => void) =>
+ callback({ html: '<p>edited</p>', design: editorDesign }),
+ exportPlainText: (callback: (data: any) => void) => callback({ text: 'edited' }),
+ },
+ }) as unknown as EditorRef
+
+ beforeEach(() => {
+ onChange = jest.fn()
+ loadDesign = jest.fn()
+ editorListeners = {}
+ editorDesign = DESIGN_NORMALIZED
+ logic = emailTemplaterLogic(
+ makeProps({
+ value: { ...DEFAULT_EMAIL_TEMPLATE, design: DESIGN_STORED },
+ onChange,
+ type: 'native_email_template',
+ layout: 'inline',
+ })
+ )
+ logic.mount()
+ logic.actions.setEmailEditorRef(fakeEditorRef())
+ logic.actions.onEmailEditorReady()
})
- emailTemplaterLogic(updatedProps)
- await expectLogic(logic).toMatchValues({
- revealedAdvancedFields: ['replyTo'],
- visibleFields: expect.arrayContaining([expect.objectContaining({ key: 'replyTo' })]),
+ it('propagates a user edit to the parent after the debounce', async () => {
+ expect(loadDesign).toHaveBeenCalledWith(DESIGN_STORED)
+
+ jest.useFakeTimers()
+ editorDesign = DESIGN_EDITED
+ editorListeners['design:updated']?.()
+ await jest.advanceTimersByTimeAsync(500)
+ jest.useRealTimers()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(onChange).toHaveBeenCalledTimes(1)
+ expect(onChange.mock.calls[0][0]).toMatchObject({
+ design: DESIGN_EDITED,
+ html: '<p>edited</p>',
+ text: 'edited',
+ })
+ })
+
+ it('propagates an edit made immediately after a design load', async () => {
+ // The load rebaselines via design:loaded...
+ expect(editorListeners['design:loaded']).toBeTruthy()
+ editorListeners['design:loaded']()
+ await expectLogic(logic).toFinishAllListeners()
+
+ // ...and an edit fired straight after must still reach the parent, not be
+ // discarded as a load echo.
+ jest.useFakeTimers()
+ editorDesign = DESIGN_EDITED
+ editorListeners['design:updated']?.()
+ await jest.advanceTimersByTimeAsync(500)
+ jest.useRealTimers()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(onChange).toHaveBeenCalledTimes(1)
+ expect(onChange.mock.calls[0][0]).toMatchObject({ design: DESIGN_EDITED })
+ })
+
+ it('rebaselines on design:loaded so the normalized export does not count as an edit', async () => {
+ expect(editorListeners['design:loaded']).toBeTruthy()
+ editorListeners['design:loaded']()
+ await expectLogic(logic).toFinishAllListeners()
+
+ jest.useFakeTimers()
+ // The editor re-exports the normalized design unchanged - not a user edit.
+ editorListeners['design:updated']?.()
+ await jest.advanceTimersByTimeAsync(500)
+ jest.useRealTimers()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(onChange).not.toHaveBeenCalled()
})
})
})
diff --git a/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx b/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx
index 7a61459dbfcf..4d05643005bd 100644
--- a/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx
+++ b/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx
@@ -109,6 +109,12 @@ export interface EmailTemplaterLogicProps {
defaultValue?: EmailTemplate | null
templating?: boolean | 'hog' | 'liquid'
onChangeTemplating?: (templating: 'hog' | 'liquid') => void
+ /**
+ * 'modal' (default): preview with an editing modal, changes propagate on save.
+ * 'inline': the full editor rendered in place, changes propagate live (debounced) so the
+ * parent form's dirty state and save flow see them without a separate editor-level save.
+ */
+ layout?: 'modal' | 'inline'
}
function autoRevealAdvancedFields(
@@ -149,6 +155,7 @@ export interface emailTemplaterLogicValues {
isEmailTemplateValid: boolean
isModalOpen: boolean
isSaveTemplateModalOpen: boolean
+ isTemplatePickerOpen: boolean
logicProps: EmailTemplaterLogicProps
mergeTags: UnlayerMergeTags
personPropertyDefinitions: PropertyDefinition[]
@@ -170,6 +177,12 @@ export interface emailTemplaterLogicActions {
closeWithConfirmation: () => {
value: true
}
+ designLoaded: () => {
+ value: true
+ }
+ designUpdated: () => {
+ value: true
+ }
hideAdvancedField: (key: EmailMetaFieldKey) => {
key: EmailMetaFieldKey
}
@@ -244,6 +257,9 @@ export interface emailTemplaterLogicActions {
setIsSaveTemplateModalOpen: (isOpen: boolean) => {
isOpen: boolean
}
+ setIsTemplatePickerOpen: (isOpen: boolean) => {
+ isOpen: boolean
+ }
setTemplatingEngine: (templating: 'hog' | 'liquid') => {
templating: 'hog' | 'liquid'
}
@@ -297,6 +313,9 @@ export const emailTemplaterLogic = kea<emailTemplaterLogicType>([
onEmailEditorReady: true,
setIsModalOpen: (isModalOpen: boolean) => ({ isModalOpen }),
setIsSaveTemplateModalOpen: (isOpen: boolean) => ({ isOpen }),
+ setIsTemplatePickerOpen: (isOpen: boolean) => ({ isOpen }),
+ designUpdated: true,
+ designLoaded: true,
applyTemplate: (template: MessageTemplate) => ({ template }),
closeWithConfirmation: true,
setTemplatingEngine: (templating: 'hog' | 'liquid') => ({ templating }),
@@ -331,6 +350,13 @@ export const emailTemplaterLogic = kea<emailTemplaterLogicType>([
setIsSaveTemplateModalOpen: (_, { isOpen }) => isOpen,
},
],
+ isTemplatePickerOpen: [
+ false,
+ {
+ setIsTemplatePickerOpen: (_, { isOpen }) => isOpen,
+ setIsModalOpen: (state, { isModalOpen }) => (isModalOpen ? state : false),
+ },
+ ],
appliedTemplate: [
null as MessageTemplate | null,
{
@@ -442,7 +468,7 @@ export const emailTemplaterLogic = kea<emailTemplaterLogicType>([
],
}),
- forms(({ actions, values, props }) => ({
+ forms(({ actions, values, props, cache }) => ({
emailTemplate: {
defaults: props.defaultValue as EmailTemplate,
submit: async (formValues: EmailTemplate | undefined) => {
@@ -480,19 +506,73 @@ export const emailTemplaterLogic = kea<emailTemplaterLogicType>([
design: htmlData.design,
}
+ cache.lastEditorDesign = htmlData.design
props.onChange(finalValues)
actions.setIsModalOpen(false)
},
},
})),
- listeners(({ props, values, actions }) => ({
+ listeners(({ props, values, actions, cache }) => ({
onEmailEditorReady: () => {
+ // Listeners must attach before loadDesign so the initial design:loaded is heard and
+ // rebaselines - otherwise the load echo is indistinguishable from a user edit.
+ if (props.layout === 'inline') {
+ values.emailEditorRef?.editor?.addEventListener('design:updated', () => actions.designUpdated())
+ values.emailEditorRef?.editor?.addEventListener('design:loaded', () => actions.designLoaded())
+ }
if (props.value?.design) {
+ cache.lastEditorDesign = props.value.design
values.emailEditorRef?.editor?.loadDesign(props.value.design)
}
},
+ designLoaded: async (_, breakpoint) => {
+ // Re-baseline off the editor's own normalized export: unlayer rewrites loaded JSON
+ // (defaults, ids), so comparing raw stored designs against later exports would flag
+ // every load echo as an edit and falsely dirty the parent form.
+ const editor = values.emailEditorRef?.editor
+ if (!editor || props.layout !== 'inline') {
+ return
+ }
+ const htmlData: { design: JSONTemplate } = await new Promise<any>((res) => editor.exportHtml(res))
+ breakpoint()
+ cache.lastEditorDesign = htmlData.design
+ },
+
+ designUpdated: async (_, breakpoint) => {
+ // A programmatic loadDesign fires design:updated too; the debounce lets designLoaded
+ // rebaseline first, and the equality check below then filters the echo. A genuine user
+ // edit differs from the baseline, so it always propagates - even right after a load.
+ await breakpoint(500)
+
+ const editor = values.emailEditorRef?.editor
+ if (!editor || !values.isEmailEditorReady) {
+ return
+ }
+
+ const [htmlData, textData]: [{ html: string; design: JSONTemplate }, { text: string }] = await Promise.all([
+ new Promise<any>((res) => editor.exportHtml(res)),
+ new Promise<any>((res) => editor.exportPlainText(res)),
+ ])
+ breakpoint()
+
+ // Only real changes propagate - an export identical to the last known editor state is a
+ // load echo, and pushing it would only mark the parent form dirty.
+ if (objectsEqual(htmlData.design, cache.lastEditorDesign)) {
+ return
+ }
+ cache.lastEditorDesign = htmlData.design
+ props.onChange({
+ ...values.emailTemplate,
+ html: ['native_email', 'native_email_template'].includes(props.type)
+ ? htmlData.html
+ : escapeHTMLStringCurlies(htmlData.html),
+ text: textData.text,
+ design: htmlData.design,
+ })
+ },
+
setEmailTemplateValue: ({ name, value }) => {
if (values.isModalOpen) {
// When open we only update on save
@@ -520,8 +600,9 @@ export const emailTemplaterLogic = kea<emailTemplaterLogicType>([
setIsModalOpen: ({ isModalOpen }) => {
if (isModalOpen && props.value) {
- const hasHtml = !!props.value.html
- actions.setActiveContentTab(hasHtml ? 'visual' : 'plaintext')
+ // Plain text only when the email is genuinely text-only; a blank email starts visual.
+ const plainTextOnly = !!props.value.text && !props.value.html && !props.value.design
+ actions.setActiveContentTab(plainTextOnly ? 'plaintext' : 'visual')
}
},
@@ -531,6 +612,7 @@ export const emailTemplaterLogic = kea<emailTemplaterLogicType>([
// Load the design into the editor if it's ready and has a design
if (values.isEmailEditorReady && emailTemplateContent.design) {
+ cache.lastEditorDesign = emailTemplateContent.design
values.emailEditorRef?.editor?.loadDesign(emailTemplateContent.design)
}
},
diff --git a/nodejs/src/cdp/templates/_destinations/email/email.template.ts b/nodejs/src/cdp/templates/_destinations/email/email.template.ts
index 45e4d56dc4b8..666feed2cf7e 100644
--- a/nodejs/src/cdp/templates/_destinations/email/email.template.ts
+++ b/nodejs/src/cdp/templates/_destinations/email/email.template.ts
@@ -36,8 +36,8 @@ export const template: HogFunctionTemplate = {
bcc: '',
subject: '',
preheader: '',
- text: 'Hello from PostHog!',
- html: '<div>Hi {{ person.properties.name }}, this email was sent from PostHog!</div>',
+ text: '',
+ html: '',
},
secret: false,
description: 'The email message to send. Configure the recipient, sender, subject, and content.',
diff --git a/products/workflows/frontend/TemplateLibrary/MessageTemplate.tsx b/products/workflows/frontend/TemplateLibrary/MessageTemplate.tsx
index 196320e386a2..346d13ce4cf7 100644
--- a/products/workflows/frontend/TemplateLibrary/MessageTemplate.tsx
+++ b/products/workflows/frontend/TemplateLibrary/MessageTemplate.tsx
@@ -1,13 +1,12 @@
import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
-import { IconCode } from '@posthog/icons'
-import { LemonButton, LemonDivider, LemonInput, LemonTextArea, Spinner, Tooltip } from '@posthog/lemon-ui'
+import { LemonButton, LemonDivider, Spinner } from '@posthog/lemon-ui'
import { More } from 'lib/lemon-ui/LemonButton/More'
-import { LemonField } from 'lib/lemon-ui/LemonField'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
-import { EmailTemplater } from 'scenes/hog-functions/email-templater/EmailTemplater'
+import { EmailTemplater, TemplatePickerModal } from 'scenes/hog-functions/email-templater/EmailTemplater'
+import { emailTemplaterLogic } from 'scenes/hog-functions/email-templater/emailTemplaterLogic'
import { SceneExport } from 'scenes/sceneTypes'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
@@ -30,25 +29,88 @@ export const scene: SceneExport<MessageTemplateSceneLogicProps> = {
export function MessageTemplate(props: MessageTemplateSceneLogicProps): JSX.Element {
const sceneLogic = messageTemplateSceneLogic(props)
const logic = messageTemplateLogic(props)
- const { submitTemplate, resetTemplate, setTemplateValue, duplicateTemplate, deleteTemplate } = useActions(logic)
- const { template, originalTemplate, isTemplateSubmitting, templateChanged, messageLoading } = useValues(logic)
+ const {
+ submitTemplate,
+ resetTemplate,
+ setTemplateValue,
+ duplicateTemplate,
+ deleteTemplate,
+ setTemplatePickerOpen,
+ } = useActions(logic)
+ const {
+ template,
+ originalTemplate,
+ isTemplateSubmitting,
+ templateChanged,
+ messageLoading,
+ templateLoading,
+ templatePickerOpen,
+ } = useValues(logic)
+
+ const { setIsSaveTemplateModalOpen } = useActions(emailTemplaterLogic)
// Attach template logic to scene logic so it persists across tab switches
useAttachedLogic(logic, sceneLogic)
return (
- <Form logic={messageTemplateLogic} formKey="template" props={props}>
- <SceneContent>
+ <Form
+ logic={messageTemplateLogic}
+ formKey="template"
+ props={props}
+ {...{ className: 'flex flex-col grow h-full' }}
+ >
+ <SceneContent className="h-full flex flex-col grow">
<SceneTitleSection
name={template.name}
+ description={template.description}
resourceType={{ type: 'template' }}
+ canEdit
+ descriptionAlwaysVisible
+ isLoading={messageLoading || templateLoading}
+ onNameChange={(name) => setTemplateValue('name', name)}
+ onDescriptionChange={(description) => setTemplateValue('description', description)}
actions={
<>
- {props.id !== 'new' && (
- <>
- <More
- size="small"
- overlay={
+ <LemonDivider vertical />
+ {templateChanged && (
+ <LemonButton
+ data-attr="cancel-message-template"
+ type="secondary"
+ onClick={() => resetTemplate(originalTemplate)}
+ size="small"
+ >
+ Discard changes
+ </LemonButton>
+ )}
+ <LemonButton
+ type="primary"
+ htmlType="submit"
+ form="template"
+ onClick={submitTemplate}
+ loading={isTemplateSubmitting}
+ disabledReason={
+ !templateChanged
+ ? 'No changes to save'
+ : !template.name
+ ? 'Name is required'
+ : undefined
+ }
+ size="small"
+ >
+ {props.id === 'new' ? 'Create' : 'Save'}
+ </LemonButton>
+ <More
+ size="small"
+ overlay={
+ <>
+ <LemonButton
+ data-attr="save-as-new-template"
+ fullWidth
+ onClick={() => setIsSaveTemplateModalOpen(true)}
+ >
+ Save as new template
+ </LemonButton>
+ {props.id !== 'new' && (
<>
<LemonButton
data-attr="duplicate-message-template"
@@ -72,77 +134,30 @@ export function MessageTemplate(props: MessageTemplateSceneLogicProps): JSX.Elem
Delete
</LemonButton>
</>
- }
- />
- <LemonDivider vertical />
- </>
- )}
- {templateChanged && (
- <LemonButton
- data-attr="cancel-message-template"
- type="secondary"
- onClick={() => resetTemplate(originalTemplate)}
- size="small"
- >
- Discard changes
- </LemonButton>
- )}
- <LemonButton
- type="primary"
- htmlType="submit"
- form="template"
- onClick={submitTemplate}
- loading={isTemplateSubmitting}
- disabledReason={templateChanged ? undefined : 'No changes to save'}
- size="small"
- >
- {props.id === 'new' ? 'Create' : 'Save'}
- </LemonButton>
+ )}
+ </>
+ }
+ />
</>
}
/>
- <div className="flex flex-wrap gap-4 items-start">
- <div className="flex-1 self-start p-3 space-y-2 rounded border min-w-100 bg-surface-primary">
- <LemonField name="name" label="Name">
- <LemonInput disabled={messageLoading} />
- </LemonField>
-
- <LemonField
- name="description"
- label="Description"
- showOptional
- info="Add a description to share context with other team members"
- >
- <LemonTextArea disabled={messageLoading} />
- </LemonField>
- </div>
+ <TemplatePickerModal isOpen={templatePickerOpen} onClose={() => setTemplatePickerOpen(false)} />
- <div className="p-3 space-y-2 rounded border flex-2 min-w-100 bg-surface-primary">
- <div className="flex justify-between items-center">
- <h3>Email template</h3>
- <Tooltip
- title="You can use Liquid templating in any email text field."
- docLink="https://liquidjs.com/filters/overview.html"
- >
- <span>
- <IconCode fontSize={24} />
- </span>
- </Tooltip>
- </div>
- {messageLoading ? (
- <Spinner className="text-lg" />
- ) : (
- <EmailTemplater
- value={template?.content.email}
- onChange={(value) => setTemplateValue('content.email', value)}
- onChangeTemplating={(templating) =>
- setTemplateValue('content.email.templating', templating)
- }
- type="native_email_template"
- />
- )}
- </div>
+ <div className="flex flex-col flex-1 gap-2 min-h-0 relative">
+ {messageLoading || templateLoading ? (
+ <Spinner className="text-lg" />
+ ) : (
+ <EmailTemplater
+ value={template?.content.email}
+ onChange={(value) => setTemplateValue('content.email', value)}
+ onChangeTemplating={(templating) =>
+ setTemplateValue('content.email.templating', templating)
+ }
+ type="native_email_template"
+ layout="inline"
+ />
+ )}
</div>
</SceneContent>
</Form>
diff --git a/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.test.ts b/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.test.ts
index a1b195ac7568..46827063b8b9 100644
--- a/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.test.ts
+++ b/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.test.ts
@@ -1,44 +1,123 @@
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { messageTemplateLogic } from './messageTemplateLogic'
-describe('messageTemplateLogic unsaved-changes guard', () => {
+jest.mock('lib/lemon-ui/LemonToast', () => ({
+ lemonToast: {
+ success: jest.fn(),
+ error: jest.fn(),
+ },
+}))
+
+const mockToast = require('lib/lemon-ui/LemonToast').lemonToast
+
+describe('messageTemplateLogic', () => {
let logic: ReturnType<typeof messageTemplateLogic.build>
- let confirmSpy: jest.SpyInstance
beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/environments/:team_id/messaging_templates/:id/': { id: 'existing-id', name: 'Existing' },
+ '/api/environments/:team_id/hog_functions/:id/': { id: 'message-id', name: 'Sent message' },
+ },
+ })
initKeaTests()
- // window.confirm is the boundary kea-router calls to block in-app navigation.
- confirmSpy = jest.spyOn(window, 'confirm').mockReturnValue(true)
- logic = messageTemplateLogic({ id: 'new' })
- logic.mount()
})
afterEach(() => {
- logic.unmount()
- confirmSpy.mockRestore()
+ logic?.unmount()
})
- it.each([
- { description: 'blocks navigation away from an unsaved new template', changed: true, expectedCalls: 1 },
- {
- description: 'does not block navigation when there are no unsaved changes',
- changed: false,
- expectedCalls: 0,
- },
- ])('$description', async ({ changed, expectedCalls }) => {
- if (changed) {
- logic.actions.setTemplateValue('name', 'My one-hour template')
- await expectLogic(logic).toMatchValues({ templateChanged: true })
- } else {
- await expectLogic(logic).toMatchValues({ templateChanged: false })
- }
-
- router.actions.push('/workflows/library')
-
- expect(confirmSpy).toHaveBeenCalledTimes(expectedCalls)
+ describe('unsaved-changes guard', () => {
+ let confirmSpy: jest.SpyInstance
+
+ beforeEach(() => {
+ // window.confirm is the boundary kea-router calls to block in-app navigation.
+ confirmSpy = jest.spyOn(window, 'confirm').mockReturnValue(true)
+ logic = messageTemplateLogic({ id: 'new' })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ confirmSpy.mockRestore()
+ })
+
+ it.each([
+ { description: 'blocks navigation away from an unsaved new template', changed: true, expectedCalls: 1 },
+ {
+ description: 'does not block navigation when there are no unsaved changes',
+ changed: false,
+ expectedCalls: 0,
+ },
+ ])('$description', async ({ changed, expectedCalls }) => {
+ if (changed) {
+ logic.actions.setTemplateValue('name', 'My one-hour template')
+ await expectLogic(logic).toMatchValues({ templateChanged: true })
+ } else {
+ await expectLogic(logic).toMatchValues({ templateChanged: false })
+ }
+
+ router.actions.push('/workflows/library')
+
+ expect(confirmSpy).toHaveBeenCalledTimes(expectedCalls)
+ })
+ })
+
+ describe('submit validation feedback', () => {
+ beforeEach(() => {
+ jest.clearAllMocks()
+ })
+
+ it.each([
+ {
+ missing: 'name',
+ prefill: { key: 'content.email.subject', value: 'Welcome' },
+ toast: 'Name is required',
+ },
+ {
+ missing: 'subject',
+ prefill: { key: 'name', value: 'Welcome email' },
+ toast: 'Subject is required',
+ },
+ ])('toasts when the $missing is missing', async ({ prefill, toast }) => {
+ logic = messageTemplateLogic({ id: 'new' })
+ logic.mount()
+
+ logic.actions.setTemplateValue(prefill.key, prefill.value)
+ await expectLogic(logic, () => {
+ logic.actions.submitTemplate()
+ }).toDispatchActions(['submitTemplateFailure'])
+
+ expect(mockToast.error).toHaveBeenCalledWith(toast)
+ })
+ })
+
+ describe('starting-point picker', () => {
+ it.each([
+ {
+ description: 'opens for a brand-new template',
+ props: { id: 'new' },
+ expectedOpen: true,
+ },
+ {
+ description: 'does not open when creating from a sent message',
+ props: { id: 'new', messageId: 'message-id' },
+ expectedOpen: false,
+ },
+ {
+ description: 'does not open for an existing template',
+ props: { id: 'existing-id' },
+ expectedOpen: false,
+ },
+ ])('$description', async ({ props, expectedOpen }) => {
+ logic = messageTemplateLogic(props)
+ logic.mount()
+
+ await expectLogic(logic).toMatchValues({ templatePickerOpen: expectedOpen })
+ })
})
})
diff --git a/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.ts b/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.ts
index 5d8403acf175..a4a741fa7f8a 100644
--- a/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.ts
+++ b/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.ts
@@ -51,6 +51,7 @@ export interface messageTemplateLogicValues {
templateHasErrors: boolean
templateLoading: boolean
templateManualErrors: Record<string, any>
+ templatePickerOpen: boolean
templateTouched: boolean
templateTouches: Record<string, boolean>
templateValidationErrors: DeepPartialMap<
@@ -157,6 +158,9 @@ export interface messageTemplateLogicActions {
setTemplateManualErrors: (errors: Record<string, any>) => {
errors: Record<string, any>
}
+ setTemplatePickerOpen: (open: boolean) => {
+ open: boolean
+ }
setTemplateValue: (
key: FieldName,
value: any
@@ -283,6 +287,7 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([
setOriginalTemplate: (template: MessageTemplate) => ({ template }),
duplicateTemplate: true,
deleteTemplate: true,
+ setTemplatePickerOpen: (open: boolean) => ({ open }),
}),
selectors({
logicProps: [
@@ -324,6 +329,12 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([
},
},
],
+ templatePickerOpen: [
+ false,
+ {
+ setTemplatePickerOpen: (_, { open }) => open,
+ },
+ ],
}),
loaders(({ props }) => ({
template: {
@@ -355,7 +366,9 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([
listeners(({ actions, values }) => ({
submitTemplateFailure: () => {
const errors = values.templateAllErrors
- if (errors?.content?.email?.subject) {
+ if (errors?.name) {
+ lemonToast.error('Name is required')
+ } else if (errors?.content?.email?.subject) {
lemonToast.error('Subject is required')
}
},
@@ -427,6 +440,11 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([
// If we've previously loaded a message, reset the template to the default
actions.resetTemplate(NEW_TEMPLATE)
}
+
+ // A fresh template starts from the picker: blank, or one of the existing templates.
+ if (props.id === 'new' && !props.messageId) {
+ actions.setTemplatePickerOpen(true)
+ }
}),
beforeUnload(({ values, actions }) => ({
// Guards both new and existing templates - a brand-new template only exists in form