feat(engagement): the template editor, the trigger catalog and the send log (engagement Phase 5b)
All checks were successful
PR Checks / bot-tests (pull_request) Successful in 27s
PR Checks / client-build (pull_request) Successful in 31s
PR Checks / server-tests (pull_request) Successful in 2m38s

Phase 5a gave templates a table, a renderer and nine seeded rows; nothing could
change one. This is the screen that lets an operator change one without being able
to break the mail the system depends on — plus the two screens Q4 promised Phase 5:
Triggers (read-only, from the registries) and the Send Log, which closes G15.

The shape follows from one fact: a mail body is rendered by the SERVER, so the
preview is too, and framed rather than redrawn in React. A client-side renderer
would be a second implementation of the one artifact that matters, agreeing with
the send path on the day it was written and drifting from the first Outlook fix on.

Settled with the org lead before any code: a shipped default is edited IN PLACE
(`protected` blocks deletion and nothing else, `customized = 1` keeps the edit);
duplicate is the only way to a new template; `renderByKey` now requires
`published`; a test send is logged under a synthetic `core.admin.test-send`; and a
template a rule points at refuses deletion with a 409 naming the rules.

Three things the plan did not know, found by building it:

  - The undeclared-variable check cannot be a token scan. `email.itemList.variable`
    holds a BARE name, so a digest pointed at `itmes` would have saved clean and
    arrived empty. Blocks now declare `variables(props)`; the editor makes that
    field a select over the trigger's list variables so the typo is unavailable.
  - A duplicate that drops `seed_key` loses its variable palette, so duplicating
    `notify.event` would have been refused for the tokens it was copied with — the
    one action §4.6.2 offers, refusing itself. The copy inherits it; `customized`
    is what the seeder actually reads.
  - `validateEmailBlocks` returns `{ valid, errors }`, not an array, and the first
    version tested it with `.length` — so block validation never ran at all.

Also fixes a Phase 4a defect the live walk found, with the org lead's approval: a
rule's template key was checked against a pattern with no dot in it, so no rule
could name any template that exists — §4.6.2's whole duplicate-and-point-a-rule-at-it
workflow was unreachable. Both models now read one pattern.

Verified against the running stack: real multipart mail into a mailpit catcher
including an unsaved draft, the draft/published arms both ways through the real
mailer path, every refusal, and the end-to-end duplicate → rule → 409 walk.
Server 1428 tests green, client 324.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-08-29 18:13:57 -05:00
parent 42b40fdec2
commit 3f90070566
27 changed files with 3754 additions and 20 deletions

View File

@@ -0,0 +1,12 @@
// Client email-block registry entrypoint. Importing this module registers every
// `email.*` authoring definition exactly once, then re-exports the registry API.
// The template editor imports from HERE, never from ./registry, so the
// definitions are loaded before anything reads the palette.
//
// Same shape as `blocks/index.js` — and the same reason for existing.
export * from './registry'
export { VariablePalette } from './types.jsx'
// ── Definitions (self-register on import) ──────────────────────────────────
import './types.jsx'

View File

@@ -0,0 +1,100 @@
// ── The client-side `email.*` block registry ───────────────────────────────
//
// ENGAGEMENT.md §4.6.2, Phase 5b. A sibling of `blocks/registry.js` for the same
// reason its server counterpart is a sibling of `blocks/registry.js` on that side
// — and with ONE structural difference that is the whole argument for the shape of
// this screen:
//
// **an email block definition here has no `component`.**
//
// A page block carries a React renderer because a page IS React. A mail body is a
// string this deployment's server produces, and the preview shows exactly that
// string. Giving these entries a React renderer would mean two renderers for one
// artifact — one drawing the editor's preview, one producing what actually lands
// in someone's inbox — and nothing would make them agree. They would agree on the
// day they were written and drift from the first Outlook fix onward, at which
// point the preview becomes a confident lie about mail nobody can see.
//
// So the division is: **this registry owns authoring, the server owns rendering.**
// Everything here is about the editing experience — the palette entry, the prop
// form, the starting props — and the preview arrives from
// `POST /admin/engagement/templates/:id/preview` as HTML that goes into a
// sandboxed iframe.
//
// `type` and `version` must match the server definition in
// `server/src/emailBlocks/types/`. That pairing is the same discipline the page
// family already runs on, and the save is the thing that enforces it: the server
// validates against its own registry, so a client entry that has drifted produces
// a refused save rather than a bad row.
const registry = new Map()
// The same reserved envelope keys the server's `RESERVED_KEYS` names. Duplicated
// rather than imported because the client cannot import from `server/`, exactly as
// `blocks/registry.js` duplicates them — and, as there, the server is the one that
// decides: a block this list let through is still refused at the save.
export const RESERVED_KEYS = ['id', 'type', 'version', 'visible', 'props']
/**
* Register an email block definition.
*
* @param {object} def
* @param {string} def.type must match the server type, e.g. 'email.heading'
* @param {number} def.version must match the server schema version
* @param {string} def.label palette display name
* @param {string} def.icon palette icon glyph
* @param {Function} def.editor ({ props, onChange, variables }) => JSX
* @param {Function} def.defaults starting props when the block is added
*/
export function registerEmailBlock(def) {
if (!def || typeof def.type !== 'string' || !def.type.startsWith('email.')) {
throw new Error('registerEmailBlock: a definition needs a type namespaced "email."')
}
if (registry.has(def.type)) {
throw new Error(`registerEmailBlock: block type already registered: ${def.type}`)
}
const entry = {
type: def.type,
version: Number.isInteger(def.version) ? def.version : 1,
label: def.label || def.type,
icon: def.icon || null,
// The one-line description under the palette button. Mail blocks are less
// self-evident than page ones — "Item list" does not say that it repeats over
// a variable — and the palette is where that has to be said.
hint: def.hint || '',
editor: def.editor || null,
defaults: typeof def.defaults === 'function' ? def.defaults : () => ({}),
}
registry.set(entry.type, entry)
return entry
}
/** @returns {object|null} the definition for `type`, or null if unknown. */
export function getEmailBlock(type) {
return registry.get(type) || null
}
/** @returns {object[]} every definition, in registration order — the palette. */
export function listEmailBlocks() {
return [...registry.values()]
}
/**
* A fresh block envelope of `type`, ready to push onto the array.
*
* The id is random rather than sequential because block ids are unique across the
* whole document and an operator can delete block 2 and add another; a counter
* would hand out an id that is already taken and the save would be refused for a
* reason nothing on screen explains.
*/
export function newEmailBlock(type) {
const def = getEmailBlock(type)
if (!def) return null
return {
id: `b${Math.random().toString(36).slice(2, 10)}`,
type: def.type,
version: def.version,
visible: true,
props: def.defaults(),
}
}

