Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Added a record picker and click-to-insert variables to the email template editor

Damian Legawiecd37252d359e1
diff --git a/packages/dashboard-core/src/lib/formatters.ts b/packages/dashboard-core/src/lib/formatters.ts
index 96ea14495e..03b924129a 100644
--- a/packages/dashboard-core/src/lib/formatters.ts
+++ b/packages/dashboard-core/src/lib/formatters.ts
@@ -11,6 +11,10 @@ export function formatStoreDateTime(iso: string, timezone: string) {
return formatInTimeZone(parseISO(iso), timezone, 'PPP p')
}
+export function formatStoreDate(iso: string, timezone: string) {
+ return formatInTimeZone(parseISO(iso), timezone, 'PP')
+}
+
export function getInitials(fullName: string | null | undefined, fallback: string): string {
const parts = (fullName ?? '').trim().split(/\s+/).filter(Boolean)
if (parts.length === 0) return fallback.charAt(0)
diff --git a/packages/dashboard-ui/src/ui/code-editor.tsx b/packages/dashboard-ui/src/ui/code-editor.tsx
index d8d3925a0d..8a411dcbdd 100644
--- a/packages/dashboard-ui/src/ui/code-editor.tsx
+++ b/packages/dashboard-ui/src/ui/code-editor.tsx
@@ -25,7 +25,7 @@ import {
keymap,
lineNumbers,
} from '@codemirror/view'
-import { useEffect, useRef } from 'react'
+import { type Ref, useEffect, useImperativeHandle, useRef } from 'react'
import { cn } from '../lib/utils'
export interface CodeEditorCompletion {
@@ -43,7 +43,13 @@ export interface CodeEditorDiagnostic {
message: string
}
+export interface CodeEditorHandle {
+ /** Replaces the selection with `text`, leaves the cursor after it and focuses the editor. */
+ insert: (text: string) => void
+}
+
export interface CodeEditorProps {
+ ref?: Ref<CodeEditorHandle>
value: string
onChange?: (value: string) => void
/** Variables offered after `{{` and their fields after a dot. */
@@ -111,10 +117,24 @@ function CodeEditor({
readOnly = false,
onSave,
className,
+ ref,
...props
}: CodeEditorProps) {
const containerRef = useRef<HTMLDivElement>(null)
const viewRef = useRef<EditorView | null>(null)
+
+ useImperativeHandle(
+ ref,
+ () => ({
+ insert: (text) => {
+ const view = viewRef.current
+ if (!view || view.state.readOnly) return
+ view.dispatch(view.state.replaceSelection(text), { scrollIntoView: true })
+ view.focus()
+ },
+ }),
+ [],
+ )
const languageCompartment = useRef(new Compartment())
const readOnlyCompartment = useRef(new Compartment())
const callbacks = useRef({ onChange, onSave })
diff --git a/packages/dashboard/src/components/spree/email-templates/email-preview-frame.tsx b/packages/dashboard/src/components/spree/email-templates/email-preview-frame.tsx
index 7e65241f57..f80daf0b9a 100644
--- a/packages/dashboard/src/components/spree/email-templates/email-preview-frame.tsx
+++ b/packages/dashboard/src/components/spree/email-templates/email-preview-frame.tsx
@@ -1,4 +1,5 @@
import { cn } from '@spree/dashboard-ui'
+import { useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next'
export type EmailPreviewWidth = 'desktop' | 'mobile'
@@ -6,6 +7,10 @@ export type EmailPreviewWidth = 'desktop' | 'mobile'
/**
* A rendered email in a sandboxed frame: no scripts, no navigation, nothing
* the email's markup can reach in the dashboard.
+ *
+ * Each render gets a new frame. Changing a loaded frame's document adds an
+ * entry to the page's history, so with live previews the browser's Back went
+ * through every past render before leaving the page.
*/
export function EmailPreviewFrame({
html,
@@ -21,6 +26,9 @@ export function EmailPreviewFrame({
className?: string
}) {
const { t } = useTranslation()
+ const renders = useRef(0)
+ // biome-ignore lint/correctness/useExhaustiveDependencies: a new key for every new document
+ const frameKey = useMemo(() => ++renders.current, [html])
if (view === 'text') {
return (
@@ -43,6 +51,7 @@ export function EmailPreviewFrame({
)}
>
<iframe
+ key={frameKey}
title={t('admin.email_templates.preview.frame_title')}
sandbox=""
srcDoc={html ?? ''}
diff --git a/packages/dashboard/src/components/spree/email-templates/preview-card.tsx b/packages/dashboard/src/components/spree/email-templates/preview-card.tsx
index 90d09dcce5..2cdfed3ab1 100644
--- a/packages/dashboard/src/components/spree/email-templates/preview-card.tsx
+++ b/packages/dashboard/src/components/spree/email-templates/preview-card.tsx
@@ -1,4 +1,5 @@
import type { EmailTemplate, EmailTemplatePreview } from '@spree/admin-sdk'
+import { formatStoreDate, useStore } from '@spree/dashboard-core'
import {
Button,
Card,
@@ -8,7 +9,6 @@ import {
CardTitle,
Field,
FieldLabel,
- Input,
Select,
SelectContent,
SelectItem,
@@ -27,6 +27,7 @@ import {
type EmailTemplateProblem,
templateProblems,
useEmailTemplatePreview,
+ useEmailTemplateSampleRecords,
useEmailTemplates,
} from '../../../hooks/use-email-templates'
import { emailTemplateName } from '../../../lib/email-template-name'
@@ -50,6 +51,8 @@ export interface LivePreview {
setRecordId: (value: string) => void
emailKey: string
setEmailKey: (value: string) => void
+ /** Whether previews are rendered for this caller. */
+ enabled: boolean
}
/**
@@ -123,6 +126,7 @@ export function useLivePreview(
setRecordId,
emailKey,
setEmailKey,
+ enabled,
}
}
@@ -172,17 +176,7 @@ export function EmailTemplatePreviewCard({
<CardContent className="flex flex-col gap-3">
<div className="grid gap-3 sm:grid-cols-2">
{template.kind !== 'email' && <ShownInField preview={preview} />}
- <Field>
- <FieldLabel htmlFor="email-template-preview-record">
- {t('admin.email_templates.preview.record')}
- </FieldLabel>
- <Input
- id="email-template-preview-record"
- placeholder={t('admin.email_templates.preview.record_placeholder')}
- value={preview.recordId}
- onChange={(event) => preview.setRecordId(event.target.value.trim())}
- />
- </Field>
+ <RecordField template={template} preview={preview} />
</div>
{preview.unavailable ? (
<p className="rounded-md border border-border p-4 text-sm text-muted-foreground">
@@ -218,7 +212,10 @@ function ShownInField({ preview }: { preview: LivePreview }) {
<Select
items={emailOptions}
value={preview.emailKey || preview.data?.email_key || ''}
- onValueChange={(value) => preview.setEmailKey((value as string) ?? '')}
+ onValueChange={(value) => {
+ preview.setEmailKey((value as string) ?? '')
+ preview.setRecordId('')
+ }}
>
<SelectTrigger id="email-template-preview-email">
<SelectValue />
@@ -234,3 +231,50 @@ function ShownInField({ preview }: { preview: LivePreview }) {
</Field>
)
}
+
+const LATEST = ''
+
+/** Which of the store's latest records the preview is built from. */
+function RecordField({ template, preview }: { template: EmailTemplate; preview: LivePreview }) {
+ const { t } = useTranslation()
+ const { timezone } = useStore()
+ const { data: records } = useEmailTemplateSampleRecords(
+ template.id,
+ preview.emailKey,
+ preview.enabled,
+ )
+
+ if (!records?.length) return null
+
+ const options = [
+ { value: LATEST, label: t('admin.email_templates.preview.latest_record') },
+ ...records.map((record) => ({
+ value: record.id,
+ label: `${record.label} · ${formatStoreDate(record.created_at, timezone)}`,
+ })),
+ ]
+
+ return (
+ <Field>
+ <FieldLabel htmlFor="email-template-preview-record">
+ {t('admin.email_templates.preview.record')}
+ </FieldLabel>
+ <Select
+ items={options}
+ value={preview.recordId}
+ onValueChange={(value) => preview.setRecordId((value as string) ?? LATEST)}
+ >
+ <SelectTrigger id="email-template-preview-record">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((option) => (
+ <SelectItem key={option.value || 'latest'} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/email-templates/variables-card.tsx b/packages/dashboard/src/components/spree/email-templates/variables-card.tsx
index bba49d3b5c..ca8df071d0 100644
--- a/packages/dashboard/src/components/spree/email-templates/variables-card.tsx
+++ b/packages/dashboard/src/components/spree/email-templates/variables-card.tsx
@@ -3,7 +3,14 @@ import { useTranslation } from 'react-i18next'
import { templateVariables } from '../../../lib/email-template-variables'
/** The variables a template receives, with the fields worth pointing out. */
-export function EmailTemplateVariablesCard({ templateId }: { templateId: string }) {
+export function EmailTemplateVariablesCard({
+ templateId,
+ onInsert,
+}: {
+ templateId: string
+ /** Inserts a variable into the template; chips are plain text without it. */
+ onInsert?: (text: string) => void
+}) {
const { t } = useTranslation()
return (
@@ -20,11 +27,24 @@ export function EmailTemplateVariablesCard({ templateId }: { templateId: string
<dd className="text-sm text-muted-foreground">{t(variable.descriptionKey)}</dd>
{variable.fields && (
<dd className="flex flex-wrap gap-1">
- {variable.fields.map((field) => (
- <code key={field} className="rounded bg-muted px-1.5 py-0.5 text-xs">
- {`${variable.name}.${field}`}
- </code>
- ))}
+ {variable.fields.map((field) => {
+ const path = `${variable.name}.${field}`
+ return onInsert ? (
+ <button
+ key={field}
+ type="button"
+ aria-label={t('admin.email_templates.variables.insert', { variable: path })}
+ onClick={() => onInsert(`{{ ${path} }}`)}
+ className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs hover:bg-accent-strong focus-visible:outline-2 focus-visible:outline-ring"
+ >
+ {path}
+ </button>
+ ) : (
+ <code key={field} className="rounded bg-muted px-1.5 py-0.5 text-xs">
+ {path}
+ </code>
+ )
+ })}
</dd>
)}
</div>
diff --git a/packages/dashboard/src/hooks/use-email-templates.ts b/packages/dashboard/src/hooks/use-email-templates.ts
index d53c0d5278..b762068d18 100644
--- a/packages/dashboard/src/hooks/use-email-templates.ts
+++ b/packages/dashboard/src/hooks/use-email-templates.ts
@@ -113,6 +113,29 @@ export function useSendTestEmail(id: string) {
})
}
+/**
+ * The store's latest records a template can be previewed with. Empty for an
+ * email that needs none; a caller who may not read them gets none either.
+ */
+export function useEmailTemplateSampleRecords(id: string, emailKey: string, enabled: boolean) {
+ return useQuery({
+ queryKey: useResourceKey(RESOURCE, id, 'sample-records', emailKey),
+ queryFn: async () => {
+ try {
+ return (
+ await adminClient.emailTemplates.sampleRecords.list(id, {
+ email_key: emailKey || undefined,
+ })
+ ).data
+ } catch (error) {
+ if (error instanceof SpreeError && error.status === 403) return []
+ throw error
+ }
+ },
+ enabled,
+ })
+}
+
/** Renders a template, or unsaved changes to it, with sample data. Never cached. */
export function useEmailTemplatePreview(id: string) {
return useMutation<EmailTemplatePreview, Error, EmailTemplatePreviewParams>({
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 03162aa6f0..f5821e6ee9 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -6239,9 +6239,9 @@
"mobile": "عرض الهاتف",
"shown_in": "عرض داخل",
"record": "معاينة باستخدام سجل",
- "record_placeholder": "الأحدث، أو معرّف مثل or_m3Rp9wXz",
"unavailable": "تعذر عرض المعاينة.",
- "needs_permission": "تُعرض المعاينات لمن يملك صلاحية تعديل قوالب الرسائل."
+ "needs_permission": "تُعرض المعاينات لمن يملك صلاحية تعديل قوالب الرسائل.",
+ "latest_record": "الأحدث"
},
"problems": {
"title": "لا يمكن عرض هذا القالب",
@@ -6290,7 +6290,8 @@
"company": "الشركة التي دُعي إليها العميل.",
"accept_url": "الرابط الذي يقبل الدعوة.",
"store": "متجرك: الاسم والروابط والشعار والهوية البصرية.",
- "locale": "اللغة التي تُرسل بها الرسالة."
+ "locale": "اللغة التي تُرسل بها الرسالة.",
+ "insert": "إدراج {{variable}}"
},
"messages": {
"draft_saved": "تم حفظ المسودة",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 0cff4d336c..2dd5ccfcc2 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -6199,9 +6199,9 @@
"mobile": "Mobile Breite",
"shown_in": "Anzeigen in",
"record": "Vorschau mit Datensatz",
- "record_placeholder": "Neuester oder eine ID wie or_m3Rp9wXz",
"unavailable": "Die Vorschau konnte nicht angezeigt werden.",
- "needs_permission": "Vorschauen werden für Personen erstellt, die E-Mail-Vorlagen bearbeiten dürfen."
+ "needs_permission": "Vorschauen werden für Personen erstellt, die E-Mail-Vorlagen bearbeiten dürfen.",
+ "latest_record": "Neuester"
},
"problems": {
"title": "Diese Vorlage lässt sich nicht darstellen",
@@ -6250,7 +6250,8 @@
"company": "Die Firma, zu der der Kunde eingeladen ist.",
"accept_url": "Der Link, der die Einladung annimmt.",
"store": "Ihr Shop: Name, Links, Logo und Branding.",
- "locale": "Die Sprache, in der die E-Mail gesendet wird."
+ "locale": "Die Sprache, in der die E-Mail gesendet wird.",
+ "insert": "{{variable}} einfügen"
},
"messages": {
"draft_saved": "Entwurf gespeichert",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 1f6ae8750e..56d44a93c6 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -6199,9 +6199,9 @@
"mobile": "Mobile width",
"shown_in": "Show inside",
"record": "Preview with record",
- "record_placeholder": "Latest, or an ID such as or_m3Rp9wXz",
"unavailable": "The preview could not be shown.",
- "needs_permission": "Previews are rendered for people who can edit email templates."
+ "needs_permission": "Previews are rendered for people who can edit email templates.",
+ "latest_record": "Latest"
},
"problems": {
"title": "This template does not render",
@@ -6250,7 +6250,8 @@
"company": "The company the customer is invited to.",
"accept_url": "The link that accepts the invitation.",
"store": "Your store: name, links, logo and branding.",
- "locale": "The language the email is sent in."
+ "locale": "The language the email is sent in.",
+ "insert": "Insert {{variable}}"
},
"messages": {
"draft_saved": "Draft saved",
diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.json
index bb48397dc6..37ce3b3af9 100644
--- a/packages/dashboard/src/locales/es.json
+++ b/packages/dashboard/src/locales/es.json
@@ -6199,9 +6199,9 @@
"mobile": "Ancho móvil",
"shown_in": "Mostrar dentro de",
"record": "Vista previa con registro",
- "record_placeholder": "El más reciente o un ID como or_m3Rp9wXz",
"unavailable": "No se pudo mostrar la vista previa.",
- "needs_permission": "Las vistas previas se generan para quienes pueden editar plantillas de correo."
+ "needs_permission": "Las vistas previas se generan para quienes pueden editar plantillas de correo.",
+ "latest_record": "El más reciente"
},
"problems": {
"title": "Esta plantilla no se puede mostrar",
@@ -6250,7 +6250,8 @@
"company": "La empresa a la que se invita al cliente.",
"accept_url": "El enlace que acepta la invitación.",
"store": "Tu tienda: nombre, enlaces, logotipo y marca.",
- "locale": "El idioma en que se envía el correo."
+ "locale": "El idioma en que se envía el correo.",
+ "insert": "Insertar {{variable}}"
},
"messages": {
"draft_saved": "Borrador guardado",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index d84d96e3d1..aeea710f2a 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -6199,9 +6199,9 @@
"mobile": "Largeur mobile",
"shown_in": "Afficher dans",
"record": "Aperçu avec l'enregistrement",
- "record_placeholder": "Le plus récent, ou un ID comme or_m3Rp9wXz",
"unavailable": "L'aperçu n'a pas pu être affiché.",
- "needs_permission": "Les aperçus sont générés pour les personnes autorisées à modifier les modèles d'e-mail."
+ "needs_permission": "Les aperçus sont générés pour les personnes autorisées à modifier les modèles d'e-mail.",
+ "latest_record": "Le plus récent"
},
"problems": {
"title": "Ce modèle ne s'affiche pas",
@@ -6250,7 +6250,8 @@
"company": "L'entreprise à laquelle le client est invité.",
"accept_url": "Le lien qui accepte l'invitation.",
"store": "Votre boutique : nom, liens, logo et image de marque.",
- "locale": "La langue dans laquelle l'e-mail est envoyé."
+ "locale": "La langue dans laquelle l'e-mail est envoyé.",
+ "insert": "Insérer {{variable}}"
},
"messages": {
"draft_saved": "Brouillon enregistré",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 764cc734a7..894ba3c633 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -6267,9 +6267,9 @@
"mobile": "Szerokość telefonu",
"shown_in": "Pokaż w",
"record": "Podgląd z rekordem",
- "record_placeholder": "Najnowszy lub ID, np. or_m3Rp9wXz",
"unavailable": "Nie udało się wyświetlić podglądu.",
- "needs_permission": "Podgląd jest generowany dla osób, które mogą edytować szablony e-maili."
+ "needs_permission": "Podgląd jest generowany dla osób, które mogą edytować szablony e-maili.",
+ "latest_record": "Najnowszy"
},
"problems": {
"title": "Tego szablonu nie da się wyświetlić",
@@ -6318,7 +6318,8 @@
"company": "Firma, do której zaproszono klienta.",
"accept_url": "Link przyjmujący zaproszenie.",
"store": "Twój sklep: nazwa, linki, logo i wygląd marki.",
- "locale": "Język, w którym wysyłany jest e-mail."
+ "locale": "Język, w którym wysyłany jest e-mail.",
+ "insert": "Wstaw {{variable}}"
},
"messages": {
"draft_saved": "Szkic zapisany",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index bf52b168fd..f05bdbf871 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -6186,9 +6186,9 @@
"mobile": "手机宽度",
"shown_in": "显示于",
"record": "使用记录预览",
- "record_placeholder": "最新记录,或如 or_m3Rp9wXz 的 ID",
"unavailable": "无法显示预览。",
- "needs_permission": "只有可以编辑邮件模板的人才能生成预览。"
+ "needs_permission": "只有可以编辑邮件模板的人才能生成预览。",
+ "latest_record": "最新"
},
"problems": {
"title": "此模板无法渲染",
@@ -6237,7 +6237,8 @@
"company": "邀请客户加入的公司。",
"accept_url": "接受邀请的链接。",
"store": "您的店铺:名称、链接、标志和品牌样式。",
- "locale": "邮件发送所用的语言。"
+ "locale": "邮件发送所用的语言。",
+ "insert": "插入 {{variable}}"
},
"messages": {
"draft_saved": "草稿已保存",
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/emails/templates/$templateId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/emails/templates/$templateId.tsx
index d0904b2126..fe23c89233 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/emails/templates/$templateId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/emails/templates/$templateId.tsx
@@ -33,9 +33,13 @@ import {
useConfirm,
} from '@spree/dashboard-ui'
import { HistoryIcon, RotateCcwIcon, SendIcon, Trash2Icon } from '@spree/dashboard-ui/icons'
-import { CodeEditor, type CodeEditorCompletion } from '@spree/dashboard-ui/ui/code-editor'
+import {
+ CodeEditor,
+ type CodeEditorCompletion,
+ type CodeEditorHandle,
+} from '@spree/dashboard-ui/ui/code-editor'
import { createFileRoute, useBlocker } from '@tanstack/react-router'
-import { useCallback, useMemo, useState } from 'react'
+import { useCallback, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { EmailTemplateConflictDialog } from '../../../../../../components/spree/email-templates/conflict-dialog'
import { DefaultDiffDialog } from '../../../../../../components/spree/email-templates/default-diff-dialog'
@@ -149,6 +153,7 @@ function EmailTemplateEditor({
const confirm = useConfirm()
const { permissions } = usePermissions()
const canEdit = permissions.can('update', Subject.EmailTemplate)
+ const editorRef = useRef<CodeEditorHandle>(null)
const isEmail = template.kind === 'email'
const [saved, setSaved] = useState<Version>(() => startingVersion(template))
@@ -457,6 +462,7 @@ function EmailTemplateEditor({
</Field>
)}
<CodeEditor
+ ref={editorRef}
aria-label={t('admin.email_templates.editor.body')}
value={body}
onChange={editBody}
@@ -473,7 +479,10 @@ function EmailTemplateEditor({
<EmailTemplatePreviewCard template={template} preview={preview} />
</div>
- <EmailTemplateVariablesCard templateId={template.id} />
+ <EmailTemplateVariablesCard
+ templateId={template.id}
+ onInsert={canEdit ? (text) => editorRef.current?.insert(text) : undefined}
+ />
<EmailTemplateHistorySheet
open={historyOpen}