diff --git a/server/src/admin-crud.js b/server/src/admin-crud.js index a8ae9a7..d7afa70 100644 --- a/server/src/admin-crud.js +++ b/server/src/admin-crud.js @@ -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); diff --git a/server/src/admin-schema.js b/server/src/admin-schema.js index 7ed9db7..5bca3db 100644 --- a/server/src/admin-schema.js +++ b/server/src/admin-schema.js @@ -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 ────────────────────── */ diff --git a/server/src/admin-schema/newsletters.js b/server/src/admin-schema/newsletters.js new file mode 100644 index 0000000..be6d58d --- /dev/null +++ b/server/src/admin-schema/newsletters.js @@ -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")], +}; diff --git a/server/src/migrations/057_newsletters.sql b/server/src/migrations/057_newsletters.sql new file mode 100644 index 0000000..708889d --- /dev/null +++ b/server/src/migrations/057_newsletters.sql @@ -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; diff --git a/src/components/Layout.tsx b/src/components/Layout.tsx index e5b42a6..f930891 100644 --- a/src/components/Layout.tsx +++ b/src/components/Layout.tsx @@ -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. */}
{PAGE_LINKS.map((page) => { - const pageSections = sectionsOf(page.path); + const pageSections = page.path === "/" ? [] : sectionsOf(page.path); return (
+} + 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, '&').replace(//g, '>').replace(/"/g, '"') -/* 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(/&/g, '&'), n) + return url ? `${label}` : label + }) + .replace(/\*\*([^*]+)\*\*/g, '$1') + .replace(/\*([^*]+)\*/g, '$1') +} + +/* 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) => `

${escape(part).replace(/\n/g, '
')}

`) + .map((part) => `

${(n ? inline(part, n) : escape(part)).replace(/\n/g, '
')}

`) .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) => + `${escape(label)}` + +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 + ? `

${escape(text)}

` + : '' + case 'subheading': + return text + ? `

${escape(text)}

` + : '' + case 'paragraph': + return text ? paragraphs(text, TEXT, n) : '' + case 'callout': + return text ? `
${paragraphs(text, TEXT, n)}
` : '' + case 'quote': + return text + ? `
${paragraphs(text, `${TEXT}font-style:italic;`, n)}${ + block.cite ? `

${escape(block.cite)}

` : '' + }
` + : '' + case 'list': + return items.length + ? `
    ${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 `
  • ${url ? `${label}` : label}${detail}
  • ` + }) + .join('')}
` + : '' + 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 ? `

${buttons}

` : '' + } + case 'button': + return href && text ? `

${buttonHtml(href, text)}

` : '' + case 'image': + case 'video': { + if (!block.media) return '' + const img = `${escape(block.alt ?? '')}` + const caption = text + ? `

${escape(text)}

` + : '' + return `
${href ? `${img}` : img}${caption}
` + } + case 'cards': + return items + .map((item) => { + const url = item.url ? safeHref(item.url, n) : null + if (!url || !item.text) return '' + return `
+

${escape(item.text)}

+ ${item.detail ? paragraphs(item.detail, TEXT) : ''}
` + }) + .join('') + case 'divider': + return `
` + 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)}
${escape(n.origin.replace(/^https?:\/\//, ''))}` + function itemHtml(item: NewsletterItem): string { const image = item.image ? `` @@ -116,11 +274,12 @@ export function newsletterHtml(n: Newsletter): string { ${logo}

${escape(n.title)}

- ${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('')} ${sections} - ${escape(n.siteName)}
${escape(n.origin.replace(/^https?:\/\//, ''))} + ${footerHtml(n)} @@ -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') } diff --git a/src/pages/admin/AdminNewsletter.tsx b/src/pages/admin/AdminNewsletter.tsx index 069f42d..bdd3505 100644 --- a/src/pages/admin/AdminNewsletter.tsx +++ b/src/pages/admin/AdminNewsletter.tsx @@ -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([]) const [pickedEvents, setPickedEvents] = useState>(new Set()) const [pickedPosts, setPickedPosts] = useState>(new Set()) - const [pickedCards, setPickedCards] = useState>(new Set()) + // Cards by their link: the front page's cards can be reordered + // between one save and the next. + const [pickedCards, setPickedCards] = useState>(new Set()) 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 ?? [] @@ -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() {

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

+ {message.text} +

+ )} +
+
@@ -188,6 +400,10 @@ export default function AdminNewsletter() {
+
+ +
+ ({ 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)} /> + +
+