Newsletter drafts with content blocks, a footer and Post as blog post; Home has no header dropdown

Tools → Newsletter saves drafts (migration 057: newsletters, with
content blocks owned 'newsletter'), adds blocks written for the issue
and an editable footer (no unsubscribe link: Mailchimp adds one), and
turns a draft into an unpublished blog post. The admin engine binds
child owner ids as text, so an auto-numbered record's blocks are
owned by '1', not '1.0'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-10-01 00:21:32 -05:00
parent 9daf7b1a4f
commit e8ac242e6d
8 changed files with 575 additions and 34 deletions

View file

@ -189,8 +189,9 @@ export function readRow(db, entity, rawId) {
row[ext.key] = readExtension(db, ext, id);
}
// As text, for the reason readChildren gives its nested ids.
for (const child of entity.children ?? []) {
row[child.key] = readChildren(db, child, id);
row[child.key] = readChildren(db, child, String(id));
}
return row;
@ -513,7 +514,10 @@ function keyedDbErrors(prefix, fn) {
}
}
function writeChildren(db, entity, id, payload, parentValues) {
function writeChildren(db, entity, rawId, payload, parentValues) {
// As text: an auto id is a JS number, which binds as REAL and
// lands in a TEXT owner column (a newsletter's blocks) as '1.0'.
const id = String(rawId);
for (const child of entity.children ?? []) {
if (!applies(child.when, parentValues)) {
deleteChildren(db, child, id);

View file

@ -51,6 +51,7 @@ import { timeline } from "./admin-schema/timeline.js";
import { frontPage } from "./admin-schema/frontPage.js";
import { blogPosts } from "./admin-schema/blog.js";
import { siteSettings } from "./admin-schema/siteSettings.js";
import { newsletters } from "./admin-schema/newsletters.js";
import {
communityPage,
retreatsPage,
@ -74,6 +75,7 @@ export const ENTITIES = {
organization_page: organizationPage,
history_page: historyPage,
site_settings: siteSettings,
newsletters,
};
/* ── Options for the form's select inputs ────────────────────── */

View file

@ -0,0 +1,27 @@
import { text, blocksChild } from "./columns.js";
/* ── Newsletter drafts (057_newsletters.sql) ─────────────────────
Saved from Tools → Newsletter (AdminNewsletter.tsx), which is
their only editor: there is no list or form for them in Data.
`picks` is the builder's JSON of what's ticked. Deleting a draft
takes its blocks with it (newsletters_cleanup). */
export const newsletters = {
key: "newsletters",
table: "newsletters",
idColumn: "id",
idKind: "auto",
concurrency: "updated_at",
list: {
columns: ["id", "title", "updated_at"],
filters: [],
search: ["title"],
order: "updated_at DESC, id DESC",
},
columns: [text("title"), text("intro"), text("footer"), text("picks")],
children: [blocksChild("newsletter")],
};

View file

@ -0,0 +1,111 @@
-- ═══════════════════════════════════════════════════════════════
-- 057 NEWSLETTER DRAFTS
--
-- Tools → Newsletter saves what it builds as a draft, to come back
-- to, copy into Mailchimp again, or post as a blog post:
--
-- title, intro the email's heading and opening lines
-- footer the closing lines (blank: the site's name and
-- address); no unsubscribe link, since Mailchimp
-- adds its own
-- picks what's ticked, as JSON: event ids, blog post
-- ids, and the front page cards by their link
-- ({"events": [...], "posts": [...], "cards": [...]})
-- blocks content_blocks owned 'newsletter': whatever is
-- written for this issue, under the intro
--
-- content_blocks is rebuilt for its owner_kind CHECK (as 056 did). A
-- draft deleted takes its blocks with it, by trigger.
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE newsletters (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
intro TEXT,
footer TEXT,
picks TEXT NOT NULL DEFAULT '{}' CHECK (json_valid(picks)),
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
-- ── Blocks: the new owner kind ─────────────────────────────────
CREATE TABLE content_blocks_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_kind TEXT NOT NULL
CHECK (owner_kind IN ('organization', 'event', 'person', 'team', 'blog_post', 'page_section',
'newsletter')),
owner_id TEXT NOT NULL,
slot TEXT NOT NULL DEFAULT 'body' CHECK (slot IN ('card', 'body')),
sort_order INTEGER NOT NULL DEFAULT 0,
type TEXT NOT NULL
CHECK (type IN ('heading', 'subheading', 'paragraph',
'list', 'links', 'quote', 'image', 'divider',
'video', 'button', 'callout', 'schedule', 'table', 'cards',
'people')),
text TEXT,
media TEXT,
href TEXT,
alt TEXT,
cite TEXT,
team_id TEXT REFERENCES teams (id) ON DELETE SET NULL
) STRICT;
INSERT INTO content_blocks_new
(id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite, team_id)
SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite, team_id
FROM content_blocks;
PRAGMA legacy_alter_table = ON;
DROP TABLE content_blocks;
ALTER TABLE content_blocks_new RENAME TO content_blocks;
PRAGMA legacy_alter_table = OFF;
CREATE INDEX content_blocks_owner_idx
ON content_blocks (owner_kind, owner_id, slot, sort_order);
-- ── Triggers last (see CLAUDE.md, Migrations) ──
CREATE TRIGGER newsletters_touch
AFTER UPDATE ON newsletters
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE newsletters SET updated_at = datetime('now') WHERE id = new.id;
END;
CREATE TRIGGER newsletters_cleanup
AFTER DELETE ON newsletters
BEGIN
DELETE FROM content_blocks WHERE owner_kind = 'newsletter' AND owner_id = CAST(old.id AS TEXT);
END;
CREATE TRIGGER content_blocks_owner_exists
BEFORE INSERT ON content_blocks
BEGIN
SELECT CASE
WHEN new.owner_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such event')
WHEN new.owner_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such organization')
WHEN new.owner_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such person')
WHEN new.owner_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such team')
WHEN new.owner_kind = 'blog_post'
AND NOT EXISTS (SELECT 1 FROM blog_posts WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such blog post')
WHEN new.owner_kind = 'page_section'
AND NOT EXISTS (SELECT 1 FROM page_sections WHERE CAST(id AS TEXT) = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such page section')
WHEN new.owner_kind = 'newsletter'
AND NOT EXISTS (SELECT 1 FROM newsletters WHERE CAST(id AS TEXT) = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such newsletter')
END;
END;

View file

@ -166,10 +166,12 @@ export default function Layout() {
{/* Each page, and under it on hover or keyboard focus its
sections (navSections.ts): the sections live in these
dropdowns rather than a strip of their own. */}
dropdowns rather than a strip of their own. Home has
none: it's the logo's link too, and its bands are one
scroll away. */}
<div className="hidden lg:flex items-center gap-6">
{PAGE_LINKS.map((page) => {
const pageSections = sectionsOf(page.path);
const pageSections = page.path === "/" ? [] : sectionsOf(page.path);
return (
<div key={page.path} className="group relative">
<NavLink

View file

@ -2,9 +2,17 @@
NEWSLETTER: email-ready HTML and plain text from picked items
The admin's Newsletter tool (AdminNewsletter.tsx) gathers events,
blog posts and featured cards; this turns them into one email to
paste into Mailchimp, Gmail or Church Center. Nothing is sent or
stored here.
blog posts and featured cards, with content blocks written for the
issue; this turns them into one email to paste into Mailchimp,
Gmail or Church Center. Nothing is sent from here.
Blocks draw as their email-safe equivalent: headings, paragraphs
(with **bold**, *italic* and [links](url)), callouts, quotes,
lists, link and button rows, images, cards and dividers; a video
is its still linked to the video. Schedules, tables and people,
which need the site, are left out.
No unsubscribe link: Mailchimp adds its own to every send.
Email clients ignore stylesheets, CSS variables and most layout,
so the HTML is tables with inline styles at 600px, images with
@ -27,15 +35,32 @@ export type NewsletterItem = {
export type NewsletterSection = { heading: string; items: NewsletterItem[] }
/* A content block as the block editor holds it. */
export type NewsletterBlock = {
type: string
text?: string | null
media?: string | null
href?: string | null
alt?: string | null
cite?: string | null
items?: Array<{ text?: string | null; detail?: string | null; url?: string | null; media?: string | null }>
}
export type Newsletter = {
title: string
intro?: string | null
/** Written for this issue, under the intro. */
blocks?: NewsletterBlock[]
sections: NewsletterSection[]
/** The closing lines. Blank: the site's name and address. */
footer?: string | null
/** The site's address, for the header link and footer. */
origin: string
siteName: string
/** An absolute URL of the logo for the header. */
logo?: string | null
/** A site path or upload as an absolute address (blocks hold paths and bare filenames). */
absolute: (pathOrFile: string, kind: 'link' | 'image') => string
}
/* The palette as an inbox needs it. */
@ -55,15 +80,148 @@ const BODY_FONT = "'Montserrat', Helvetica, Arial, sans-serif"
const escape = (value: string) =>
value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
/* Paragraphs from text with blank lines between them. */
const paragraphs = (text: string, style: string) =>
/* A link an email can follow: the site's own paths made absolute,
anything but http, https and mailto refused. */
function safeHref(href: string, n: Newsletter): string | null {
const value = href.trim()
if (/^(https?:|mailto:)/i.test(value)) return value
if (value.startsWith('/')) return n.absolute(value, 'link')
return null
}
/* Escaped text with the editor's **bold**, *italic* and [text](url). */
function inline(text: string, n: Newsletter): string {
return escape(text)
.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_whole, label, href) => {
const url = safeHref(href.replace(/&amp;/g, '&'), n)
return url ? `<a href="${escape(url)}" style="color:${COLOR.teal};">${label}</a>` : label
})
.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
.replace(/\*([^*]+)\*/g, '<em>$1</em>')
}
/* Paragraphs from text with blank lines between them, formatted
when given the newsletter (its links need the site's address). */
const paragraphs = (text: string, style: string, n?: Newsletter) =>
text
.split(/\n\s*\n/)
.map((part) => part.trim())
.filter(Boolean)
.map((part) => `<p style="${style}">${escape(part).replace(/\n/g, '<br>')}</p>`)
.map((part) => `<p style="${style}">${(n ? inline(part, n) : escape(part)).replace(/\n/g, '<br>')}</p>`)
.join('')
const TEXT = `margin:12px 0 0;font-family:${BODY_FONT};font-size:15px;line-height:24px;color:${COLOR.body};`
const buttonHtml = (href: string, label: string) =>
`<a href="${escape(href)}" style="display:inline-block;margin:4px 8px 4px 0;padding:10px 20px;border-radius:8px;background:${COLOR.teal};color:#ffffff;font-family:${FONT};font-size:14px;font-weight:700;text-decoration:none;">${escape(label)}</a>`
function blockHtml(block: NewsletterBlock, n: Newsletter): string {
const text = block.text?.trim() ?? ''
const href = block.href ? safeHref(block.href, n) : null
const items = block.items ?? []
switch (block.type) {
case 'heading':
return text
? `<h2 style="margin:24px 0 0;font-family:${FONT};font-size:22px;line-height:28px;font-weight:700;color:${COLOR.teal};">${escape(text)}</h2>`
: ''
case 'subheading':
return text
? `<h3 style="margin:20px 0 0;font-family:${FONT};font-size:18px;line-height:24px;font-weight:700;color:${COLOR.ink};">${escape(text)}</h3>`
: ''
case 'paragraph':
return text ? paragraphs(text, TEXT, n) : ''
case 'callout':
return text ? `<div style="margin:16px 0 0;padding:4px 16px 16px;background:${COLOR.rule};">${paragraphs(text, TEXT, n)}</div>` : ''
case 'quote':
return text
? `<blockquote style="margin:16px 0 0;padding:0 0 0 16px;border-left:4px solid ${COLOR.teal};">${paragraphs(text, `${TEXT}font-style:italic;`, n)}${
block.cite ? `<p style="${TEXT}color:${COLOR.muted};">${escape(block.cite)}</p>` : ''
}</blockquote>`
: ''
case 'list':
return items.length
? `<ul style="margin:12px 0 0;padding-left:20px;font-family:${BODY_FONT};font-size:15px;line-height:24px;color:${COLOR.body};">${items
.map((item) => {
const url = item.url ? safeHref(item.url, n) : null
const label = escape(item.text ?? '')
const detail = item.detail ? `: ${escape(item.detail)}` : ''
return `<li>${url ? `<a href="${escape(url)}" style="color:${COLOR.teal};">${label}</a>` : label}${detail}</li>`
})
.join('')}</ul>`
: ''
case 'links': {
const buttons = items
.map((item) => (item.url ? safeHref(item.url, n) : null))
.map((url, i) => (url ? buttonHtml(url, items[i].text || url) : ''))
.join('')
return buttons ? `<p style="margin:16px 0 0;">${buttons}</p>` : ''
}
case 'button':
return href && text ? `<p style="margin:16px 0 0;">${buttonHtml(href, text)}</p>` : ''
case 'image':
case 'video': {
if (!block.media) return ''
const img = `<img src="${escape(n.absolute(block.media, 'image'))}" width="552" alt="${escape(block.alt ?? '')}" style="display:block;width:100%;max-width:552px;height:auto;border:0;">`
const caption = text
? `<p style="margin:6px 0 0;font-family:${BODY_FONT};font-size:13px;line-height:20px;color:${COLOR.muted};">${escape(text)}</p>`
: ''
return `<div style="margin:16px 0 0;">${href ? `<a href="${escape(href)}">${img}</a>` : img}${caption}</div>`
}
case 'cards':
return items
.map((item) => {
const url = item.url ? safeHref(item.url, n) : null
if (!url || !item.text) return ''
return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:16px 0 0;background:${COLOR.card};border-left:4px solid ${COLOR.teal};"><tr><td style="padding:16px 20px;">
<h3 style="margin:0;font-family:${FONT};font-size:18px;line-height:24px;font-weight:700;"><a href="${escape(url)}" style="color:${COLOR.ink};text-decoration:none;">${escape(item.text)}</a></h3>
${item.detail ? paragraphs(item.detail, TEXT) : ''}</td></tr></table>`
})
.join('')
case 'divider':
return `<hr style="margin:24px 0 0;border:0;border-top:2px solid ${COLOR.rule};">`
default:
return ''
}
}
function blockText(block: NewsletterBlock, n: Newsletter): string[] {
const text = block.text?.trim() ?? ''
const items = block.items ?? []
const link = (url: string) => safeHref(url, n) ?? url
switch (block.type) {
case 'heading':
return text ? [text.toUpperCase(), ''] : []
case 'subheading':
case 'paragraph':
case 'callout':
case 'image':
return text ? [text, ''] : []
case 'quote':
return text ? [`"${text}"`, ...(block.cite ? [` ${block.cite}`] : []), ''] : []
case 'list':
return items.length
? [...items.map((item) => `- ${item.text ?? ''}${item.detail ? `: ${item.detail}` : ''}${item.url ? ` (${link(item.url)})` : ''}`), '']
: []
case 'links':
case 'cards': {
const lines = items.filter((item) => item.url).map((item) => `${item.text ?? ''}: ${link(item.url!)}`)
return lines.length ? [...lines, ''] : []
}
case 'button':
case 'video':
return block.href ? [`${text || 'Link'}: ${link(block.href)}`, ''] : []
case 'divider':
return ['---', '']
default:
return []
}
}
/* The closing lines: the admin's, or the site's name and address. */
const footerHtml = (n: Newsletter) =>
n.footer?.trim()
? paragraphs(n.footer, `margin:0 0 8px;font-family:${BODY_FONT};font-size:13px;line-height:20px;color:${COLOR.muted};`, n)
: `${escape(n.siteName)}<br><a href="${escape(n.origin)}" style="color:${COLOR.teal};">${escape(n.origin.replace(/^https?:\/\//, ''))}</a>`
function itemHtml(item: NewsletterItem): string {
const image = item.image
? `<tr><td><a href="${escape(item.href)}"><img src="${escape(item.image)}" width="552" alt="" style="display:block;width:100%;max-width:552px;height:auto;border:0;"></a></td></tr>`
@ -116,11 +274,12 @@ export function newsletterHtml(n: Newsletter): string {
<tr><td style="padding:20px 24px;background:${COLOR.body};">${logo}</td></tr>
<tr><td style="padding:28px 24px 8px;">
<h1 style="margin:0;font-family:${FONT};font-size:28px;line-height:34px;font-weight:700;color:${COLOR.ink};">${escape(n.title)}</h1>
${n.intro ? paragraphs(n.intro, `margin:12px 0 0;font-family:${BODY_FONT};font-size:16px;line-height:26px;color:${COLOR.body};`) : ''}
${n.intro ? paragraphs(n.intro, `margin:12px 0 0;font-family:${BODY_FONT};font-size:16px;line-height:26px;color:${COLOR.body};`, n) : ''}
${(n.blocks ?? []).map((block) => blockHtml(block, n)).join('')}
</td></tr>
${sections}
<tr><td style="padding:24px;border-top:2px solid ${COLOR.rule};font-family:${BODY_FONT};font-size:13px;line-height:20px;color:${COLOR.muted};">
${escape(n.siteName)}<br><a href="${escape(n.origin)}" style="color:${COLOR.teal};">${escape(n.origin.replace(/^https?:\/\//, ''))}</a>
${footerHtml(n)}
</td></tr>
</table>
</td></tr>
@ -132,6 +291,7 @@ export function newsletterHtml(n: Newsletter): string {
export function newsletterText(n: Newsletter): string {
const lines = [n.title, '='.repeat(Math.min(n.title.length, 60)), '']
if (n.intro) lines.push(n.intro.trim(), '')
for (const block of n.blocks ?? []) lines.push(...blockText(block, n))
for (const section of n.sections) {
if (section.items.length === 0) continue
lines.push(section.heading.toUpperCase(), '')
@ -142,6 +302,6 @@ export function newsletterText(n: Newsletter): string {
lines.push(`${item.cta}: ${item.href}`, '')
}
}
lines.push('--', n.siteName, n.origin)
lines.push('--', ...(n.footer?.trim() ? [n.footer.trim()] : [n.siteName, n.origin]))
return lines.join('\n')
}

View file

@ -3,10 +3,15 @@
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.
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.
Drafts are saved (the newsletters entity, 057_newsletters.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.
Picked blog posts are read from their public pages, so only a
post visitors can open makes it in, with its excerpt and cover.
@ -14,10 +19,16 @@
email is read far from this admin.
═══════════════════════════════════════════════════════════════ */
import { Check, Copy, DownloadSimple } from '@phosphor-icons/react'
import { Article, Check, Copy, DownloadSimple, FloppyDisk, Trash } from '@phosphor-icons/react'
import { useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { get } from '../../lib/api.ts'
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 { Repeater } from '../../components/admin/fields.tsx'
import { useEvents } from '../../lib/eventData.ts'
import { useFrontPage, type FeaturedCard } from '../../lib/useFrontPage.ts'
import type { BlogPostRecord } from '../../lib/useBlog.ts'
@ -26,7 +37,13 @@ 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'
import {
newsletterHtml,
newsletterText,
type NewsletterBlock,
type NewsletterItem,
type NewsletterSection,
} from '../../lib/newsletter.ts'
const MUTED = 'var(--color-muted)'
const input =
@ -39,6 +56,25 @@ const absolute = (path: string | null | undefined) => (path ? siteUrl(path) : nu
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 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,
),
}
/* 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))
function featuredHref(card: FeaturedCard): string | null {
if (card.kind === 'record' && card.ref) return refHref(card.ref.kind, card.ref.id, card.ref.org_kind)
@ -47,15 +83,27 @@ function featuredHref(card: FeaturedCard): string | null {
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())
const [pickedCards, setPickedCards] = useState<Set<number>>(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 [posts, setPosts] = useState<PostRow[] | null>(null)
const [postDetails, setPostDetails] = useState<Record<string, BlogPostRecord>>({})
const [copied, setCopied] = useState<'html' | 'text' | null>(null)
// The draft being edited: null is a new one, not saved yet.
const [drafts, setDrafts] = useState<DraftRow[]>([])
const [draft, setDraft] = useState<{ id: number; updated_at: string } | null>(null)
const [busy, setBusy] = useState(false)
const [message, setMessage] = useState<{ tone: 'ok' | 'error'; text: string } | null>(null)
const { events, loading: eventsLoading } = useEvents({ status: 'upcoming' })
const { data: frontPage } = useFrontPage()
const cards = frontPage?.featured ?? []
@ -66,6 +114,124 @@ export default function AdminNewsletter() {
.catch(() => setPosts([]))
}, [])
const loadDrafts = () =>
get('/admin/newsletters?limit=100', { ttl: 0 })
.then((data: { rows: DraftRow[] }) => setDrafts(data.rows))
.catch(() => setDrafts([]))
useEffect(() => {
loadDrafts()
}, [])
function fill(row: any) {
let picks: Picks = {}
try {
picks = JSON.parse(row?.picks || '{}')
} catch {
// A hand-edited draft: start its picks 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 ?? []))
}
async function openDraft(id: string) {
setMessage(null)
if (!id) return fill(null)
try {
const data = await get(`/admin/newsletters/${id}`, { ttl: 0 })
fill(data.row)
} catch (err) {
setMessage({ tone: 'error', text: err instanceof Error ? err.message : 'Couldn’t open that draft.' })
}
}
async function save() {
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' })),
}
try {
const data = draft
? await patch(`/admin/newsletters/${draft.id}`, { ...payload, updated_at: draft.updated_at })
: await post('/admin/newsletters', payload)
fill(data.row)
loadDrafts()
setMessage({ tone: 'ok', text: 'Draft saved.' })
} catch (err) {
const fields = err instanceof ApiError && err.fields ? Object.values(err.fields).filter(Boolean).join(' ') : ''
setMessage({ tone: 'error', text: [err instanceof Error ? err.message : 'Couldn’t save.', fields].filter(Boolean).join(' ') })
} finally {
setBusy(false)
}
}
async function remove() {
if (!draft || !window.confirm('Delete this draft? This can’t be undone.')) return
setBusy(true)
try {
await del(`/admin/newsletters/${draft.id}`)
fill(null)
loadDrafts()
setMessage({ tone: 'ok', text: 'Draft deleted.' })
} catch (err) {
setMessage({ tone: 'error', text: err instanceof Error ? err.message : 'Couldn’t delete.' })
} finally {
setBusy(false)
}
}
/* 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. */
async function postAsBlog() {
setBusy(true)
setMessage(null)
const postTitle = newsletter.content.title
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 },
{
type: 'cards',
items: section.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' }))
try {
await post('/admin/blog_posts', {
id,
title: postTitle,
excerpt: intro.trim() || null,
is_published: false,
content_blocks: body,
})
navigate(`/admin/blog_posts/${id}`)
} catch (err) {
const fields = err instanceof ApiError && err.fields ? Object.values(err.fields).filter(Boolean).join(' ') : ''
setMessage({ tone: 'error', text: [err instanceof Error ? err.message : 'Couldn’t make the post.', fields].filter(Boolean).join(' ') })
setBusy(false)
}
}
// A picked post's public page: its excerpt and cover, and proof it's live.
useEffect(() => {
for (const id of pickedPosts) {
@ -113,8 +279,8 @@ export default function AdminNewsletter() {
})
const cardItems: NewsletterItem[] = cards
.map((card, index) => ({ card, index, href: featuredHref(card) }))
.filter(({ index, href }) => pickedCards.has(index) && href)
.map((card) => ({ card, href: featuredHref(card) }))
.filter(({ href }) => href && pickedCards.has(href))
.map(({ card, href }) => ({
title: card.title ?? 'Featured',
meta: card.eyebrow ?? null,
@ -124,22 +290,31 @@ export default function AdminNewsletter() {
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: [
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 { html: newsletterHtml(content), text: newsletterText(content), count: eventItems.length + postItems.length + cardItems.length }
}, [title, intro, events, pickedEvents, posts, pickedPosts, postDetails, cards, pickedCards])
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 {
@ -169,6 +344,43 @@ export default function AdminNewsletter() {
</p>
</div>
<div className="mt-6 flex flex-wrap items-end gap-3 border-l-4 border-brand bg-raised p-4 shadow-sm">
<label className="block min-w-60 flex-1 text-sm font-semibold text-body">
Draft
<select value={draft?.id ?? ''} onChange={(e) => openDraft(e.target.value)} className={`mt-1 ${input}`}>
<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)})
</option>
))}
</select>
</label>
{canWrite(user) && (
<>
<button type="button" onClick={save} className={button} disabled={busy}>
<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}>
<Article weight="bold" aria-hidden="true" />
Post as blog post
</button>
</>
)}
{draft && canDelete(user) && (
<button type="button" onClick={remove} className={`${button} !border-danger !text-danger`} disabled={busy}>
<Trash weight="bold" aria-hidden="true" />
Delete draft
</button>
)}
{message && (
<p role="status" className={`w-full text-sm ${message.tone === 'error' ? 'text-danger' : 'text-body'}`}>
{message.text}
</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">
@ -188,6 +400,10 @@ export default function AdminNewsletter() {
</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.'}
@ -205,10 +421,29 @@ export default function AdminNewsletter() {
<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 }))}
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>
@ -228,8 +463,8 @@ export default function AdminNewsletter() {
</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".`}
? '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".`}
</p>
<iframe
title="Newsletter preview"

View file

@ -173,7 +173,7 @@ export const TOOLS_NAV = {
{
to: "/admin/newsletter",
label: "Newsletter",
blurb: "An email newsletter from upcoming events, blog posts and featured cards, ready to paste into Mailchimp or Gmail.",
blurb: "An email newsletter from upcoming events, blog posts, featured cards and blocks of its own, ready to paste into Mailchimp or Gmail. Saved as drafts, and can become a blog post.",
},
{
to: "/qr",