/* ═══════════════════════════════════════════════════════════════ NEWSLETTER (Tools) 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, 060_newsletter_layout.sql), to finish later or send again, and a draft can become an unpublished blog post: its blocks and picks as the post's body, opened in the post's editor to finish. Under it, Recipients exports organization contacts as a mailing list (NewsletterRecipients.tsx), for editors and up. 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 { Article, Check, Copy, DotsSixVertical, DownloadSimple, FloppyDisk, Trash } from '@phosphor-icons/react' import { useEffect, useMemo, useRef, useState } from 'react' import { useNavigate } from 'react-router-dom' 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, BLOCK_TYPES } from '../../lib/adminSchema/shared.ts' import { Repeater } from '../../components/admin/fields.tsx' import NewsletterRecipients from '../../components/admin/NewsletterRecipients.tsx' 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 { STORED_PALETTE } from '../../lib/color.ts' import { PLATFORMS } from '../../lib/platforms.ts' import { SOCIAL_LINKS } from '../../data/socialLinks.ts' import { DEFAULT_TITLE, newsletterHtml, newsletterText, newsletterTitle, PICK_DEFAULTS, type NewsletterItem, type NewsletterPart, type PickSource, } 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 } type DraftRow = { id: number; title?: string | null; updated_at: 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'] /* 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.'], ['social', 'Social bar', "A colored band of the site's social icons, each linked."], ['countdown', 'Event countdown', "The time left until an event, as a picture the site draws each time the email is opened, with a line under it for when pictures don't load. Gmail may keep the time of the first open."], ...(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, and the one stored, not a color blind mode's swap (color.ts). */ const SHADES = ['', ', darkest', ', light', ', lightest'] const PALETTE_OPTIONS = Object.entries(STORED_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 = { events: 'Upcoming events', posts: 'Blog posts', cards: 'Front page featured cards' } const ITEM_LABEL: Record = { 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', 'social', 'countdown']), { path: 'event', label: 'Event', widget: 'select', optionsFrom: 'countdownEvents', required: true, when: { path: 'type', value: 'countdown' }, help: 'Upcoming events with a date; a series has no one start to count to', }, { path: 'text', label: 'Words above', when: { path: 'type', value: 'countdown' }, help: "Default: the event's title" }, { 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: 'socials', label: 'Links', addLabel: 'Add link', note: `None added: the site's own (${SOCIAL_LINKS.map((link) => link.label).join(', ')}).`, when: { path: 'type', value: 'social' }, title: (row: { platform?: string; url?: string }) => PLATFORMS.find((p) => p.id === row.platform)?.label ?? 'New link', blank: { platform: '', url: '' }, fields: [ { path: 'platform', label: 'Platform', widget: 'select', options: PLATFORMS.map((p) => [p.id, p.label]), required: true }, { path: 'url', label: 'Link', required: true, help: 'eg. https://www.instagram.com/nextgenerationunity/' }, ], }, { 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)) 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 } 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('full') const navigate = useNavigate() const { user } = useAuth() const [parts, setParts] = useState(STARTER) const [posts, setPosts] = useState(null) const [postDetails, setPostDetails] = useState>({}) const [copied, setCopied] = useState<'html' | 'text' | null>(null) // The draft being edited: null is a new one, not saved yet. const [drafts, setDrafts] = useState([]) 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 ?? [] useEffect(() => { get('/admin/blog_posts?is_published=1&is_listed=1&limit=200', { ttl: 0 }) .then((data: { rows: PostRow[] }) => setPosts(data.rows)) .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 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) setParts(layout) } 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: parts.find((part) => part.type === 'title')?.text?.trim() || '', layout: JSON.stringify(parts), } 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) } } // 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() 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.photo), href: siteUrl(eventHref(event.id)), cta: PICK_DEFAULTS.events.cta, }) } const byPost = new Map() 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() 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> }, [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 }] : [] }), countdownEvents: events .filter((event) => !event.is_series && event.starts_on) .map((event) => ({ id: event.id, label: [event.title, event.date_label].filter(Boolean).join(', ') })), }), [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 }] : [] }), eventFor: (id: string) => { const event = events.find((row) => row.id === id && !row.is_series && row.starts_on) return event ? { title: event.title, starts_on: event.starts_on, href: siteUrl(eventHref(event.id)) } : null }, now: Date.now(), defaultSocials: SOCIAL_LINKS.map((link) => ({ platform: link.platform, url: link.href })), origin: SITE_ORIGIN, siteName: SITE_NAME, absolute: absoluteFor, } return { content, html: newsletterHtml(content), text: newsletterText(content) } }, [parts, lookup, events]) /* 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 = newsletterTitle(newsletter.content) const id = `${slugify(postTitle).slice(0, 52) || 'newsletter'}-${new Date().toISOString().slice(0, 10)}` 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: items.map((item) => ({ text: item.title, detail: [item.meta, item.text].filter(Boolean).join('\n\n') || null, url: item.href, media: item.image ?? null, })), }, ] } if (!EMAIL_BLOCKS.includes(part.type)) return [] const { align: _align, color: _color, size: _size, space: _space, socials: _socials, event: _event, ...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, is_published: false, content_blocks: body.map((block) => ({ ...block, slot: '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) } } 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) } const empty = parts.length === 0 const split = usePreviewWidth() return (

Newsletter

Build the email part by part, then copy it into Mailchimp, Gmail or Church Center.

{canWrite(user) && ( <> )} {draft && canDelete(user) && ( )} {message && (

{message.text}

)}
{/* The editor takes what the preview leaves; the handle between them sets the preview's width (from lg up). */}

{eventsLoading || posts === null ? 'Loading what can be picked…' : 'Picked items show once chosen; a section with none is left out.'}

{empty ? 'Add a part to build the email.' : 'In Mailchimp, paste the HTML into a Code block or "Paste in code".'}