Newsletter: every part editable and movable (v1.11.2-newsletter) #24

Merged
ngu-git-admin merged 4 commits from newsletter-layout into main 2026-10-02 19:50:04 +01:00
29 changed files with 322 additions and 27 deletions
Showing only changes of commit 00170ca912 - Show all commits

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,7 +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. |
| 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

@ -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,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

@ -14,6 +14,12 @@
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,
@ -31,6 +37,7 @@
═══════════════════════════════════════════════════════════════ */
import { readableOn } from './color.ts'
import { PLATFORMS } from './platforms.ts'
export type NewsletterItem = {
title: string
@ -70,12 +77,25 @@ export type NewsletterPart = {
rule?: string | null
/** The bar down the left of a picks section's cards. */
bar?: string | null
/** A social bar's links, in order. */
socials?: Array<{ platform?: string | null; url?: string | null }>
/** A countdown's event. */
event?: string | null
}
/* What a countdown needs of its event. */
export type CountdownEvent = { title: string; starts_on?: string | null; href: string }
export type Newsletter = {
parts: NewsletterPart[]
/** A picks part's items, ready to draw (picked, published, in order). */
itemsFor: (part: NewsletterPart) => NewsletterItem[]
/** A countdown's event, if it's one that can be counted to. */
eventFor: (id: string) => CountdownEvent | null
/** Now, for the countdown's fixed line. */
now: number
/** A social bar with no links of its own shows these (the footer's). */
defaultSocials: Array<{ platform: string; url: string }>
/** The site's address, for the header link and footer. */
origin: string
siteName: string
@ -296,6 +316,53 @@ function footerHtml(part: NewsletterPart, n: Newsletter): string {
</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':
@ -306,6 +373,10 @@ function partHtml(part: NewsletterPart, n: Newsletter): string {
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>` : ''
@ -395,6 +466,15 @@ function partText(part: NewsletterPart, n: Newsletter): string[] {
}
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)
}

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

@ -39,6 +39,8 @@ 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,
@ -73,6 +75,8 @@ const PART_TYPES: Array<[string, string, string]> = [
['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
@ -133,7 +137,17 @@ const PARTS_SPEC = {
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']),
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',
@ -173,6 +187,19 @@ const PARTS_SPEC = {
],
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',
@ -218,7 +245,7 @@ const picksOf = (parts: NewsletterPart[], source: PickSource) =>
.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 [parts, setParts] = useState<NewsletterPart[]>(STARTER)
@ -375,6 +402,9 @@ export default function AdminNewsletter() {
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],
)
@ -387,12 +417,18 @@ export default function AdminNewsletter() {
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])
}, [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
@ -420,7 +456,7 @@ export default function AdminNewsletter() {
]
}
if (!EMAIL_BLOCKS.includes(part.type)) return []
const { align: _align, color: _color, size: _size, space: _space, ...block } = part
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
@ -507,7 +543,8 @@ export default function AdminNewsletter() {
)}
</div>
<div className="mt-6 grid gap-8 lg:grid-cols-[minmax(0,30rem)_minmax(0,1fr)]">
{/* The editor takes what the preview (the email's 600px and its margin) leaves. */}
<div className="mt-6 grid gap-8 lg:grid-cols-[minmax(0,1fr)_minmax(0,42rem)]">
<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 }}>