Compare commits

..

5 commits

Author SHA1 Message Date
d067c02d33 Merge pull request 'Newsletter: every part editable and movable (v1.11.2-newsletter)' (#24) from newsletter-layout into main
Reviewed-on: #24
2026-10-02 19:50:03 +01:00
Zaldimmar
c81712ef32 Newsletter: a handle between the parts and the preview sets their widths
Drag it, or focus it and use the arrow keys, Home and End; 320px
(a phone's view of the email) up to all but 360px of the parts list.
Remembered in the browser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 01:07:13 -05:00
Zaldimmar
00170ca912 Newsletter: social bar and event countdown parts, full-width builder
- Social bar: a colored band of the site's platform icons, linked;
  no links added shows the footer's (src/data/socialLinks.ts, shared)
- Icons are white and ink PNGs in public/email/, made from
  PlatformIcon.tsx by scripts/email-icons.mjs (no SVG in Gmail/Outlook)
- Event countdown: a picture drawn by /api/countdown/<id>.png when the
  email is opened (days, hours, minutes to local midnight in
  America/Chicago; then happening now; then over), with a fixed line
  under it as of copying
- The builder takes the whole window (useWideAdminPage('full'))

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 00:43:28 -05:00
Zaldimmar
a943ecd3a3 Version v1.11.2-newsletter
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 19:41:23 -05:00
Zaldimmar
3194fdbb7d Newsletter: every part editable and movable
A draft is one ordered list of parts (migration 060, newsletters.layout
as JSON), edited with the content block editor so any part can be
moved, copied or removed, each aligned left or center:
- header: words, a PNG/JPEG logo, band color or none
- title
- any email block; dividers take color, thickness and spacing
- picked items: events, posts or front page cards picked in order,
  with the heading, its underline, the card bar and the button label
- footer: its lines and the line above

Colors come from the palette or none. 057's fixed fields and blocks
are dropped; that migration never reached a live database.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 19:37:26 -05:00
32 changed files with 970 additions and 419 deletions

View file

@ -34,6 +34,7 @@ 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`.

View file

@ -285,6 +285,7 @@ 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` | |

Binary file not shown.

After

Width:  |  Height:  |  Size: 997 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 838 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 921 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 806 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 608 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 531 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 445 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 401 B

BIN
public/email/tiktok-ink.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 864 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 746 B

BIN
public/email/x-ink.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

BIN
public/email/x-white.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1,017 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 622 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 522 B

30
scripts/email-icons.mjs Normal file
View file

@ -0,0 +1,30 @@
/* ═══════════════════════════════════════════════════════════════
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 = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="48" height="48"><path fill="${fill}" d="${d}"/></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(", ")}`);

View file

@ -1,11 +1,12 @@
import { text, blocksChild } from "./columns.js";
import { text } from "./columns.js";
/* ── Newsletter drafts (057_newsletters.sql) ─────────────────────
/* ── Newsletter drafts (057, 060_newsletter_layout.sql) ─────────
Saved from Tools → Newsletter (AdminNewsletter.tsx), which is
their only editor: there is no list or form for them in Data.
`picks` is the builder's JSON of what's ticked. Deleting a draft
takes its blocks with it (newsletters_cleanup). */
`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. */
export const newsletters = {
key: "newsletters",
@ -21,7 +22,5 @@ export const newsletters = {
order: "updated_at DESC, id DESC",
},
columns: [text("title"), text("intro"), text("footer"), text("picks")],
children: [blocksChild("newsletter")],
columns: [text("title"), text("layout", { required: true })],
};

View file

@ -39,6 +39,7 @@ 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";
@ -74,6 +75,14 @@ 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
@ -178,6 +187,11 @@ 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 }));

View file

@ -0,0 +1,47 @@
-- ═══════════════════════════════════════════════════════════════
-- 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;

View file

@ -0,0 +1,119 @@
/* ═══════════════════════════════════════════════════════════════
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, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
/* 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 = `<text x="${W / 2}" y="68" text-anchor="middle" font-family="${FONT}" font-size="34" font-weight="700" fill="${fg}">${xml(label)}</text>`;
if (!left) {
return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}"><rect width="100%" height="100%" fill="${bg}"/>${top}
<text x="${W / 2}" y="190" text-anchor="middle" font-family="${FONT}" font-size="72" font-weight="700" fill="${fg}">${over ? "Thanks for joining us" : "Happening now"}</text></svg>`;
}
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 `<text x="${x}" y="182" text-anchor="middle" font-family="${FONT}" font-size="96" font-weight="700" fill="${fg}">${String(n).padStart(2, "0")}</text>
<text x="${x}" y="232" text-anchor="middle" font-family="${FONT}" font-size="24" font-weight="700" letter-spacing="3" fill="${fg}" fill-opacity="0.8">${unit}</text>`;
})
.join("");
return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}"><rect width="100%" height="100%" fill="${bg}"/>${top}${cells}</svg>`;
}
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;

View file

