A newsletter builder (Tools → Newsletter)

Tick upcoming events, published blog posts and the front page's
featured cards, write a title and intro, and copy an email-ready
newsletter (table layout, inline styles, the palette in hex, a
plain-text copy alongside) into Mailchimp, Gmail or Church Center,
or download it. Picked posts are read from their public pages, so
only live posts make it in; links and images point at the live
site. Nothing is sent or stored. The builder is src/lib/newsletter.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-30 22:38:04 -05:00
parent 177a65005e
commit 2a926971f7
4 changed files with 446 additions and 0 deletions

View file

@ -0,0 +1,292 @@
/* ═══════════════════════════════════════════════════════════════
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 and an intro, 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 or saved here;
the builder is src/lib/newsletter.ts.
Picked blog posts are read from their public pages, so only a
post visitors can open makes it in, with its excerpt and cover.
Links and images are the live site's (SITE_ORIGIN), since an
email is read far from this admin.
═══════════════════════════════════════════════════════════════ */
import { Check, Copy, DownloadSimple } from '@phosphor-icons/react'
import { useEffect, useMemo, useState } from 'react'
import { get } from '../../lib/api.ts'
import { useEvents } from '../../lib/eventData.ts'
import { useFrontPage, type FeaturedCard } from '../../lib/useFrontPage.ts'
import type { BlogPostRecord } from '../../lib/useBlog.ts'
import { blogHref, eventHref, refHref } from '../../lib/hrefs.ts'
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 { newsletterHtml, newsletterText, type NewsletterItem } from '../../lib/newsletter.ts'
const MUTED = 'var(--color-muted)'
const input =
'w-full border border-muted/25 bg-surface px-3 py-2 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25'
const button =
'btn inline-flex items-center gap-2 border border-brand px-4 py-2 text-sm text-link transition-colors hover:bg-tint disabled:opacity-50'
/* An address on the live site, whatever it started as. */
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 }
function featuredHref(card: FeaturedCard): string | null {
if (card.kind === 'record' && card.ref) return refHref(card.ref.kind, card.ref.id, card.ref.org_kind)
return card.url
}
export default function AdminNewsletter() {
useWideAdminPage()
const [title, setTitle] = useState('')
const [intro, setIntro] = useState('')
const [pickedEvents, setPickedEvents] = useState<Set<string>>(new Set())
const [pickedPosts, setPickedPosts] = useState<Set<string>>(new Set())
const [pickedCards, setPickedCards] = useState<Set<number>>(new Set())
const [posts, setPosts] = useState<PostRow[] | null>(null)
const [postDetails, setPostDetails] = useState<Record<string, BlogPostRecord>>({})
const [copied, setCopied] = useState<'html' | 'text' | null>(null)
const { events, loading: eventsLoading } = useEvents({ status: 'upcoming' })
const { data: frontPage } = useFrontPage()
const cards = frontPage?.featured ?? []
useEffect(() => {
get('/admin/blog_posts?limit=200', { ttl: 0 })
.then((data: { rows: PostRow[] }) => setPosts(data.rows.filter((row) => row.is_published && row.is_listed)))
.catch(() => setPosts([]))
}, [])
// 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, index) => ({ card, index, href: featuredHref(card) }))
.filter(({ index, href }) => pickedCards.has(index) && 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 content = {
title: title.trim() || `News from ${SITE_NAME}`,
intro: intro.trim() || null,
origin: SITE_ORIGIN,
siteName: SITE_NAME,
// 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: [
{ heading: 'Coming up', items: eventItems },
{ heading: 'From the blog', items: postItems },
{ heading: 'Featured', items: cardItems },
],
}
return { html: newsletterHtml(content), text: newsletterText(content), count: eventItems.length + postItems.length + cardItems.length }
}, [title, intro, events, pickedEvents, posts, pickedPosts, postDetails, cards, pickedCards])
async function copy(kind: 'html' | 'text') {
try {
await navigator.clipboard.writeText(kind === 'html' ? newsletter.html : newsletter.text)
setCopied(kind)
window.setTimeout(() => setCopied(null), 2000)
} catch {
setCopied(null)
}
}
function download() {
const blob = new Blob([newsletter.html], { type: 'text/html' })
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = `newsletter-${new Date().toISOString().slice(0, 10)}.html`
link.click()
URL.revokeObjectURL(link.href)
}
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.
</p>
</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>
<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.map((card, index) => ({ value: index, label: card.title ?? card.url ?? 'Card', detail: card.kind }))}
picked={pickedCards}
onToggle={(value) => toggle(pickedCards, value, setPickedCards)}
/>
</div>
<div>
<div className="flex flex-wrap gap-3">
<button type="button" onClick={() => copy('html')} className={button} disabled={newsletter.count === 0}>
{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}>
{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}>
<DownloadSimple weight="bold" aria-hidden="true" />
Download .html
</button>
</div>
<p className="mt-2 text-xs" style={{ color: MUTED }}>
{newsletter.count === 0
? 'Tick at least one item to build the email.'
: `${newsletter.count} item${newsletter.count === 1 ? '' : 's'}. 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"
/>
</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>
)
}