Codebase audits, privacy, dark mode, palette (v1.9.0 to v1.9.4-audit) #14

Merged
ngu-git-admin merged 30 commits from audit into main 2026-09-29 18:07:25 +01:00
23 changed files with 420 additions and 139 deletions
Showing only changes of commit f72a9604d2 - 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`.
- 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`.
- Google sign-in for @nextgenerationofunity.org admin accounts: on when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set on the service. Only existing accounts (made by admin-cli) get in; passwords still work. Setup: `docs/google-sign-in.md`.

71
docs/performance.md Normal file
View file

@ -0,0 +1,71 @@
# Performance
What keeps the site fast, and what nginx has to do for it.
## nginx
In the site's `server` block (both are in `nginx-dev`):
```nginx
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 5;
gzip_min_length 1024;
gzip_types text/css application/javascript text/javascript application/json
image/svg+xml application/xml application/rss+xml text/plain;
listen 443 ssl http2;
listen [::]:443 ssl http2;
```
Ubuntu's `nginx.conf` turns gzip on for `text/html` only, so without
`gzip_types` the JS, CSS, JSON and SVG go out full size (the main JS is
about 314 kB, about 98 kB gzipped). Check with
`curl -sI -H 'Accept-Encoding: gzip' https://<site>/assets/<file>.js | grep -i content-encoding`.
`http2` on the `listen` line works on every nginx; 1.25.1 and later
also take a separate `http2 on;`.
## Caching
- `/assets/` (hashed build files): a year, `immutable` (nginx).
- `/uploads/`: 30 days, `immutable` (nginx). Filenames are random and
never reused.
- Page HTML: `no-cache` (the API, `routes/pages.js`). The page names the
build's hashed assets, so a cached old page after a deploy would ask
for files that are gone.
- Public API reads: 60 s, plus 5 minutes stale while revalidating
(`CACHE` in `server/src/shape.js`).
- RSS feeds: read at most every 30 minutes; a visitor never waits for
one after the first read (`server/src/feeds.js`).
## The bundle
Only the home page is in the main bundle. Every other page, and the
whole admin, loads when first visited (`src/App.tsx`). A tab still
running an old build that asks for a page removed by a deploy reloads
once to pick up the new one.
The home page asks for events and the timeline alongside its own data
(`src/pages/Home.tsx`), and the server tells the browser to fetch
`/api/front-page` and the first hero photo while the JS downloads
(`preload` in `server/src/pageMeta.js`).
## Images
Every raster upload gets a copy at most 640 px on its longer side,
`<name>-640.webp`, beside it in the uploads folder
(`server/src/media.js`). Logos, avatars and card pictures load that copy
(`useSmallImage` in `src/lib/useSmallImage.ts`) and fall back to the
full file if it's missing. The server makes any missing copies in the
background when it starts, so older uploads and files copied in by hand
get one too; deleting an upload deletes its copy.
## Server
- Password checks run off the event loop (`verifyPassword`, async
scrypt), so a login doesn't stall other requests.
- Only `/api/admin/*` is logged per request; nginx's access log has the
rest.
- ffmpeg encodes run at `nice 19` on Linux, so a clip doesn't slow the
site down.

View file

