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): add search and tag filters to email template pickers (#124633)

Meikel Ratz8372fad9c94b
diff --git a/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx b/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx
index 870dac0a65a8..0d8638e7da28 100644
--- a/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx
+++ b/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx
@@ -24,6 +24,7 @@ import {
insertTemplateReference,
templateReferenceForOption,
} from 'lib/components/CyclotronJob/cyclotronJobTemplateSuggestionsLogic'
+import { TagSelect } from 'lib/components/TagSelect'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { LemonField } from 'lib/lemon-ui/LemonField'
@@ -37,6 +38,7 @@ import { urls } from 'scenes/urls'
import { sceneLayoutLogic } from '~/layout/scenes/sceneLayoutLogic'
import 'products/workflows/frontend/TemplateLibrary/MessageTemplatesGrid.scss'
+import { filterMessageTemplates } from 'products/workflows/frontend/TemplateLibrary/filterMessageTemplates'
import { MessageTemplateCard } from 'products/workflows/frontend/TemplateLibrary/MessageTemplateCard'
import { collapseToolsPanelCustomJs } from './custom-tools/collapseToolsPanel'
@@ -503,30 +505,73 @@ function LiquidSupportedText({
export function TemplatePickerModal({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }): JSX.Element {
const { templates } = useValues(emailTemplaterLogic)
const { applyTemplate } = useActions(emailTemplaterLogic)
+ const [search, setSearch] = useState('')
+ const [tags, setTags] = useState<string[]>([])
+ const filteredTemplates = filterMessageTemplates(templates, { search, tags })
+
+ const close = (): void => {
+ setSearch('')
+ setTags([])
+ onClose()
+ }
return (
- <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()
- }}
+ <LemonModal
+ isOpen={isOpen}
+ onClose={close}
+ title="Choose a starting point"
+ width={880}
+ description={
+ <div className="flex flex-wrap gap-2 items-center">
+ <LemonInput
+ type="search"
+ placeholder="Search templates"
+ value={search}
+ onChange={setSearch}
+ className="flex-1 min-w-48"
+ autoFocus
+ data-attr="template-picker-search"
+ />
+ {templates.some((template) => template.tags?.length) && (
+ <TagSelect
+ size="small"
+ defaultLabel="Any tags"
+ value={tags}
+ onChange={setTags}
+ listDataAttr="template-picker-tags-filter-list"
/>
- </div>
- ))}
+ )}
+ </div>
+ }
+ >
+ <div className="flex flex-col gap-3">
+ <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={close}
+ data-attr="template-picker-blank"
+ >
+ <IconPlus className="text-2xl" />
+ <span>Blank template</span>
+ </LemonCard>
+ {filteredTemplates.map((template, index) => (
+ <div key={template.id} className="w-48 h-56">
+ <MessageTemplateCard
+ template={template}
+ index={index}
+ onClick={() => {
+ applyTemplate(template)
+ close()
+ }}
+ />
+ </div>
+ ))}
+ </div>
+ {templates.length > 0 && filteredTemplates.length === 0 && (
+ <p className="text-secondary m-0" data-attr="template-picker-no-matches">
+ No templates match. Try another search or clear the tag filter.
+ </p>
+ )}
</div>
</LemonModal>
)
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 36b88fe6d841..93deb4bf268b 100644
--- a/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.test.ts
+++ b/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.test.ts
@@ -266,6 +266,39 @@ describe('emailTemplaterLogic', () => {
}),
})
})
+
+ it('applying a text-only template clears the previous html body and design', async () => {
+ const onChange = jest.fn()
+ logic = emailTemplaterLogic(
+ makeProps({
+ value: {
+ ...DEFAULT_EMAIL_TEMPLATE,
+ html: '<p>Hello from PostHog!</p>',
+ design: {} as EmailTemplate['design'],
+ },
+ onChange,
+ })
+ )
+ logic.mount()
+
+ logic.actions.applyTemplate({
+ id: 'template-2',
+ name: 'Plain receipt',
+ content: {
+ templating: 'liquid',
+ email: { subject: 'Your receipt', text: 'Thanks for your order.' },
+ },
+ } as MessageTemplate)
+
+ expect(onChange).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ subject: 'Your receipt',
+ text: 'Thanks for your order.',
+ html: '',
+ design: null,
+ })
+ )
+ })
})
describe('html-only emails', () => {
diff --git a/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx b/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx
index 16467bceb6b9..13b5c169c76f 100644
--- a/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx
+++ b/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx
@@ -803,7 +803,14 @@ export const emailTemplaterLogic = kea<emailTemplaterLogicType>([
// A transactional template's sender and reply-to belong to its own sends, so applying it keeps the
// email's current ones.
const { from: _from, replyTo: _replyTo, ...emailTemplateContent } = template.content.email
- actions.setEmailTemplateValues(emailTemplateContent)
+ // The values merge into the current email, so a body field the template omits is cleared to keep the
+ // previous email's html or design from being sent.
+ actions.setEmailTemplateValues({
+ ...emailTemplateContent,
+ html: emailTemplateContent.html ?? '',
+ text: emailTemplateContent.text ?? '',
+ design: emailTemplateContent.design ?? null,
+ })
// Load the design into the editor if it's ready and has a design
if (values.isEmailEditorReady && emailTemplateContent.design) {
diff --git a/products/workflows/frontend/TemplateLibrary/filterMessageTemplates.ts b/products/workflows/frontend/TemplateLibrary/filterMessageTemplates.ts
new file mode 100644
index 000000000000..85e56e3e7768
--- /dev/null
+++ b/products/workflows/frontend/TemplateLibrary/filterMessageTemplates.ts
@@ -0,0 +1,34 @@
+import { MessageTemplate } from './types'
+
+export interface MessageTemplateFilters {
+ search?: string
+ tags?: string[]
+ createdBy?: number | null
+ transactionalOnly?: boolean
+}
+
+export function filterMessageTemplates(
+ templates: MessageTemplate[],
+ { search, tags, createdBy, transactionalOnly }: MessageTemplateFilters
+): MessageTemplate[] {
+ let filtered = templates
+ if (search) {
+ const lowerSearch = search.toLowerCase()
+ filtered = filtered.filter(
+ (t) =>
+ (t.name ?? '').toLowerCase().includes(lowerSearch) ||
+ (t.description ?? '').toLowerCase().includes(lowerSearch) ||
+ (t.tags ?? []).some((tag) => tag.toLowerCase().includes(lowerSearch))
+ )
+ }
+ if (tags?.length) {
+ filtered = filtered.filter((t) => (t.tags ?? []).some((tag) => tags.includes(tag)))
+ }
+ if (createdBy != null) {
+ filtered = filtered.filter((t) => t.created_by?.id === createdBy)
+ }
+ if (transactionalOnly) {
+ filtered = filtered.filter((t) => !!t.transactional_hog_flow_id)
+ }
+ return filtered
+}
diff --git a/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.ts b/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.ts
index 2ae498c2cacb..f32d1d25a109 100644
--- a/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.ts
+++ b/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.ts
@@ -35,6 +35,7 @@ import type { IntegrationType } from '../../../../frontend/src/types'
import { workflowLogic } from '../Workflows/workflowLogic'
import { NEW_TEMPLATE } from './constants'
import { newTemplateAgentLogic } from './newTemplateAgentLogic'
+import { omitNullDesign } from './omitNullDesign'
import { TemplateSection, templateLibraryUrl, templateSectionFor, templateUrlInSection } from './templateSection'
import { MessageTemplate } from './types'
@@ -736,10 +737,13 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([
// Saving the content publishes it, and the server clears the draft. The sensitive setting
// and the tags each save on their own, so a publish never sends them and can't undo a
// change made in another tab since this one loaded the template.
- const { sensitive: _sensitive, tags: _tags, ...content } = template
+ const payload = template.content?.email
+ ? { ...template, content: { ...template.content, email: omitNullDesign(template.content.email) } }
+ : template
+ const { sensitive: _sensitive, tags: _tags, ...content } = payload
const saved =
template.id === 'new'
- ? await api.messaging.createTemplate(template)
+ ? await api.messaging.createTemplate(payload)
: await api.messaging.updateTemplate(template.id, content)
const { form, draft, published } = splitDraft(saved)
actions.setDraftState(draft, published)
diff --git a/products/workflows/frontend/TemplateLibrary/messageTemplatesLogic.ts b/products/workflows/frontend/TemplateLibrary/messageTemplatesLogic.ts
index ae6228b23ef7..e1d69eb29f7f 100644
--- a/products/workflows/frontend/TemplateLibrary/messageTemplatesLogic.ts
+++ b/products/workflows/frontend/TemplateLibrary/messageTemplatesLogic.ts
@@ -8,6 +8,7 @@ import { teamLogic } from 'scenes/teamLogic'
import { tagsModel } from '~/models/tagsModel'
+import { filterMessageTemplates } from './filterMessageTemplates'
import { MessageTemplate } from './types'
export type { MessageTemplate }
@@ -267,28 +268,13 @@ export const messageTemplatesLogic = kea<messageTemplatesLogicType>([
createdByFilter: number | null,
transactionalOnly: boolean,
tagsFilter: string[]
- ): MessageTemplate[] => {
- let filtered = templates
- if (search) {
- const lowerSearch = search.toLowerCase()
- filtered = filtered.filter(
- (t) =>
- (t.name ?? '').toLowerCase().includes(lowerSearch) ||
- (t.description ?? '').toLowerCase().includes(lowerSearch) ||
- (t.tags ?? []).some((tag) => tag.toLowerCase().includes(lowerSearch))
- )
- }
- if (tagsFilter.length) {
- filtered = filtered.filter((t) => (t.tags ?? []).some((tag) => tagsFilter.includes(tag)))
- }
- if (createdByFilter !== null) {
- filtered = filtered.filter((t) => t.created_by?.id === createdByFilter)
- }
- if (transactionalOnly) {
- filtered = filtered.filter((t) => !!t.transactional_hog_flow_id)
- }
- return filtered
- },
+ ): MessageTemplate[] =>
+ filterMessageTemplates(templates, {
+ search,
+ tags: tagsFilter,
+ createdBy: createdByFilter,
+ transactionalOnly,
+ }),
],
}),
afterMount(({ actions }) => {
diff --git a/products/workflows/frontend/TemplateLibrary/omitNullDesign.ts b/products/workflows/frontend/TemplateLibrary/omitNullDesign.ts
new file mode 100644
index 000000000000..54206f9a84ce
--- /dev/null
+++ b/products/workflows/frontend/TemplateLibrary/omitNullDesign.ts
@@ -0,0 +1,10 @@
+import type { EmailTemplate } from 'scenes/hog-functions/email-templater/types'
+
+/** The template API rejects a null design, which applying a text-only template leaves in the email. */
+export function omitNullDesign(email: EmailTemplate): EmailTemplate {
+ if (email.design != null) {
+ return email
+ }
+ const { design: _design, ...emailWithoutDesign } = email
+ return emailWithoutDesign as EmailTemplate
+}
diff --git a/products/workflows/frontend/Transactional/wizard/steps/ContentStep.tsx b/products/workflows/frontend/Transactional/wizard/steps/ContentStep.tsx
index 37d5ac0909bb..922f4292d957 100644
--- a/products/workflows/frontend/Transactional/wizard/steps/ContentStep.tsx
+++ b/products/workflows/frontend/Transactional/wizard/steps/ContentStep.tsx
@@ -4,7 +4,7 @@ import { useState } from 'react'
import { IconPlus } from '@posthog/icons'
import { LemonButton, LemonInput, LemonTag } from '@posthog/lemon-ui'
-import { EmailTemplater } from 'scenes/hog-functions/email-templater/EmailTemplater'
+import { EmailTemplater, TemplatePickerModal } from 'scenes/hog-functions/email-templater/EmailTemplater'
import { cleanVariableName } from '../emailVariables'
import { transactionalEmailWizardLogic } from '../transactionalEmailWizardLogic'
@@ -13,6 +13,7 @@ export function ContentStep(): JSX.Element {
const { draft, variables, panelVariables, editorGlobals } = useValues(transactionalEmailWizardLogic)
const { updateDraft, addVariable } = useActions(transactionalEmailWizardLogic)
const [newVariable, setNewVariable] = useState('')
+ const [templatePickerOpen, setTemplatePickerOpen] = useState(false)
const newVariableName = cleanVariableName(newVariable)
const submitNewVariable = (): void => {
if (newVariableName) {
@@ -23,7 +24,17 @@ export function ContentStep(): JSX.Element {
return (
<div className="flex flex-col @min-[64rem]/main-content:flex-row gap-4 min-h-[36rem]">
- <div className="flex flex-col flex-1 min-w-0">
+ <div className="flex flex-col flex-1 min-w-0 gap-2">
+ <div className="flex justify-end">
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={() => setTemplatePickerOpen(true)}
+ data-attr="transactional-email-wizard-template-picker"
+ >
+ Start from template
+ </LemonButton>
+ </div>
<EmailTemplater
value={draft.email}
onChange={(email) => updateDraft({ email })}
@@ -31,6 +42,8 @@ export function ContentStep(): JSX.Element {
variables={editorGlobals}
layout="inline"
/>
+ {/* The picker reads the unkeyed templater logic, so it renders after the editor to mount that logic with the editor's props. */}
+ <TemplatePickerModal isOpen={templatePickerOpen} onClose={() => setTemplatePickerOpen(false)} />
</div>
<div
className="flex flex-col gap-2 @min-[64rem]/main-content:w-64 shrink-0 border rounded p-3 self-start"
diff --git a/products/workflows/frontend/Transactional/wizard/transactionalEmailWizardLogic.test.ts b/products/workflows/frontend/Transactional/wizard/transactionalEmailWizardLogic.test.ts
index cf5d3bf9e3e1..7220e9d3afed 100644
--- a/products/workflows/frontend/Transactional/wizard/transactionalEmailWizardLogic.test.ts
+++ b/products/workflows/frontend/Transactional/wizard/transactionalEmailWizardLogic.test.ts
@@ -13,10 +13,14 @@ jest.mock('lib/lemon-ui/LemonToast', () => ({ lemonToast: { success: jest.fn(),
describe('transactionalEmailWizardLogic', () => {
let logic: ReturnType<typeof transactionalEmailWizardLogic.build>
let createTemplate: jest.Mock
+ let createTemplateBody: Record<string, any> | undefined
let makeTransactional: jest.Mock
beforeEach(() => {
- createTemplate = jest.fn(() => [201, { id: 'created-id' }])
+ createTemplate = jest.fn(async ({ request }) => {
+ createTemplateBody = await request.json()
+ return [201, { id: 'created-id' }]
+ })
makeTransactional = jest.fn(() => [200, { id: 'created-id', transactional_hog_flow_id: 'flow-id' }])
useMocks({
get: {
@@ -66,4 +70,21 @@ describe('transactionalEmailWizardLogic', () => {
expect(removeProjectIdIfPresent(router.values.location.pathname)).toEqual(expectedPath)
expect(logic.values.currentStep).toEqual(expectedStep)
})
+
+ it('leaves out the design that a text-only template clears, since the API rejects a null design', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.updateDraft({ name: 'Plain receipt' })
+ logic.actions.updateEmail({
+ from: { integrationId: 7 },
+ subject: 'Your receipt',
+ text: 'Thanks for your order.',
+ html: '',
+ design: null,
+ })
+
+ await expectLogic(logic, () => logic.actions.createTransactionalEmail()).toFinishAllListeners()
+
+ expect(createTemplateBody?.content.email).toEqual(expect.objectContaining({ text: 'Thanks for your order.' }))
+ expect(createTemplateBody?.content.email).not.toHaveProperty('design')
+ })
})
diff --git a/products/workflows/frontend/Transactional/wizard/transactionalEmailWizardLogic.ts b/products/workflows/frontend/Transactional/wizard/transactionalEmailWizardLogic.ts
index d222c9e89dd9..14aa12b537ed 100644
--- a/products/workflows/frontend/Transactional/wizard/transactionalEmailWizardLogic.ts
+++ b/products/workflows/frontend/Transactional/wizard/transactionalEmailWizardLogic.ts
@@ -18,6 +18,7 @@ import {
import type { MessageTemplateContentApi } from 'products/messaging/frontend/generated/api.schemas'
import { NEW_TEMPLATE } from '../../TemplateLibrary/constants'
+import { omitNullDesign } from '../../TemplateLibrary/omitNullDesign'
import { cleanVariableName, transactionalEditorGlobals, variablesInEmail } from './emailVariables'
export type TransactionalEmailWizardStep = 'name' | 'sender' | 'content' | 'send'
@@ -258,7 +259,10 @@ export const transactionalEmailWizardLogic = kea<transactionalEmailWizardLogicTy
name: name.trim(),
description,
sensitive,
- content: { templating: 'liquid', email } as unknown as MessageTemplateContentApi,
+ content: {
+ templating: 'liquid',
+ email: omitNullDesign(email),
+ } as unknown as MessageTemplateContentApi,
})
templateId = template.id
} catch (error: any) {