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 ``;
- }
- 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 ``;
-}
-
-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 */}
+
+`
}
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() {
{draft ? 'Save draft' : 'Save as a new draft'}
-
- {/* The editor takes what the preview leaves; the handle between
- them sets the preview's width (from lg up). */}
-
-
-
-
- {eventsLoading || posts === null ? 'Loading what can be picked…' : 'Picked items show once chosen; a section with none is left out.'}
-
- {empty ? 'Add a part to build the email.' : 'In Mailchimp, paste the HTML into a Code block or "Paste in code".'}
+ {newsletter.count === 0
+ ? 'Tick an item or add a block to build the email.'
+ : `${newsletter.count} part${newsletter.count === 1 ? '' : 's'}. In Mailchimp, paste the HTML into a Code block or "Paste in code".`}
@@ -606,70 +478,50 @@ export default function AdminNewsletter() {
)
}
-/* ── The handle between the parts and the preview ─────────────
- Drag it, or focus it and use the arrow keys (Home and End for
- the narrowest and widest). Under the email's 600px the preview
- shows it as a phone would. The width is remembered in this
- browser, a convenience only. */
-
-const PREVIEW_MIN = 320
-const PARTS_MIN = 360 // what the parts list keeps, at least
-const PREVIEW_DEFAULT = 672
-const PREVIEW_KEY = 'site-newsletter-preview-width'
-const STEP = 32
-
-function usePreviewWidth() {
- const ref = useRef(null)
- const [room, setRoom] = useState(0)
- const [wanted, setWanted] = useState(() => {
- try {
- const saved = Number(window.localStorage.getItem(PREVIEW_KEY))
- return saved >= PREVIEW_MIN ? saved : PREVIEW_DEFAULT
- } catch {
- return PREVIEW_DEFAULT
- }
- })
-
- // The row's width, so the widest the preview can be follows the window.
- useEffect(() => {
- const row = ref.current
- if (!row) return undefined
- const observer = new ResizeObserver(() => setRoom(row.clientWidth))
- observer.observe(row)
- return () => observer.disconnect()
- }, [])
-
- const max = Math.max(PREVIEW_MIN, room ? room - PARTS_MIN : PREVIEW_DEFAULT)
- const width = Math.min(max, Math.max(PREVIEW_MIN, wanted))
-
- const set = (next: number) => {
- const clamped = Math.round(Math.min(max, Math.max(PREVIEW_MIN, next)))
- setWanted(clamped)
- try {
- window.localStorage.setItem(PREVIEW_KEY, String(clamped))
- } catch {
- // Storage off: the width lasts until the page is left.
- }
- }
-
- return {
- ref,
- width,
- max,
- start: (e: React.PointerEvent) => e.currentTarget.setPointerCapture(e.pointerId),
- drag: (e: React.PointerEvent) => {
- if (!e.currentTarget.hasPointerCapture(e.pointerId) || !ref.current) return
- set(ref.current.getBoundingClientRect().right - e.clientX - e.currentTarget.offsetWidth / 2)
- },
- end: (e: React.PointerEvent) => {
- if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId)
- },
- key: (e: React.KeyboardEvent) => {
- // Left widens the preview (the handle moves left), Right narrows it.
- const next = { ArrowLeft: width + STEP, ArrowRight: width - STEP, Home: PREVIEW_MIN, End: max }[e.key]
- if (next === undefined) return
- e.preventDefault()
- set(next)
- },
- }
+function PickList({
+ title,
+ empty,
+ options,
+ picked,
+ onToggle,
+}: {
+ title: string
+ empty: string
+ options: Array<{ value: T; label: string; detail?: string | null }>
+ picked: Set
+ onToggle: (value: T) => void
+}) {
+ return (
+
+