@ -18,9 +18,11 @@
import {
createHash,
randomBytes,
scrypt,
scryptSync,
timingSafeEqual,
} from "node:crypto";
import { promisify } from "node:util";
import { getCookie, setCookie, deleteCookie } from "hono/cookie";
const SESSION_DAYS = 30;
@ -68,7 +70,11 @@ export function hashPassword(password) {
].join("$");
}
export function verifyPassword(password, stored) {
/* Async: a login's hash runs on libuv's thread pool, so the ~100 ms it
takes doesn't stall every other request while it runs. */
const scryptAsync = promisify(scrypt);
export async function verifyPassword(password, stored) {
if (typeof stored !== "string") return false;
const [scheme, N, r, p, saltHex, keyHex] = stored.split("$");
@ -76,7 +82,7 @@ export function verifyPassword(password, stored) {
let candidate;
try {
candidate = scryptSync(
candidate = await scryptAsync(
password.normalize("NFKC"),
Buffer.from(saltHex, "hex"),
Buffer.from(keyHex, "hex").length,

View file

@ -150,11 +150,16 @@ export function checkClip(input, source) {
/* Runs a tool, calling onLine for each line of its output, and
resolves with the tail of stderr, or rejects with it. */
function run(command, args, { onLine } = {}) {
function run(command, args, { onLine, background = false } = {}) {
return new Promise((resolve, reject) => {
let child;
// An encode takes every core it can get; at the lowest priority it
// still does, but the API and its pages come first. Linux only
// (the VPS); elsewhere it runs as it is.
const [cmd, argv] =
background && process.platform === "linux" ? ["nice", ["-n", "19", command, ...args]] : [command, args];
try {
child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
child = spawn(cmd, argv, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
} catch (err) {
reject(err);
return;
@ -425,6 +430,7 @@ async function cut(db, job) {
args.push("-progress", "pipe:1", "-nostats", filePath(name));
await run(FFMPEG, args, {
background: true,
onLine: (line) => {
const us = line.match(/^out_time_us=(\d+)/);
if (us) update(db, job.id, { progress: Math.min(0.99, Number(us[1]) / 1e6 / length) });

View file

@ -35,7 +35,7 @@ import adminEntities from "./routes/admin-entities.js";
import media from "./routes/media.js";
import clips from "./routes/clips.js";
import { CLIPS_DIR, startClipWorker } from "./clips.js";
import { UPLOADS_DIR } from "./media.js";
import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
import { logSafe, startSessionSweeper } from "./auth.js";
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
import { ENTITIES } from "./admin-schema.js";
@ -53,12 +53,20 @@ syncDescriptorsWithSchema(db, ENTITIES);
console.log(`db ${DB_PATH} (${db.driverName}, schema v${version})`);
await mkdir(UPLOADS_DIR, { recursive: true });
console.log(`uploads ${UPLOADS_DIR}`);
// In the background: pages fall back to the full file until it's done.
writeMissingThumbs()
.then((made) => made && console.log(`uploads: made ${made} small copies`))
.catch((err) => console.warn(`uploads: small copies failed: ${err.message}`));
/* ── App ─────────────────────────────────────────────────────── */
const app = new Hono();
app.use("*", logger());
// One log line per admin request, for the record of who did what.
// Public traffic is left to nginx's access log: logging every request
// here too would double the lines and, under a spike, cost the event
// loop a synchronous write each.
app.use("/api/admin/*", logger());
/* Headers for every response. Referrer kept to the origin (YouTube
embeds refuse to play without one). No HSTS here: nginx sends it on

View file

@ -172,6 +172,7 @@ export async function store(buf, { keepOriginal = false } = {}) {
const tmp = path.join(UPLOADS_DIR, `.${filename}.tmp`);
await writeFile(tmp, out);
await rename(tmp, path.join(UPLOADS_DIR, filename));
if (kind !== "svg") await writeThumb(filename, out);
return {
filename,
@ -183,16 +184,72 @@ export async function store(buf, { keepOriginal = false } = {}) {
};
}
/* Deletes one stored file. A file that's already gone is not an
error: the row is what's being removed. */
/* ── Small copies ──────────────────────────────────────────────
Beside every raster upload, <name>-640.webp: the same image at most
640px on its longer side. Photos and logos shown small (avatars,
cards, marks) load it instead of the full file; the page falls back
to the full file if it's missing (src/lib/media.ts, mediaThumb).
Made when a file is uploaded, and at boot for any upload that
doesn't have one yet (files from before this, or copied in by hand).
───────────────────────────────────────────────────────────── */
export const THUMB_EDGE = 640;
const THUMB = /-640\.webp$/;
export const thumbName = (filename) => `${filename.replace(/\.[^.]+$/, "")}-640.webp`;
async function writeThumb(filename, buf) {
const name = thumbName(filename);
const tmp = path.join(UPLOADS_DIR, `.${name}.tmp`);
try {
await sharp(buf, { animated: true, limitInputPixels: MAX_INPUT_PIXELS })
.rotate()
.resize({ width: THUMB_EDGE, height: THUMB_EDGE, fit: "inside", withoutEnlargement: true })
.webp({ quality: WEBP_QUALITY })
.toFile(tmp);
await rename(tmp, path.join(UPLOADS_DIR, name));
} catch (err) {
// The full file is what matters; without a copy the page uses it.
await unlink(tmp).catch(() => {});
console.warn(`media: no small copy of ${filename}: ${err.message}`);
}
}
/* Makes the small copy for every raster upload that lacks one.
Returns how many it made. */
export async function writeMissingThumbs() {
let names;
try {
names = await readdir(UPLOADS_DIR);
} catch (err) {
if (err.code === "ENOENT") return 0;
throw err;
}
const present = new Set(names);
let made = 0;
for (const name of names) {
if (name.startsWith(".") || THUMB.test(name) || /\.svg$/i.test(name)) continue;
if (present.has(thumbName(name))) continue;
const buf = await readFile(path.join(UPLOADS_DIR, name)).catch(() => null);
if (!buf || !sniff(buf) || sniff(buf) === "svg") continue;
await writeThumb(name, buf);
made += 1;
}
return made;
}
/* Deletes one stored file and its small copy. A file that's already
gone is not an error: the row is what's being removed. */
export async function remove(filename) {
// filename comes from our own table, but it's joined onto a
// directory, so refuse anything that isn't a bare name.
if (path.basename(filename) !== filename) return;
try {
await unlink(path.join(UPLOADS_DIR, filename));
} catch (err) {
if (err.code !== "ENOENT") throw err;
for (const name of [filename, thumbName(filename)]) {
try {
await unlink(path.join(UPLOADS_DIR, name));
} catch (err) {
if (err.code !== "ENOENT") throw err;
}
}
}
@ -252,7 +309,7 @@ export async function registerLooseFiles(db) {
let added = 0;
for (const name of names) {
if (known.has(name) || name.startsWith(".") || path.basename(name) !== name) continue;
if (known.has(name) || name.startsWith(".") || THUMB.test(name) || path.basename(name) !== name) continue;
let row;
try {
row = await describe(name);

View file

@ -0,0 +1,10 @@
-- ═══════════════════════════════════════════════════════════════
-- 042 AWARD RECIPIENTS BY AWARD
--
-- person_awards is read by award (an award's page lists its
-- recipients, an organization counts them), but its only index
-- starts with person_id, so those reads scan the table. Tiny today;
-- this keeps it from mattering later.
-- ═══════════════════════════════════════════════════════════════
CREATE INDEX person_awards_award_idx ON person_awards (award_id);

View file

@ -347,8 +347,23 @@ export function metaFor(db, rawPath) {
const meta = defaults(site, db, pathname);
if (pathname === "/") {
// The home page's data, and its first hero photo when the hero is
// a slideshow, requested alongside the app's JavaScript instead of
// after it has run.
const hero = db.prepare(`SELECT hero_backdrop FROM front_page WHERE id = 'home'`).get();
const slide =
hero?.hero_backdrop === "photos"
? db
.prepare(`SELECT media FROM front_page_slides WHERE page_id = 'home' ORDER BY sort_order LIMIT 1`)
.get()
: null;
const slideSrc = slide?.media ? (/^(https?:|\/)/.test(slide.media) ? slide.media : `${UPLOADS}/${slide.media}`) : null;
return {
...meta,
preload: [
{ href: "/api/front-page", as: "fetch" },
...(slideSrc ? [{ href: slideSrc, as: "image" }] : []),
],
jsonLd: {
"@context": "https://schema.org",
"@type": "Organization",
@ -446,6 +461,11 @@ export function renderPage(html, meta) {
site.icons?.icon && `<link rel="icon" href="${escapeHtml(site.icons.icon)}">`,
site.icons?.apple && `<link rel="apple-touch-icon" href="${escapeHtml(site.icons.apple)}">`,
meta.jsonLd && `<script type="application/ld+json">${scriptJson(meta.jsonLd)}</script>`,
...(meta.preload ?? []).map((p) =>
p.as === "fetch"
? `<link rel="preload" href="${escapeHtml(p.href)}" as="fetch" crossorigin>`
: `<link rel="preload" href="${escapeHtml(p.href)}" as="image" fetchpriority="high">`,
),
// Read by src/lib/site.ts before the app's module runs (a plain
// script in the head runs during parsing; modules wait).
`<script>window.__NGU_SITE__ = ${scriptJson(forBrowser(site))}</script>`,

View file

@ -94,8 +94,8 @@ auth.post("/login", async (c) => {
const ok =
user && user.is_active === 1
? verifyPassword(password, user.password_hash)
: (verifyPassword(password, DUMMY_HASH), false);
? await verifyPassword(password, user.password_hash)
: (await verifyPassword(password, DUMMY_HASH), false);
if (!ok) {
loginFailures.fail(email);

View file

@ -120,8 +120,12 @@ pages.get("*", (c, next) => {
return c.html(html, 200, { "Cache-Control": "no-store" });
}
// no-cache: a browser may keep the page but asks again each time.
// HTML names the build's hashed /assets files, and after a deploy
// those are gone, so a cached old page would load nothing. Pages
// are rebuilt in well under a millisecond.
return c.html(page, meta.status, {
"Cache-Control": meta.status === 200 ? CACHE : "no-store",
"Cache-Control": meta.status === 200 ? "no-cache" : "no-store",
});
});

View file

@ -1,50 +1,86 @@
import { BrowserRouter, Routes, Route, Outlet, Navigate } from "react-router-dom";
import { lazy, Suspense } from "react";
import {
BrowserRouter,
Routes,
Route,
Outlet,
Navigate,
} from "react-router-dom"
import { lazy, Suspense } from "react"
/*Components*/
import Layout from "./components/Layout.tsx";
import Layout from "./components/Layout.tsx"
/*Libraries*/
import { AuthProvider, RequireAuth } from "./lib/auth.tsx";
import RequireRole from "./pages/admin/RequireRole.tsx";
import { AuthProvider, RequireAuth } from "./lib/auth.tsx"
import RequireRole from "./pages/admin/RequireRole.tsx"
/*Primary Pages*/
import Home from "./pages/Home.tsx";
import Retreats from "./pages/Retreats.tsx";
import Community from "./pages/Community.tsx";
import Leadership from "./pages/Leadership.tsx";
import Resources from "./pages/Resources.tsx";
import History from "./pages/History.tsx";
/*Pages*/
// Home is the landing page, so it ships in the main bundle. Every
// other page, and all of the admin, is fetched when first visited:
// a visitor to the front page never downloads the admin, the QR
// encoder, the calendar or the chapter map. Layout and AdminLayout
// wrap their <Outlet /> in <Suspense>, so the header stays put while
// a page loads.
import Home from "./pages/Home.tsx"
/*Secondary Pages*/
import Feedback from "./pages/Feedback.tsx";
import Giving from "./pages/Giving.tsx";
/* A page's chunk can be missing when a deploy replaced the build while
this tab still ran the old one. Reload once to pick up the new
build; if that doesn't help, let the error surface. */
const CHUNK_RELOAD = "ngu-chunk-reload"
const lazyPage = (load) =>
lazy(() =>
load()
.then((page) => {
try {
sessionStorage.removeItem(CHUNK_RELOAD)
} catch {}
return page
})
.catch((err) => {
const key = CHUNK_RELOAD
let reloaded = false
try {
reloaded = sessionStorage.getItem(key) === "1"
sessionStorage.setItem(key, "1")
} catch {}
if (!reloaded) {
window.location.reload()
return new Promise(() => {})
}
throw err
}),
)
const Retreats = lazyPage(() => import("./pages/Retreats.tsx"))
const Community = lazyPage(() => import("./pages/Community.tsx"))
const Leadership = lazyPage(() => import("./pages/Leadership.tsx"))
const Resources = lazyPage(() => import("./pages/Resources.tsx"))
const History = lazyPage(() => import("./pages/History.tsx"))
const Feedback = lazyPage(() => import("./pages/Feedback.tsx"))
const Giving = lazyPage(() => import("./pages/Giving.tsx"))
const QrCodes = lazyPage(() => import("./pages/QrCodes.tsx"))
const Privacy = lazyPage(() => import("./pages/Privacy.tsx"))
const Terms = lazyPage(() => import("./pages/Terms.tsx"))
const NotFound = lazyPage(() => import("./pages/NotFound.tsx"))
/*Entity Pages*/
import EventDetail from './pages/EventDetail.tsx'
import OrganizationDetail from './pages/OrganizationDetail.tsx'
import TeamDetail from './pages/TeamDetail.tsx'
import AwardDetail from './pages/AwardDetail.tsx'
import PersonDetail from './pages/PersonDetail.tsx'
import BlogPost from './pages/BlogPost.tsx'
const EventDetail = lazyPage(() => import("./pages/EventDetail.tsx"))
const OrganizationDetail = lazyPage(
() => import("./pages/OrganizationDetail.tsx"),
)
const TeamDetail = lazyPage(() => import("./pages/TeamDetail.tsx"))
const AwardDetail = lazyPage(() => import("./pages/AwardDetail.tsx"))
const PersonDetail = lazyPage(() => import("./pages/PersonDetail.tsx"))
const BlogPost = lazyPage(() => import("./pages/BlogPost.tsx"))
/*Admin Pages*/
import AdminLayout from "./pages/admin/AdminLayout.tsx";
import AdminLogin from "./pages/admin/AdminLogin.tsx";
import AdminPanel from "./pages/admin/AdminPanel.tsx";
import AdminHome from "./pages/admin/AdminHome.tsx";
import AdminFeedback from "./pages/admin/AdminFeedback.tsx";
import AdminMedia from "./pages/admin/AdminMedia.tsx";
import AdminClips from "./pages/admin/AdminClips.tsx";
import EntityList from "./pages/admin/EntityList.tsx";
import EntityEdit from "./pages/admin/EntityEdit.tsx";
/*Ternary Pages*/
import Privacy from "./pages/Privacy.tsx";
import Terms from "./pages/Terms.tsx";
import NotFound from "./pages/NotFound.tsx";
// Loaded on demand: it brings the QR encoder, which no other page needs.
const QrCodes = lazy(() => import("./pages/QrCodes.tsx"));
const AdminLayout = lazyPage(() => import("./pages/admin/AdminLayout.tsx"))
const AdminLogin = lazyPage(() => import("./pages/admin/AdminLogin.tsx"))
const AdminPanel = lazyPage(() => import("./pages/admin/AdminPanel.tsx"))
const AdminHome = lazyPage(() => import("./pages/admin/AdminHome.tsx"))
const AdminFeedback = lazyPage(() => import("./pages/admin/AdminFeedback.tsx"))
const AdminMedia = lazyPage(() => import("./pages/admin/AdminMedia.tsx"))
const AdminClips = lazyPage(() => import("./pages/admin/AdminClips.tsx"))
const EntityList = lazyPage(() => import("./pages/admin/EntityList.tsx"))
const EntityEdit = lazyPage(() => import("./pages/admin/EntityEdit.tsx"))
export default function App() {
return (
@ -54,46 +90,54 @@ export default function App() {
<Route element={<Layout />}>
<Route index element={<Home />} />
<Route path="retreats" element={<Retreats />} />
<Route path="/events/:id" element={<EventDetail />} />
<Route path="/events/:id" element={<EventDetail />} />
<Route path="community" element={<Community />} />
<Route path="/regions/:id" element={<OrganizationDetail />} />
<Route path="/chapters/:id" element={<OrganizationDetail />} />
<Route path="/partners/:id" element={<OrganizationDetail />} />
<Route path="/organizations/:id" element={<OrganizationDetail />} />
<Route path="/teams/:id" element={<TeamDetail />} />
<Route path="/awards/:id" element={<AwardDetail />} />
<Route path="/people/:id" element={<PersonDetail />} />
<Route path="/blog/:id" element={<BlogPost />} />
<Route path="/regions/:id" element={<OrganizationDetail />} />
<Route path="/chapters/:id" element={<OrganizationDetail />} />
<Route path="/partners/:id" element={<OrganizationDetail />} />
<Route path="/organizations/:id" element={<OrganizationDetail />} />
<Route path="/teams/:id" element={<TeamDetail />} />
<Route path="/awards/:id" element={<AwardDetail />} />
<Route path="/people/:id" element={<PersonDetail />} />
<Route path="/blog/:id" element={<BlogPost />} />
<Route path="leadership" element={<Leadership />} />
<Route path="resources" element={<Resources />} />
<Route path="history" element={<History />} />
<Route path="feedback" element={<Feedback />} />
<Route path="qr" element={<Suspense fallback={null}><QrCodes /></Suspense>} />
<Route path="feedback" element={<Feedback />} />
<Route path="qr" element={<QrCodes />} />
<Route path="give" element={<Giving />} />
<Route path="privacy" element={<Privacy />} />
<Route path="terms" element={<Terms />} />
<Route path="*" element={<NotFound />} />
</Route>
<Route element={<AuthProvider><Outlet /></AuthProvider>}>
<Route path="/admin/login" element={<AdminLogin />} />
<Route element={<RequireAuth />}>
<Route path="/admin" element={<AdminLayout />}>
<Route index element={<Navigate to="/admin/home" replace />} />
<Route path="home" element={<AdminHome />} />
<Route element={<RequireRole role="superadmin" />}>
<Route path="panel" element={<AdminPanel />} />
</Route>
<Route path="feedback" element={<AdminFeedback />} />
<Route path="media" element={<AdminMedia />} />
<Route element={<RequireRole role="admin" />}>
<Route path="clips" element={<AdminClips />} />
</Route>
<Route path=":entity" element={<EntityList />} />
<Route
element={
<AuthProvider>
<Suspense fallback={null}>
<Outlet />
</Suspense>
</AuthProvider>
}
>
<Route path="/admin/login" element={<AdminLogin />} />
<Route element={<RequireAuth />}>
<Route path="/admin" element={<AdminLayout />}>
<Route index element={<Navigate to="/admin/home" replace />} />
<Route path="home" element={<AdminHome />} />
<Route element={<RequireRole role="superadmin" />}>
<Route path="panel" element={<AdminPanel />} />
</Route>
<Route path="feedback" element={<AdminFeedback />} />
<Route path="media" element={<AdminMedia />} />
<Route element={<RequireRole role="admin" />}>
<Route path="clips" element={<AdminClips />} />
</Route>
<Route path=":entity" element={<EntityList />} />
<Route path=":entity/:id" element={<EntityEdit />} />
</Route>
</Route>
</Route>
</Route>
</Route>
</Route>
</Routes>
</BrowserRouter>
);
)
}

View file

@ -18,13 +18,13 @@
panel instead, since cropping a logo to 16:9 cuts it off.
═══════════════════════════════════════════════════════════════ */
import { useState } from 'react'
import HomeLink from '../pages/sections/home/HomeLink.tsx'
import VideoPlayer from './VideoPlayer.tsx'
import { refHref } from '../lib/hrefs.ts'
import { mediaUrl } from '../lib/media.ts'
import type { FeaturedCard } from '../lib/useFrontPage.ts'
import { useSmallImage } from '../lib/useSmallImage.ts'
/* Image kinds that are photographs, drawn edge to edge. Anything
else is a logo, drawn whole. */
@ -38,29 +38,28 @@ function hrefFor(card: FeaturedCard): string | null {
}
function Picture({ card }: { card: FeaturedCard }) {
const [failed, setFailed] = useState(false)
const src = card.image ? mediaUrl(card.image.file) : null
const img = useSmallImage(card.image ? mediaUrl(card.image.file) : null)
const photo = card.image ? PHOTO_KINDS.has(card.image.kind) : false
if (!src || failed) {
if (img.failed) {
return <div className="aspect-video w-full bg-tint" />
}
return photo ? (
<img
src={src}
src={img.src}
alt=""
loading="lazy"
onError={() => setFailed(true)}
onError={img.onError}
className="aspect-video w-full object-cover"
/>
) : (
<div className="flex aspect-video w-full items-center justify-center bg-tint p-8">
<img
src={src}
src={img.src}
alt=""
loading="lazy"
onError={() => setFailed(true)}
onError={img.onError}
className="max-h-full max-w-full object-contain"
/>
</div>

View file

@ -1,4 +1,4 @@
import { useState, useEffect, useRef } from "react";
import { Suspense, useState, useEffect, useRef } from "react";
import { NavLink, Link, Outlet, useLocation } from "react-router-dom";
import { PAGE_LINKS, PAGE_SECTIONS, NAV_ACTIONS } from "../navConfig.ts";
import Banner from "./Banner.tsx";
@ -268,7 +268,9 @@ export default function Layout() {
{/* Page content */}
<main id="main" tabIndex={-1} className="outline-none" inert={mobileMenuOpen}>
<Outlet />
<Suspense fallback={null}>
<Outlet />
</Suspense>
</main>
{/*Site Footer applied to every page*/}

View file

@ -3,12 +3,14 @@
An <img> for a logo or mark that may not exist: no src, or a file
that 404s, and it draws `fallback` instead (initials, a colour dot,
or nothing). `src` is already resolved (mediaUrl in media.ts).
Decorative by default (alt ""), since a logo sits next to the
name it stands for.
or nothing). `src` is already resolved (mediaUrl in media.ts). An
upload loads its 640px copy first (useSmallImage). Decorative by
default (alt ""), since a logo sits next to the name it stands for.
═══════════════════════════════════════════════════════════════ */
import { useState, type ReactNode } from 'react'
import type { ReactNode } from 'react'
import { useSmallImage } from '../lib/useSmallImage.ts'
export default function Logo({
src,
@ -21,7 +23,7 @@ export default function Logo({
className?: string
fallback?: ReactNode
}) {
const [failed, setFailed] = useState(false)
if (!src || failed) return <>{fallback}</>
return <img src={src} alt={alt} loading="lazy" className={className} onError={() => setFailed(true)} />
const img = useSmallImage(src)
if (img.failed) return <>{fallback}</>
return <img src={img.src} alt={alt} loading="lazy" className={className} onError={img.onError} />
}

View file

@ -13,6 +13,7 @@ import { Link } from "react-router-dom";
import { get } from "../lib/api.ts";
import { isBadId, personHref } from "../lib/hrefs.ts";
import { mediaUrl, initials } from "../lib/media.ts";
import { useSmallImage } from "../lib/useSmallImage.ts";
import "./PeopleTiles.css";
/**
@ -588,13 +589,9 @@ function Tile({
}
function Photo({ src, name }: { src?: string | null; name: string }) {
const [failed, setFailed] = useState(false);
const img = useSmallImage(src);
useEffect(() => {
setFailed(false);
}, [src]);
if (!src || failed) {
if (img.failed) {
return (
<span className="pl__initials" aria-hidden="true">
{initials(name)}
@ -605,11 +602,11 @@ function Photo({ src, name }: { src?: string | null; name: string }) {
return (
<img
className="pl__img"
src={src}
src={img.src}
alt=""
loading="lazy"
decoding="async"
onError={() => setFailed(true)}
onError={img.onError}
/>
);
}

View file

@ -28,6 +28,7 @@ import { mediaUrl, initials } from '../lib/media.ts'
import type { ContentBlockItem } from '../lib/useContent.ts'
import { Anchor, Paragraphs } from './InlineText.tsx'
import { withAlpha, accentText, readableOn } from '../lib/color.ts'
import { useSmallImage } from '../lib/useSmallImage.ts'
const BODY = 'var(--color-muted)'
const WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
@ -65,10 +66,9 @@ const mapLink = (place: string) =>
`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(place)}`
function Avatar({ person, size }: { person: NonNullable<ContentBlockItem['person']>; size: string }) {
const [failed, setFailed] = useState(false)
const src = mediaUrl(person.photo)
return src && !failed ? (
<img src={src} alt="" onError={() => setFailed(true)} className={`${size} shrink-0 rounded-full object-cover`} />
const img = useSmallImage(mediaUrl(person.photo))
return !img.failed ? (
<img src={img.src} alt="" onError={img.onError} className={`${size} shrink-0 rounded-full object-cover`} />
) : (
<span
aria-hidden="true"

36
src/lib/useSmallImage.ts Normal file
View file

@ -0,0 +1,36 @@
/* ═══════════════════════════════════════════════════════════════
useSmallImage
For an upload shown small (an avatar, a logo, a card picture):
try its 640px copy first (<name>-640.webp, which the server makes
beside every raster upload, server/src/media.js), then the full
file if the copy isn't there, then give up so the caller can draw
its fallback. Anything that isn't an upload, and SVGs, go straight
to the full file.
const img = useSmallImage(mediaUrl(person.photo))
img.failed ? <Initials /> : <img src={img.src} onError={img.onError} />
═══════════════════════════════════════════════════════════════ */
import { useEffect, useState } from 'react'
/* '/uploads/abc.webp' → '/uploads/abc-640.webp'; null for anything else. */
export function smallCopy(src?: string | null): string | null {
if (!src || !src.startsWith('/uploads/') || /\.svg(\?|#|$)/i.test(src)) return null
return src.replace(/\.[^./?#]+(?=$|[?#])/, '') + '-640.webp'
}
export function useSmallImage(src?: string | null) {
// 0: the small copy (when there is one), 1: the full file, 2: failed
const [stage, setStage] = useState(0)
useEffect(() => setStage(0), [src])
const small = smallCopy(src)
const current = !src ? null : stage === 0 && small ? small : stage <= 1 ? src : null
return {
src: current ?? undefined,
failed: current === null,
onError: () => setStage((s) => (s === 0 && small ? 1 : 2)),
}
}

View file

@ -33,6 +33,7 @@ import StatsBand from './sections/home/StatsBand.tsx'
import FeaturedBand from './sections/home/FeaturedBand.tsx'
import FeaturedTimelineRail from './sections/home/FeaturedTimelineRail.tsx'
import Pathfinder from './sections/home/Pathfinder.tsx'
import { get } from '../lib/api.ts'
import { documentTitle } from '../lib/site.ts'
import {
useFrontPage,
@ -105,6 +106,15 @@ const SECTIONS: Record<
export default function Home() {
const { data: page, error, reload } = useFrontPage()
// The bands below ask for events and the timeline once the front
// page has said which of them to show. Start both now, alongside it:
// api.ts hands the same request to the bands when they mount, so
// the page waits for one round trip instead of two.
useEffect(() => {
get('/events').catch(() => {})
get('/history').catch(() => {})
}, [])
// Back to the site name when a visitor returns here from a page.
useEffect(() => {
document.title = documentTitle()

View file

@ -20,7 +20,7 @@
The route guard and the API are what actually say no.
═══════════════════════════════════════════════════════════════ */
import { useCallback, useEffect, useMemo, useState } from "react";
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";
@ -210,7 +210,9 @@ export default function AdminLayout() {
<main className={`mx-auto w-full flex-1 px-6 py-10 ${wide ? "max-w-[82rem]" : "max-w-5xl"}`}>
<AdminTitleContext.Provider value={titleContext}>
<AdminWidthContext.Provider value={setWide}>
<Outlet />
<Suspense fallback={null}>
<Outlet />
</Suspense>
</AdminWidthContext.Provider>
</AdminTitleContext.Provider>
</main>

View file

@ -25,6 +25,7 @@ import { preview } from '../../lib/text.ts'
import { postDate, useCommunityBlog, type BlogPostSummary } from '../../lib/useBlog.ts'
import HomeLink from './home/HomeLink.tsx'
import { accentText } from '../../lib/color.ts'
import { useSmallImage } from '../../lib/useSmallImage.ts'
/* Headings for a half the admin didn't title. */
const DEFAULTS = {
@ -36,14 +37,14 @@ const DEFAULTS = {
const EXCERPT_CHARS = 180
function PostCard({ post, accent }: { post: BlogPostSummary; accent: string }) {
const cover = mediaUrl(post.cover_image)
const cover = useSmallImage(mediaUrl(post.cover_image))
const date = postDate(post.published_on)
const authors = post.authors.map((author) => author.name).join(', ')
return (
<li className="relative flex flex-col overflow-hidden rounded-2xl border border-brand/15 bg-surface shadow-sm transition-shadow hover:shadow-lg">
{cover ? (
<img src={cover} alt="" loading="lazy" className="aspect-video w-full object-cover" />
{!cover.failed ? (
<img src={cover.src} alt="" loading="lazy" onError={cover.onError} className="aspect-video w-full object-cover" />
) : (
<div className="aspect-video w-full bg-tint" />
)}

View file

@ -2,6 +2,7 @@ import { Link } from 'react-router-dom'
import { MONTH_LABELS, type PersonRef, type TimelineItem } from '../../../lib/timeline.ts'
import { hrefFor, logoSrc } from '../../../lib/timelineRefs.ts'
import { initials, mediaUrl } from '../../../lib/media.ts'
import { useSmallImage } from '../../../lib/useSmallImage.ts'
const KIND_NAMES: Record<TimelineItem['kind'], string> = {
milestone: 'Milestone',
@ -28,11 +29,11 @@ function fullMarker(item: TimelineItem): string {
}
function PersonChip({ person }: { person: PersonRef }) {
const src = mediaUrl(person.photo)
const img = useSmallImage(mediaUrl(person.photo))
return (
<li className="ngu-tl__person">
{src ? (
<img className="ngu-tl__personPhoto" src={src} alt="" loading="lazy" />
{!img.failed ? (
<img className="ngu-tl__personPhoto" src={img.src} alt="" loading="lazy" onError={img.onError} />
) : (
<span className="ngu-tl__personPhoto ngu-tl__personPhoto--blank" aria-hidden="true">
{initials(person.name)}

View file

@ -75,7 +75,7 @@ export default function HeroStage({ hero }: { hero: Hero | null }) {
return (
<section
id="hero"
className="relative isolate flex min-h-[92vh] items-center overflow-hidden pt-24 pb-16"
className="relative isolate flex min-h-[92dvh] items-center overflow-hidden pt-24 pb-16"
style={{ background: DEEP }}
>
{backdrop === 'photos' ? (
@ -114,7 +114,6 @@ export default function HeroStage({ hero }: { hero: Hero | null }) {
/* ── The words ───────────────────────────────────────────────── */
function Words({ hero, feature }: { hero: Hero; feature: HeroFeature }) {
const words = hero.headline.split(/\s+/).filter(Boolean)
const live = feature === 'livestream'
const beside = feature !== 'none'
@ -153,27 +152,23 @@ function Words({ hero, feature }: { hero: Hero; feature: HeroFeature }) {
)
)}
{/* One piece, not word by word: the headline is usually the
page's largest paint, and a staggered entrance held it back
by over a second. Sized so an admin's headline stays within
about two lines. */}
<h1
className={`font-display font-extrabold leading-[0.95] tracking-tight ${
beside ? 'text-5xl md:text-6xl' : 'text-6xl md:text-8xl'
className={`hp-rise font-display font-extrabold leading-[1.02] tracking-tight ${
beside ? 'text-4xl md:text-5xl' : 'text-5xl md:text-6xl lg:text-7xl'
}`}
style={{ animationDelay: '60ms' }}
>
{words.map((word, index) => (
<span key={`${word}-${index}`}>
<span
className="hp-rise"
style={{ animationDelay: `${120 + index * 110}ms` }}
>
{word}
</span>{' '}
</span>
))}
{hero.headline}
</h1>
{hero.subhead && (
<p
className="hp-rise mt-8 max-w-2xl text-lg leading-relaxed text-white/75 md:text-xl"
style={{ animationDelay: `${200 + words.length * 110}ms` }}
style={{ animationDelay: '180ms' }}
>
{hero.subhead}
</p>
@ -182,7 +177,7 @@ function Words({ hero, feature }: { hero: Hero; feature: HeroFeature }) {
{(hero.primary || hero.secondary) && (
<div
className="hp-rise mt-10 flex flex-wrap gap-4"
style={{ animationDelay: `${320 + words.length * 110}ms` }}
style={{ animationDelay: '300ms' }}
>
{hero.primary && (
<HomeLink
@ -290,7 +285,13 @@ function PhotoBackdrop({ slides, seconds }: { slides: HeroSlide[]; seconds: numb
className={`hp-slide ${i === index ? 'hp-slide--on' : ''}`}
aria-hidden={i !== index}
>
<img src={mediaUrl(slide.media) ?? ''} alt={slide.alt ?? ''} loading={i === 0 ? 'eager' : 'lazy'} />
<img
src={mediaUrl(slide.media) ?? ''}
alt={slide.alt ?? ''}
loading={i === 0 ? 'eager' : 'lazy'}
fetchPriority={i === 0 ? 'high' : 'low'}
decoding="async"
/>
</div>
))}
<div

View file

@ -27,7 +27,10 @@ export default defineConfig({
},
},
build: {
sourcemap: true,
// Source maps are written for debugging a production error, but
// not linked from the bundle, so the site doesn't publish its
// source to every visitor's devtools.
sourcemap: 'hidden',
},
})