View File

@@ -0,0 +1,272 @@
// The six `email.*` block editors, in one file rather than one file each.
//
// The page family gives every block its own module because each carries a React
// RENDERER as well as a form, and those are substantial. An email block carries
// only a form — the rendering is the server's (see ./registry.js) — and six short
// prop panels split across six files would be six imports of the same three
// controls to no benefit.
//
// Every `type` and `version` here pairs with a definition in
// `server/src/emailBlocks/types/`, and the field lists are the server's `onlyKeys`
// lists. Where a server schema has a bound (`MAX_TEXT`, `MAX_LABEL`), the input
// carries the same `maxLength` — not as the check, which is the server's, but so
// that an operator meets the limit while typing rather than at the save.
import { TextField, TextAreaField, SelectField, Field } from '../blocks/editorKit.jsx'
import { registerEmailBlock } from './registry'
/**
* The variable palette, rendered under whichever field is being edited.
*
* Clicking a variable APPENDS its token rather than inserting at the caret. That
* is a deliberate simplification: tracking a caret across a controlled React input
* that a parent may re-render costs a ref and a selection-restore on every change,
* and appending is both predictable and trivially undone. §4.6.2's requirement is
* that inserting a variable "writes a token; it is never free-text" — which this
* satisfies — not that it lands at the cursor.
*/
export function VariablePalette({ variables, onInsert }) {
if (!variables || !variables.length) return null
return (
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 6 }}>
{variables.map((v) => (
<button
key={v.name}
type="button"
className="btn btn-ghost btn-xs"
title={`${v.type || 'string'}${v.required ? ' · required' : ''}${v.description ? `${v.description}` : ''}`}
onClick={() => onInsert(`{{${v.name}}}`)}
style={{ fontFamily: 'monospace', fontSize: '0.72rem', padding: '2px 6px' }}
>
{v.name}
</button>
))}
</div>
)
}
/** A text field with the palette attached — the shape four of the six blocks want. */
function VariableTextField({ label, hint, value, onChange, variables, maxLength, area, rows }) {
const Control = area ? TextAreaField : TextField
return (
<div>
<Control
label={label}
hint={hint}
value={value}
onChange={onChange}
maxLength={maxLength}
rows={rows}
/>
<VariablePalette variables={variables} onInsert={(token) => onChange(`${value || ''}${token}`)} />
</div>
)
}
registerEmailBlock({
type: 'email.heading',
version: 1,
label: 'Heading',
icon: 'H',
hint: 'A section heading, at one of three sizes.',
defaults: () => ({ level: 'h2', text: 'Heading' }),
editor: ({ props, onChange, variables }) => (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<SelectField
label="Size"
// Named "Size" and not "Level" for the reason the server block's header
// gives: mail clients build no outline from a message, so this is
// typography rather than structure, and calling it a level in the UI would
// invite someone to use it as one.
hint="Mail clients build no document outline, so this is a size, not a rank."
value={props.level || 'h2'}
onChange={(level) => onChange({ ...props, level })}
options={[
['h1', 'Large'],
['h2', 'Medium'],
['h3', 'Small'],
]}
/>
<VariableTextField
label="Text"
value={props.text}
maxLength={200}
variables={variables}
onChange={(text) => onChange({ ...props, text })}
/>
</div>
),
})
registerEmailBlock({
type: 'email.text',
version: 1,
label: 'Paragraph',
icon: '¶',
hint: 'A paragraph of body text.',
defaults: () => ({ text: 'Write your message here.', muted: false }),
editor: ({ props, onChange, variables }) => (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<VariableTextField
label="Text"
area
rows={5}
value={props.text}
maxLength={4000}
variables={variables}
onChange={(text) => onChange({ ...props, text })}
/>
<Field label="Style">
<label className="sans" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<input
type="checkbox"
checked={Boolean(props.muted)}
onChange={(e) => onChange({ ...props, muted: e.target.checked })}
/>
<span>Quieter for footnotes and small print</span>
</label>
</Field>
</div>
),
})
registerEmailBlock({
type: 'email.button',
version: 1,
label: 'Button / link',
icon: '▭',
hint: 'The call to action. Its plain-text form is a sentence plus the URL.',
defaults: () => ({ label: 'Open', url: '/', textLead: 'Open it here:' }),
editor: ({ props, onChange, variables }) => (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<TextField
label="Button text"
value={props.label}
maxLength={80}
onChange={(label) => onChange({ ...props, label })}
/>
<VariableTextField
label="Link"
hint="Usually a variable, so the link is built for each recipient."
value={props.url}
maxLength={600}
variables={variables}
onChange={(url) => onChange({ ...props, url })}
/>
<TextField
label="Plain-text lead-in"
// The server block's header is worth repeating here in one line, because
// this field looks optional and is the difference between a bare URL and a
// sentence in every text-only inbox.
hint="A button is nothing in plain text. This sentence introduces the link there, e.g. “Choose a new password here:”."
value={props.textLead}
maxLength={200}
onChange={(textLead) => onChange({ ...props, textLead })}
/>
</div>
),
})
registerEmailBlock({
type: 'email.divider',
version: 1,
label: 'Divider',
icon: '—',
hint: 'A horizontal rule.',
defaults: () => ({}),
editor: () => (
<p className="sans dim" style={{ fontSize: '0.85rem' }}>
A divider has nothing to configure.
</p>
),
})
registerEmailBlock({
type: 'email.image',
version: 1,
label: 'Image',
icon: '▣',
hint: 'An image by URL. Many clients block images until the reader allows them.',
defaults: () => ({ url: '/brand/logo.png', alt: 'Logo' }),
editor: ({ props, onChange, variables }) => (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<VariableTextField
label="Image URL"
value={props.url}
maxLength={600}
variables={variables}
onChange={(url) => onChange({ ...props, url })}
/>
<TextField
label="Alt text"
hint="Most mail clients block images by default, so for many readers this IS the image."
value={props.alt}
maxLength={200}
onChange={(alt) => onChange({ ...props, alt })}
/>
<Field label="Width" hint="Pixels, 16-560. Leave blank to let the image size itself.">
<input
type="number"
className="input"
min={16}
max={560}
value={props.width ?? ''}
// Blank REMOVES the prop rather than setting it to 0. The server accepts
// `width` absent or between 16 and 560, so a 0 left behind by an empty
// field is a refused save whose message names a field the operator
// believes they cleared.
onChange={(e) => {
const next = { ...props }
const value = Number(e.target.value)
if (!e.target.value || !Number.isFinite(value)) delete next.width
else next.width = Math.trunc(value)
onChange(next)
}}
/>
</Field>
</div>
),
})
registerEmailBlock({
type: 'email.itemList',
version: 1,
label: 'Item list',
icon: '☰',
hint: 'Repeats over a list variable — this is how a digest lists its items.',
defaults: () => ({ variable: '', emptyText: '' }),
editor: ({ props, onChange, variables }) => {
// Only LIST variables may be chosen, and the field is a select rather than a
// text input because this prop is a bare NAME, not a token: a typo here is the
// one variable reference a reader of the template cannot see is wrong, and it
// renders as an empty mail rather than as a visible gap.
const lists = (variables || []).filter((v) => v.type === 'list' || v.type === 'array')
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{lists.length ? (
<SelectField
label="List variable"
hint="Each item becomes a row with its heading, excerpt and link."
value={props.variable || ''}
onChange={(variable) => onChange({ ...props, variable })}
options={[['', 'Choose a list…'], ...lists.map((v) => [v.name, v.name])]}
/>
) : (
<Field label="List variable">
<p className="sans dim" style={{ fontSize: '0.85rem', margin: 0 }}>
This templates trigger declares no list variable, so an item list has nothing to
repeat over. Point the template at a trigger that declares one a digest, typically
or use paragraphs instead.
</p>
</Field>
)}
<TextField
label="When the list is empty"
hint="Shown instead of the list. Leave blank to show nothing at all."
value={props.emptyText}
maxLength={200}
onChange={(emptyText) => onChange({ ...props, emptyText })}
/>
</div>
)
},
})