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:
parent
9daf7b1a4f
commit
e8ac242e6d
8 changed files with 575 additions and 34 deletions
|
|
@ -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 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: [
|
||||
{ heading: 'Coming up', items: eventItems },
|
||||
{ heading: 'From the blog', items: postItems },
|
||||
{ heading: 'Featured', items: cardItems },
|
||||
],
|
||||
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"
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue