diff --git a/CLAUDE.md b/CLAUDE.md index 3e95d37..24281e0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -34,7 +34,6 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`. - Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html), with Panel → Site settings (the `site_settings` table) laid over site.json, and serves `/robots.txt` from the same merge. nginx setup: `docs/seo.md`. - Video clips (Tools, admins and up): yt-dlp downloads our YouTube/Facebook videos into `CLIPS_DIR`, ffmpeg cuts them; one job at a time, files swept after a day (`server/src/clips.js`). Needs yt-dlp and ffmpeg on the VPS: `docs/video-clips.md`. -- Newsletter countdown pictures: `/api/countdown/:id.png` (`server/src/routes/countdown.js`), drawn with sharp when an email is opened; it uses the VPS's fonts, so install Poppins there (eg. into `/usr/local/share/fonts`, then `fc-cache`) or it falls back to a plain sans. The social bar's icons are static files in `public/email/`. - Word import: Blog posts → Import from Word turns a .docx into an unpublished post (headings, paragraphs, lists, tables, links); nginx needs a block for `/api/admin/import/docx` with an 11m body limit: `docs/importing.md`. - Speed: nginx must gzip JS/CSS/JSON/SVG and speak HTTP/2; page HTML is `no-cache`; uploads get a `-640.webp` small copy made at upload and at boot: `docs/performance.md`. - Security headers: the API sends them (Hono `secureHeaders()`, plus a CSRF check on `/api` writes); nginx sends HSTS on everything and must pass `Host` and `X-Forwarded-For` to the API: `docs/security-headers.md`. diff --git a/docs/updating-data-in-code.md b/docs/updating-data-in-code.md index 2866be8..7798117 100644 --- a/docs/updating-data-in-code.md +++ b/docs/updating-data-in-code.md @@ -285,7 +285,6 @@ The numbers band's "Number Source" dropdown works the same way: | Organization kind labels ("Region", "Group") | the Kind options in `src/lib/adminSchema/organizations.ts` (admin); `orgListHref` in `src/lib/hrefs.ts` (the public back link, "All regions") | | | Admin account roles | `src/lib/roles.ts` (labels, notes) and `ROLES` in `server/src/auth.js` | Adding a role is also a CHECK change on `admin_users.role`. | | Admin navigation | `src/pages/admin/adminNav.ts` | | -| Newsletter parts and their defaults (Tools → Newsletter) | `PARTS_SPEC`, `PART_TYPES` and `STARTER` in `src/pages/admin/AdminNewsletter.tsx`; `PICK_DEFAULTS`, `DEFAULT_TITLE` and `COLOR` in `src/lib/newsletter.ts` | A draft is one JSON list of parts (`newsletters.layout`, 060), so adding a part or a setting needs no migration: a field in `PARTS_SPEC` and its drawing in `newsletter.ts`. The color choices are `PALETTE`; `COLOR` holds the defaults as hex, since an inbox has no theme tokens. `STARTER` is what a new draft starts with. The social bar's icons are PNGs in `public/email/` (Gmail and Outlook don't show SVG), made from `PlatformIcon.tsx` by `node scripts/email-icons.mjs`: run it again after adding a platform. A social bar with no links shows the footer's, `SOCIAL_LINKS` in `src/data/socialLinks.ts`. The countdown picture is `server/src/routes/countdown.js`, counting to local midnight in its `TIME_ZONE` (America/Chicago). | | The live site's address (used by QR codes) | `SITE_ORIGIN` in `src/lib/site.ts` | | | Version shown on the admin home page | `src/lib/version.ts` | | | Image directories (where logos and photos are looked up) | `src/lib/media.ts` | | diff --git a/public/email/discord-ink.png b/public/email/discord-ink.png deleted file mode 100644 index c9de1eb..0000000 Binary files a/public/email/discord-ink.png and /dev/null differ diff --git a/public/email/discord-white.png b/public/email/discord-white.png deleted file mode 100644 index 834dc30..0000000 Binary files a/public/email/discord-white.png and /dev/null differ diff --git a/public/email/facebook-ink.png b/public/email/facebook-ink.png deleted file mode 100644 index 6643b9a..0000000 Binary files a/public/email/facebook-ink.png and /dev/null differ diff --git a/public/email/facebook-white.png b/public/email/facebook-white.png deleted file mode 100644 index 4c33c97..0000000 Binary files a/public/email/facebook-white.png and /dev/null differ diff --git a/public/email/instagram-ink.png b/public/email/instagram-ink.png deleted file mode 100644 index f33c454..0000000 Binary files a/public/email/instagram-ink.png and /dev/null differ diff --git a/public/email/instagram-white.png b/public/email/instagram-white.png deleted file mode 100644 index 9460dbb..0000000 Binary files a/public/email/instagram-white.png and /dev/null differ diff --git a/public/email/linkedin-ink.png b/public/email/linkedin-ink.png deleted file mode 100644 index d57dcb5..0000000 Binary files a/public/email/linkedin-ink.png and /dev/null differ diff --git a/public/email/linkedin-white.png b/public/email/linkedin-white.png deleted file mode 100644 index 4ba8474..0000000 Binary files a/public/email/linkedin-white.png and /dev/null differ diff --git a/public/email/spotify-ink.png b/public/email/spotify-ink.png deleted file mode 100644 index 7badd18..0000000 Binary files a/public/email/spotify-ink.png and /dev/null differ diff --git a/public/email/spotify-white.png b/public/email/spotify-white.png deleted file mode 100644 index 45b17a4..0000000 Binary files a/public/email/spotify-white.png and /dev/null differ diff --git a/public/email/substack-ink.png b/public/email/substack-ink.png deleted file mode 100644 index 865e541..0000000 Binary files a/public/email/substack-ink.png and /dev/null differ diff --git a/public/email/substack-white.png b/public/email/substack-white.png deleted file mode 100644 index 185255c..0000000 Binary files a/public/email/substack-white.png and /dev/null differ diff --git a/public/email/tiktok-ink.png b/public/email/tiktok-ink.png deleted file mode 100644 index 240e2ff..0000000 Binary files a/public/email/tiktok-ink.png and /dev/null differ diff --git a/public/email/tiktok-white.png b/public/email/tiktok-white.png deleted file mode 100644 index 5491504..0000000 Binary files a/public/email/tiktok-white.png and /dev/null differ diff --git a/public/email/x-ink.png b/public/email/x-ink.png deleted file mode 100644 index 970812a..0000000 Binary files a/public/email/x-ink.png and /dev/null differ diff --git a/public/email/x-white.png b/public/email/x-white.png deleted file mode 100644 index 2be00ac..0000000 Binary files a/public/email/x-white.png and /dev/null differ diff --git a/public/email/youtube-ink.png b/public/email/youtube-ink.png deleted file mode 100644 index 2b9a18b..0000000 Binary files a/public/email/youtube-ink.png and /dev/null differ diff --git a/public/email/youtube-white.png b/public/email/youtube-white.png deleted file mode 100644 index dc59d9e..0000000 Binary files a/public/email/youtube-white.png and /dev/null differ diff --git a/scripts/email-icons.mjs b/scripts/email-icons.mjs deleted file mode 100644 index 20950b0..0000000 --- a/scripts/email-icons.mjs +++ /dev/null @@ -1,30 +0,0 @@ -/* ═══════════════════════════════════════════════════════════════ - EMAIL ICONS: node scripts/email-icons.mjs (from the repo root) - - Gmail and Outlook don't show SVG, so a newsletter's social bar - (src/lib/newsletter.ts) uses PNG copies of the platform icons in - PlatformIcon.tsx: white and ink, 48px square (shown at 24), into - public/email/, which the build copies as they are, so the files - keep their addresses in emails already sent. Run it again after - adding a platform or changing an icon. Uses the server's sharp. - ═══════════════════════════════════════════════════════════════ */ - -import { readFileSync, writeFileSync } from "node:fs"; -import { createRequire } from "node:module"; - -const sharp = createRequire(new URL("../server/package.json", import.meta.url))("sharp"); -const source = readFileSync(new URL("../src/components/PlatformIcon.tsx", import.meta.url), "utf8"); - -const paths = {}; -for (const [, id, d] of source.matchAll(/^\s*(\w+):\s*'([^']+)'/gm)) paths[id] = d; -for (const [, id, d] of source.matchAll(/^\s*(\w+):\s*\n\s*'([^']+)'/gm)) paths[id] = d; -paths.instagram = /INSTAGRAM_PATH =\s*'([^']+)'/.exec(source)[1]; - -const TONES = { white: "#ffffff", ink: "#001011" }; -for (const [id, d] of Object.entries(paths)) { - for (const [tone, fill] of Object.entries(TONES)) { - const svg = ``; - writeFileSync(new URL(`../public/email/${id}-${tone}.png`, import.meta.url), await sharp(Buffer.from(svg)).png().toBuffer()); - } -} -console.log(`${Object.keys(paths).length} icons: ${Object.keys(paths).join(", ")}`); diff --git a/server/src/admin-schema/newsletters.js b/server/src/admin-schema/newsletters.js index c083221..be6d58d 100644 --- a/server/src/admin-schema/newsletters.js +++ b/server/src/admin-schema/newsletters.js @@ -1,12 +1,11 @@ -import { text } from "./columns.js"; +import { text, blocksChild } from "./columns.js"; -/* ── Newsletter drafts (057, 060_newsletter_layout.sql) ───────── +/* ── 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. - `layout` is the builder's JSON list of parts, in order - (src/lib/newsletter.ts); `title` is the title part's text, kept - apart for the list of drafts. */ + `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", @@ -22,5 +21,7 @@ export const newsletters = { order: "updated_at DESC, id DESC", }, - columns: [text("title"), text("layout", { required: true })], + columns: [text("title"), text("intro"), text("footer"), text("picks")], + + children: [blocksChild("newsletter")], }; diff --git a/server/src/index.js b/server/src/index.js index 1014a53..7cd715b 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -39,7 +39,6 @@ import media from "./routes/media.js"; import clips from "./routes/clips.js"; import imports from "./routes/import.js"; import files from "./routes/files.js"; -import countdown from "./routes/countdown.js"; import { CLIPS_DIR, startClipWorker } from "./clips.js"; import { UPLOADS_DIR, writeMissingThumbs } from "./media.js"; import { logSafe, startSessionSweeper } from "./auth.js"; @@ -75,14 +74,6 @@ const app = new Hono(); // loop a synchronous write each. app.use("/api/admin/*", logger()); -/* A newsletter's countdown picture is shown inside other sites' - webmail, which the same-origin resource policy set below would - refuse. Registered first so it runs last, after secureHeaders. */ -app.use("/api/countdown/*", async (c, next) => { - await next(); - c.res.headers.set("Cross-Origin-Resource-Policy", "cross-origin"); -}); - /* Headers for every response. Referrer kept to the origin (YouTube embeds refuse to play without one). No HSTS here: nginx sends it on everything, including the files it serves from disk @@ -187,11 +178,6 @@ app.route("/api", home); app.route("/api", directory); app.route("/api", blog); app.route("/api", sitePages); -// Opened by everyone a newsletter goes to, often through one mail -// proxy's address, so looser than the rest; each picture is kept for -// its minute (routes/countdown.js). -app.use("/api/countdown/*", rateLimit({ windowMs: 60_000, max: 600 })); -app.route("/api", countdown); // Tighter limit on the write path than anything else gets. app.use("/api/feedback", rateLimit({ windowMs: 60_000, max: 5 })); diff --git a/server/src/migrations/060_newsletter_layout.sql b/server/src/migrations/060_newsletter_layout.sql deleted file mode 100644 index d6f9286..0000000 --- a/server/src/migrations/060_newsletter_layout.sql +++ /dev/null @@ -1,47 +0,0 @@ --- ═══════════════════════════════════════════════════════════════ --- 060 NEWSLETTER LAYOUT --- --- A newsletter is one ordered list of parts now, each movable and --- each with its own settings (src/lib/newsletter.ts reads them): --- the header band, the title, any email block, a section of picked --- events, posts or front page cards, and the footer. It's kept as --- JSON in `layout`, the builder's only editor. --- --- That replaces 057's fixed fields (intro, footer, picks) and the --- drafts' content_blocks. 057 never reached a live database, so --- there are no drafts to carry over: the table is rebuilt keeping --- each row's id, title and dates, and its blocks are deleted. --- `title` stays as its own column, for the list of drafts. --- ═══════════════════════════════════════════════════════════════ - -DELETE FROM content_blocks WHERE owner_kind = 'newsletter'; - -DROP TRIGGER newsletters_touch; -DROP TRIGGER newsletters_cleanup; - -CREATE TABLE newsletters_new ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - title TEXT, - layout TEXT NOT NULL DEFAULT '[]' CHECK (json_valid(layout) AND json_type(layout) = 'array'), - created_at TEXT NOT NULL DEFAULT (datetime('now')), - updated_at TEXT NOT NULL DEFAULT (datetime('now')) -) STRICT; - -INSERT INTO newsletters_new (id, title, created_at, updated_at) -SELECT id, title, created_at, updated_at FROM newsletters; - --- content_blocks_owner_exists names this table. -PRAGMA legacy_alter_table = ON; -DROP TABLE newsletters; -ALTER TABLE newsletters_new RENAME TO newsletters; -PRAGMA legacy_alter_table = OFF; - - --- ── 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; diff --git a/server/src/routes/countdown.js b/server/src/routes/countdown.js deleted file mode 100644 index abd0601..0000000 --- a/server/src/routes/countdown.js +++ /dev/null @@ -1,119 +0,0 @@ -/* ═══════════════════════════════════════════════════════════════ - COUNTDOWN IMAGE: GET /api/countdown/:id.png - - A newsletter's countdown block (src/lib/newsletter.ts) is this - picture: the time left until a published one-off event starts, - drawn when the email is opened, since an email can't run code. - Gmail fetches images once through its proxy and keeps them, so - there it shows the time of the first open; the block's fixed line - under the image covers that and clients that block images. - - ?bg=003a45 the band's color (hex, no #) - ?fg=ffffff the text's color - ?t=... the line above the numbers (default: the event's title) - - An event starts at local midnight on starts_on in TIME_ZONE (events - carry a date, not a time) and is over when ends_on (or starts_on) - is; the picture says which. A series has no one start to count - to, so it isn't offered. - - Each picture is kept for the minute it shows, a few hundred at most, - so a newsletter opened by everyone at once draws it once a minute. - ═══════════════════════════════════════════════════════════════ */ - -import { Hono } from "hono"; -import sharp from "sharp"; - -// The organization's home time zone (Unity Village, Missouri). -export const TIME_ZONE = "America/Chicago"; -const MAX_KEPT = 300; - -const countdown = new Hono(); -const kept = new Map(); // key → png Buffer - -const hex = (value, fallback) => (/^[0-9a-f]{6}$/i.test(value ?? "") ? `#${value}` : fallback); -const xml = (value) => - String(value).replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); - -/* The instant a date's local midnight is in a time zone, as ms. */ -export function zonedMidnight(date, timeZone = TIME_ZONE) { - const [y, m, d] = date.split("-").map(Number); - const guess = Date.UTC(y, m - 1, d); - // How far the zone's clock is from UTC at that instant, twice so a - // clock change between the guess and the answer is caught. - const offset = (at) => { - const parts = Object.fromEntries( - new Intl.DateTimeFormat("en-US", { timeZone, hourCycle: "h23", year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric" }) - .formatToParts(at) - .map((p) => [p.type, Number(p.value)]), - ); - return Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second) - at; - }; - const first = guess - offset(guess); - return guess - offset(first); -} - -/* Days, hours and minutes left, or null once it's started. */ -export function remaining(target, now = Date.now()) { - const left = target - now; - if (left <= 0) return null; - const minutes = Math.floor(left / 60_000); - return { days: Math.floor(minutes / 1440), hours: Math.floor(minutes / 60) % 24, minutes: minutes % 60 }; -} - -const W = 1104; // twice the email's 552px, for sharp screens -const H = 280; -const FONT = "Poppins, Montserrat, Helvetica, Arial, sans-serif"; - -function svg({ label, left, over, bg, fg }) { - const top = `${xml(label)}`; - if (!left) { - return `${top} -${over ? "Thanks for joining us" : "Happening now"}`; - } - const cells = [ - [left.days, left.days === 1 ? "DAY" : "DAYS"], - [left.hours, left.hours === 1 ? "HOUR" : "HOURS"], - [left.minutes, left.minutes === 1 ? "MINUTE" : "MINUTES"], - ] - .map(([n, unit], i) => { - const x = (W / 3) * i + W / 6; - return `${String(n).padStart(2, "0")} -${unit}`; - }) - .join(""); - return `${top}${cells}`; -} - -countdown.get("/countdown/:file", async (c) => { - const id = /^(.+)\.png$/.exec(c.req.param("file"))?.[1]; - const event = id - ? c - .get("db") - .prepare(`SELECT title, starts_on, ends_on FROM events WHERE id = ? AND is_published = 1 AND is_series = 0 AND starts_on IS NOT NULL`) - .get(id) - : null; - if (!event) return c.json({ error: "No such event" }, 404); - - const bg = hex(c.req.query("bg"), "#003a45"); - const fg = hex(c.req.query("fg"), "#ffffff"); - const label = (c.req.query("t") ?? "").trim().slice(0, 60) || event.title.slice(0, 60); - const left = remaining(zonedMidnight(event.starts_on)); - // Over once the last day's midnight has passed. - const over = !left && Date.now() >= zonedMidnight(event.ends_on ?? event.starts_on) + 86_400_000; - const key = JSON.stringify([id, bg, fg, label, left, over]); - - let png = kept.get(key); - if (!png) { - png = await sharp(Buffer.from(svg({ label, left, over, bg, fg }))).png().toBuffer(); - if (kept.size >= MAX_KEPT) kept.delete(kept.keys().next().value); - kept.set(key, png); - } - return c.body(png, 200, { - "Content-Type": "image/png", - // Asked for again at every open, where the client allows it. - "Cache-Control": "no-cache, max-age=0, must-revalidate", - }); -}); - -export default countdown; diff --git a/src/components/Footer.tsx b/src/components/Footer.tsx index a291b87..6f25a42 100644 --- a/src/components/Footer.tsx +++ b/src/components/Footer.tsx @@ -4,7 +4,12 @@ import { useNavSections } from "../lib/navSections.ts"; import siteLogo from "../assets/logos/NGU_Logo.svg"; import PlatformIcon from "./PlatformIcon.tsx"; import { ORGANIZATION_DETAILS as Organization_Details } from "../data/organizationDetails.ts"; -import { SOCIAL_LINKS } from "../data/socialLinks.ts"; + +const Social_Links = [ + { label: "Instagram", href: "https://www.instagram.com/nextgenerationunity/", platform: "instagram" }, + { label: "Facebook", href: "https://www.facebook.com/NextGenerationofUnity", platform: "facebook" }, + { label: "Discord", href: "https://discord.com/invite/AtngzpqaX5", platform: "discord" }, +]; // Give's destination lives in navConfig so the footer and the nav can't drift. // Only the label differs down here. @@ -83,7 +88,7 @@ export default function Footer() { {/* Socials + get in touch */}
- {SOCIAL_LINKS.map(({ label, href, platform }) => ( + {Social_Links.map(({ label, href, platform }) => ( = [ - { label: 'Instagram', href: 'https://www.instagram.com/nextgenerationunity/', platform: 'instagram' }, - { label: 'Facebook', href: 'https://www.facebook.com/NextGenerationofUnity', platform: 'facebook' }, - { label: 'Discord', href: 'https://discord.com/invite/AtngzpqaX5', platform: 'discord' }, -] diff --git a/src/lib/adminWidth.tsx b/src/lib/adminWidth.tsx index 02cdb0e..5bd3a1e 100644 --- a/src/lib/adminWidth.tsx +++ b/src/lib/adminWidth.tsx @@ -3,8 +3,7 @@ The admin column is max-w-5xl. The record editor wants more (its section nav sits to the left of a form that keeps that width), and - so does the admin home (three cards across): "wide". The newsletter - builder takes the whole window, its editor beside a preview: "full". + so does the admin home (three cards across). Like the title (adminTitle.tsx), the page asks and the layout decides, so AdminLayout stays the one place that sets
's width. @@ -15,16 +14,14 @@ import { createContext, useContext, useEffect } from "react"; -export type AdminWidth = "normal" | "wide" | "full"; +export const AdminWidthContext = createContext<((wide: boolean) => void) | null>(null); -export const AdminWidthContext = createContext<((width: AdminWidth) => void) | null>(null); - -export function useWideAdminPage(width: Exclude = "wide") { - const setWidth = useContext(AdminWidthContext); +export function useWideAdminPage() { + const setWide = useContext(AdminWidthContext); useEffect(() => { - if (!setWidth) return undefined; - setWidth(width); - return () => setWidth("normal"); - }, [setWidth, width]); + if (!setWide) return undefined; + setWide(true); + return () => setWide(false); + }, [setWide]); } diff --git a/src/lib/newsletter.ts b/src/lib/newsletter.ts index cd9d349..91c9681 100644 --- a/src/lib/newsletter.ts +++ b/src/lib/newsletter.ts @@ -1,33 +1,18 @@ /* ═══════════════════════════════════════════════════════════════ - NEWSLETTER: email-ready HTML and plain text from a list of parts + NEWSLETTER: email-ready HTML and plain text from picked items - The admin's Newsletter tool (AdminNewsletter.tsx) edits a draft as - one ordered list of parts (060_newsletter_layout.sql); this turns - it into one email to paste into Mailchimp, Gmail or Church Center. - Nothing is sent from here. The parts, each aligned left or center: + The admin's Newsletter tool (AdminNewsletter.tsx) gathers events, + blog posts and featured cards, with content blocks written for the + issue; this turns them into one email to paste into Mailchimp, + Gmail or Church Center. Nothing is sent from here. - header the band above the title: text, a logo, its color - (or no band); left out when the part is removed - title the email's heading - picks a section of picked events, blog posts or front page - cards: its heading and underline, each card's left - bar, and the button label - footer the closing lines (blank: the site's name and - address) and the rule above them - social a band of the site's platform icons, each linked - (PNGs in public/email/: scripts/email-icons.mjs) - countdown a picture of the time left until a picked event, - drawn by the API when the email is opened - (server/src/routes/countdown.js), with a fixed line - under it, as of copying, for when images don't load - any block drawn as its email-safe equivalent: headings, - paragraphs (with **bold**, *italic* and [links](url)), - callouts, quotes, lists, link and button rows, images, - cards and dividers (with their color, thickness and - spacing); a video is its still linked to the video + Blocks draw as their email-safe equivalent: headings, paragraphs + (with **bold**, *italic* and [links](url)), callouts, quotes, + lists, link and button rows, images, cards and dividers; a video + is its still linked to the video. Schedules, tables and people, + which need the site, are left out. - Colors are the site's palette (PALETTE) or "none"; blank is the - default. No unsubscribe link: Mailchimp adds its own to every send. + No unsubscribe link: Mailchimp adds its own to every send. Email clients ignore stylesheets, CSS variables and most layout, so the HTML is tables with inline styles at 600px, images with @@ -36,9 +21,6 @@ plain-text copy goes alongside for clients that show no HTML. ═══════════════════════════════════════════════════════════════ */ -import { readableOn } from './color.ts' -import { PLATFORMS } from './platforms.ts' - export type NewsletterItem = { title: string /** A line under the title: dates and place, a byline. */ @@ -51,54 +33,32 @@ export type NewsletterItem = { cta: string } -export type PickSource = 'events' | 'posts' | 'cards' +export type NewsletterSection = { heading: string; items: NewsletterItem[] } -/* One part of the email, as the builder's editor holds it. Blocks - use the content block fields; the other parts add their own. */ -export type NewsletterPart = { +/* A content block as the block editor holds it. */ +export type NewsletterBlock = { type: string - align?: 'left' | 'center' | '' | null text?: string | null media?: string | null href?: string | null alt?: string | null cite?: string | null items?: Array<{ text?: string | null; detail?: string | null; url?: string | null; media?: string | null }> - /** The header's band, a divider's line. */ - color?: string | null - /** A divider's thickness and the space above it, in pixels. */ - size?: string | number | null - space?: string | number | null - /** A picks section: what it picks from, its picks in order, its button label. */ - source?: PickSource | '' | null - picked?: Array<{ ref?: string | null }> - cta?: string | null - /** A picks section's underline, the footer's rule. */ - rule?: string | null - /** The bar down the left of a picks section's cards. */ - bar?: string | null - /** A social bar's links, in order. */ - socials?: Array<{ platform?: string | null; url?: string | null }> - /** A countdown's event. */ - event?: string | null } -/* What a countdown needs of its event. */ -export type CountdownEvent = { title: string; starts_on?: string | null; href: string } - export type Newsletter = { - parts: NewsletterPart[] - /** A picks part's items, ready to draw (picked, published, in order). */ - itemsFor: (part: NewsletterPart) => NewsletterItem[] - /** A countdown's event, if it's one that can be counted to. */ - eventFor: (id: string) => CountdownEvent | null - /** Now, for the countdown's fixed line. */ - now: number - /** A social bar with no links of its own shows these (the footer's). */ - defaultSocials: Array<{ platform: string; url: string }> + 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 } @@ -114,38 +74,12 @@ const COLOR = { rule: '#d6f5fa', } -/* What each picks section is called and says on its buttons, unless - the part says otherwise. */ -export const PICK_DEFAULTS: Record = { - events: { heading: 'Coming up', cta: 'Event details' }, - posts: { heading: 'From the blog', cta: 'Read the post' }, - cards: { heading: 'Featured', cta: 'Learn more' }, -} - -export const DEFAULT_TITLE = (siteName: string) => `News from ${siteName}` - const FONT = "'Poppins', Helvetica, Arial, sans-serif" const BODY_FONT = "'Montserrat', Helvetica, Arial, sans-serif" const escape = (value: string) => value.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"') -/* A part's color: blank is `fallback`, "none" is no color at all, - and anything but a hex color (it lands in a style attribute) is - the fallback too. */ -function colorOf(value: string | null | undefined, fallback: string): string | null { - if (value === 'none') return null - return value && /^#[0-9a-f]{6}$/i.test(value) ? value : fallback -} - -/* A whole number of pixels within bounds, or the fallback. */ -function px(value: string | number | null | undefined, fallback: number, min: number, max: number): number { - const n = Math.round(Number(value)) - return value === '' || value == null || !Number.isFinite(n) ? fallback : Math.min(max, Math.max(min, n)) -} - -const alignOf = (part: NewsletterPart) => (part.align === 'center' ? 'center' : 'left') - /* 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 { @@ -177,18 +111,13 @@ const paragraphs = (text: string, style: string, n?: Newsletter) => .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, align: string) => - `${escape(label)}` +const buttonHtml = (href: string, label: string) => + `${escape(label)}` -/* A full-width picture; centered by its row when it's narrower. */ -const imageTag = (src: string, alt: string) => - `${escape(alt)}` - -function blockHtml(block: NewsletterPart, n: Newsletter): string { +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 ?? [] - const align = alignOf(block) switch (block.type) { case 'heading': return text @@ -210,7 +139,7 @@ function blockHtml(block: NewsletterPart, n: Newsletter): string { : '' case 'list': return items.length - ? `
    ${items + ? `
      ${items .map((item) => { const url = item.url ? safeHref(item.url, n) : null const label = escape(item.text ?? '') @@ -222,16 +151,16 @@ function blockHtml(block: NewsletterPart, n: Newsletter): string { case 'links': { const buttons = items .map((item) => (item.url ? safeHref(item.url, n) : null)) - .map((url, i) => (url ? buttonHtml(url, items[i].text || url, align) : '')) + .map((url, i) => (url ? buttonHtml(url, items[i].text || url) : '')) .join('') return buttons ? `

      ${buttons}

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

      ${buttonHtml(href, text, align)}

      ` : '' + return href && text ? `

      ${buttonHtml(href, text)}

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

      ${escape(text)}

      ` : '' @@ -242,175 +171,19 @@ function blockHtml(block: NewsletterPart, n: Newsletter): string { .map((item) => { const url = item.url ? safeHref(item.url, n) : null if (!url || !item.text) return '' - return `` -} - -function itemHtml(item: NewsletterItem, part: NewsletterPart, align: string): string { - const bar = colorOf(part.bar, COLOR.teal) - const image = item.image - ? `` - : '' - const meta = item.meta - ? `

      ${escape(item.meta)}

      ` - : '' - const text = item.text ? paragraphs(item.text, TEXT) : '' - return ` -
      + return `

      ${escape(item.text)}

      ${item.detail ? paragraphs(item.detail, TEXT) : ''}
      ` }) .join('') - case 'divider': { - const color = colorOf(block.color, COLOR.rule) - // "none" keeps the space without a line. - const line = color ? `border-top:${px(block.size, 2, 1, 8)}px solid ${color};` : '' - return `
      ` - } + case 'divider': + return `
      ` default: return '' } } -function headerHtml(part: NewsletterPart, n: Newsletter): string { - const band = colorOf(part.color, COLOR.body) - const ink = band ? readableOn(band) : COLOR.ink - const align = alignOf(part) - const logo = part.media - ? `${escape(part.text?.trim() || n.siteName)}` - : '' - // With a logo, words only when written; without one, the site's name. - const words = part.text?.trim() || (part.media ? '' : n.siteName) - const name = words - ? `${escape(words)}` - : '' - return `
      ${logo}${logo && name ? `
      ${name}
      ` : name}
      ${imageTag(item.image, '')}
      - ${image} - -
      -

      ${escape(item.title)}

      - ${meta}${text} -

      ${buttonHtml(item.href, item.cta, align)}

      -
      ` -} - -function picksHtml(part: NewsletterPart, n: Newsletter): string { - const items = n.itemsFor(part) - if (items.length === 0) return '' - const source = (part.source || 'events') as PickSource - const heading = part.text?.trim() || PICK_DEFAULTS[source].heading - const rule = colorOf(part.rule, COLOR.rule) - const align = alignOf(part) - return ` -

      ${escape(heading)}

      - ${items.map((item) => itemHtml(item, part, align)).join('')} -` -} - -function footerHtml(part: NewsletterPart, n: Newsletter): string { - const rule = colorOf(part.rule, COLOR.rule) - const lines = part.text?.trim() - ? paragraphs(part.text, `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?:\/\//, ''))}` - return `
      - ${lines} -
      ` -} - -/* The site's platform icons as PNGs, white or ink to read on the band. */ -const platformLabel = (id: string) => PLATFORMS.find((p) => p.id === id)?.label ?? id -const socialsOf = (part: NewsletterPart, n: Newsletter) => - (part.socials?.length ? part.socials : n.defaultSocials).filter((link) => link.platform && link.url) - -const iconUrl = (n: Newsletter, platform: string, band: string | null) => - `${n.origin}/email/${encodeURIComponent(platform)}-${band && readableOn(band) === '#ffffff' ? 'white' : 'ink'}.png` - -function socialHtml(part: NewsletterPart, n: Newsletter): string { - const band = colorOf(part.color, COLOR.body) - const links = socialsOf(part, n) - .map((link) => ({ platform: link.platform!, url: safeHref(link.url!, n) })) - .filter((link) => link.url) - if (links.length === 0) return '' - const icons = links - .map( - (link) => - `${escape(platformLabel(link.platform))}`, - ) - .join('') - return `
      ${icons}
      ` -} - -/* "12 days to go", as of `now`: an event starts at its date's - midnight. Null once it has, or with no date. */ -export function countdownLine(event: CountdownEvent, now: number): string | null { - if (!event.starts_on) return null - const [y, m, d] = event.starts_on.split('-').map(Number) - const days = Math.ceil((new Date(y, m - 1, d).getTime() - now) / 86_400_000) - if (days <= 0) return null - return days === 1 ? '1 day to go' : `${days} days to go` -} - -function countdownHtml(part: NewsletterPart, n: Newsletter): string { - const event = part.event ? n.eventFor(part.event) : null - if (!event || !part.event) return '' - const band = colorOf(part.color, COLOR.body) ?? COLOR.page - const label = part.text?.trim() || event.title - const query = new URLSearchParams({ bg: band.slice(1), fg: readableOn(band).slice(1), t: label }) - const src = `${n.origin}/api/countdown/${encodeURIComponent(part.event)}.png?${query}` - const line = countdownLine(event, n.now) ?? 'Happening now' - return ` - ${imageTag(src, `${label}: ${line}`)} -

      ${escape(line)}: ${escape(event.title)}

      -` -} - -function partHtml(part: NewsletterPart, n: Newsletter): string { - switch (part.type) { - case 'header': - return headerHtml(part, n) - case 'title': - return `

      ${escape(part.text?.trim() || DEFAULT_TITLE(n.siteName))}

      ` - case 'picks': - return picksHtml(part, n) - case 'footer': - return footerHtml(part, n) - case 'social': - return socialHtml(part, n) - case 'countdown': - return countdownHtml(part, n) - default: { - const html = blockHtml(part, n) - return html ? `${html}` : '' - } - } -} - -/* The email's title, for the HTML's and the drafts list. */ -export function newsletterTitle(n: Pick<Newsletter, 'parts' | 'siteName'>): string { - return n.parts.find((part) => part.type === 'title')?.text?.trim() || DEFAULT_TITLE(n.siteName) -} - -export function newsletterHtml(n: Newsletter): string { - return `<!doctype html> -<html lang="en"> -<head> -<meta charset="utf-8"> -<meta name="viewport" content="width=device-width, initial-scale=1"> -<title>${escape(newsletterTitle(n))} - - - - -
      - - ${n.parts.map((part) => partHtml(part, n)).join('\n ')} - -
      -
      - -` -} - -function blockText(block: NewsletterPart, n: Newsletter): string[] { +function blockText(block: NewsletterBlock, n: Newsletter): string[] { const text = block.text?.trim() ?? '' const items = block.items ?? [] const link = (url: string) => safeHref(url, n) ?? url @@ -443,43 +216,92 @@ function blockText(block: NewsletterPart, n: Newsletter): string[] { } } -function partText(part: NewsletterPart, n: Newsletter): string[] { - switch (part.type) { - case 'header': - return [part.text?.trim() || n.siteName, ''] - case 'title': { - const title = part.text?.trim() || DEFAULT_TITLE(n.siteName) - return [title, '='.repeat(Math.min(title.length, 60)), ''] - } - case 'picks': { - const items = n.itemsFor(part) - if (items.length === 0) return [] - const source = (part.source || 'events') as PickSource - const lines = [(part.text?.trim() || PICK_DEFAULTS[source].heading).toUpperCase(), ''] - for (const item of 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}`, '') - } - return lines - } - case 'footer': - return ['--', ...(part.text?.trim() ? [part.text.trim()] : [n.siteName, n.origin]), ''] - case 'social': { - const lines = socialsOf(part, n).map((link) => `${platformLabel(link.platform!)}: ${link.url}`) - return lines.length ? [...lines, ''] : [] - } - case 'countdown': { - const event = part.event ? n.eventFor(part.event) : null - if (!event) return [] - return [`${countdownLine(event, n.now) ?? 'Happening now'}: ${event.title}`, event.href, ''] - } - default: - return blockText(part, n) - } +/* 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 + ? `` + : '' + const meta = item.meta + ? `

      ${escape(item.meta)}

      ` + : '' + 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 ` + + + ${image} + +
      +

      ${escape(item.title)}

      + ${meta}${text} +

      ${escape(item.cta)}

      +
      +` +} + +export function newsletterHtml(n: Newsletter): string { + const sections = n.sections + .filter((section) => section.items.length > 0) + .map( + (section) => ` + +

      ${escape(section.heading)}

      +${section.items.map(itemHtml).join('')}`, + ) + .join('') + + const logo = n.logo + ? `${escape(n.siteName)}` + : `${escape(n.siteName)}` + + return ` + + + + +${escape(n.title)} + + + + +
      + + + + ${sections} + +
      ${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) : ''} + ${(n.blocks ?? []).map((block) => blockHtml(block, n)).join('')} +
      + ${footerHtml(n)} +
      +
      + +` } export function newsletterText(n: Newsletter): string { - return n.parts.flatMap((part) => partText(part, n)).join('\n').trim() + 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(), '') + 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.footer?.trim() ? [n.footer.trim()] : [n.siteName, n.origin])) + return lines.join('\n') } diff --git a/src/lib/version.ts b/src/lib/version.ts index e951ea8..084ac9a 100644 --- a/src/lib/version.ts +++ b/src/lib/version.ts @@ -7,4 +7,4 @@ box or a build banner can read the same value later. ═══════════════════════════════════════════════════════════════ */ -export const SITE_VERSION = "NGU-Web.v1.11.2-newsletter"; +export const SITE_VERSION = "NGU-Web.v1.11.1-audit"; diff --git a/src/pages/admin/AdminLayout.tsx b/src/pages/admin/AdminLayout.tsx index 8cd77a5..16e95b9 100644 --- a/src/pages/admin/AdminLayout.tsx +++ b/src/pages/admin/AdminLayout.tsx @@ -25,7 +25,7 @@ import { Suspense, useCallback, useEffect, useMemo, useState } from "react"; import { Link, NavLink, Outlet, useLocation, useNavigate } from "react-router-dom"; import { useAuth } from "../../lib/auth.tsx"; import { AdminTitleContext } from "../../lib/adminTitle.tsx"; -import { AdminWidthContext, type AdminWidth } from "../../lib/adminWidth.tsx"; +import { AdminWidthContext } from "../../lib/adminWidth.tsx"; import { SITE_VERSION } from "../../lib/version.ts"; import { ROLE_LABELS, isSuper } from "../../lib/roles.ts"; import siteLogo from "../../assets/logos/NGU_Logo.svg"; @@ -111,13 +111,12 @@ export default function AdminLayout() { const stableSet = useCallback((value) => setDetail(value), []); const titleContext = useMemo(() => ({ setDetail: stableSet }), [stableSet]); - // How much room the page below asked for (adminWidth.tsx): the - // record editor more, for its section nav; the newsletter builder - // the whole window. setWidth is a state setter, so it's stable. - const [width, setWidth] = useState("normal"); + // Whether the page below asked for extra room (the record editor, + // for its section nav). setWide is a state setter, so it's stable. + const [wide, setWide] = useState(false); // The header, its strip and the footer line up with the content, // however wide the page asked for. - const column = { normal: "max-w-5xl", wide: "max-w-[82rem]", full: "max-w-none" }[width]; + const column = wide ? "max-w-[82rem]" : "max-w-5xl"; useEffect(() => { // Sections only exist in the CMS. Home and Panel already say @@ -212,7 +211,7 @@ export default function AdminLayout() { without ever floating over it. */}
      - + diff --git a/src/pages/admin/AdminNewsletter.tsx b/src/pages/admin/AdminNewsletter.tsx index ea73605..4223445 100644 --- a/src/pages/admin/AdminNewsletter.tsx +++ b/src/pages/admin/AdminNewsletter.tsx @@ -1,18 +1,17 @@ /* ═══════════════════════════════════════════════════════════════ 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. + 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, 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, 060_newsletter_layout.sql), + 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 blocks and picks as the post's body, - opened in the post's editor to finish. + 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. @@ -20,15 +19,15 @@ 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 { Article, Check, Copy, DownloadSimple, FloppyDisk, Trash } from '@phosphor-icons/react' +import { useEffect, useMemo, 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 { 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' @@ -38,18 +37,12 @@ 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 { 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 NewsletterBlock, type NewsletterItem, - type NewsletterPart, - type PickSource, + type NewsletterSection, } from '../../lib/newsletter.ts' const MUTED = 'var(--color-muted)' @@ -62,175 +55,24 @@ const button = 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 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'] - -/* 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. */ -const SHADES = ['', ', darkest', ', light', ', lightest'] -const PALETTE_OPTIONS = Object.entries(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 }, - })), - }, - ], +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 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)) @@ -239,16 +81,19 @@ function featuredHref(card: FeaturedCard): string | null { 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') + useWideAdminPage() const navigate = useNavigate() const { user } = useAuth() - const [parts, setParts] = useState(STARTER) + 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()) + // 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) @@ -278,17 +123,20 @@ export default function AdminNewsletter() { }, []) 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. - } + 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) - setParts(layout) + 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) { @@ -306,8 +154,11 @@ export default function AdminNewsletter() { setBusy(true) setMessage(null) const payload = { - title: parts.find((part) => part.type === 'title')?.text?.trim() || '', - layout: JSON.stringify(parts), + 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 @@ -339,134 +190,39 @@ export default function AdminNewsletter() { } } - // 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.card_image), - 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. */ + /* 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 = newsletterTitle(newsletter.content) + const postTitle = newsletter.content.title 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 }, + 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: items.map((item) => ({ + 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, })), }, - ] - } - 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 + ]), + ].map((block) => ({ ...block, slot: 'body' })) try { await post('/admin/blog_posts', { id, title: postTitle, - excerpt, + excerpt: intro.trim() || null, is_published: false, - content_blocks: body.map((block) => ({ ...block, slot: 'body' })), + content_blocks: body, }) navigate(`/admin/blog_posts/${id}`) } catch (err) { @@ -476,6 +232,90 @@ export default function AdminNewsletter() { } } + // 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 = (set: Set, value: T, update: (next: Set) => 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) => ({ card, href: featuredHref(card) })) + .filter(({ href }) => href && pickedCards.has(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 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, + } + 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 { await navigator.clipboard.writeText(kind === 'html' ? newsletter.html : newsletter.text) @@ -495,15 +335,12 @@ export default function AdminNewsletter() { 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. + Pick what to include, then copy the email into Mailchimp, Gmail or Church Center.

      @@ -514,7 +351,7 @@ export default function AdminNewsletter() { {drafts.map((row) => ( ))} @@ -525,7 +362,7 @@ export default function AdminNewsletter() {
      - {/* 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.'} -

      -
      +
      +
      +
      + +