- People tags (062): Data → People tags (Musicians seeded); a person's Directories repeater tags them and their Specialty line shows on their tile. A People directory section preset shows a tag's first 12 and links to its full page, /directory/<tag>, with page meta and a sitemap entry. Tiles' details panels show a person's links. - Ministries (063): a new organization kind. A group picks its ministry and its page says "Ministry: <name>", linked to the ministry's website. Ministries have no public page, list, sitemap or timeline entry, and aren't offered where a record links to its organization. organizations is rebuilt for the kind CHECK. - Organization contacts (064): Data → Contact types; a private Contacts repeater on each organization (editors and up, readRole on a child collection). Tools → Newsletter → Recipients filters them by type, kind, region and published and downloads a Mailchimp CSV. - A trigger refusing a save with a sentence is shown as that message. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
682 lines
29 KiB
TypeScript
682 lines
29 KiB
TypeScript
/* ═══════════════════════════════════════════════════════════════
|
||
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<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', '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<NewsletterPart[]>(STARTER)
|
||
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 ?? []
|
||
|
||
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<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.photo),
|
||
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 }] : []
|
||
}),
|
||
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 (
|
||
<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 }}>
|
||
Build the email part by part, then copy it into Mailchimp, Gmail or Church Center.
|
||
</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 || DEFAULT_TITLE(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 || empty}>
|
||
<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>
|
||
|
||
{/* The editor takes what the preview leaves; the handle between
|
||
them sets the preview's width (from lg up). */}
|
||
<div
|
||
ref={split.ref}
|
||
className="mt-6 grid gap-8 lg:grid-cols-[minmax(0,1fr)_auto_var(--preview-width)] lg:gap-3"
|
||
style={{ '--preview-width': `${split.width}px` } as React.CSSProperties}
|
||
>
|
||
<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
|
||
role="separator"
|
||
aria-orientation="vertical"
|
||
aria-label="Resize the parts and the preview"
|
||
aria-valuemin={PREVIEW_MIN}
|
||
aria-valuemax={split.max}
|
||
aria-valuenow={split.width}
|
||
tabIndex={0}
|
||
onPointerDown={split.start}
|
||
onPointerMove={split.drag}
|
||
onPointerUp={split.end}
|
||
onPointerCancel={split.end}
|
||
onKeyDown={split.key}
|
||
className="hidden cursor-col-resize touch-none items-start justify-center self-stretch border-x border-brand/20 bg-tint-soft px-0.5 pt-6 text-muted hover:bg-tint hover:text-link focus-visible:bg-tint focus-visible:text-link lg:flex"
|
||
>
|
||
<DotsSixVertical size={16} weight="bold" aria-hidden="true" className="lg:sticky lg:top-1/2" />
|
||
</div>
|
||
|
||
<div className="min-w-0">
|
||
<div className="flex flex-wrap gap-3">
|
||
<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={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={empty}>
|
||
<DownloadSimple weight="bold" aria-hidden="true" />
|
||
Download .html
|
||
</button>
|
||
</div>
|
||
<p className="mt-2 text-xs" style={{ color: MUTED }}>
|
||
{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-[80vh] w-full border border-brand/20 bg-white lg:sticky lg:top-24"
|
||
/>
|
||
</div>
|
||
</div>
|
||
|
||
{canWrite(user) && <NewsletterRecipients />}
|
||
</div>
|
||
)
|
||
}
|
||
|
||
/* ── The handle between the parts and the preview ─────────────
|
||
Drag it, or focus it and use the arrow keys (Home and End for
|
||
the narrowest and widest). Under the email's 600px the preview
|
||
shows it as a phone would. The width is remembered in this
|
||
browser, a convenience only. */
|
||
|
||
const PREVIEW_MIN = 320
|
||
const PARTS_MIN = 360 // what the parts list keeps, at least
|
||
const PREVIEW_DEFAULT = 672
|
||
const PREVIEW_KEY = 'site-newsletter-preview-width'
|
||
const STEP = 32
|
||
|
||
function usePreviewWidth() {
|
||
const ref = useRef<HTMLDivElement>(null)
|
||
const [room, setRoom] = useState(0)
|
||
const [wanted, setWanted] = useState(() => {
|
||
try {
|
||
const saved = Number(window.localStorage.getItem(PREVIEW_KEY))
|
||
return saved >= PREVIEW_MIN ? saved : PREVIEW_DEFAULT
|
||
} catch {
|
||
return PREVIEW_DEFAULT
|
||
}
|
||
})
|
||
|
||
// The row's width, so the widest the preview can be follows the window.
|
||
useEffect(() => {
|
||
const row = ref.current
|
||
if (!row) return undefined
|
||
const observer = new ResizeObserver(() => setRoom(row.clientWidth))
|
||
observer.observe(row)
|
||
return () => observer.disconnect()
|
||
}, [])
|
||
|
||
const max = Math.max(PREVIEW_MIN, room ? room - PARTS_MIN : PREVIEW_DEFAULT)
|
||
const width = Math.min(max, Math.max(PREVIEW_MIN, wanted))
|
||
|
||
const set = (next: number) => {
|
||
const clamped = Math.round(Math.min(max, Math.max(PREVIEW_MIN, next)))
|
||
setWanted(clamped)
|
||
try {
|
||
window.localStorage.setItem(PREVIEW_KEY, String(clamped))
|
||
} catch {
|
||
// Storage off: the width lasts until the page is left.
|
||
}
|
||
}
|
||
|
||
return {
|
||
ref,
|
||
width,
|
||
max,
|
||
start: (e: React.PointerEvent<HTMLDivElement>) => e.currentTarget.setPointerCapture(e.pointerId),
|
||
drag: (e: React.PointerEvent<HTMLDivElement>) => {
|
||
if (!e.currentTarget.hasPointerCapture(e.pointerId) || !ref.current) return
|
||
set(ref.current.getBoundingClientRect().right - e.clientX - e.currentTarget.offsetWidth / 2)
|
||
},
|
||
end: (e: React.PointerEvent<HTMLDivElement>) => {
|
||
if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId)
|
||
},
|
||
key: (e: React.KeyboardEvent<HTMLDivElement>) => {
|
||
// Left widens the preview (the handle moves left), Right narrows it.
|
||
const next = { ArrowLeft: width + STEP, ArrowRight: width - STEP, Home: PREVIEW_MIN, End: max }[e.key]
|
||
if (next === undefined) return
|
||
e.preventDefault()
|
||
set(next)
|
||
},
|
||
}
|
||
}
|