Newsletter: every part editable and movable

A draft is one ordered list of parts (migration 060, newsletters.layout
as JSON), edited with the content block editor so any part can be
moved, copied or removed, each aligned left or center:
- header: words, a PNG/JPEG logo, band color or none
- title
- any email block; dividers take color, thickness and spacing
- picked items: events, posts or front page cards picked in order,
  with the heading, its underline, the card bar and the button label
- footer: its lines and the line above

Colors come from the palette or none. 057's fixed fields and blocks
are dropped; that migration never reached a live database.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-10-01 19:37:26 -05:00
parent 222c9e69a2
commit 3194fdbb7d
5 changed files with 561 additions and 397 deletions

View file

@ -1,17 +1,18 @@
/* ═══════════════════════════════════════════════════════════════
NEWSLETTER (Tools)
Builds an email newsletter from what's already on the site: tick
upcoming events, published blog posts and the front page's
featured cards, write a title, an intro, content blocks and a
footer, and copy the result, email-ready HTML or plain text, into
Mailchimp, Gmail or Church Center (or download it as a file).
Nothing is sent from here; the builder is src/lib/newsletter.ts.
Builds an email newsletter as one list of parts, each movable and
each with its own settings (PARTS_SPEC): the header band, the
title, content blocks, sections of picked upcoming events,
published blog posts or front page cards, and the footer. Copy
the result, email-ready HTML or plain text, into Mailchimp, Gmail
or Church Center (or download it as a file). Nothing is sent from
here; the builder is src/lib/newsletter.ts.
Drafts are saved (the newsletters entity, 057_newsletters.sql),
Drafts are saved (the newsletters entity, 060_newsletter_layout.sql),
to finish later or send again, and a draft can become an
unpublished blog post: its intro, blocks and picks as the post's
body, opened in the post's editor to finish.
unpublished blog post: its blocks and picks as the post's body,
opened in the post's editor to finish.
Picked blog posts are read from their public pages, so only a
post visitors can open makes it in, with its excerpt and cover.
@ -27,7 +28,7 @@ import { ApiError, del, get, patch, post } from '../../lib/api.ts'
import { useAuth } from '../../lib/auth.tsx'
import { canDelete, canWrite } from '../../lib/roles.ts'
import { slugify } from '../../lib/adminSchema.ts'
import { blocksChild } from '../../lib/adminSchema/shared.ts'
import { blocksChild, BLOCK_TYPES } from '../../lib/adminSchema/shared.ts'
import { Repeater } from '../../components/admin/fields.tsx'
import { useEvents } from '../../lib/eventData.ts'
import { useFrontPage, type FeaturedCard } from '../../lib/useFrontPage.ts'
@ -37,12 +38,16 @@ import { mediaUrl } from '../../lib/media.ts'
import { SITE_NAME, SITE_ORIGIN, siteUrl } from '../../lib/site.ts'
import { seriesLabel } from '../../lib/eventSeries.ts'
import { useWideAdminPage } from '../../lib/adminWidth.tsx'
import { PALETTE } from '../../lib/color.ts'
import {
DEFAULT_TITLE,
newsletterHtml,
newsletterText,
type NewsletterBlock,
newsletterTitle,
PICK_DEFAULTS,
type NewsletterItem,
type NewsletterSection,
type NewsletterPart,
type PickSource,
} from '../../lib/newsletter.ts'
const MUTED = 'var(--color-muted)'
@ -55,24 +60,150 @@ const button =
const absolute = (path: string | null | undefined) => (path ? siteUrl(path) : null)
const imageFor = (file: string | null | undefined) => absolute(mediaUrl(file))
type PostRow = { id: string; title: string; published_on?: string | null; is_published: number; is_listed: number }
type PostRow = { id: string; title: string; published_on?: string | null }
type DraftRow = { id: number; title?: string | null; updated_at: string }
type Picks = { events?: string[]; posts?: string[]; cards?: string[] }
/* The block types an email can show (newsletter.ts draws them);
schedules, tables and people need the site. */
const EMAIL_BLOCKS = ['paragraph', 'heading', 'subheading', 'callout', 'quote', 'list', 'links', 'button', 'image', 'video', 'cards', 'divider']
const BLOCKS_SPEC = {
...blocksChild,
label: 'Blocks',
note: 'Written for this issue, under the intro. A video shows as its still, linked to the video.',
fields: blocksChild.fields
.filter((field) => field.path !== 'slot')
.map((field) =>
field.path === 'type' ? { ...field, options: (field.options ?? []).filter(([type]) => EMAIL_BLOCKS.includes(type)) } : field,
),
/* The parts that aren't content blocks, then the blocks an email shows. */
const PART_TYPES: Array<[string, string, string]> = [
['header', 'Header', 'The band above the title: words, a logo, its color. Remove this part to leave it out.'],
['title', 'Title', "The email's heading."],
['picks', 'Picked items', 'Upcoming events, published blog posts or front page cards, each as a card with a button.'],
['footer', 'Footer', 'The closing lines. No unsubscribe link needed: Mailchimp adds its own.'],
...(BLOCK_TYPES.filter(([type]) => EMAIL_BLOCKS.includes(type)) as Array<[string, string, string]>),
]
const partLabel = (type: string) => PART_TYPES.find(([value]) => value === type)?.[1] ?? type
/* The site's palette as choices; an inbox needs the hex itself. */
const SHADES = ['', ', darkest', ', light', ', lightest']
const PALETTE_OPTIONS = Object.entries(PALETTE).flatMap(([family, shades]) =>
shades.map((hex, i) => [hex, `${family[0].toUpperCase()}${family.slice(1)}${SHADES[i]}`]),
)
const colorField = (path: string, label: string, fallback: string, none: string, types: string[]) => ({
path,
label,
widget: 'select',
options: [['none', none], ...PALETTE_OPTIONS],
blankLabel: `Default: ${fallback}`,
when: { path: 'type', value: types },
})
const SOURCES: PickSource[] = ['events', 'posts', 'cards']
const SOURCE_LABEL: Record<PickSource, string> = { events: 'Upcoming events', posts: 'Blog posts', cards: 'Front page featured cards' }
const ITEM_LABEL: Record<PickSource, string> = { events: 'Event', posts: 'Blog post', cards: 'Featured card' }
const sourceOf = (part: NewsletterPart): PickSource => (SOURCES.includes(part.source as PickSource) ? (part.source as PickSource) : 'events')
/* Every part is a row: one editor for blocks and the email's own
parts, so any of them can be moved, copied or removed. */
const blockFields = blocksChild.fields.filter((field) => !['slot', 'team_id', 'type'].includes(field.path))
const PARTS_SPEC = {
key: 'parts',
label: 'Parts',
addLabel: 'Add part',
note: 'Top to bottom, as the email shows them. A video shows as its still, linked to the video.',
title: (row: NewsletterPart) => {
if (row.type === 'picks') {
const count = row.picked?.filter((pick) => pick.ref).length ?? 0
return `${row.text?.trim() || PICK_DEFAULTS[sourceOf(row)].heading}: ${count} picked`
}
const text = (row.text ?? '').trim().slice(0, 40)
return text ? `${partLabel(row.type)}: ${text}` : partLabel(row.type)
},
blank: { type: 'paragraph', text: '' },
fields: [
{
path: 'type',
label: 'Part',
widget: 'select',
options: PART_TYPES.map(([value, label]) => [value, label]),
help: (row: NewsletterPart) => PART_TYPES.find(([value]) => value === row?.type)?.[2],
},
{ path: 'align', label: 'Alignment', widget: 'select', options: [['center', 'Center']], blankLabel: 'Default: left' },
{ path: 'text', label: 'Words', when: { path: 'type', value: 'header' }, help: "Default: the site's name, or nothing beside a logo" },
{
path: 'media',
label: 'Logo',
widget: 'image',
folder: 'logos',
resolve: mediaUrl,
full: true,
when: { path: 'type', value: 'header' },
help: "A PNG or JPEG: Gmail and Outlook don't show SVG. Default: none, the words alone",
},
colorField('color', 'Band color', 'Teal, darkest', 'None: no band', ['header']),
{ path: 'text', label: 'Title', full: true, when: { path: 'type', value: 'title' }, help: `Default: ${DEFAULT_TITLE(SITE_NAME)}` },
{
path: 'source',
label: 'Pick from',
widget: 'select',
options: SOURCES.filter((source) => source !== 'events').map((source) => [source, SOURCE_LABEL[source]]),
blankLabel: `Default: ${SOURCE_LABEL.events}`,
when: { path: 'type', value: 'picks' },
},
{
path: 'text',
label: 'Heading',
when: { path: 'type', value: 'picks' },
help: (row: NewsletterPart) => `Default: ${PICK_DEFAULTS[sourceOf(row)].heading}`,
},
{
path: 'cta',
label: 'Button',
when: { path: 'type', value: 'picks' },
help: (row: NewsletterPart) => `On each card. Default: ${PICK_DEFAULTS[sourceOf(row)].cta}`,
},
colorField('rule', 'Heading underline', 'Teal, lightest', 'None: no line', ['picks']),
colorField('bar', 'Card bar', 'Teal', 'None: no bar', ['picks']),
{
path: 'text',
label: 'Footer',
widget: 'textarea',
full: true,
when: { path: 'type', value: 'footer' },
help: `Default: ${SITE_NAME} and ${SITE_ORIGIN}`,
},
colorField('rule', 'Line above', 'Teal, lightest', 'None: no line', ['footer']),
...blockFields,
colorField('color', 'Line color', 'Teal, lightest', 'None: space only', ['divider']),
{ path: 'size', label: 'Thickness', widget: 'number', when: { path: 'type', value: 'divider' }, help: 'In pixels, 1 to 8. Default: 2' },
{ path: 'space', label: 'Space above', widget: 'number', when: { path: 'type', value: 'divider' }, help: 'In pixels, 0 to 64. Default: 24' },
],
children: [
...(blocksChild.children ?? []),
{
key: 'picked',
label: 'Picked',
addLabel: 'Pick one',
when: { path: 'type', value: 'picks' },
title: () => 'Picked',
blank: { ref: '' },
// One select per source, the parent's choosing which shows.
fields: SOURCES.map((source) => ({
path: 'ref',
label: ITEM_LABEL[source],
widget: 'select',
optionsFrom: source,
required: true,
when: { scope: 'parent', path: 'source', value: source === 'events' ? ['', null, undefined, 'events'] : source },
})),
},
],
}
/* A new draft: the email as it always looked, every part in place. */
const STARTER: NewsletterPart[] = [
{ type: 'header' },
{ type: 'title', text: '' },
{ type: 'paragraph', text: '' },
{ type: 'picks', source: 'events', picked: [] },
{ type: 'picks', source: 'posts', picked: [] },
{ type: 'picks', source: 'cards', picked: [] },
{ type: 'footer' },
]
/* A site path or upload on the live site, for the email. */
const absoluteFor = (value: string, kind: 'link' | 'image') => (kind === 'image' ? imageFor(value) ?? value : siteUrl(value))
@ -81,19 +212,16 @@ function featuredHref(card: FeaturedCard): string | null {
return card.url
}
const picksOf = (parts: NewsletterPart[], source: PickSource) =>
parts
.filter((part) => part.type === 'picks' && sourceOf(part) === source)
.flatMap((part) => (part.picked ?? []).map((pick) => pick.ref).filter((ref): ref is string => Boolean(ref)))
export default function AdminNewsletter() {
useWideAdminPage()
const navigate = useNavigate()
const { user } = useAuth()
const [title, setTitle] = useState('')
const [intro, setIntro] = useState('')
const [footer, setFooter] = useState('')
const [blocks, setBlocks] = useState<NewsletterBlock[]>([])
const [pickedEvents, setPickedEvents] = useState<Set<string>>(new Set())
const [pickedPosts, setPickedPosts] = useState<Set<string>>(new Set())
// Cards by their link: the front page's cards can be reordered
// between one save and the next.
const [pickedCards, setPickedCards] = useState<Set<string>>(new Set())
const [parts, setParts] = useState<NewsletterPart[]>(STARTER)
const [posts, setPosts] = useState<PostRow[] | null>(null)
const [postDetails, setPostDetails] = useState<Record<string, BlogPostRecord>>({})
const [copied, setCopied] = useState<'html' | 'text' | null>(null)
@ -123,20 +251,17 @@ export default function AdminNewsletter() {
}, [])
function fill(row: any) {
let picks: Picks = {}
try {
picks = JSON.parse(row?.picks || '{}')
} catch {
// A hand-edited draft: start its picks over.
let layout: NewsletterPart[] = STARTER
if (row) {
try {
const parsed = JSON.parse(row.layout || '[]')
layout = Array.isArray(parsed) ? parsed : []
} catch {
// A hand-edited draft: start its parts over.
}
}
setDraft(row ? { id: row.id, updated_at: row.updated_at } : null)
setTitle(row?.title ?? '')
setIntro(row?.intro ?? '')
setFooter(row?.footer ?? '')
setBlocks(row?.content_blocks ?? [])
setPickedEvents(new Set(picks.events ?? []))
setPickedPosts(new Set(picks.posts ?? []))
setPickedCards(new Set(picks.cards ?? []))
setParts(layout)
}
async function openDraft(id: string) {
@ -154,11 +279,8 @@ export default function AdminNewsletter() {
setBusy(true)
setMessage(null)
const payload = {
title: title.trim(),
intro: intro.trim(),
footer: footer.trim(),
picks: JSON.stringify({ events: [...pickedEvents], posts: [...pickedPosts], cards: [...pickedCards] }),
content_blocks: blocks.map((block) => ({ ...block, slot: 'body' })),
title: parts.find((part) => part.type === 'title')?.text?.trim() || '',
layout: JSON.stringify(parts),
}
try {
const data = draft
@ -190,39 +312,125 @@ export default function AdminNewsletter() {
}
}
/* An unpublished blog post from what's built: the intro, the
blocks, then each section's picks as a heading and link cards.
It opens in the post's editor to finish and publish. */
// A picked post's public page: its excerpt and cover, and proof it's live.
const pickedPostKey = picksOf(parts, 'posts').join(',')
useEffect(() => {
for (const id of pickedPostKey.split(',').filter(Boolean)) {
if (postDetails[id]) continue
get(`/blog/${encodeURIComponent(id)}`)
.then((data: { post: BlogPostRecord }) => setPostDetails((current) => ({ ...current, [id]: data.post })))
.catch(() => {})
}
}, [pickedPostKey, postDetails])
// What each source's picks can be, by ref, as the email draws them.
const lookup = useMemo(() => {
const byEvent = new Map<string, NewsletterItem>()
for (const event of events) {
byEvent.set(event.id, {
title: event.title,
meta: [seriesLabel(event.series, event.starts_on) ?? event.date_label, event.is_online && !event.location_label ? 'Online' : event.location_label]
.filter(Boolean)
.join(', '),
text: event.tagline ?? event.description?.[0] ?? null,
image: imageFor(event.card_image),
href: siteUrl(eventHref(event.id)),
cta: PICK_DEFAULTS.events.cta,
})
}
const byPost = new Map<string, NewsletterItem>()
for (const [id, post] of Object.entries(postDetails)) {
const byline = post.authors.map((a) => a.name).concat(post.guest ? [post.guest.name] : []).join(', ')
byPost.set(id, {
title: post.title,
meta: byline ? `By ${byline}` : null,
text: post.excerpt ?? null,
image: imageFor(post.cover_image),
href: siteUrl(blogHref(post.id)),
cta: PICK_DEFAULTS.posts.cta,
})
}
const byCard = new Map<string, NewsletterItem>()
for (const card of cards) {
const href = featuredHref(card)
if (!href) continue
byCard.set(href, {
title: card.title ?? 'Featured',
meta: card.eyebrow ?? null,
text: card.blurb ?? null,
image: card.image ? imageFor(card.image.file) : null,
href: absolute(href) ?? href,
cta: card.kind === 'video' ? 'Watch' : PICK_DEFAULTS.cards.cta,
})
}
return { events: byEvent, posts: byPost, cards: byCard } as Record<PickSource, Map<string, NewsletterItem>>
}, [events, postDetails, cards])
// The picks selects' choices, by source (PARTS_SPEC's optionsFrom).
const pickOptions = useMemo(
() => ({
events: events.map((event) => ({ id: event.id, label: [event.title, event.date_label].filter(Boolean).join(', ') })),
posts: (posts ?? []).map((row) => ({ id: row.id, label: [row.title, row.published_on].filter(Boolean).join(', ') })),
cards: cards.flatMap((card) => {
const href = featuredHref(card)
return href ? [{ id: href, label: card.title ?? href }] : []
}),
}),
[events, posts, cards],
)
const newsletter = useMemo(() => {
const content = {
parts,
itemsFor: (part: NewsletterPart) =>
(part.picked ?? []).flatMap((pick) => {
const item = pick.ref ? lookup[sourceOf(part)].get(pick.ref) : undefined
return item ? [{ ...item, cta: part.cta?.trim() || item.cta }] : []
}),
origin: SITE_ORIGIN,
siteName: SITE_NAME,
absolute: absoluteFor,
}
return { content, html: newsletterHtml(content), text: newsletterText(content) }
}, [parts, lookup])
/* An unpublished blog post from what's built: the blocks, then each
picks section as a heading and link cards. The header, title and
footer are the email's own. It opens in the post's editor. */
async function postAsBlog() {
setBusy(true)
setMessage(null)
const postTitle = newsletter.content.title
const postTitle = newsletterTitle(newsletter.content)
const id = `${slugify(postTitle).slice(0, 52) || 'newsletter'}-${new Date().toISOString().slice(0, 10)}`
const body = [
...(intro.trim() ? [{ type: 'paragraph', text: intro.trim() }] : []),
...blocks,
...newsletter.content.sections
.filter((section) => section.items.length > 0)
.flatMap((section) => [
{ type: 'heading', text: section.heading },
const body = parts.flatMap((part) => {
if (part.type === 'picks') {
const items = newsletter.content.itemsFor(part)
if (items.length === 0) return []
return [
{ type: 'heading', text: part.text?.trim() || PICK_DEFAULTS[sourceOf(part)].heading },
{
type: 'cards',
items: section.items.map((item) => ({
items: items.map((item) => ({
text: item.title,
detail: [item.meta, item.text].filter(Boolean).join('\n\n') || null,
url: item.href,
media: item.image ?? null,
})),
},
]),
].map((block) => ({ ...block, slot: 'body' }))
]
}
if (!EMAIL_BLOCKS.includes(part.type)) return []
const { align: _align, color: _color, size: _size, space: _space, ...block } = part
return [block]
})
const excerpt = parts.find((part) => part.type === 'paragraph' && part.text?.trim())?.text?.trim() ?? null
try {
await post('/admin/blog_posts', {
id,
title: postTitle,
excerpt: intro.trim() || null,
excerpt,
is_published: false,
content_blocks: body,
content_blocks: body.map((block) => ({ ...block, slot: 'body' })),
})
navigate(`/admin/blog_posts/${id}`)
} catch (err) {
@ -232,90 +440,6 @@ export default function AdminNewsletter() {
}
}
// A picked post's public page: its excerpt and cover, and proof it's live.
useEffect(() => {
for (const id of pickedPosts) {
if (postDetails[id]) continue
get(`/blog/${encodeURIComponent(id)}`)
.then((data: { post: BlogPostRecord }) => setPostDetails((current) => ({ ...current, [id]: data.post })))
.catch(() => {})
}
}, [pickedPosts, postDetails])
const toggle = <T,>(set: Set<T>, value: T, update: (next: Set<T>) => void) => {
const next = new Set(set)
if (next.has(value)) next.delete(value)
else next.add(value)
update(next)
}
const newsletter = useMemo(() => {
const eventItems: NewsletterItem[] = events
.filter((event) => pickedEvents.has(event.id))
.map((event) => ({
title: event.title,
meta: [seriesLabel(event.series, event.starts_on) ?? event.date_label, event.is_online && !event.location_label ? 'Online' : event.location_label]
.filter(Boolean)
.join(', '),
text: event.tagline ?? event.description?.[0] ?? null,
image: imageFor(event.card_image),
href: siteUrl(eventHref(event.id)),
cta: 'Event details',
}))
const postItems: NewsletterItem[] = (posts ?? [])
.filter((row) => pickedPosts.has(row.id) && postDetails[row.id])
.map((row) => {
const post = postDetails[row.id]
const byline = post.authors.map((a) => a.name).concat(post.guest ? [post.guest.name] : []).join(', ')
return {
title: post.title,
meta: byline ? `By ${byline}` : null,
text: post.excerpt ?? null,
image: imageFor(post.cover_image),
href: siteUrl(blogHref(post.id)),
cta: 'Read the post',
}
})
const cardItems: NewsletterItem[] = cards
.map((card) => ({ card, href: featuredHref(card) }))
.filter(({ href }) => href && pickedCards.has(href))
.map(({ card, href }) => ({
title: card.title ?? 'Featured',
meta: card.eyebrow ?? null,
text: card.blurb ?? null,
image: card.image ? imageFor(card.image.file) : null,
href: absolute(href) ?? href!,
cta: card.kind === 'video' ? 'Watch' : 'Learn more',
}))
const sections: NewsletterSection[] = [
{ heading: 'Coming up', items: eventItems },
{ heading: 'From the blog', items: postItems },
{ heading: 'Featured', items: cardItems },
]
const content = {
title: title.trim() || `News from ${SITE_NAME}`,
intro: intro.trim() || null,
blocks,
footer: footer.trim() || null,
origin: SITE_ORIGIN,
siteName: SITE_NAME,
absolute: absoluteFor,
// The site's logo is an SVG, which Gmail and Outlook don't show,
// so the header is the site name in type. A PNG logo could go here.
logo: null,
sections,
}
return {
content,
html: newsletterHtml(content),
text: newsletterText(content),
count: eventItems.length + postItems.length + cardItems.length + blocks.length,
}
}, [title, intro, footer, blocks, events, pickedEvents, posts, pickedPosts, postDetails, cards, pickedCards])
async function copy(kind: 'html' | 'text') {
try {
await navigator.clipboard.writeText(kind === 'html' ? newsletter.html : newsletter.text)
@ -335,12 +459,14 @@ export default function AdminNewsletter() {
URL.revokeObjectURL(link.href)
}
const empty = parts.length === 0
return (
<div>
<div className="flex flex-wrap items-baseline gap-3">
<h1 className="text-2xl font-bold text-link">Newsletter</h1>
<p className="text-sm" style={{ color: MUTED }}>
Pick what to include, then copy the email into Mailchimp, Gmail or Church Center.
Build the email part by part, then copy it into Mailchimp, Gmail or Church Center.
</p>
</div>
@ -351,7 +477,7 @@ export default function AdminNewsletter() {
<option value="">New draft</option>
{drafts.map((row) => (
<option key={row.id} value={row.id}>
{row.title || `News from ${SITE_NAME}`} (saved {row.updated_at.slice(0, 16)})
{row.title || DEFAULT_TITLE(SITE_NAME)} (saved {row.updated_at.slice(0, 16)})
</option>
))}
</select>
@ -362,7 +488,7 @@ export default function AdminNewsletter() {
<FloppyDisk weight="bold" aria-hidden="true" />
{draft ? 'Save draft' : 'Save as a new draft'}
</button>
<button type="button" onClick={postAsBlog} className={button} disabled={busy || newsletter.count === 0}>
<button type="button" onClick={postAsBlog} className={button} disabled={busy || empty}>
<Article weight="bold" aria-hidden="true" />
Post as blog post
</button>
@ -381,147 +507,40 @@ export default function AdminNewsletter() {
)}
</div>
<div className="mt-6 grid gap-8 lg:grid-cols-[minmax(0,26rem)_minmax(0,1fr)]">
<div className="space-y-6">
<section className="space-y-3 border-l-4 border-brand bg-raised p-5 shadow-sm">
<label className="block text-sm font-semibold text-body">
Title
<input value={title} onChange={(e) => setTitle(e.target.value)} placeholder={`News from ${SITE_NAME}`} className={`mt-1 ${input}`} />
</label>
<label className="block text-sm font-semibold text-body">
Intro
<textarea
value={intro}
onChange={(e) => setIntro(e.target.value)}
rows={4}
placeholder="eg. A few things coming up this month…"
className={`mt-1 resize-y ${input}`}
/>
</label>
</section>
<section className="border-l-4 border-brand bg-raised p-5 shadow-sm">
<Repeater spec={BLOCKS_SPEC} rows={blocks} options={{}} errors={{}} errorPrefix="content_blocks." className="" onChange={setBlocks} />
</section>
<PickList
title="Upcoming events"
empty={eventsLoading ? 'Loading…' : 'No upcoming events.'}
options={events.map((event) => ({ value: event.id, label: event.title, detail: event.date_label }))}
picked={pickedEvents}
onToggle={(value) => toggle(pickedEvents, value, setPickedEvents)}
/>
<PickList
title="Blog posts"
empty={posts ? 'No published posts.' : 'Loading…'}
options={(posts ?? []).map((post) => ({ value: post.id, label: post.title, detail: post.published_on }))}
picked={pickedPosts}
onToggle={(value) => toggle(pickedPosts, value, setPickedPosts)}
/>
<PickList
title="Featured cards (front page)"
empty="No featured cards."
options={cards.flatMap((card) => {
const href = featuredHref(card)
return href ? [{ value: href, label: card.title ?? href, detail: card.kind }] : []
})}
picked={pickedCards}
onToggle={(value) => toggle(pickedCards, value, setPickedCards)}
/>
<section className="border-l-4 border-brand bg-raised p-5 shadow-sm">
<label className="block text-sm font-semibold text-body">
Footer
<textarea
value={footer}
onChange={(e) => setFooter(e.target.value)}
rows={3}
placeholder={`${SITE_NAME}\n${SITE_ORIGIN}`}
className={`mt-1 resize-y ${input}`}
/>
</label>
<p className="mt-1 text-xs" style={{ color: MUTED }}>
Default: the site's name and address. No unsubscribe link needed: Mailchimp adds its own.
</p>
</section>
</div>
<div className="mt-6 grid gap-8 lg:grid-cols-[minmax(0,30rem)_minmax(0,1fr)]">
<section className="border-l-4 border-brand bg-raised p-5 shadow-sm">
<Repeater spec={PARTS_SPEC} rows={parts} options={pickOptions} errors={{}} errorPrefix="parts." className="" onChange={setParts} />
<p className="mt-3 text-xs" style={{ color: MUTED }}>
{eventsLoading || posts === null ? 'Loading what can be picked…' : 'Picked items show once chosen; a section with none is left out.'}
</p>
</section>
<div>
<div className="flex flex-wrap gap-3">
<button type="button" onClick={() => copy('html')} className={button} disabled={newsletter.count === 0}>
<button type="button" onClick={() => copy('html')} className={button} disabled={empty}>
{copied === 'html' ? <Check weight="bold" aria-hidden="true" /> : <Copy weight="bold" aria-hidden="true" />}
{copied === 'html' ? 'Copied' : 'Copy HTML'}
</button>
<button type="button" onClick={() => copy('text')} className={button} disabled={newsletter.count === 0}>
<button type="button" onClick={() => copy('text')} className={button} disabled={empty}>
{copied === 'text' ? <Check weight="bold" aria-hidden="true" /> : <Copy weight="bold" aria-hidden="true" />}
{copied === 'text' ? 'Copied' : 'Copy plain text'}
</button>
<button type="button" onClick={download} className={button} disabled={newsletter.count === 0}>
<button type="button" onClick={download} className={button} disabled={empty}>
<DownloadSimple weight="bold" aria-hidden="true" />
Download .html
</button>
</div>
<p className="mt-2 text-xs" style={{ color: MUTED }}>
{newsletter.count === 0
? 'Tick an item or add a block to build the email.'
: `${newsletter.count} part${newsletter.count === 1 ? '' : 's'}. In Mailchimp, paste the HTML into a Code block or "Paste in code".`}
{empty ? 'Add a part to build the email.' : 'In Mailchimp, paste the HTML into a Code block or "Paste in code".'}
</p>
<iframe
title="Newsletter preview"
srcDoc={newsletter.html}
sandbox=""
className="mt-4 h-[70vh] w-full border border-brand/20 bg-white"
className="mt-4 h-[80vh] w-full border border-brand/20 bg-white lg:sticky lg:top-24"
/>
</div>
</div>
</div>
)
}
function PickList<T extends string | number>({
title,
empty,
options,
picked,
onToggle,
}: {
title: string
empty: string
options: Array<{ value: T; label: string; detail?: string | null }>
picked: Set<T>
onToggle: (value: T) => void
}) {
return (
<section className="border-l-4 border-brand bg-raised p-5 shadow-sm">
<h2 className="text-base font-bold text-ink">{title}</h2>
{options.length === 0 ? (
<p className="mt-2 text-sm" style={{ color: MUTED }}>
{empty}
</p>
) : (
<ul className="mt-2 max-h-72 space-y-1 overflow-y-auto">
{options.map((option) => (
<li key={String(option.value)}>
<label className="flex cursor-pointer items-start gap-3 px-2 py-1.5 hover:bg-tint-soft">
<input
type="checkbox"
checked={picked.has(option.value)}
onChange={() => onToggle(option.value)}
className="mt-1 h-4 w-4 accent-[var(--color-action)]"
/>
<span className="min-w-0">
<span className="block text-sm text-ink">{option.label}</span>
{option.detail && (
<span className="block text-xs" style={{ color: MUTED }}>
{option.detail}
</span>
)}
</span>
</label>
</li>
))}
</ul>
)}
</section>
)
}