From f72a9604d26244054a9b1253890b7882b83b2819 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Tue, 29 Sep 2026 02:41:45 -0500 Subject: [PATCH] Make the site faster to load and lighter on the server - Every page but Home, and the whole admin, loads on first visit: the main bundle drops from 579 kB to 314 kB (173 to 98 kB gzipped); a tab on an old build reloads once when a page chunk has gone - Home asks for events and the timeline alongside its own data, and the server preloads /api/front-page and the first hero photo - Hero headline rises in as one piece (it held back the page's largest paint), sized to stay within two lines; min-h in dvh; first slide fetched at high priority - Every raster upload gets a 640px copy (at upload, and at boot for older files); logos, avatars and card pictures load it and fall back to the full file - Login password checks run off the event loop; only admin requests are logged per request; ffmpeg runs at nice 19 on Linux - Page HTML is no-cache, so a deploy can't strand a cached page on missing assets; source maps are no longer linked - Migration 042: index person_awards by award - docs/performance.md, and gzip and HTTP/2 for nginx Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 1 + docs/performance.md | 71 +++++++ server/src/auth.js | 10 +- server/src/clips.js | 10 +- server/src/index.js | 12 +- server/src/media.js | 71 ++++++- .../migrations/042_person_awards_index.sql | 10 + server/src/pageMeta.js | 20 ++ server/src/routes/auth.js | 4 +- server/src/routes/pages.js | 6 +- src/App.tsx | 180 +++++++++++------- src/components/FeaturedCards.tsx | 15 +- src/components/Layout.tsx | 6 +- src/components/Logo.tsx | 16 +- src/components/PeopleTiles.tsx | 13 +- src/components/ScheduleBlock.tsx | 8 +- src/lib/useSmallImage.ts | 36 ++++ src/pages/Home.tsx | 10 + src/pages/admin/AdminLayout.tsx | 6 +- src/pages/sections/CommunityBlog.tsx | 7 +- src/pages/sections/history/TimelineEntry.tsx | 7 +- src/pages/sections/home/HeroStage.tsx | 35 ++-- vite.config.ts | 5 +- 23 files changed, 420 insertions(+), 139 deletions(-) create mode 100644 docs/performance.md create mode 100644 server/src/migrations/042_person_awards_index.sql create mode 100644 src/lib/useSmallImage.ts diff --git a/CLAUDE.md b/CLAUDE.md index 051f5ee..43a287e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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`. diff --git a/docs/performance.md b/docs/performance.md new file mode 100644 index 0000000..5744786 --- /dev/null +++ b/docs/performance.md @@ -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:///assets/.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, +`-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. diff --git a/server/src/auth.js b/server/src/auth.js index 084d513..e6df145 100644 --- a/server/src/auth.js +++ b/server/src/auth.js @@ -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, diff --git a/server/src/clips.js b/server/src/clips.js index bd56ee7..28f05e3 100644 --- a/server/src/clips.js +++ b/server/src/clips.js @@ -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) }); diff --git a/server/src/index.js b/server/src/index.js index 420b7b9..68a0263 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -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 diff --git a/server/src/media.js b/server/src/media.js index 9c5b1fd..d7580f2 100644 --- a/server/src/media.js +++ b/server/src/media.js @@ -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, -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); diff --git a/server/src/migrations/042_person_awards_index.sql b/server/src/migrations/042_person_awards_index.sql new file mode 100644 index 0000000..2c8b10d --- /dev/null +++ b/server/src/migrations/042_person_awards_index.sql @@ -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); diff --git a/server/src/pageMeta.js b/server/src/pageMeta.js index aecca40..7cd826e 100644 --- a/server/src/pageMeta.js +++ b/server/src/pageMeta.js @@ -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 && ``, site.icons?.apple && ``, meta.jsonLd && ``, + ...(meta.preload ?? []).map((p) => + p.as === "fetch" + ? `` + : ``, + ), // Read by src/lib/site.ts before the app's module runs (a plain // script in the head runs during parsing; modules wait). ``, diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index 4bebca5..efac38d 100644 --- a/server/src/routes/auth.js +++ b/server/src/routes/auth.js @@ -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); diff --git a/server/src/routes/pages.js b/server/src/routes/pages.js index 694a53e..c0e34c6 100644 --- a/server/src/routes/pages.js +++ b/server/src/routes/pages.js @@ -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", }); }); diff --git a/src/App.tsx b/src/App.tsx index d74e648..3bd6951 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -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 in , 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() { }> } /> } /> - } /> + } /> } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> } /> } /> } /> - } /> - } /> + } /> + } /> } /> } /> } /> } /> - }> - } /> - }> - }> - } /> - } /> - }> - } /> - - } /> - } /> - }> - } /> - - } /> + + + + + + } + > + } /> + }> + }> + } /> + } /> + }> + } /> + + } /> + } /> + }> + } /> + + } /> } /> - - - + + + - ); + ) } diff --git a/src/components/FeaturedCards.tsx b/src/components/FeaturedCards.tsx index 61e16e5..3b183a7 100644 --- a/src/components/FeaturedCards.tsx +++ b/src/components/FeaturedCards.tsx @@ -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
} return photo ? ( setFailed(true)} + onError={img.onError} className="aspect-video w-full object-cover" /> ) : (
setFailed(true)} + onError={img.onError} className="max-h-full max-w-full object-contain" />
diff --git a/src/components/Layout.tsx b/src/components/Layout.tsx index 83bd113..973fb73 100644 --- a/src/components/Layout.tsx +++ b/src/components/Layout.tsx @@ -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 */}
- + + +
{/*Site Footer applied to every page*/} diff --git a/src/components/Logo.tsx b/src/components/Logo.tsx index b2bb72c..0a606a6 100644 --- a/src/components/Logo.tsx +++ b/src/components/Logo.tsx @@ -3,12 +3,14 @@ An 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 {alt} setFailed(true)} /> + const img = useSmallImage(src) + if (img.failed) return <>{fallback} + return {alt} } diff --git a/src/components/PeopleTiles.tsx b/src/components/PeopleTiles.tsx index d9cce11..096df44 100644 --- a/src/components/PeopleTiles.tsx +++ b/src/components/PeopleTiles.tsx @@ -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 (