Page updates: v1.10.3 to v1.10.6 #20

Merged
ngu-git-admin merged 19 commits from page-updates into main 2026-10-01 09:23:31 +01:00
4 changed files with 446 additions and 0 deletions
Showing only changes of commit 2a926971f7 - Show all commits

View file

@ -80,6 +80,7 @@ const AdminHome = lazyPage(() => import("./pages/admin/AdminHome.tsx"))
const AdminFeedback = lazyPage(() => import("./pages/admin/AdminFeedback.tsx")) const AdminFeedback = lazyPage(() => import("./pages/admin/AdminFeedback.tsx"))
const AdminMedia = lazyPage(() => import("./pages/admin/AdminMedia.tsx")) const AdminMedia = lazyPage(() => import("./pages/admin/AdminMedia.tsx"))
const AdminClips = lazyPage(() => import("./pages/admin/AdminClips.tsx")) const AdminClips = lazyPage(() => import("./pages/admin/AdminClips.tsx"))
const AdminNewsletter = lazyPage(() => import("./pages/admin/AdminNewsletter.tsx"))
const EntityList = lazyPage(() => import("./pages/admin/EntityList.tsx")) const EntityList = lazyPage(() => import("./pages/admin/EntityList.tsx"))
const EntityEdit = lazyPage(() => import("./pages/admin/EntityEdit.tsx")) const EntityEdit = lazyPage(() => import("./pages/admin/EntityEdit.tsx"))
@ -133,6 +134,7 @@ export default function App() {
<Route path="data-requests" element={<AdminFeedback kind="privacy" />} /> <Route path="data-requests" element={<AdminFeedback kind="privacy" />} />
<Route path="requests" element={<AdminFeedback kind="content" />} /> <Route path="requests" element={<AdminFeedback kind="content" />} />
<Route path="media" element={<AdminMedia />} /> <Route path="media" element={<AdminMedia />} />
<Route path="newsletter" element={<AdminNewsletter />} />
<Route element={<RequireRole role="admin" />}> <Route element={<RequireRole role="admin" />}>
<Route path="clips" element={<AdminClips />} /> <Route path="clips" element={<AdminClips />} />
</Route> </Route>

147
src/lib/newsletter.ts Normal file
View file

@ -0,0 +1,147 @@
/* ═══════════════════════════════════════════════════════════════
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.
Email clients ignore stylesheets, CSS variables and most layout,
so the HTML is tables with inline styles at 600px, images with
width and alt, and the palette written out as hex (the one place
the site's colors are literals: an inbox has no theme tokens). A
plain-text copy goes alongside for clients that show no HTML.
═══════════════════════════════════════════════════════════════ */
export type NewsletterItem = {
title: string
/** A line under the title: dates and place, a byline. */
meta?: string | null
text?: string | null
/** An absolute image URL. */
image?: string | null
/** An absolute link. */
href: string
cta: string
}
export type NewsletterSection = { heading: string; items: NewsletterItem[] }
export type Newsletter = {
title: string
intro?: string | null
sections: NewsletterSection[]
/** 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
}
/* The palette as an inbox needs it. */
const COLOR = {
ink: '#001011',
body: '#003a45',
muted: '#3b5456',
teal: '#00748a',
page: '#f5f9f8',
card: '#ffffff',
rule: '#d6f5fa',
}
const FONT = "'Poppins', Helvetica, Arial, sans-serif"
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) =>
text
.split(/\n\s*\n/)
.map((part) => part.trim())
.filter(Boolean)
.map((part) => `<p style="${style}">${escape(part).replace(/\n/g, '<br>')}</p>`)
.join('')
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>`
: ''
const meta = item.meta
? `<p style="margin:4px 0 0;font-family:${BODY_FONT};font-size:14px;line-height:20px;color:${COLOR.muted};">${escape(item.meta)}</p>`
: ''
const text = item.text
? paragraphs(item.text, `margin:12px 0 0;font-family:${BODY_FONT};font-size:15px;line-height:24px;color:${COLOR.body};`)
: ''
return `
<tr><td style="padding:0 24px 24px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:${COLOR.card};border-left:4px solid ${COLOR.teal};">
${image}
<tr><td style="padding:20px 24px 24px;">
<h3 style="margin:0;font-family:${FONT};font-size:20px;line-height:26px;font-weight:700;color:${COLOR.ink};"><a href="${escape(item.href)}" style="color:${COLOR.ink};text-decoration:none;">${escape(item.title)}</a></h3>
${meta}${text}
<p style="margin:16px 0 0;"><a href="${escape(item.href)}" style="display:inline-block;padding:10px 20px;border-radius:8px;background:${COLOR.teal};color:#ffffff;font-family:${FONT};font-size:14px;font-weight:700;text-decoration:none;">${escape(item.cta)}</a></p>
</td></tr>
</table>
</td></tr>`
}
export function newsletterHtml(n: Newsletter): string {
const sections = n.sections
.filter((section) => section.items.length > 0)
.map(
(section) => `
<tr><td style="padding:16px 24px 12px;">
<h2 style="margin:0;padding-bottom:8px;border-bottom:2px solid ${COLOR.rule};font-family:${FONT};font-size:22px;line-height:28px;font-weight:700;color:${COLOR.teal};">${escape(section.heading)}</h2>
</td></tr>${section.items.map(itemHtml).join('')}`,
)
.join('')
const logo = n.logo
? `<a href="${escape(n.origin)}"><img src="${escape(n.logo)}" height="48" alt="${escape(n.siteName)}" style="display:block;height:48px;width:auto;border:0;"></a>`
: `<a href="${escape(n.origin)}" style="font-family:${FONT};font-size:18px;font-weight:700;color:#ffffff;text-decoration:none;">${escape(n.siteName)}</a>`
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${escape(n.title)}</title>
</head>
<body style="margin:0;padding:0;background:${COLOR.page};">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:${COLOR.page};">
<tr><td align="center" style="padding:24px 12px;">
<table role="presentation" width="600" cellpadding="0" cellspacing="0" style="width:100%;max-width:600px;background:${COLOR.page};">
<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};`) : ''}
</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>
</td></tr>
</table>
</td></tr>
</table>
</body>
</html>`
}
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 section of n.sections) {
if (section.items.length === 0) continue
lines.push(section.heading.toUpperCase(), '')
for (const item of section.items) {
lines.push(item.title)
if (item.meta) lines.push(item.meta)
if (item.text) lines.push(item.text.trim())
lines.push(`${item.cta}: ${item.href}`, '')
}
}
lines.push('--', n.siteName, n.origin)
return lines.join('\n')
}

View file

@ -0,0 +1,292 @@
/* ═══════════════════════════════════════════════════════════════
NEWSLETTER (Tools)
Builds an email newsletter from what's already on the site: tick
upcoming events, published blog posts and the front page's
featured cards, write a title and an intro, and copy the result,
email-ready HTML or plain text, into Mailchimp, Gmail or Church
Center (or download it as a file). Nothing is sent or saved here;
the builder is src/lib/newsletter.ts.
Picked blog posts are read from their public pages, so only a
post visitors can open makes it in, with its excerpt and cover.
Links and images are the live site's (SITE_ORIGIN), since an
email is read far from this admin.
═══════════════════════════════════════════════════════════════ */
import { Check, Copy, DownloadSimple } from '@phosphor-icons/react'
import { useEffect, useMemo, useState } from 'react'
import { get } from '../../lib/api.ts'
import { useEvents } from '../../lib/eventData.ts'
import { useFrontPage, type FeaturedCard } from '../../lib/useFrontPage.ts'
import type { BlogPostRecord } from '../../lib/useBlog.ts'
import { blogHref, eventHref, refHref } from '../../lib/hrefs.ts'
import { mediaUrl } from '../../lib/media.ts'
import { SITE_NAME, SITE_ORIGIN, siteUrl } from '../../lib/site.ts'
import { seriesLabel } from '../../lib/eventSeries.ts'
import { useWideAdminPage } from '../../lib/adminWidth.tsx'
import { newsletterHtml, newsletterText, type NewsletterItem } from '../../lib/newsletter.ts'
const MUTED = 'var(--color-muted)'
const input =
'w-full border border-muted/25 bg-surface px-3 py-2 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25'
const button =
'btn inline-flex items-center gap-2 border border-brand px-4 py-2 text-sm text-link transition-colors hover:bg-tint disabled:opacity-50'
/* An address on the live site, whatever it started as. */
const absolute = (path: string | null | undefined) => (path ? siteUrl(path) : null)
const imageFor = (file: string | null | undefined) => absolute(mediaUrl(file))
type PostRow = { id: string; title: string; published_on?: string | null; is_published: number; is_listed: number }
function featuredHref(card: FeaturedCard): string | null {
if (card.kind === 'record' && card.ref) return refHref(card.ref.kind, card.ref.id, card.ref.org_kind)
return card.url
}
export default function AdminNewsletter() {
useWideAdminPage()
const [title, setTitle] = useState('')
const [intro, setIntro] = useState('')
const [pickedEvents, setPickedEvents] = useState<Set<string>>(new Set())
const [pickedPosts, setPickedPosts] = useState<Set<string>>(new Set())
const [pickedCards, setPickedCards] = useState<Set<number>>(new Set())
const [posts, setPosts] = useState<PostRow[] | null>(null)
const [postDetails, setPostDetails] = useState<Record<string, BlogPostRecord>>({})
const [copied, setCopied] = useState<'html' | 'text' | null>(null)
const { events, loading: eventsLoading } = useEvents({ status: 'upcoming' })
const { data: frontPage } = useFrontPage()
const cards = frontPage?.featured ?? []
useEffect(() => {
get('/admin/blog_posts?limit=200', { ttl: 0 })
.then((data: { rows: PostRow[] }) => setPosts(data.rows.filter((row) => row.is_published && row.is_listed)))
.catch(() => setPosts([]))
}, [])
// A picked post's public page: its excerpt and cover, and proof it's live.
useEffect(() => {
for (const id of pickedPosts) {
if (postDetails[id]) continue
get(`/blog/${encodeURIComponent(id)}`)
.then((data: { post: BlogPostRecord }) => setPostDetails((current) => ({ ...current, [id]: data.post })))
.catch(() => {})
}
}, [pickedPosts, postDetails])
const toggle = <T,>(set: Set<T>, value: T, update: (next: Set<T>) => void) => {
const next = new Set(set)
if (next.has(value)) next.delete(value)
else next.add(value)
update(next)
}
const newsletter = useMemo(() => {
const eventItems: NewsletterItem[] = events
.filter((event) => pickedEvents.has(event.id))
.map((event) => ({
title: event.title,
meta: [seriesLabel(event.series, event.starts_on) ?? event.date_label, event.is_online && !event.location_label ? 'Online' : event.location_label]
.filter(Boolean)
.join(', '),
text: event.tagline ?? event.description?.[0] ?? null,
image: imageFor(event.card_image),
href: siteUrl(eventHref(event.id)),
cta: 'Event details',
}))
const postItems: NewsletterItem[] = (posts ?? [])
.filter((row) => pickedPosts.has(row.id) && postDetails[row.id])
.map((row) => {
const post = postDetails[row.id]
const byline = post.authors.map((a) => a.name).concat(post.guest ? [post.guest.name] : []).join(', ')
return {
title: post.title,
meta: byline ? `By ${byline}` : null,
text: post.excerpt ?? null,
image: imageFor(post.cover_image),
href: siteUrl(blogHref(post.id)),
cta: 'Read the post',
}
})
const cardItems: NewsletterItem[] = cards
.map((card, index) => ({ card, index, href: featuredHref(card) }))
.filter(({ index, href }) => pickedCards.has(index) && href)
.map(({ card, href }) => ({
title: card.title ?? 'Featured',
meta: card.eyebrow ?? null,
text: card.blurb ?? null,
image: card.image ? imageFor(card.image.file) : null,
href: absolute(href) ?? href!,
cta: card.kind === 'video' ? 'Watch' : 'Learn more',
}))
const content = {
title: title.trim() || `News from ${SITE_NAME}`,
intro: intro.trim() || null,
origin: SITE_ORIGIN,
siteName: SITE_NAME,
// The site's logo is an SVG, which Gmail and Outlook don't show,
// so the header is the site name in type. A PNG logo could go here.
logo: null,
sections: [
{ heading: 'Coming up', items: eventItems },
{ heading: 'From the blog', items: postItems },
{ heading: 'Featured', items: cardItems },
],
}
return { html: newsletterHtml(content), text: newsletterText(content), count: eventItems.length + postItems.length + cardItems.length }
}, [title, intro, events, pickedEvents, posts, pickedPosts, postDetails, cards, pickedCards])
async function copy(kind: 'html' | 'text') {
try {
await navigator.clipboard.writeText(kind === 'html' ? newsletter.html : newsletter.text)
setCopied(kind)
window.setTimeout(() => setCopied(null), 2000)
} catch {
setCopied(null)
}
}
function download() {
const blob = new Blob([newsletter.html], { type: 'text/html' })
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = `newsletter-${new Date().toISOString().slice(0, 10)}.html`
link.click()
URL.revokeObjectURL(link.href)
}
return (
<div>
<div className="flex flex-wrap items-baseline gap-3">
<h1 className="text-2xl font-bold text-link">Newsletter</h1>
<p className="text-sm" style={{ color: MUTED }}>
Pick what to include, then copy the email into Mailchimp, Gmail or Church Center.
</p>
</div>
<div className="mt-6 grid gap-8 lg:grid-cols-[minmax(0,26rem)_minmax(0,1fr)]">
<div className="space-y-6">
<section className="space-y-3 border-l-4 border-brand bg-raised p-5 shadow-sm">
<label className="block text-sm font-semibold text-body">
Title
<input value={title} onChange={(e) => setTitle(e.target.value)} placeholder={`News from ${SITE_NAME}`} className={`mt-1 ${input}`} />
</label>
<label className="block text-sm font-semibold text-body">
Intro
<textarea
value={intro}
onChange={(e) => setIntro(e.target.value)}
rows={4}
placeholder="eg. A few things coming up this month…"
className={`mt-1 resize-y ${input}`}
/>
</label>
</section>
<PickList
title="Upcoming events"
empty={eventsLoading ? 'Loading…' : 'No upcoming events.'}
options={events.map((event) => ({ value: event.id, label: event.title, detail: event.date_label }))}
picked={pickedEvents}
onToggle={(value) => toggle(pickedEvents, value, setPickedEvents)}
/>
<PickList
title="Blog posts"
empty={posts ? 'No published posts.' : 'Loading…'}
options={(posts ?? []).map((post) => ({ value: post.id, label: post.title, detail: post.published_on }))}
picked={pickedPosts}
onToggle={(value) => toggle(pickedPosts, value, setPickedPosts)}
/>
<PickList
title="Featured cards (front page)"
empty="No featured cards."
options={cards.map((card, index) => ({ value: index, label: card.title ?? card.url ?? 'Card', detail: card.kind }))}
picked={pickedCards}
onToggle={(value) => toggle(pickedCards, value, setPickedCards)}
/>
</div>
<div>
<div className="flex flex-wrap gap-3">
<button type="button" onClick={() => copy('html')} className={button} disabled={newsletter.count === 0}>
{copied === 'html' ? <Check weight="bold" aria-hidden="true" /> : <Copy weight="bold" aria-hidden="true" />}
{copied === 'html' ? 'Copied' : 'Copy HTML'}
</button>
<button type="button" onClick={() => copy('text')} className={button} disabled={newsletter.count === 0}>
{copied === 'text' ? <Check weight="bold" aria-hidden="true" /> : <Copy weight="bold" aria-hidden="true" />}
{copied === 'text' ? 'Copied' : 'Copy plain text'}
</button>
<button type="button" onClick={download} className={button} disabled={newsletter.count === 0}>
<DownloadSimple weight="bold" aria-hidden="true" />
Download .html
</button>
</div>
<p className="mt-2 text-xs" style={{ color: MUTED }}>
{newsletter.count === 0
? 'Tick at least one item to build the email.'
: `${newsletter.count} item${newsletter.count === 1 ? '' : 's'}. In Mailchimp, paste the HTML into a Code block or "Paste in code".`}
</p>
<iframe
title="Newsletter preview"
srcDoc={newsletter.html}
sandbox=""
className="mt-4 h-[70vh] w-full border border-brand/20 bg-white"
/>
</div>
</div>
</div>
)
}
function PickList<T extends string | number>({
title,
empty,
options,
picked,
onToggle,
}: {
title: string
empty: string
options: Array<{ value: T; label: string; detail?: string | null }>
picked: Set<T>
onToggle: (value: T) => void
}) {
return (
<section className="border-l-4 border-brand bg-raised p-5 shadow-sm">
<h2 className="text-base font-bold text-ink">{title}</h2>
{options.length === 0 ? (
<p className="mt-2 text-sm" style={{ color: MUTED }}>
{empty}
</p>
) : (
<ul className="mt-2 max-h-72 space-y-1 overflow-y-auto">
{options.map((option) => (
<li key={String(option.value)}>
<label className="flex cursor-pointer items-start gap-3 px-2 py-1.5 hover:bg-tint-soft">
<input
type="checkbox"
checked={picked.has(option.value)}
onChange={() => onToggle(option.value)}
className="mt-1 h-4 w-4 accent-[var(--color-action)]"
/>
<span className="min-w-0">
<span className="block text-sm text-ink">{option.label}</span>
{option.detail && (
<span className="block text-xs" style={{ color: MUTED }}>
{option.detail}
</span>
)}
</span>
</label>
</li>
))}
</ul>
)}
</section>
)
}

View file

@ -148,6 +148,11 @@ export const TOOLS_NAV = {
blurb: "Cut clips from our YouTube and Facebook videos: trimmed, reshaped for Reels, or audio only.", blurb: "Cut clips from our YouTube and Facebook videos: trimmed, reshaped for Reels, or audio only.",
minRole: "admin", minRole: "admin",
}, },
{
to: "/admin/newsletter",
label: "Newsletter",
blurb: "An email newsletter from upcoming events, blog posts and featured cards, ready to paste into Mailchimp or Gmail.",
},
{ {
to: "/qr", to: "/qr",
label: "QR code generator", label: "QR code generator",