@ -4,12 +4,7 @@ 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";
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" },
];
import { SOCIAL_LINKS } from "../data/socialLinks.ts";
// Give's destination lives in navConfig so the footer and the nav can't drift.
// Only the label differs down here.
@ -88,7 +83,7 @@ export default function Footer() {
{/* Socials + get in touch */}
<div className="md:col-span-3 flex flex-col items-center md:items-start">
<div className="flex gap-4 mb-8">
{Social_Links.map(({ label, href, platform }) => (
{SOCIAL_LINKS.map(({ label, href, platform }) => (
<a
key={label}
href={href}

15
src/data/socialLinks.ts Normal file
View file

@ -0,0 +1,15 @@
/* ═══════════════════════════════════════════════════════════════
SOCIAL LINKS
The site's own accounts: the footer's icons, and what a newsletter's
social bar starts with (AdminNewsletter.tsx). `platform` is one of
PLATFORMS (src/lib/platforms.ts), which picks the icon.
═══════════════════════════════════════════════════════════════ */
import type { Platform } from '../lib/platforms.ts'
export const SOCIAL_LINKS: Array<{ label: string; href: string; platform: 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' },
]

View file

@ -3,7 +3,8 @@
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).
so does the admin home (three cards across): "wide". The newsletter
builder takes the whole window, its editor beside a preview: "full".
Like the title (adminTitle.tsx), the page asks and the layout
decides, so AdminLayout stays the one place that sets <main>'s
width.
@ -14,14 +15,16 @@
import { createContext, useContext, useEffect } from "react";
export const AdminWidthContext = createContext<((wide: boolean) => void) | null>(null);
export type AdminWidth = "normal" | "wide" | "full";
export function useWideAdminPage() {
const setWide = useContext(AdminWidthContext);
export const AdminWidthContext = createContext<((width: AdminWidth) => void) | null>(null);
export function useWideAdminPage(width: Exclude<AdminWidth, "normal"> = "wide") {
const setWidth = useContext(AdminWidthContext);
useEffect(() => {
if (!setWide) return undefined;
setWide(true);
return () => setWide(false);
}, [setWide]);
if (!setWidth) return undefined;
setWidth(width);
return () => setWidth("normal");
}, [setWidth, width]);
}

View file

@ -1,18 +1,33 @@
/* ═══════════════════════════════════════════════════════════════
NEWSLETTER: email-ready HTML and plain text from picked items
NEWSLETTER: email-ready HTML and plain text from a list of parts
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.
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:
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.
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
No unsubscribe link: Mailchimp adds its own to every send.
Colors are the site's palette (PALETTE) or "none"; blank is the
default. 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
@ -21,6 +36,9 @@
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. */
@ -33,32 +51,54 @@ export type NewsletterItem = {
cta: string
}
export type NewsletterSection = { heading: string; items: NewsletterItem[] }
export type PickSource = 'events' | 'posts' | 'cards'
/* A content block as the block editor holds it. */
export type NewsletterBlock = {
/* 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 = {
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 = {
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
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 }>
/** 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
}
@ -74,12 +114,38 @@ 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<PickSource, { heading: string; cta: string }> = {
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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
/* 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 {
@ -111,13 +177,18 @@ 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) =>
`<a href="${escape(href)}" style="display:inline-block;margin:4px 8px 4px 0;padding:10px 20px;border-radius:8px;background:${COLOR.teal};color:#ffffff;font-family:${FONT};font-size:14px;font-weight:700;text-decoration:none;">${escape(label)}</a>`
const buttonHtml = (href: string, label: string, align: string) =>
`<a href="${escape(href)}" style="display:inline-block;margin:${align === 'center' ? '4px' : '4px 8px 4px 0'};padding:10px 20px;border-radius:8px;background:${COLOR.teal};color:#ffffff;font-family:${FONT};font-size:14px;font-weight:700;text-decoration:none;">${escape(label)}</a>`
function blockHtml(block: NewsletterBlock, n: Newsletter): string {
/* A full-width picture; centered by its row when it's narrower. */
const imageTag = (src: string, alt: string) =>
`<img src="${escape(src)}" width="552" alt="${escape(alt)}" style="display:block;margin:0 auto;width:100%;max-width:552px;height:auto;border:0;">`
function blockHtml(block: NewsletterPart, 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
@ -139,7 +210,7 @@ function blockHtml(block: NewsletterBlock, n: Newsletter): string {
: ''
case 'list':
return items.length
? `<ul style="margin:12px 0 0;padding-left:20px;font-family:${BODY_FONT};font-size:15px;line-height:24px;color:${COLOR.body};">${items
? `<ul style="margin:12px 0 0;padding-left:${align === 'center' ? '0' : '20px'};list-style-position:${align === 'center' ? 'inside' : 'outside'};font-family:${BODY_FONT};font-size:15px;line-height:24px;color:${COLOR.body};">${items
.map((item) => {
const url = item.url ? safeHref(item.url, n) : null
const label = escape(item.text ?? '')
@ -151,16 +222,16 @@ function blockHtml(block: NewsletterBlock, 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) : ''))
.map((url, i) => (url ? buttonHtml(url, items[i].text || url, align) : ''))
.join('')
return buttons ? `<p style="margin:16px 0 0;">${buttons}</p>` : ''
}
case 'button':
return href && text ? `<p style="margin:16px 0 0;">${buttonHtml(href, text)}</p>` : ''
return href && text ? `<p style="margin:16px 0 0;">${buttonHtml(href, text, align)}</p>` : ''
case 'image':
case 'video': {
if (!block.media) return ''
const img = `<img src="${escape(n.absolute(block.media, 'image'))}" width="552" alt="${escape(block.alt ?? '')}" style="display:block;width:100%;max-width:552px;height:auto;border:0;">`
const img = imageTag(n.absolute(block.media, 'image'), block.alt ?? '')
const caption = text
? `<p style="margin:6px 0 0;font-family:${BODY_FONT};font-size:13px;line-height:20px;color:${COLOR.muted};">${escape(text)}</p>`
: ''
@ -171,19 +242,175 @@ function blockHtml(block: NewsletterBlock, n: Newsletter): string {
.map((item) => {
const url = item.url ? safeHref(item.url, n) : null
if (!url || !item.text) return ''
return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:16px 0 0;background:${COLOR.card};border-left:4px solid ${COLOR.teal};"><tr><td style="padding:16px 20px;">
return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:16px 0 0;background:${COLOR.card};border-left:4px solid ${COLOR.teal};"><tr><td style="padding:16px 20px;text-align:${align};">
<h3 style="margin:0;font-family:${FONT};font-size:18px;line-height:24px;font-weight:700;"><a href="${escape(url)}" style="color:${COLOR.ink};text-decoration:none;">${escape(item.text)}</a></h3>
${item.detail ? paragraphs(item.detail, TEXT) : ''}</td></tr></table>`
})
.join('')
case 'divider':
return `<hr style="margin:24px 0 0;border:0;border-top:2px solid ${COLOR.rule};">`
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 `<hr style="margin:${px(block.space, 24, 0, 64)}px 0 0;border:0;${line}">`
}
default:
return ''
}
}
function blockText(block: NewsletterBlock, n: Newsletter): string[] {
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
? `<a href="${escape(n.origin)}"><img src="${escape(n.absolute(part.media, 'image'))}" height="48" alt="${escape(part.text?.trim() || n.siteName)}" style="display:${align === 'center' ? 'block;margin:0 auto' : 'inline-block'};height:48px;width:auto;border:0;"></a>`
: ''
// 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
? `<a href="${escape(n.origin)}" style="font-family:${FONT};font-size:18px;font-weight:700;color:${ink};text-decoration:none;">${escape(words)}</a>`
: ''
return `<tr><td style="padding:20px 24px;text-align:${align};${band ? `background:${band};` : ''}">${logo}${logo && name ? `<div style="margin-top:8px;">${name}</div>` : name}</td></tr>`
}
function itemHtml(item: NewsletterItem, part: NewsletterPart, align: string): string {
const bar = colorOf(part.bar, COLOR.teal)
const image = item.image
? `<tr><td><a href="${escape(item.href)}">${imageTag(item.image, '')}</a></td></tr>`
: ''
const meta = item.meta
? `<p style="margin:4px 0 0;font-family:${BODY_FONT};font-size:14px;line-height:20px;color:${COLOR.muted};">${escape(item.meta)}</p>`
: ''
const text = item.text ? paragraphs(item.text, TEXT) : ''
return `
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:16px 0 0;background:${COLOR.card};${bar ? `border-left:4px solid ${bar};` : ''}">
${image}
<tr><td style="padding:20px 24px 24px;text-align:${align};">
<h3 style="margin:0;font-family:${FONT};font-size:20px;line-height:26px;font-weight:700;color:${COLOR.ink};"><a href="${escape(item.href)}" style="color:${COLOR.ink};text-decoration:none;">${escape(item.title)}</a></h3>
${meta}${text}
<p style="margin:16px 0 0;">${buttonHtml(item.href, item.cta, align)}</p>
</td></tr>
</table>`
}
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 `<tr><td style="padding:24px 24px 0;text-align:${align};">
<h2 style="margin:0;padding-bottom:8px;${rule ? `border-bottom:2px solid ${rule};` : ''}font-family:${FONT};font-size:22px;line-height:28px;font-weight:700;color:${COLOR.teal};">${escape(heading)}</h2>
${items.map((item) => itemHtml(item, part, align)).join('')}
</td></tr>`
}
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)}<br><a href="${escape(n.origin)}" style="color:${COLOR.teal};">${escape(n.origin.replace(/^https?:\/\//, ''))}</a>`
return `<tr><td style="padding:24px;text-align:${alignOf(part)};"><div style="padding-top:24px;${rule ? `border-top:2px solid ${rule};` : ''}font-family:${BODY_FONT};font-size:13px;line-height:20px;color:${COLOR.muted};">
${lines}
</div></td></tr>`
}
/* 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) =>
`<a href="${escape(link.url!)}" style="display:inline-block;margin:0 8px;"><img src="${escape(iconUrl(n, link.platform, band))}" width="24" height="24" alt="${escape(platformLabel(link.platform))}" style="display:block;width:24px;height:24px;border:0;"></a>`,
)
.join('')
return `<tr><td style="padding:24px 24px 0;"><div style="padding:16px 16px;text-align:${alignOf(part)};${band ? `background:${band};` : ''}">${icons}</div></td></tr>`
}
/* "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 `<tr><td style="padding:24px 24px 0;text-align:${alignOf(part)};">
<a href="${escape(event.href)}">${imageTag(src, `${label}: ${line}`)}</a>
<p style="margin:8px 0 0;font-family:${FONT};font-size:15px;line-height:22px;font-weight:700;color:${COLOR.ink};">${escape(line)}: <a href="${escape(event.href)}" style="color:${COLOR.teal};">${escape(event.title)}</a></p>
</td></tr>`
}
function partHtml(part: NewsletterPart, n: Newsletter): string {
switch (part.type) {
case 'header':
return headerHtml(part, n)
case 'title':
return `<tr><td style="padding:28px 24px 0;text-align:${alignOf(part)};"><h1 style="margin:0;font-family:${FONT};font-size:28px;line-height:34px;font-weight:700;color:${COLOR.ink};">${escape(part.text?.trim() || DEFAULT_TITLE(n.siteName))}</h1></td></tr>`
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 ? `<tr><td style="padding:0 24px;text-align:${alignOf(part)};">${html}</td></tr>` : ''
}
}
}
/* The email's title, for the HTML's <title> 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))}</title>
</head>
<body style="margin:0;padding:0;background:${COLOR.page};">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:${COLOR.page};">
<tr><td align="center" style="padding:24px 12px;">
<table role="presentation" width="600" cellpadding="0" cellspacing="0" style="width:100%;max-width:600px;background:${COLOR.page};">
${n.parts.map((part) => partHtml(part, n)).join('\n ')}
<tr><td style="padding:0 0 24px;"></td></tr>
</table>
</td></tr>
</table>
</body>
</html>`
}
function blockText(block: NewsletterPart, n: Newsletter): string[] {
const text = block.text?.trim() ?? ''
const items = block.items ?? []
const link = (url: string) => safeHref(url, n) ?? url
@ -216,92 +443,43 @@ function blockText(block: NewsletterBlock, n: Newsletter): string[] {
}
}
/* 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)}<br><a href="${escape(n.origin)}" style="color:${COLOR.teal};">${escape(n.origin.replace(/^https?:\/\//, ''))}</a>`
function itemHtml(item: NewsletterItem): string {
const image = item.image
? `<tr><td><a href="${escape(item.href)}"><img src="${escape(item.image)}" width="552" alt="" style="display:block;width:100%;max-width:552px;height:auto;border:0;"></a></td></tr>`
: ''
const meta = item.meta
? `<p style="margin:4px 0 0;font-family:${BODY_FONT};font-size:14px;line-height:20px;color:${COLOR.muted};">${escape(item.meta)}</p>`
: ''
const text = item.text
? paragraphs(item.text, `margin:12px 0 0;font-family:${BODY_FONT};font-size:15px;line-height:24px;color:${COLOR.body};`)
: ''
return `
<tr><td style="padding:0 24px 24px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:${COLOR.card};border-left:4px solid ${COLOR.teal};">
${image}
<tr><td style="padding:20px 24px 24px;">
<h3 style="margin:0;font-family:${FONT};font-size:20px;line-height:26px;font-weight:700;color:${COLOR.ink};"><a href="${escape(item.href)}" style="color:${COLOR.ink};text-decoration:none;">${escape(item.title)}</a></h3>
${meta}${text}
<p style="margin:16px 0 0;"><a href="${escape(item.href)}" style="display:inline-block;padding:10px 20px;border-radius:8px;background:${COLOR.teal};color:#ffffff;font-family:${FONT};font-size:14px;font-weight:700;text-decoration:none;">${escape(item.cta)}</a></p>
</td></tr>
</table>
</td></tr>`
}
export function newsletterHtml(n: Newsletter): string {
const sections = n.sections
.filter((section) => section.items.length > 0)
.map(
(section) => `
<tr><td style="padding:16px 24px 12px;">
<h2 style="margin:0;padding-bottom:8px;border-bottom:2px solid ${COLOR.rule};font-family:${FONT};font-size:22px;line-height:28px;font-weight:700;color:${COLOR.teal};">${escape(section.heading)}</h2>
</td></tr>${section.items.map(itemHtml).join('')}`,
)
.join('')
const logo = n.logo
? `<a href="${escape(n.origin)}"><img src="${escape(n.logo)}" height="48" alt="${escape(n.siteName)}" style="display:block;height:48px;width:auto;border:0;"></a>`
: `<a href="${escape(n.origin)}" style="font-family:${FONT};font-size:18px;font-weight:700;color:#ffffff;text-decoration:none;">${escape(n.siteName)}</a>`
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${escape(n.title)}</title>
</head>
<body style="margin:0;padding:0;background:${COLOR.page};">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:${COLOR.page};">
<tr><td align="center" style="padding:24px 12px;">
<table role="presentation" width="600" cellpadding="0" cellspacing="0" style="width:100%;max-width:600px;background:${COLOR.page};">
<tr><td style="padding:20px 24px;background:${COLOR.body};">${logo}</td></tr>
<tr><td style="padding:28px 24px 8px;">
<h1 style="margin:0;font-family:${FONT};font-size:28px;line-height:34px;font-weight:700;color:${COLOR.ink};">${escape(n.title)}</h1>
${n.intro ? paragraphs(n.intro, `margin:12px 0 0;font-family:${BODY_FONT};font-size:16px;line-height:26px;color:${COLOR.body};`, n) : ''}
${(n.blocks ?? []).map((block) => blockHtml(block, n)).join('')}
</td></tr>
${sections}
<tr><td style="padding:24px;border-top:2px solid ${COLOR.rule};font-family:${BODY_FONT};font-size:13px;line-height:20px;color:${COLOR.muted};">
${footerHtml(n)}
</td></tr>
</table>
</td></tr>
</table>
</body>
</html>`
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)
}
}
export function newsletterText(n: Newsletter): string {
const lines = [n.title, '='.repeat(Math.min(n.title.length, 60)), '']
if (n.intro) lines.push(n.intro.trim(), '')
for (const block of n.blocks ?? []) lines.push(...blockText(block, n))
for (const section of n.sections) {
if (section.items.length === 0) continue
lines.push(section.heading.toUpperCase(), '')
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')
return n.parts.flatMap((part) => partText(part, n)).join('\n').trim()
}

View file

@ -7,4 +7,4 @@
box or a build banner can read the same value later.
═══════════════════════════════════════════════════════════════ */
export const SITE_VERSION = "NGU-Web.v1.11.1-audit";
export const SITE_VERSION = "NGU-Web.v1.11.2-newsletter";

View file

@ -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 } from "../../lib/adminWidth.tsx";
import { AdminWidthContext, type AdminWidth } 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,12 +111,13 @@ export default function AdminLayout() {
const stableSet = useCallback((value) => setDetail(value), []);
const titleContext = useMemo(() => ({ setDetail: stableSet }), [stableSet]);
// 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);
// 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<AdminWidth>("normal");
// The header, its strip and the footer line up with the content,
// however wide the page asked for.
const column = wide ? "max-w-[82rem]" : "max-w-5xl";
const column = { normal: "max-w-5xl", wide: "max-w-[82rem]", full: "max-w-none" }[width];
useEffect(() => {
// Sections only exist in the CMS. Home and Panel already say
@ -211,7 +212,7 @@ export default function AdminLayout() {
without ever floating over it. */}
<main className={`mx-auto w-full flex-1 px-6 py-10 ${column}`}>
<AdminTitleContext.Provider value={titleContext}>
<AdminWidthContext.Provider value={setWide}>
<AdminWidthContext.Provider value={setWidth}>
<Suspense fallback={null}>
<Outlet />
</Suspense>

View file

@ -1,17 +1,18 @@
/* ═══════════════════════════════════════════════════════════════
NEWSLETTER (Tools)
Builds an email newsletter from what's already on the site: tick
upcoming events, published blog posts and the front page's
featured cards, write a title, 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.
Builds an email newsletter as one list of parts, each movable and
each with its own settings (PARTS_SPEC): the header band, the
title, content blocks, sections of picked upcoming events,
published blog posts or front page cards, and the footer. Copy
the result, email-ready HTML or plain text, into Mailchimp, Gmail
or Church Center (or download it as a file). Nothing is sent from
here; the builder is src/lib/newsletter.ts.
Drafts are saved (the newsletters entity, 057_newsletters.sql),
Drafts are saved (the newsletters entity, 060_newsletter_layout.sql),
to finish later or send again, and a draft can become an
unpublished blog post: its intro, blocks and picks as the post's
body, opened in the post's editor to finish.
unpublished blog post: its 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.
@ -19,15 +20,15 @@
email is read far from this admin.
═══════════════════════════════════════════════════════════════ */
import { Article, Check, Copy, DownloadSimple, FloppyDisk, Trash } from '@phosphor-icons/react'
import { useEffect, useMemo, useState } from 'react'
import { Article, Check, Copy, DotsSixVertical, DownloadSimple, FloppyDisk, Trash } from '@phosphor-icons/react'
import { useEffect, useMemo, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { ApiError, del, get, patch, post } from '../../lib/api.ts'
import { useAuth } from '../../lib/auth.tsx'
import { canDelete, canWrite } from '../../lib/roles.ts'
import { slugify } from '../../lib/adminSchema.ts'
import { blocksChild } from '../../lib/adminSchema/shared.ts'
import { blocksChild, BLOCK_TYPES } 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'
@ -37,12 +38,18 @@ 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,
type NewsletterBlock,
newsletterTitle,
PICK_DEFAULTS,
type NewsletterItem,
type NewsletterSection,
type NewsletterPart,
type PickSource,
} from '../../lib/newsletter.ts'
const MUTED = 'var(--color-muted)'
@ -55,24 +62,175 @@ 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; is_published: number; is_listed: number }
type PostRow = { id: string; title: string; published_on?: string | null }
type DraftRow = { id: number; title?: string | null; updated_at: string }
type Picks = { events?: string[]; posts?: string[]; cards?: string[] }
/* The block types an email can show (newsletter.ts draws them);
schedules, tables and people need the site. */
const EMAIL_BLOCKS = ['paragraph', 'heading', 'subheading', 'callout', 'quote', 'list', 'links', 'button', 'image', 'video', 'cards', 'divider']
const BLOCKS_SPEC = {
...blocksChild,
label: 'Blocks',
note: 'Written for this issue, under the intro. A video shows as its still, linked to the video.',
fields: blocksChild.fields
.filter((field) => field.path !== 'slot')
.map((field) =>
field.path === 'type' ? { ...field, options: (field.options ?? []).filter(([type]) => EMAIL_BLOCKS.includes(type)) } : field,
),
/* 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<PickSource, string> = { events: 'Upcoming events', posts: 'Blog posts', cards: 'Front page featured cards' }
const ITEM_LABEL: Record<PickSource, string> = { events: 'Event', posts: 'Blog post', cards: 'Featured card' }
const sourceOf = (part: NewsletterPart): PickSource => (SOURCES.includes(part.source as PickSource) ? (part.source as PickSource) : 'events')
/* Every part is a row: one editor for blocks and the email's own
parts, so any of them can be moved, copied or removed. */
const blockFields = blocksChild.fields.filter((field) => !['slot', 'team_id', 'type'].includes(field.path))
const PARTS_SPEC = {
key: 'parts',
label: 'Parts',
addLabel: 'Add part',
note: 'Top to bottom, as the email shows them. A video shows as its still, linked to the video.',
title: (row: NewsletterPart) => {
if (row.type === 'picks') {
const count = row.picked?.filter((pick) => pick.ref).length ?? 0
return `${row.text?.trim() || PICK_DEFAULTS[sourceOf(row)].heading}: ${count} picked`
}
const text = (row.text ?? '').trim().slice(0, 40)
return text ? `${partLabel(row.type)}: ${text}` : partLabel(row.type)
},
blank: { type: 'paragraph', text: '' },
fields: [
{
path: 'type',
label: 'Part',
widget: 'select',
options: PART_TYPES.map(([value, label]) => [value, label]),
help: (row: NewsletterPart) => PART_TYPES.find(([value]) => value === row?.type)?.[2],
},
{ path: 'align', label: 'Alignment', widget: 'select', options: [['center', 'Center']], blankLabel: 'Default: left' },
{ path: 'text', label: 'Words', when: { path: 'type', value: 'header' }, help: "Default: the site's name, or nothing beside a logo" },
{
path: 'media',
label: 'Logo',
widget: 'image',
folder: 'logos',
resolve: mediaUrl,
full: true,
when: { path: 'type', value: 'header' },
help: "A PNG or JPEG: Gmail and Outlook don't show SVG. Default: none, the words alone",
},
colorField('color', 'Band color', 'Teal, darkest', 'None: no band', ['header', 'social', 'countdown']),
{
path: 'event',
label: 'Event',
widget: 'select',
optionsFrom: 'countdownEvents',
required: true,
when: { path: 'type', value: 'countdown' },
help: 'Upcoming events with a date; a series has no one start to count to',
},
{ path: 'text', label: 'Words above', when: { path: 'type', value: 'countdown' }, help: "Default: the event's title" },
{ path: 'text', label: 'Title', full: true, when: { path: 'type', value: 'title' }, help: `Default: ${DEFAULT_TITLE(SITE_NAME)}` },
{
path: 'source',
label: 'Pick from',
widget: 'select',
options: SOURCES.filter((source) => source !== 'events').map((source) => [source, SOURCE_LABEL[source]]),
blankLabel: `Default: ${SOURCE_LABEL.events}`,
when: { path: 'type', value: 'picks' },
},
{
path: 'text',
label: 'Heading',
when: { path: 'type', value: 'picks' },
help: (row: NewsletterPart) => `Default: ${PICK_DEFAULTS[sourceOf(row)].heading}`,
},
{
path: 'cta',
label: 'Button',
when: { path: 'type', value: 'picks' },
help: (row: NewsletterPart) => `On each card. Default: ${PICK_DEFAULTS[sourceOf(row)].cta}`,
},
colorField('rule', 'Heading underline', 'Teal, lightest', 'None: no line', ['picks']),
colorField('bar', 'Card bar', 'Teal', 'None: no bar', ['picks']),
{
path: 'text',
label: 'Footer',
widget: 'textarea',
full: true,
when: { path: 'type', value: 'footer' },
help: `Default: ${SITE_NAME} and ${SITE_ORIGIN}`,
},
colorField('rule', 'Line above', 'Teal, lightest', 'None: no line', ['footer']),
...blockFields,
colorField('color', 'Line color', 'Teal, lightest', 'None: space only', ['divider']),
{ path: 'size', label: 'Thickness', widget: 'number', when: { path: 'type', value: 'divider' }, help: 'In pixels, 1 to 8. Default: 2' },
{ path: 'space', label: 'Space above', widget: 'number', when: { path: 'type', value: 'divider' }, help: 'In pixels, 0 to 64. Default: 24' },
],
children: [
...(blocksChild.children ?? []),
{
key: 'socials',
label: 'Links',
addLabel: 'Add link',
note: `None added: the site's own (${SOCIAL_LINKS.map((link) => link.label).join(', ')}).`,
when: { path: 'type', value: 'social' },
title: (row: { platform?: string; url?: string }) => PLATFORMS.find((p) => p.id === row.platform)?.label ?? 'New link',
blank: { platform: '', url: '' },
fields: [
{ path: 'platform', label: 'Platform', widget: 'select', options: PLATFORMS.map((p) => [p.id, p.label]), required: true },
{ path: 'url', label: 'Link', required: true, help: 'eg. https://www.instagram.com/nextgenerationunity/' },
],
},
{
key: 'picked',
label: 'Picked',
addLabel: 'Pick one',
when: { path: 'type', value: 'picks' },
title: () => 'Picked',
blank: { ref: '' },
// One select per source, the parent's choosing which shows.
fields: SOURCES.map((source) => ({
path: 'ref',
label: ITEM_LABEL[source],
widget: 'select',
optionsFrom: source,
required: true,
when: { scope: 'parent', path: 'source', value: source === 'events' ? ['', null, undefined, 'events'] : source },
})),
},
],
}
/* A new draft: the email as it always looked, every part in place. */
const STARTER: NewsletterPart[] = [
{ type: 'header' },
{ type: 'title', text: '' },
{ type: 'paragraph', text: '' },
{ type: 'picks', source: 'events', picked: [] },
{ type: 'picks', source: 'posts', picked: [] },
{ type: 'picks', source: 'cards', picked: [] },
{ type: 'footer' },
]
/* A site path or upload on the live site, for the email. */
const absoluteFor = (value: string, kind: 'link' | 'image') => (kind === 'image' ? imageFor(value) ?? value : siteUrl(value))
@ -81,19 +239,16 @@ 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()
useWideAdminPage('full')
const navigate = useNavigate()
const { user } = useAuth()
const [title, setTitle] = useState('')
const [intro, setIntro] = useState('')
const [footer, setFooter] = useState('')
const [blocks, setBlocks] = useState<NewsletterBlock[]>([])
const [pickedEvents, setPickedEvents] = useState<Set<string>>(new Set())
const [pickedPosts, setPickedPosts] = useState<Set<string>>(new Set())
// Cards by their link: the front page's cards can be reordered
// between one save and the next.
const [pickedCards, setPickedCards] = useState<Set<string>>(new Set())
const [parts, setParts] = useState<NewsletterPart[]>(STARTER)
const [posts, setPosts] = useState<PostRow[] | null>(null)
const [postDetails, setPostDetails] = useState<Record<string, BlogPostRecord>>({})
const [copied, setCopied] = useState<'html' | 'text' | null>(null)
@ -123,20 +278,17 @@ export default function AdminNewsletter() {
}, [])
function fill(row: any) {
let picks: Picks = {}
try {
picks = JSON.parse(row?.picks || '{}')
} catch {
// A hand-edited draft: start its picks over.
let layout: NewsletterPart[] = STARTER
if (row) {
try {
const parsed = JSON.parse(row.layout || '[]')
layout = Array.isArray(parsed) ? parsed : []
} catch {
// A hand-edited draft: start its parts over.
}
}
setDraft(row ? { id: row.id, updated_at: row.updated_at } : null)
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 ?? []))
setParts(layout)
}
async function openDraft(id: string) {
@ -154,11 +306,8 @@ export default function AdminNewsletter() {
setBusy(true)
setMessage(null)
const payload = {
title: title.trim(),
intro: intro.trim(),
footer: footer.trim(),
picks: JSON.stringify({ events: [...pickedEvents], posts: [...pickedPosts], cards: [...pickedCards] }),
content_blocks: blocks.map((block) => ({ ...block, slot: 'body' })),
title: parts.find((part) => part.type === 'title')?.text?.trim() || '',
layout: JSON.stringify(parts),
}
try {
const data = draft
@ -190,39 +339,134 @@ export default function AdminNewsletter() {
}
}
/* 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. */
// A picked post's public page: its excerpt and cover, and proof it's live.
const pickedPostKey = picksOf(parts, 'posts').join(',')
useEffect(() => {
for (const id of pickedPostKey.split(',').filter(Boolean)) {
if (postDetails[id]) continue
get(`/blog/${encodeURIComponent(id)}`)
.then((data: { post: BlogPostRecord }) => setPostDetails((current) => ({ ...current, [id]: data.post })))
.catch(() => {})
}
}, [pickedPostKey, postDetails])
// What each source's picks can be, by ref, as the email draws them.
const lookup = useMemo(() => {
const byEvent = new Map<string, NewsletterItem>()
for (const event of events) {
byEvent.set(event.id, {
title: event.title,
meta: [seriesLabel(event.series, event.starts_on) ?? event.date_label, event.is_online && !event.location_label ? 'Online' : event.location_label]
.filter(Boolean)
.join(', '),
text: event.tagline ?? event.description?.[0] ?? null,
image: imageFor(event.card_image),
href: siteUrl(eventHref(event.id)),
cta: PICK_DEFAULTS.events.cta,
})
}
const byPost = new Map<string, NewsletterItem>()
for (const [id, post] of Object.entries(postDetails)) {
const byline = post.authors.map((a) => a.name).concat(post.guest ? [post.guest.name] : []).join(', ')
byPost.set(id, {
title: post.title,
meta: byline ? `By ${byline}` : null,
text: post.excerpt ?? null,
image: imageFor(post.cover_image),
href: siteUrl(blogHref(post.id)),
cta: PICK_DEFAULTS.posts.cta,
})
}
const byCard = new Map<string, NewsletterItem>()
for (const card of cards) {
const href = featuredHref(card)
if (!href) continue
byCard.set(href, {
title: card.title ?? 'Featured',
meta: card.eyebrow ?? null,
text: card.blurb ?? null,
image: card.image ? imageFor(card.image.file) : null,
href: absolute(href) ?? href,
cta: card.kind === 'video' ? 'Watch' : PICK_DEFAULTS.cards.cta,
})
}
return { events: byEvent, posts: byPost, cards: byCard } as Record<PickSource, Map<string, NewsletterItem>>
}, [events, postDetails, cards])
// The picks selects' choices, by source (PARTS_SPEC's optionsFrom).
const pickOptions = useMemo(
() => ({
events: events.map((event) => ({ id: event.id, label: [event.title, event.date_label].filter(Boolean).join(', ') })),
posts: (posts ?? []).map((row) => ({ id: row.id, label: [row.title, row.published_on].filter(Boolean).join(', ') })),
cards: cards.flatMap((card) => {
const href = featuredHref(card)
return href ? [{ id: href, label: card.title ?? href }] : []
}),
countdownEvents: events
.filter((event) => !event.is_series && event.starts_on)
.map((event) => ({ id: event.id, label: [event.title, event.date_label].filter(Boolean).join(', ') })),
}),
[events, posts, cards],
)
const newsletter = useMemo(() => {
const content = {
parts,
itemsFor: (part: NewsletterPart) =>
(part.picked ?? []).flatMap((pick) => {
const item = pick.ref ? lookup[sourceOf(part)].get(pick.ref) : undefined
return item ? [{ ...item, cta: part.cta?.trim() || item.cta }] : []
}),
eventFor: (id: string) => {
const event = events.find((row) => row.id === id && !row.is_series && row.starts_on)
return event ? { title: event.title, starts_on: event.starts_on, href: siteUrl(eventHref(event.id)) } : null
},
now: Date.now(),
defaultSocials: SOCIAL_LINKS.map((link) => ({ platform: link.platform, url: link.href })),
origin: SITE_ORIGIN,
siteName: SITE_NAME,
absolute: absoluteFor,
}
return { content, html: newsletterHtml(content), text: newsletterText(content) }
}, [parts, lookup, events])
/* An unpublished blog post from what's built: the blocks, then each
picks section as a heading and link cards. The header, title and
footer are the email's own. It opens in the post's editor. */
async function postAsBlog() {
setBusy(true)
setMessage(null)
const postTitle = newsletter.content.title
const postTitle = newsletterTitle(newsletter.content)
const id = `${slugify(postTitle).slice(0, 52) || 'newsletter'}-${new Date().toISOString().slice(0, 10)}`
const body = [
...(intro.trim() ? [{ type: 'paragraph', text: intro.trim() }] : []),
...blocks,
...newsletter.content.sections
.filter((section) => section.items.length > 0)
.flatMap((section) => [
{ type: 'heading', text: section.heading },
const body = parts.flatMap((part) => {
if (part.type === 'picks') {
const items = newsletter.content.itemsFor(part)
if (items.length === 0) return []
return [
{ type: 'heading', text: part.text?.trim() || PICK_DEFAULTS[sourceOf(part)].heading },
{
type: 'cards',
items: section.items.map((item) => ({
items: items.map((item) => ({
text: item.title,
detail: [item.meta, item.text].filter(Boolean).join('\n\n') || null,
url: item.href,
media: item.image ?? null,
})),
},
]),
].map((block) => ({ ...block, slot: 'body' }))
]
}
if (!EMAIL_BLOCKS.includes(part.type)) return []
const { align: _align, color: _color, size: _size, space: _space, socials: _socials, event: _event, ...block } = part
return [block]
})
const excerpt = parts.find((part) => part.type === 'paragraph' && part.text?.trim())?.text?.trim() ?? null
try {
await post('/admin/blog_posts', {
id,
title: postTitle,
excerpt: intro.trim() || null,
excerpt,
is_published: false,
content_blocks: body,
content_blocks: body.map((block) => ({ ...block, slot: 'body' })),
})
navigate(`/admin/blog_posts/${id}`)
} catch (err) {
@ -232,90 +476,6 @@ 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 = <T,>(set: Set<T>, value: T, update: (next: Set<T>) => void) => {
const next = new Set(set)
if (next.has(value)) next.delete(value)
else next.add(value)
update(next)
}
const newsletter = useMemo(() => {
const eventItems: NewsletterItem[] = events
.filter((event) => pickedEvents.has(event.id))
.map((event) => ({
title: event.title,
meta: [seriesLabel(event.series, event.starts_on) ?? event.date_label, event.is_online && !event.location_label ? 'Online' : event.location_label]
.filter(Boolean)
.join(', '),
text: event.tagline ?? event.description?.[0] ?? null,
image: imageFor(event.card_image),
href: siteUrl(eventHref(event.id)),
cta: 'Event details',
}))
const postItems: NewsletterItem[] = (posts ?? [])
.filter((row) => pickedPosts.has(row.id) && postDetails[row.id])
.map((row) => {
const post = postDetails[row.id]
const byline = post.authors.map((a) => a.name).concat(post.guest ? [post.guest.name] : []).join(', ')
return {
title: post.title,
meta: byline ? `By ${byline}` : null,
text: post.excerpt ?? null,
image: imageFor(post.cover_image),
href: siteUrl(blogHref(post.id)),
cta: 'Read the post',
}
})
const cardItems: NewsletterItem[] = cards
.map((card) => ({ 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)
@ -335,12 +495,15 @@ export default function AdminNewsletter() {
URL.revokeObjectURL(link.href)
}
const empty = parts.length === 0
const split = usePreviewWidth()
return (
<div>
<div className="flex flex-wrap items-baseline gap-3">
<h1 className="text-2xl font-bold text-link">Newsletter</h1>
<p className="text-sm" style={{ color: MUTED }}>
Pick what to include, then copy the email into Mailchimp, Gmail or Church Center.
Build the email part by part, then copy it into Mailchimp, Gmail or Church Center.
</p>
</div>
@ -351,7 +514,7 @@ export default function AdminNewsletter() {
<option value="">New draft</option>
{drafts.map((row) => (
<option key={row.id} value={row.id}>
{row.title || `News from ${SITE_NAME}`} (saved {row.updated_at.slice(0, 16)})
{row.title || DEFAULT_TITLE(SITE_NAME)} (saved {row.updated_at.slice(0, 16)})
</option>
))}
</select>
@ -362,7 +525,7 @@ export default function AdminNewsletter() {
<FloppyDisk weight="bold" aria-hidden="true" />
{draft ? 'Save draft' : 'Save as a new draft'}
</button>
<button type="button" onClick={postAsBlog} className={button} disabled={busy || newsletter.count === 0}>
<button type="button" onClick={postAsBlog} className={button} disabled={busy || empty}>
<Article weight="bold" aria-hidden="true" />
Post as blog post
</button>
@ -381,96 +544,61 @@ export default function AdminNewsletter() {
)}
</div>
<div className="mt-6 grid gap-8 lg:grid-cols-[minmax(0,26rem)_minmax(0,1fr)]">
<div className="space-y-6">
<section className="space-y-3 border-l-4 border-brand bg-raised p-5 shadow-sm">
<label className="block text-sm font-semibold text-body">
Title
<input value={title} onChange={(e) => setTitle(e.target.value)} placeholder={`News from ${SITE_NAME}`} className={`mt-1 ${input}`} />
</label>
<label className="block text-sm font-semibold text-body">
Intro
<textarea
value={intro}
onChange={(e) => setIntro(e.target.value)}
rows={4}
placeholder="eg. A few things coming up this month…"
className={`mt-1 resize-y ${input}`}
/>
</label>
</section>
{/* The editor takes what the preview leaves; the handle between
them sets the preview's width (from lg up). */}
<div
ref={split.ref}
className="mt-6 grid gap-8 lg:grid-cols-[minmax(0,1fr)_auto_var(--preview-width)] lg:gap-3"
style={{ '--preview-width': `${split.width}px` } as React.CSSProperties}
>
<section className="border-l-4 border-brand bg-raised p-5 shadow-sm">
<Repeater spec={PARTS_SPEC} rows={parts} options={pickOptions} errors={{}} errorPrefix="parts." className="" onChange={setParts} />
<p className="mt-3 text-xs" style={{ color: MUTED }}>
{eventsLoading || posts === null ? 'Loading what can be picked…' : 'Picked items show once chosen; a section with none is left out.'}
</p>
</section>
<section className="border-l-4 border-brand bg-raised p-5 shadow-sm">
<Repeater spec={BLOCKS_SPEC} rows={blocks} options={{}} errors={{}} errorPrefix="content_blocks." className="" onChange={setBlocks} />
</section>
<PickList
title="Upcoming events"
empty={eventsLoading ? 'Loading…' : 'No upcoming events.'}
options={events.map((event) => ({ value: event.id, label: event.title, detail: event.date_label }))}
picked={pickedEvents}
onToggle={(value) => toggle(pickedEvents, value, setPickedEvents)}
/>
<PickList
title="Blog posts"
empty={posts ? 'No published posts.' : 'Loading…'}
options={(posts ?? []).map((post) => ({ value: post.id, label: post.title, detail: post.published_on }))}
picked={pickedPosts}
onToggle={(value) => toggle(pickedPosts, value, setPickedPosts)}
/>
<PickList
title="Featured cards (front page)"
empty="No featured cards."
options={cards.flatMap((card) => {
const href = featuredHref(card)
return href ? [{ value: href, label: card.title ?? href, detail: card.kind }] : []
})}
picked={pickedCards}
onToggle={(value) => toggle(pickedCards, value, setPickedCards)}
/>
<section className="border-l-4 border-brand bg-raised p-5 shadow-sm">
<label className="block text-sm font-semibold text-body">
Footer
<textarea
value={footer}
onChange={(e) => setFooter(e.target.value)}
rows={3}
placeholder={`${SITE_NAME}\n${SITE_ORIGIN}`}
className={`mt-1 resize-y ${input}`}
/>
</label>
<p className="mt-1 text-xs" style={{ color: MUTED }}>
Default: the site's name and address. No unsubscribe link needed: Mailchimp adds its own.
</p>
</section>
<div
role="separator"
aria-orientation="vertical"
aria-label="Resize the parts and the preview"
aria-valuemin={PREVIEW_MIN}
aria-valuemax={split.max}
aria-valuenow={split.width}
tabIndex={0}
onPointerDown={split.start}
onPointerMove={split.drag}
onPointerUp={split.end}
onPointerCancel={split.end}
onKeyDown={split.key}
className="hidden cursor-col-resize touch-none items-start justify-center self-stretch border-x border-brand/20 bg-tint-soft px-0.5 pt-6 text-muted hover:bg-tint hover:text-link focus-visible:bg-tint focus-visible:text-link lg:flex"
>
<DotsSixVertical size={16} weight="bold" aria-hidden="true" className="lg:sticky lg:top-1/2" />
</div>
<div>
<div className="min-w-0">
<div className="flex flex-wrap gap-3">
<button type="button" onClick={() => copy('html')} className={button} disabled={newsletter.count === 0}>
<button type="button" onClick={() => copy('html')} className={button} disabled={empty}>
{copied === 'html' ? <Check weight="bold" aria-hidden="true" /> : <Copy weight="bold" aria-hidden="true" />}
{copied === 'html' ? 'Copied' : 'Copy HTML'}
</button>
<button type="button" onClick={() => copy('text')} className={button} disabled={newsletter.count === 0}>
<button type="button" onClick={() => copy('text')} className={button} disabled={empty}>
{copied === 'text' ? <Check weight="bold" aria-hidden="true" /> : <Copy weight="bold" aria-hidden="true" />}
{copied === 'text' ? 'Copied' : 'Copy plain text'}
</button>
<button type="button" onClick={download} className={button} disabled={newsletter.count === 0}>
<button type="button" onClick={download} className={button} disabled={empty}>
<DownloadSimple weight="bold" aria-hidden="true" />
Download .html
</button>
</div>
<p className="mt-2 text-xs" style={{ color: MUTED }}>
{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".`}
{empty ? 'Add a part to build the email.' : 'In Mailchimp, paste the HTML into a Code block or "Paste in code".'}
</p>
<iframe
title="Newsletter preview"
srcDoc={newsletter.html}
sandbox=""
className="mt-4 h-[70vh] w-full border border-brand/20 bg-white"
className="mt-4 h-[80vh] w-full border border-brand/20 bg-white lg:sticky lg:top-24"
/>
</div>
</div>
@ -478,50 +606,70 @@ export default function AdminNewsletter() {
)
}
function PickList<T extends string | number>({
title,
empty,
options,
picked,
onToggle,
}: {
title: string
empty: string
options: Array<{ value: T; label: string; detail?: string | null }>
picked: Set<T>
onToggle: (value: T) => void
}) {
return (
<section className="border-l-4 border-brand bg-raised p-5 shadow-sm">
<h2 className="text-base font-bold text-ink">{title}</h2>
{options.length === 0 ? (
<p className="mt-2 text-sm" style={{ color: MUTED }}>
{empty}
</p>
) : (
<ul className="mt-2 max-h-72 space-y-1 overflow-y-auto">
{options.map((option) => (
<li key={String(option.value)}>
<label className="flex cursor-pointer items-start gap-3 px-2 py-1.5 hover:bg-tint-soft">
<input
type="checkbox"
checked={picked.has(option.value)}
onChange={() => onToggle(option.value)}
className="mt-1 h-4 w-4 accent-[var(--color-action)]"
/>
<span className="min-w-0">
<span className="block text-sm text-ink">{option.label}</span>
{option.detail && (
<span className="block text-xs" style={{ color: MUTED }}>
{option.detail}
</span>
)}
</span>
</label>
</li>
))}
</ul>
)}
</section>
)
/* ── The handle between the parts and the preview ─────────────
Drag it, or focus it and use the arrow keys (Home and End for
the narrowest and widest). Under the email's 600px the preview
shows it as a phone would. The width is remembered in this
browser, a convenience only. */
const PREVIEW_MIN = 320
const PARTS_MIN = 360 // what the parts list keeps, at least
const PREVIEW_DEFAULT = 672
const PREVIEW_KEY = 'site-newsletter-preview-width'
const STEP = 32
function usePreviewWidth() {
const ref = useRef<HTMLDivElement>(null)
const [room, setRoom] = useState(0)
const [wanted, setWanted] = useState(() => {
try {
const saved = Number(window.localStorage.getItem(PREVIEW_KEY))
return saved >= PREVIEW_MIN ? saved : PREVIEW_DEFAULT
} catch {
return PREVIEW_DEFAULT
}
})
// The row's width, so the widest the preview can be follows the window.
useEffect(() => {
const row = ref.current
if (!row) return undefined
const observer = new ResizeObserver(() => setRoom(row.clientWidth))
observer.observe(row)
return () => observer.disconnect()
}, [])
const max = Math.max(PREVIEW_MIN, room ? room - PARTS_MIN : PREVIEW_DEFAULT)
const width = Math.min(max, Math.max(PREVIEW_MIN, wanted))
const set = (next: number) => {
const clamped = Math.round(Math.min(max, Math.max(PREVIEW_MIN, next)))
setWanted(clamped)
try {
window.localStorage.setItem(PREVIEW_KEY, String(clamped))
} catch {
// Storage off: the width lasts until the page is left.
}
}
return {
ref,
width,
max,
start: (e: React.PointerEvent<HTMLDivElement>) => e.currentTarget.setPointerCapture(e.pointerId),
drag: (e: React.PointerEvent<HTMLDivElement>) => {
if (!e.currentTarget.hasPointerCapture(e.pointerId) || !ref.current) return
set(ref.current.getBoundingClientRect().right - e.clientX - e.currentTarget.offsetWidth / 2)
},
end: (e: React.PointerEvent<HTMLDivElement>) => {
if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId)
},
key: (e: React.KeyboardEvent<HTMLDivElement>) => {
// Left widens the preview (the handle moves left), Right narrows it.
const next = { ArrowLeft: width + STEP, ArrowRight: width - STEP, Home: PREVIEW_MIN, End: max }[e.key]
if (next === undefined) return
e.preventDefault()
set(next)
},
}
}