From 8c26ec4906eaa9b68273e22065b7fb490af5713b Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Sat, 26 Sep 2026 17:55:51 -0500 Subject: [PATCH 01/22] Add a featured video mode to the front page hero MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A fourth hero mode beside brand, photos and livestream: a recorded video next to the words, under a "Featured video · " badge. Unlike the livestream it never autoplays: an embed waits for play, and a file shows the browser's own player with preload="metadata". video_url takes a YouTube, Vimeo or Facebook link (turned into an embed, as the livestream's is) or a video file: a filename in public/front-page/, a /path, or an https URL ending in .mp4, .webm, .m4v, .mov or .ogv. Anything else that can't be framed still gets a "Watch the video" button. Files follow the embeds' https-only rule. Its own video_url and video_title columns rather than the livestream's, so both can be set up ahead of time and the mode switches between them. Migration 024 rebuilds front_page for the wider hero_mode CHECK; its children, keys and touch trigger survive. embeds.ts gains an autoplay switch shared by both modes, and videoSource() to tell a file from an embed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- server/src/admin-schema.js | 4 +- .../src/migrations/024_front_page_video.sql | 79 +++++++++++++++ server/src/routes/home.js | 3 + src/lib/adminSchema.ts | 17 +++- src/lib/embeds.ts | 56 +++++++++-- src/lib/media.ts | 4 + src/lib/useFrontPage.ts | 4 +- src/pages/sections/home/HeroStage.tsx | 98 +++++++++++++++++-- 8 files changed, 243 insertions(+), 22 deletions(-) create mode 100644 server/src/migrations/024_front_page_video.sql diff --git a/server/src/admin-schema.js b/server/src/admin-schema.js index 5e4a465..f292863 100644 --- a/server/src/admin-schema.js +++ b/server/src/admin-schema.js @@ -676,7 +676,7 @@ const frontPage = { }, columns: [ - enumeration("hero_mode", ["brand", "photos", "livestream"]), + enumeration("hero_mode", ["brand", "photos", "livestream", "video"]), text("eyebrow"), text("headline"), text("subhead"), @@ -687,6 +687,8 @@ const frontPage = { int("slide_seconds"), text("livestream_url"), text("livestream_title"), + text("video_url"), + text("video_title"), text("countdown_event_id"), ], diff --git a/server/src/migrations/024_front_page_video.sql b/server/src/migrations/024_front_page_video.sql new file mode 100644 index 0000000..9fe43fa --- /dev/null +++ b/server/src/migrations/024_front_page_video.sql @@ -0,0 +1,79 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 024 FRONT PAGE: FEATURED VIDEO +-- +-- A fourth hero mode, 'video': a recorded video beside the words, +-- the way 'livestream' puts a stream there, but without the LIVE +-- badge and without autoplay — a visitor presses play. +-- +-- Its own two columns rather than reusing the livestream's, so a +-- featured video and a stream can both be set up ahead of time and +-- the mode switches between them, as photos and livestream already +-- can. +-- +-- video_url a YouTube, Vimeo or Facebook link (turned into an +-- embed), or a video file: a filename in +-- public/front-page/, a /path, or an https URL ending +-- in .mp4, .webm, .m4v, .mov or .ogv, which plays in +-- the browser's own player +-- video_title shown after "Featured video" above the headline +-- +-- hero_mode's CHECK can't be altered in place, so front_page is +-- rebuilt. Its children (slides, sections, stats, paths) reference +-- it by name; the runner has foreign keys off, so the DROP leaves +-- them alone and the rename puts front_page back underneath them. +-- No view or other table's trigger names front_page, so the rename +-- needs no legacy_alter_table. front_page_touch goes with the old +-- table and is recreated last. +-- +-- PRAGMA user_version; -- reads 23 before this file +-- ═══════════════════════════════════════════════════════════════ + +CREATE TABLE front_page_new ( + id TEXT PRIMARY KEY CHECK (id = 'home'), + + hero_mode TEXT NOT NULL DEFAULT 'brand' + CHECK (hero_mode IN ('brand', 'photos', 'livestream', 'video')), + eyebrow TEXT, + headline TEXT NOT NULL DEFAULT 'Next Generation of Unity', + subhead TEXT, + primary_label TEXT, + primary_url TEXT, + secondary_label TEXT, + secondary_url TEXT, + + slide_seconds INTEGER NOT NULL DEFAULT 7 + CHECK (slide_seconds BETWEEN 3 AND 60), + + livestream_url TEXT, + livestream_title TEXT, + + video_url TEXT, + video_title TEXT, + + countdown_event_id TEXT REFERENCES events (id) ON DELETE SET NULL, + + updated_at TEXT NOT NULL DEFAULT (datetime('now')) +) STRICT; + +INSERT INTO front_page_new + (id, hero_mode, eyebrow, headline, subhead, + primary_label, primary_url, secondary_label, secondary_url, + slide_seconds, livestream_url, livestream_title, + countdown_event_id, updated_at) +SELECT + id, hero_mode, eyebrow, headline, subhead, + primary_label, primary_url, secondary_label, secondary_url, + slide_seconds, livestream_url, livestream_title, + countdown_event_id, updated_at + FROM front_page; + +DROP TABLE front_page; + +ALTER TABLE front_page_new RENAME TO front_page; + +CREATE TRIGGER front_page_touch +AFTER UPDATE ON front_page +FOR EACH ROW WHEN new.updated_at = old.updated_at +BEGIN + UPDATE front_page SET updated_at = datetime('now') WHERE id = new.id; +END; diff --git a/server/src/routes/home.js b/server/src/routes/home.js index 312d087..2f5da60 100644 --- a/server/src/routes/home.js +++ b/server/src/routes/home.js @@ -174,6 +174,9 @@ home.get("/front-page", (c) => { livestream: page.livestream_url ? { url: page.livestream_url, title: page.livestream_title } : null, + video: page.video_url + ? { url: page.video_url, title: page.video_title } + : null, }, sections, stats, diff --git a/src/lib/adminSchema.ts b/src/lib/adminSchema.ts index 3760483..10f685c 100644 --- a/src/lib/adminSchema.ts +++ b/src/lib/adminSchema.ts @@ -950,8 +950,9 @@ const timeline = { One record (see the singleton note in server/src/admin-schema.js). The groups are the hero; the collections below are the rest of - the page. Photos and the livestream are editable whatever the - mode, so either can be ready before the switch is flipped. + the page. Photos, the livestream and the featured video are + editable whatever the mode, so each can be ready before the + switch is flipped. Section keys and stat sources are the CHECK lists on front_page_sections and front_page_stats. The labels here are what the admin reads; the values are @@ -1000,6 +1001,7 @@ const frontPage = { ["brand", "Brand — animated colour, no media"], ["photos", "Photos — cycles through the photos below"], ["livestream", "Livestream — embeds the stream with a LIVE badge"], + ["video", "Featured video — shows the video below, click to play"], ], blankLabel: "— brand —", help: "Switch to Livestream when you go live, and back when you're done", @@ -1014,7 +1016,7 @@ const frontPage = { ], }, { - legend: "Photos and livestream", + legend: "Photos, livestream and video", fields: [ { path: "slide_seconds", @@ -1029,6 +1031,15 @@ const frontPage = { help: "A YouTube, Facebook or Vimeo link, or any embed URL", }, { path: "livestream_title", label: "Livestream title", full: true }, + { + path: "video_url", + label: "Featured video", + full: true, + help: + "A YouTube, Vimeo or Facebook link, or a video file: a filename in " + + "public/front-page/ or a link ending in .mp4 or .webm", + }, + { path: "video_title", label: "Video title", full: true, help: "Shown after \"Featured video\" above the headline" }, ], }, { diff --git a/src/lib/embeds.ts b/src/lib/embeds.ts index 4f0f52e..306e658 100644 --- a/src/lib/embeds.ts +++ b/src/lib/embeds.ts @@ -9,10 +9,21 @@ through; anything that isn't https is refused, so the hero never frames a plain-http or javascript: URL. - Streams start muted: browsers only autoplay muted video, and a - hero that starts shouting is worse than one that asks. + Streams start playing, muted: browsers only autoplay muted + video, and a hero that starts shouting is worse than one that + asks. A featured video doesn't start at all — it's a recording, + so the visitor presses play. + + A featured video can also be a file rather than a link: a + filename in public/front-page/, a /path, or an https URL ending + in a video extension. videoSource() says which, so the hero can + hand a file to <video> and a link to an <iframe>. ═══════════════════════════════════════════════════════════════ */ +import { heroVideo } from './media.ts' + +const VIDEO_FILE = /\.(mp4|webm|m4v|mov|ogv)$/i + function youtubeId(url: URL): string | null { const host = url.hostname.replace(/^www\.|^m\./, '') if (host === 'youtu.be') return url.pathname.slice(1) || null @@ -26,8 +37,8 @@ function youtubeId(url: URL): string | null { return match?.[1] ?? null } -/** An iframe src for a pasted stream link, or null if it can't be framed. */ -export function livestreamEmbedUrl(raw?: string | null): string | null { +/** An iframe src for a pasted link, or null if it can't be framed. */ +function embedUrl(raw: string | null | undefined, autoplay: boolean): string | null { if (!raw) return null let url: URL @@ -40,7 +51,8 @@ export function livestreamEmbedUrl(raw?: string | null): string | null { const yt = youtubeId(url) if (yt) { - return `https://www.youtube-nocookie.com/embed/${encodeURIComponent(yt)}?autoplay=1&mute=1&playsinline=1` + const play = autoplay ? '?autoplay=1&mute=1&playsinline=1' : '?playsinline=1' + return `https://www.youtube-nocookie.com/embed/${encodeURIComponent(yt)}${play}` } const host = url.hostname.replace(/^www\./, '') @@ -48,15 +60,43 @@ export function livestreamEmbedUrl(raw?: string | null): string | null { if (host === 'vimeo.com') { const id = url.pathname.match(/^\/(?:event\/)?(\d+)/)?.[1] if (id) { + const play = autoplay ? '?autoplay=1&muted=1' : '' return url.pathname.startsWith('/event/') - ? `https://vimeo.com/event/${id}/embed?autoplay=1&muted=1` - : `https://player.vimeo.com/video/${id}?autoplay=1&muted=1` + ? `https://vimeo.com/event/${id}/embed${play}` + : `https://player.vimeo.com/video/${id}${play}` } } if ((host === 'facebook.com' || host === 'fb.watch') && !url.pathname.startsWith('/plugins/')) { - return `https://www.facebook.com/plugins/video.php?href=${encodeURIComponent(url.href)}&autoplay=1&mute=1` + const play = autoplay ? '&autoplay=1&mute=1' : '' + return `https://www.facebook.com/plugins/video.php?href=${encodeURIComponent(url.href)}${play}` } return url.href } + +/** An iframe src for a pasted stream link, or null if it can't be framed. */ +export function livestreamEmbedUrl(raw?: string | null): string | null { + return embedUrl(raw, true) +} + +export type VideoSource = { kind: 'file' | 'embed'; src: string } + +/** How to play a featured video: a file for <video>, an embed for + * an <iframe>, or null when it's neither (the hero then links to + * it instead). Files follow the same https-only rule as embeds. */ +export function videoSource(raw?: string | null): VideoSource | null { + const value = raw?.trim() + if (!value) return null + + if (VIDEO_FILE.test(value.split(/[?#]/)[0])) { + if (/^https:\/\//i.test(value) || !/^[a-z][a-z0-9+.-]*:/i.test(value)) { + const src = heroVideo(value) + if (src) return { kind: 'file', src } + } + return null + } + + const src = embedUrl(value, false) + return src ? { kind: 'embed', src } : null +} diff --git a/src/lib/media.ts b/src/lib/media.ts index f5698f0..0234c91 100644 --- a/src/lib/media.ts +++ b/src/lib/media.ts @@ -35,6 +35,10 @@ export const awardLogo = inDir('/award-logos') // ⚠ guess the Front page editor, which names the directory in its help. */ export const heroPhoto = inDir('/front-page') +/* front_page.video_url when it names a file rather than a link: + same directory as the photos. */ +export const heroVideo = inDir('/front-page') + /* content_blocks.media, which can be an image on any owner's page, so it can't share a per-entity directory. */ export const blockMedia = inDir('/media') // ⚠ guess diff --git a/src/lib/useFrontPage.ts b/src/lib/useFrontPage.ts index 19f7fa9..6169ca5 100644 --- a/src/lib/useFrontPage.ts +++ b/src/lib/useFrontPage.ts @@ -13,7 +13,7 @@ import { useRecord, type Resource } from './useRecord.ts' import type { EventSeries } from './eventSeries.ts' -export type HeroMode = 'brand' | 'photos' | 'livestream' +export type HeroMode = 'brand' | 'photos' | 'livestream' | 'video' /** The CHECK list on front_page_sections.section. */ export type FrontPageSectionKey = @@ -43,6 +43,8 @@ export type Hero = { slide_seconds: number slides: HeroSlide[] livestream: { url: string; title?: string | null } | null + /** A link to embed or a video file; see videoSource in embeds.ts. */ + video: { url: string; title?: string | null } | null } export type FrontPageSection = { diff --git a/src/pages/sections/home/HeroStage.tsx b/src/pages/sections/home/HeroStage.tsx index 38e4c0a..b344c7e 100644 --- a/src/pages/sections/home/HeroStage.tsx +++ b/src/pages/sections/home/HeroStage.tsx @@ -11,11 +11,14 @@ that moves on its own for more than five seconds needs one) livestream the stream beside the words, with a LIVE badge + video a featured video beside the words, under a + "Featured video" badge. Never autoplays: an embed + waits for play, a file shows the browser's player A mode that has nothing to show falls back to brand: photos with - no photos, or a livestream link that can't be embedded. A stream - link that can't be framed still gets a "Watch live" button, so - switching the mode on is never a no-op. + no photos, or livestream/video with no link set. A link that + can't be framed still gets a "Watch live" or "Watch the video" + button, so switching the mode on is never a no-op. `hero` is null while the page config loads or when it failed; the stage still draws, empty, so the page doesn't jump when it @@ -26,7 +29,7 @@ import { useEffect, useState, type CSSProperties } from 'react' import HomeLink from './HomeLink.tsx' import DoveMark from '../../../components/DoveMark.tsx' -import { livestreamEmbedUrl } from '../../../lib/embeds.ts' +import { livestreamEmbedUrl, videoSource, type VideoSource } from '../../../lib/embeds.ts' import { heroPhoto } from '../../../lib/media.ts' import type { Hero, HeroSlide } from '../../../lib/useFrontPage.ts' @@ -35,13 +38,19 @@ const DEEP = '#04262e' export default function HeroStage({ hero }: { hero: Hero | null }) { const slides = (hero?.slides ?? []).filter((slide) => heroPhoto(slide.media)) const embed = livestreamEmbedUrl(hero?.livestream?.url) + const video = videoSource(hero?.video?.url) const mode = hero?.mode === 'photos' && slides.length > 0 ? 'photos' : hero?.mode === 'livestream' && hero.livestream ? 'livestream' - : 'brand' + : hero?.mode === 'video' && hero.video + ? 'video' + : 'brand' + + // Livestream and video share a layout: words left, player right. + const beside = mode === 'livestream' || mode === 'video' return ( <section @@ -56,8 +65,8 @@ export default function HeroStage({ hero }: { hero: Hero | null }) { )} <div className="relative z-10 mx-auto grid w-full max-w-7xl items-center gap-12 px-6 lg:grid-cols-12"> - <div className={mode === 'livestream' ? 'lg:col-span-5' : 'lg:col-span-8'}> - {hero && <Words hero={hero} live={mode === 'livestream'} />} + <div className={beside ? 'lg:col-span-5' : 'lg:col-span-8'}> + {hero && <Words hero={hero} mode={mode} />} </div> {mode === 'livestream' && hero?.livestream && ( @@ -65,6 +74,12 @@ export default function HeroStage({ hero }: { hero: Hero | null }) { <LiveFrame src={embed} url={hero.livestream.url} title={hero.livestream.title} /> </div> )} + + {mode === 'video' && hero?.video && ( + <div className="lg:col-span-7"> + <VideoFrame source={video} url={hero.video.url} title={hero.video.title} /> + </div> + )} </div> </section> ) @@ -72,8 +87,10 @@ export default function HeroStage({ hero }: { hero: Hero | null }) { /* ── The words ───────────────────────────────────────────────── */ -function Words({ hero, live }: { hero: Hero; live: boolean }) { +function Words({ hero, mode }: { hero: Hero; mode: 'brand' | 'photos' | 'livestream' | 'video' }) { const words = hero.headline.split(/\s+/).filter(Boolean) + const live = mode === 'livestream' + const beside = live || mode === 'video' return ( <div className="text-white"> @@ -87,6 +104,16 @@ function Words({ hero, live }: { hero: Hero; live: boolean }) { </span> )} </p> + ) : mode === 'video' ? ( + <p className="mb-6 inline-flex items-center gap-3 rounded-full bg-white/10 px-4 py-1.5 text-sm font-semibold uppercase tracking-[0.2em] backdrop-blur"> + <span className="text-[#9fe7d0]" aria-hidden="true">▶</span> + Featured video + {hero.video?.title && ( + <span className="normal-case tracking-normal text-white/75"> + · {hero.video.title} + </span> + )} + </p> ) : ( hero.eyebrow && ( <p className="mb-6 inline-block rounded-full border border-white/20 px-4 py-1.5 text-xs font-semibold uppercase tracking-[0.25em] text-[#9fe7d0]"> @@ -97,7 +124,7 @@ function Words({ hero, live }: { hero: Hero; live: boolean }) { <h1 className={`font-display font-extrabold leading-[0.95] tracking-tight ${ - live ? 'text-5xl md:text-6xl' : 'text-6xl md:text-8xl' + beside ? 'text-5xl md:text-6xl' : 'text-6xl md:text-8xl' }`} > {words.map((word, index) => ( @@ -326,3 +353,56 @@ function LiveFrame({ src, url, title }: { src: string | null; url: string; title </div> ) } + +/* ── Featured video ──────────────────────────────────────────── */ + +/* A file plays in <video> with the browser's controls; preload + "metadata" fetches enough for the first frame and the length, + not the whole file. An embed waits for play. A link that is + neither still gets a button out to it. */ +function VideoFrame({ + source, + url, + title, +}: { + source: VideoSource | null + url: string + title?: string | null +}) { + return ( + <div + className="relative overflow-hidden rounded-3xl border border-white/15 bg-black shadow-2xl" + style={{ boxShadow: '0 30px 80px -20px rgba(92, 231, 255, 0.35)' }} + > + <div className="aspect-video w-full"> + {source?.kind === 'file' ? ( + <video + src={source.src} + title={title || 'Featured video'} + className="h-full w-full" + controls + playsInline + preload="metadata" + /> + ) : source?.kind === 'embed' ? ( + <iframe + src={source.src} + title={title || 'Featured video'} + className="h-full w-full" + allow="encrypted-media; picture-in-picture; fullscreen" + allowFullScreen + /> + ) : ( + <div className="flex h-full w-full items-center justify-center"> + <HomeLink + url={url} + className="rounded-full bg-white px-6 py-3 font-semibold text-[#04262e] hover:scale-105" + > + Watch the video + </HomeLink> + </div> + )} + </div> + </div> + ) +} From 97c1827ca99cbe6576b351c9fcb1299cf43363c0 Mon Sep 17 00:00:00 2001 From: Zaldimmar <Zaldimmar@gmail.com> Date: Sat, 26 Sep 2026 18:24:08 -0500 Subject: [PATCH 02/22] Add a QR code page at /qr for any page on the site Pick "Main navigation" or a kind of record (events, organizations, teams, awards, people), then the page or record, and for a main page optionally one of its #sections. The code, a copy-link button, and PNG (1024px) and SVG downloads follow. An "NGU dove in the centre" option puts the dove on a white badge over the code and raises error correction to H so it still scans. Codes always point at SITE_ORIGIN (https://nextgenerationofunity.org, in src/lib/site.ts), so one made on localhost works on a poster. Main pages come from navConfig.ts and record URLs from hrefs.ts, the same sources the site links with. GET /api/directory lists every published record with a page, as id, name and (for organizations) kind, each filtered by the same rule as that record's own page: a team also needs its organization published. /api/people only answers for ids it's given, so there was no public list to read. The `qrcode` package does the encoding; QrCode.tsx draws the modules as one SVG path, so the preview and both downloads are one picture. The page is lazy-loaded so the encoder isn't in the main bundle. The page is unlisted: not in navConfig, so not in the header or footer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- package.json | 2 + pnpm-lock.yaml | 226 ++++++++++++++++++ server/src/index.js | 2 + server/src/routes/directory.js | 77 ++++++ src/App.tsx | 5 + src/components/QrCode.tsx | 94 ++++++++ src/lib/qr.ts | 48 ++++ src/lib/site.ts | 13 + src/lib/useContent.ts | 17 ++ src/pages/QrCodes.tsx | 37 +++ src/pages/sections/QrCodeMaker.tsx | 371 +++++++++++++++++++++++++++++ 11 files changed, 892 insertions(+) create mode 100644 server/src/routes/directory.js create mode 100644 src/components/QrCode.tsx create mode 100644 src/lib/qr.ts create mode 100644 src/lib/site.ts create mode 100644 src/pages/QrCodes.tsx create mode 100644 src/pages/sections/QrCodeMaker.tsx diff --git a/package.json b/package.json index 16ec736..16df0d3 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "dependencies": { "@fontsource/montserrat": "^5.3.0", "@fontsource/poppins": "^5.3.0", + "qrcode": "^1.5.4", "react": "^19.0.0", "react-dom": "^19.0.0", "react-router-dom": "^7.18.4" @@ -19,6 +20,7 @@ "devDependencies": { "@tailwindcss/vite": "^4.0.0", "@types/node": "^22.0.0", + "@types/qrcode": "^1.5.6", "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", "@vitejs/plugin-react": "^6.0.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d5e8552..70bbb7b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -14,6 +14,9 @@ importers: '@fontsource/poppins': specifier: ^5.3.0 version: 5.3.0 + qrcode: + specifier: ^1.5.4 + version: 1.5.4 react: specifier: ^19.0.0 version: 19.3.0 @@ -30,6 +33,9 @@ importers: '@types/node': specifier: ^22.0.0 version: 22.20.3 + '@types/qrcode': + specifier: ^1.5.6 + version: 1.5.6 '@types/react': specifier: ^19.0.0 version: 19.3.0 @@ -319,6 +325,9 @@ packages: '@types/node@22.20.3': resolution: {integrity: sha512-DZmzkmwHzXrLPAXPyKNDzlIwMMUZCVacoD25ywdy5YTKGbOx/2ld+Q38Im2zJ0vBuZP5Prd3VZutKZyXwkOS8A==} + '@types/qrcode@1.5.6': + resolution: {integrity: sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==} + '@types/react-dom@19.3.0': resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==} peerDependencies: @@ -343,6 +352,28 @@ packages: oxc-transform-react: optional: true + ansi-regex@5.0.1: + resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} + engines: {node: '>=8'} + + ansi-styles@4.3.0: + resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} + engines: {node: '>=8'} + + camelcase@5.3.1: + resolution: {integrity: sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==} + engines: {node: '>=6'} + + cliui@6.0.0: + resolution: {integrity: sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==} + + color-convert@2.0.1: + resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} + engines: {node: '>=7.0.0'} + + color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + cookie@1.1.1: resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==} engines: {node: '>=18'} @@ -350,10 +381,20 @@ packages: csstype@3.2.3: resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + decamelize@1.2.0: + resolution: {integrity: sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==} + engines: {node: '>=0.10.0'} + detect-libc@2.1.2: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} + dijkstrajs@1.0.3: + resolution: {integrity: sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==} + + emoji-regex@8.0.0: + resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} + enhanced-resolve@5.25.1: resolution: {integrity: sha512-nGXts5znJzmWPu+mIE9izCOzdg63oJca2mDzGWWTth7sr4aCToKcoyFVBQwN75Ij5Pf6p510EwkTqViTRzDV+w==} engines: {node: '>=10.13.0'} @@ -367,14 +408,26 @@ packages: picomatch: optional: true + find-up@4.1.0: + resolution: {integrity: sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==} + engines: {node: '>=8'} + fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} os: [darwin] + get-caller-file@2.0.5: + resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} + engines: {node: 6.* || 8.* || >= 10.*} + graceful-fs@4.2.11: resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} + is-fullwidth-code-point@3.0.0: + resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} + engines: {node: '>=8'} + jiti@2.7.0: resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} hasBin: true @@ -527,6 +580,10 @@ packages: resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} engines: {node: '>= 12.0.0'} + locate-path@5.0.0: + resolution: {integrity: sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==} + engines: {node: '>=8'} + magic-string@0.30.21: resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} @@ -540,6 +597,22 @@ packages: engines: {node: '>=8.*'} hasBin: true + p-limit@2.3.0: + resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==} + engines: {node: '>=6'} + + p-locate@4.1.0: + resolution: {integrity: sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==} + engines: {node: '>=8'} + + p-try@2.2.0: + resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==} + engines: {node: '>=6'} + + path-exists@4.0.0: + resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} + engines: {node: '>=8'} + picocolors@1.1.1: resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} @@ -547,10 +620,19 @@ packages: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} + pngjs@5.0.0: + resolution: {integrity: sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==} + engines: {node: '>=10.13.0'} + postcss@8.5.28: resolution: {integrity: sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==} engines: {node: ^10 || ^12 || >=14} + qrcode@1.5.4: + resolution: {integrity: sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==} + engines: {node: '>=10.13.0'} + hasBin: true + react-dom@19.3.0: resolution: {integrity: sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==} peerDependencies: @@ -577,6 +659,13 @@ packages: resolution: {integrity: sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==} engines: {node: '>=0.10.0'} + require-directory@2.1.1: + resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==} + engines: {node: '>=0.10.0'} + + require-main-filename@2.0.0: + resolution: {integrity: sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==} + rolldown@1.2.9: resolution: {integrity: sha512-hx/Pv0N1haXRb11qkfnK5MXB/iqr7i0yjWQqmO9uHqZpBgQSqzc8UsSnEpalsh+j1I8qQ2CkXAkJC8Br3dKSlg==} engines: {node: ^20.19.0 || >=22.12.0} @@ -585,6 +674,9 @@ packages: scheduler@0.28.0: resolution: {integrity: sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==} + set-blocking@2.0.0: + resolution: {integrity: sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==} + set-cookie-parser@2.7.2: resolution: {integrity: sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==} @@ -592,6 +684,14 @@ packages: resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} engines: {node: '>=0.10.0'} + string-width@4.2.3: + resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} + engines: {node: '>=8'} + + strip-ansi@6.0.1: + resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} + engines: {node: '>=8'} + tailwindcss@4.3.3: resolution: {integrity: sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ==} @@ -654,6 +754,24 @@ packages: yaml: optional: true + which-module@2.0.1: + resolution: {integrity: sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==} + + wrap-ansi@6.2.0: + resolution: {integrity: sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==} + engines: {node: '>=8'} + + y18n@4.0.3: + resolution: {integrity: sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==} + + yargs-parser@18.1.3: + resolution: {integrity: sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==} + engines: {node: '>=6'} + + yargs@15.4.1: + resolution: {integrity: sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==} + engines: {node: '>=8'} + snapshots: '@fontsource/montserrat@5.3.0': {} @@ -824,6 +942,10 @@ snapshots: dependencies: undici-types: 6.21.0 + '@types/qrcode@1.5.6': + dependencies: + '@types/node': 22.20.3 + '@types/react-dom@19.3.0(@types/react@19.3.0)': dependencies: '@types/react': 19.3.0 @@ -837,12 +959,38 @@ snapshots: '@rolldown/pluginutils': 1.0.1 vite: 8.3.0(@types/node@22.20.3)(jiti@2.7.0) + ansi-regex@5.0.1: {} + + ansi-styles@4.3.0: + dependencies: + color-convert: 2.0.1 + + camelcase@5.3.1: {} + + cliui@6.0.0: + dependencies: + string-width: 4.2.3 + strip-ansi: 6.0.1 + wrap-ansi: 6.2.0 + + color-convert@2.0.1: + dependencies: + color-name: 1.1.4 + + color-name@1.1.4: {} + cookie@1.1.1: {} csstype@3.2.3: {} + decamelize@1.2.0: {} + detect-libc@2.1.2: {} + dijkstrajs@1.0.3: {} + + emoji-regex@8.0.0: {} + enhanced-resolve@5.25.1: dependencies: graceful-fs: 4.2.11 @@ -852,11 +1000,20 @@ snapshots: optionalDependencies: picomatch: 4.0.7 + find-up@4.1.0: + dependencies: + locate-path: 5.0.0 + path-exists: 4.0.0 + fsevents@2.3.3: optional: true + get-caller-file@2.0.5: {} + graceful-fs@4.2.11: {} + is-fullwidth-code-point@3.0.0: {} + jiti@2.7.0: {} lightningcss-android-arm64@1.32.0: @@ -957,6 +1114,10 @@ snapshots: lightningcss-win32-arm64-msvc: 1.33.0 lightningcss-win32-x64-msvc: 1.33.0 + locate-path@5.0.0: + dependencies: + p-locate: 4.1.0 + magic-string@0.30.21: dependencies: '@jridgewell/sourcemap-codec': 1.6.0 @@ -974,16 +1135,36 @@ snapshots: '@oxfmt/win32-arm64': 0.2.0 '@oxfmt/win32-x64': 0.2.0 + p-limit@2.3.0: + dependencies: + p-try: 2.2.0 + + p-locate@4.1.0: + dependencies: + p-limit: 2.3.0 + + p-try@2.2.0: {} + + path-exists@4.0.0: {} + picocolors@1.1.1: {} picomatch@4.0.7: {} + pngjs@5.0.0: {} + postcss@8.5.28: dependencies: nanoid: 3.3.19 picocolors: 1.1.1 source-map-js: 1.2.1 + qrcode@1.5.4: + dependencies: + dijkstrajs: 1.0.3 + pngjs: 5.0.0 + yargs: 15.4.1 + react-dom@19.3.0(react@19.3.0): dependencies: react: 19.3.0 @@ -1005,6 +1186,10 @@ snapshots: react@19.3.0: {} + require-directory@2.1.1: {} + + require-main-filename@2.0.0: {} + rolldown@1.2.9: dependencies: '@oxc-project/types': 0.150.0 @@ -1028,10 +1213,22 @@ snapshots: scheduler@0.28.0: {} + set-blocking@2.0.0: {} + set-cookie-parser@2.7.2: {} source-map-js@1.2.1: {} + string-width@4.2.3: + dependencies: + emoji-regex: 8.0.0 + is-fullwidth-code-point: 3.0.0 + strip-ansi: 6.0.1 + + strip-ansi@6.0.1: + dependencies: + ansi-regex: 5.0.1 + tailwindcss@4.3.3: {} tapable@2.3.3: {} @@ -1056,3 +1253,32 @@ snapshots: '@types/node': 22.20.3 fsevents: 2.3.3 jiti: 2.7.0 + + which-module@2.0.1: {} + + wrap-ansi@6.2.0: + dependencies: + ansi-styles: 4.3.0 + string-width: 4.2.3 + strip-ansi: 6.0.1 + + y18n@4.0.3: {} + + yargs-parser@18.1.3: + dependencies: + camelcase: 5.3.1 + decamelize: 1.2.0 + + yargs@15.4.1: + dependencies: + cliui: 6.0.0 + decamelize: 1.2.0 + find-up: 4.1.0 + get-caller-file: 2.0.5 + require-directory: 2.1.1 + require-main-filename: 2.0.0 + set-blocking: 2.0.0 + string-width: 4.2.3 + which-module: 2.0.1 + y18n: 4.0.3 + yargs-parser: 18.1.3 diff --git a/server/src/index.js b/server/src/index.js index 6eab6ca..2be4ef8 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -18,6 +18,7 @@ import content from "./routes/content.js"; import people from "./routes/people.js"; import history from "./routes/history.js"; import home from "./routes/home.js"; +import directory from "./routes/directory.js"; import feedback from "./routes/feedback.js"; import auth from "./routes/auth.js"; import admin from "./routes/admin.js"; @@ -58,6 +59,7 @@ app.route("/api", content); app.route("/api", people); app.route("/api", history); app.route("/api", home); +app.route("/api", directory); // Tighter limit on the write path than anything else gets. app.use("/api/feedback", rateLimit({ windowMs: 60_000, max: 5 })); diff --git a/server/src/routes/directory.js b/server/src/routes/directory.js new file mode 100644 index 0000000..1d55a93 --- /dev/null +++ b/server/src/routes/directory.js @@ -0,0 +1,77 @@ +/* ═══════════════════════════════════════════════════════════════ + DIRECTORY ROUTE — read-only, mounted under /api + + GET /directory every public record that has a page + + One flat list per kind, each row just enough to name a record + and build its URL: id and name, plus the organization's kind, + which decides whether its page is /regions, /chapters or + /partners. The QR code page reads it to offer "any page on the + site" without five list requests carrying descriptions, links + and blocks it would throw away. + + Each list applies the same visibility rule as that record's own + page, so nothing here leads to a 404: + + events published + organizations published + teams published, and so is the organization + awards published + people published + + The site already serves each of these at its own URL; this only + lists them in one place. + ═══════════════════════════════════════════════════════════════ */ + +import { Hono } from "hono"; + +const directory = new Hono(); + +const CACHE = "public, max-age=60, stale-while-revalidate=300"; + +directory.get("/directory", (c) => { + const db = c.get("db"); + const all = (sql) => db.prepare(sql).all(); + + return c.json( + { + directory: { + events: all( + `SELECT id, title AS name, starts_on + FROM events + WHERE is_published = 1 + ORDER BY starts_on IS NULL, starts_on DESC, title`, + ), + organizations: all( + `SELECT id, name, kind + FROM organizations + WHERE is_published = 1 + ORDER BY kind, name`, + ), + teams: all( + `SELECT t.id, t.name, o.name AS org_name + FROM teams t + JOIN organizations o ON o.id = t.org_id AND o.is_published = 1 + WHERE t.is_published = 1 + ORDER BY o.name, t.sort_order, t.name`, + ), + awards: all( + `SELECT id, name + FROM awards + WHERE is_published = 1 + ORDER BY name`, + ), + people: all( + `SELECT id, display_name AS name + FROM people + WHERE is_published = 1 + ORDER BY COALESCE(sort_name, display_name)`, + ), + }, + }, + 200, + { "Cache-Control": CACHE }, + ); +}); + +export default directory; diff --git a/src/App.tsx b/src/App.tsx index ff85789..c72c0f2 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,4 +1,5 @@ import { BrowserRouter, Routes, Route, Outlet, Navigate } from "react-router-dom"; +import { lazy, Suspense } from "react"; /*Components*/ import Layout from "./components/Layout.tsx"; @@ -39,6 +40,9 @@ 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")); + export default function App() { return ( <BrowserRouter> @@ -60,6 +64,7 @@ export default function App() { <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="give" element={<Giving />} /> <Route path="privacy" element={<Privacy />} /> <Route path="terms" element={<Terms />} /> diff --git a/src/components/QrCode.tsx b/src/components/QrCode.tsx new file mode 100644 index 0000000..80a7da2 --- /dev/null +++ b/src/components/QrCode.tsx @@ -0,0 +1,94 @@ +/* ═══════════════════════════════════════════════════════════════ + QR CODE + + A QR code as an <svg>, sized by its container. With `dove`, the + NGU dove sits on a white badge over the centre; the code switches + to high error correction so the modules under the badge are + recovered when it's scanned (see lib/qr.ts). The badge covers + under 6% of the code, well inside what 'H' repairs, and never + reaches the three corner finder patterns. + + Everything is drawn in the SVG itself — no CSS, no external + references — so the element serialises to a file that looks the + same outside the page. `ref` reaches the <svg> for exactly that. + ═══════════════════════════════════════════════════════════════ */ + +import { useMemo, type Ref } from 'react' + +import DoveMark from './DoveMark.tsx' +import { qrMatrix, qrPath } from '../lib/qr.ts' + +/* The spec's minimum quiet zone, in modules. Less and some + scanners can't find the edge of the code. */ +const MARGIN = 4 + +/* Dark enough to scan as black; the site's deep teal. */ +const INK = '#04262e' +const TEAL = '#138ba0' + +/* Badge side as a share of the code's width. */ +const BADGE = 0.24 + +/* DoveMark's own viewBox is 72.87 × 48.57. */ +const DOVE_ASPECT = 72.867699 / 48.568241 + +export default function QrCode({ + value, + dove = false, + label, + ref, + className, +}: { + value: string + dove?: boolean + /** Accessible name for the image, e.g. "QR code for /retreats". */ + label: string + ref?: Ref<SVGSVGElement> + className?: string +}) { + const matrix = useMemo(() => qrMatrix(value, dove ? 'H' : 'M'), [value, dove]) + const path = useMemo(() => qrPath(matrix, MARGIN), [matrix]) + + const total = matrix.size + MARGIN * 2 + const badge = matrix.size * BADGE + const badgeAt = (total - badge) / 2 + const doveWidth = badge * 0.78 + const doveHeight = doveWidth / DOVE_ASPECT + + return ( + <svg + ref={ref} + xmlns="http://www.w3.org/2000/svg" + viewBox={`0 0 ${total} ${total}`} + role="img" + aria-label={label} + className={className} + shapeRendering="crispEdges" + > + <rect width={total} height={total} fill="#ffffff" /> + <path d={path} fill={INK} /> + + {dove && ( + <g shapeRendering="auto"> + <rect + x={badgeAt} + y={badgeAt} + width={badge} + height={badge} + rx={badge * 0.22} + fill="#ffffff" + stroke={INK} + strokeWidth={0.35} + /> + <DoveMark + x={(total - doveWidth) / 2} + y={(total - doveHeight) / 2} + width={doveWidth} + height={doveHeight} + style={{ color: TEAL }} + /> + </g> + )} + </svg> + ) +} diff --git a/src/lib/qr.ts b/src/lib/qr.ts new file mode 100644 index 0000000..06a3ad2 --- /dev/null +++ b/src/lib/qr.ts @@ -0,0 +1,48 @@ +/* ═══════════════════════════════════════════════════════════════ + QR CODES + + The encoding comes from the `qrcode` package: which modules are + dark, at which error-correction level. Drawing is QrCode.tsx's + job, so the on-screen code, the SVG download and the PNG download + are one picture rather than three renderers that could disagree. + + Error correction is the share of the code that can be damaged and + still scan. A logo over the middle is damage, so a code carrying + the dove uses 'H' (about 30% recoverable); a plain one uses 'M', + which keeps it less dense and easier to scan from a distance. + ═══════════════════════════════════════════════════════════════ */ + +import { create } from 'qrcode' + +export type QrLevel = 'L' | 'M' | 'Q' | 'H' + +export type QrMatrix = { + /** Modules per side, not counting the quiet zone. */ + size: number + dark: (row: number, col: number) => boolean +} + +export function qrMatrix(text: string, level: QrLevel): QrMatrix { + const { modules } = create(text, { errorCorrectionLevel: level }) + return { size: modules.size, dark: (row, col) => modules.get(row, col) === 1 } +} + +/* The dark modules as one SVG path, a run of horizontal neighbours + per subpath, offset by the quiet zone. One element instead of a + rect per module keeps the markup (and the SVG download) small. */ +export function qrPath(matrix: QrMatrix, margin: number): string { + const parts: string[] = [] + for (let row = 0; row < matrix.size; row++) { + let col = 0 + while (col < matrix.size) { + if (!matrix.dark(row, col)) { + col++ + continue + } + const start = col + while (col < matrix.size && matrix.dark(row, col)) col++ + parts.push(`M${start + margin} ${row + margin}h${col - start}v1h-${col - start}z`) + } + } + return parts.join('') +} diff --git a/src/lib/site.ts b/src/lib/site.ts new file mode 100644 index 0000000..a7668e3 --- /dev/null +++ b/src/lib/site.ts @@ -0,0 +1,13 @@ +/* ═══════════════════════════════════════════════════════════════ + SITE + + The public address of the live site. Used where a URL has to + leave the browser and still work — a printed QR code made on + localhost or a preview has to point here, not at wherever it was + generated. Everything inside the site links by path, not this. + ═══════════════════════════════════════════════════════════════ */ + +export const SITE_ORIGIN = 'https://nextgenerationofunity.org' + +/** A site path as a full URL on the live site. */ +export const siteUrl = (path: string): string => new URL(path, SITE_ORIGIN).href diff --git a/src/lib/useContent.ts b/src/lib/useContent.ts index df27c41..86feaa1 100644 --- a/src/lib/useContent.ts +++ b/src/lib/useContent.ts @@ -336,3 +336,20 @@ export type PersonRecord = { export const usePerson = (id?: string): Resource<PersonRecord> => useRecord<PersonRecord>(detailPath('/people', id), 'person') + +/* ── Directory ───────────────────────────────────────────────── + GET /directory: every public record that has a page, one list + per kind, each row just enough to build its URL with hrefs.ts. */ + +export type DirectoryEntry = { id: string; name: string } + +export type Directory = { + events: Array<DirectoryEntry & { starts_on?: string | null }> + organizations: Array<DirectoryEntry & { kind: OrganizationRecord['kind'] }> + teams: Array<DirectoryEntry & { org_name: string }> + awards: DirectoryEntry[] + people: DirectoryEntry[] +} + +export const useDirectory = (): Resource<Directory> => + useRecord<Directory>('/directory', 'directory') diff --git a/src/pages/QrCodes.tsx b/src/pages/QrCodes.tsx new file mode 100644 index 0000000..1341b5d --- /dev/null +++ b/src/pages/QrCodes.tsx @@ -0,0 +1,37 @@ +import PageShell from '../components/PageShell.tsx' +import QrCodeMaker from './sections/QrCodeMaker.tsx' + +/* ═══════════════════════════════════════════════════════════════ + QR CODES PAGE — /qr + + A QR code for any page on the site, for flyers, slides and + signs. Unlisted: not in navConfig, so neither the header nor the + footer links here. It lists only published records, so there is + nothing on it a visitor couldn't already reach. + ═══════════════════════════════════════════════════════════════ */ + +const SECTIONS = [ + { + id: 'make', + title: 'Make a QR code', + blurb: + 'Pick a page from the main navigation, or any event, organization, team, award or person on the site. The code always points at the live site.', + accent: '#138ba0', + background: '#eef9fb', + content: ( + <div className="mx-auto max-w-6xl px-6"> + <QrCodeMaker /> + </div> + ), + }, +] + +export default function QrCodes() { + return ( + <PageShell + title="QR Codes" + intro="Codes for flyers, slides and signs, pointing at any page on the site." + sections={SECTIONS} + /> + ) +} diff --git a/src/pages/sections/QrCodeMaker.tsx b/src/pages/sections/QrCodeMaker.tsx new file mode 100644 index 0000000..25b53e1 --- /dev/null +++ b/src/pages/sections/QrCodeMaker.tsx @@ -0,0 +1,371 @@ +/* ═══════════════════════════════════════════════════════════════ + QR CODE MAKER + + Pick a page, get a QR code for it on the live site. + + What main navigation, or one kind of record + Which the page or record itself + Section for a main page with a subnav, optionally one of + its #sections + + The main pages come from navConfig.ts, the same list the header + draws; records come from GET /directory, which lists only what's + published, and their URLs from hrefs.ts, the same builders the + site links with. So a code can only point at a page that exists. + + Codes point at SITE_ORIGIN, never at wherever this page is open, + so one made on localhost still works on a poster. + + Downloads are the on-screen <svg> itself: serialised for the SVG, + drawn onto a canvas for the PNG. Neither needs a server. + ═══════════════════════════════════════════════════════════════ */ + +import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react' + +import QrCode from '../../components/QrCode.tsx' +import { NAV_ACTIONS, PAGE_LINKS, PAGE_SECTIONS } from '../../navConfig.ts' +import { awardHref, eventHref, orgHref, personHref, teamHref } from '../../lib/hrefs.ts' +import { siteUrl } from '../../lib/site.ts' +import { useDirectory, type Directory } from '../../lib/useContent.ts' + +const TEAL = '#138ba0' +const MUTED = '#4a6b72' + +/* PNG download size in pixels. Plenty for print at a few inches; + anything bigger should use the SVG. */ +const PNG_SIZE = 1024 + +type Kind = 'pages' | 'events' | 'organizations' | 'teams' | 'awards' | 'people' + +const KINDS: Array<[Kind, string]> = [ + ['pages', 'Main navigation'], + ['events', 'Events'], + ['organizations', 'Organizations'], + ['teams', 'Teams'], + ['awards', 'Awards'], + ['people', 'People'], +] + +/* Organizations are grouped by kind in the dropdown, in this order. */ +const ORG_GROUPS: Array<[string, string]> = [ + ['national', 'NGU'], + ['region', 'Regions'], + ['chapter', 'Chapters'], + ['partner', 'Partner organizations'], +] + +type Choice = { path: string; label: string } +type Group = { label?: string; choices: Choice[] } + +/* The header's pages, then any nav action that is a page of its own + rather than an anchor on one of them (Give, not Contact Us). */ +function mainPages(): Choice[] { + const pages = PAGE_LINKS.map((p) => ({ path: p.path, label: p.label })) + const known = new Set(pages.map((p) => p.path)) + for (const action of NAV_ACTIONS) { + const path = action.to.split('#')[0] + if (!action.to.includes('#') && !known.has(path)) { + pages.push({ path, label: action.label }) + known.add(path) + } + } + return pages +} + +function groupsFor(kind: Kind, directory: Directory | null): Group[] { + if (kind === 'pages') return [{ choices: mainPages() }] + if (!directory) return [] + + switch (kind) { + case 'events': + return [ + { + choices: directory.events.map((e) => ({ + path: eventHref(e.id), + label: e.starts_on ? `${e.name} (${e.starts_on.slice(0, 4)})` : e.name, + })), + }, + ] + case 'organizations': + return ORG_GROUPS.map(([orgKind, label]) => ({ + label, + choices: directory.organizations + .filter((o) => o.kind === orgKind) + .map((o) => ({ path: orgHref(o.id, o.kind), label: o.name })), + })).filter((group) => group.choices.length > 0) + case 'teams': + return [ + { + choices: directory.teams.map((t) => ({ + path: teamHref(t.id), + label: `${t.name} — ${t.org_name}`, + })), + }, + ] + case 'awards': + return [{ choices: directory.awards.map((a) => ({ path: awardHref(a.id), label: a.name })) }] + case 'people': + return [{ choices: directory.people.map((p) => ({ path: personHref(p.id), label: p.name })) }] + } +} + +/* "/regions/northwest#events" → "regions-northwest-events". */ +function fileStem(path: string): string { + const stem = path.replace(/^\//, '').replace(/[^a-z0-9]+/gi, '-').replace(/^-|-$/g, '') + return `ngu-qr-${stem || 'home'}` +} + +function download(href: string, filename: string) { + const a = document.createElement('a') + a.href = href + a.download = filename + document.body.appendChild(a) + a.click() + a.remove() +} + +function svgMarkup(svg: SVGSVGElement): string { + return new XMLSerializer().serializeToString(svg) +} + +function downloadSvg(svg: SVGSVGElement, stem: string) { + const url = URL.createObjectURL(new Blob([svgMarkup(svg)], { type: 'image/svg+xml' })) + download(url, `${stem}.svg`) + URL.revokeObjectURL(url) +} + +function downloadPng(svg: SVGSVGElement, stem: string) { + const image = new Image() + image.onload = () => { + const canvas = document.createElement('canvas') + canvas.width = PNG_SIZE + canvas.height = PNG_SIZE + const context = canvas.getContext('2d') + if (!context) return + context.imageSmoothingEnabled = false + context.drawImage(image, 0, 0, PNG_SIZE, PNG_SIZE) + canvas.toBlob((blob) => { + if (!blob) return + const url = URL.createObjectURL(blob) + download(url, `${stem}.png`) + URL.revokeObjectURL(url) + }, 'image/png') + } + image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgMarkup(svg))}` +} + +export default function QrCodeMaker() { + const { data: directory, loading, error } = useDirectory() + + const [kind, setKind] = useState<Kind>('pages') + const [path, setPath] = useState('/') + const [section, setSection] = useState('') + const [dove, setDove] = useState(true) + const [copied, setCopied] = useState(false) + const svgRef = useRef<SVGSVGElement>(null) + + const groups = useMemo(() => groupsFor(kind, directory), [kind, directory]) + const choices = useMemo(() => groups.flatMap((group) => group.choices), [groups]) + + // A new kind, or the directory arriving, can leave the current + // path outside the list; fall back to its first entry. + useEffect(() => { + if (choices.length > 0 && !choices.some((c) => c.path === path)) { + setPath(choices[0].path) + setSection('') + } + }, [choices, path]) + + const sections = kind === 'pages' ? (PAGE_SECTIONS[path] ?? []) : [] + const selected = choices.find((c) => c.path === path) ?? null + const target = selected ? `${selected.path}${section}` : null + const url = target ? siteUrl(target) : null + + useEffect(() => setCopied(false), [url]) + + async function copy() { + if (!url) return + try { + await navigator.clipboard.writeText(url) + setCopied(true) + } catch { + // Clipboard refused (an insecure origin, or a denied + // permission). The link is on screen to copy by hand. + setCopied(false) + } + } + + const needsDirectory = kind !== 'pages' + + return ( + <div className="grid gap-10 lg:grid-cols-2 lg:items-start"> + <div className="space-y-5"> + <Select id="qr-kind" label="What to link to" value={kind} onChange={(v) => setKind(v as Kind)}> + {KINDS.map(([value, label]) => ( + <option key={value} value={value}> + {label} + </option> + ))} + </Select> + + {needsDirectory && loading && !directory ? ( + <p style={{ color: MUTED }}>Loading the list…</p> + ) : needsDirectory && error ? ( + <p className="text-[#b3261e]">Couldn't load the list of pages. {error}</p> + ) : choices.length === 0 ? ( + <p style={{ color: MUTED }}>Nothing published here yet.</p> + ) : ( + <Select + id="qr-target" + label={kind === 'pages' ? 'Page' : 'Which one'} + value={path} + onChange={(v) => { + setPath(v) + setSection('') + }} + > + {groups.map((group, i) => + group.label ? ( + <optgroup key={group.label} label={group.label}> + {group.choices.map((c) => ( + <option key={c.path} value={c.path}> + {c.label} + </option> + ))} + </optgroup> + ) : ( + group.choices.map((c) => ( + <option key={`${i}-${c.path}`} value={c.path}> + {c.label} + </option> + )) + ), + )} + </Select> + )} + + {sections.length > 0 && ( + <Select id="qr-section" label="Section of that page" value={section} onChange={setSection}> + <option value="">The page as a whole</option> + {sections.map((s) => ( + <option key={s.hash} value={s.hash}> + {s.label.replace(/^#/, '')} + </option> + ))} + </Select> + )} + + <label className="flex items-center gap-3 text-[#26454c]"> + <input + type="checkbox" + checked={dove} + onChange={(e) => setDove(e.target.checked)} + className="h-4 w-4 accent-[#138ba0]" + /> + NGU dove in the centre + </label> + + {url && ( + <div> + <p className="text-sm font-medium text-[#26454c]">Links to</p> + <div className="mt-2 flex flex-wrap items-center gap-3"> + <code className="break-all rounded-lg bg-white px-3 py-2 text-sm text-[#26454c] ring-1 ring-[#4a6b72]/20"> + {url} + </code> + <button + type="button" + onClick={copy} + className="rounded-full border px-4 py-2 text-sm font-semibold transition-colors hover:bg-[#138ba0]/10" + style={{ borderColor: TEAL, color: TEAL }} + > + {copied ? 'Copied ✓' : 'Copy link'} + </button> + </div> + </div> + )} + </div> + + <div className="flex flex-col items-center gap-5"> + {url ? ( + <> + <div className="w-full max-w-sm rounded-3xl bg-white p-6 shadow-lg ring-1 ring-[#4a6b72]/10"> + <QrCode + ref={svgRef} + value={url} + dove={dove} + label={`QR code for ${url}`} + className="block h-auto w-full" + /> + </div> + <div className="flex flex-wrap justify-center gap-3"> + <DownloadButton onClick={() => svgRef.current && downloadPng(svgRef.current, fileStem(target!))}> + Download PNG + </DownloadButton> + <DownloadButton onClick={() => svgRef.current && downloadSvg(svgRef.current, fileStem(target!))}> + Download SVG + </DownloadButton> + </div> + <p className="max-w-sm text-center text-sm" style={{ color: MUTED }}> + PNG for documents and slides, {PNG_SIZE}px square. SVG for print: it stays sharp at + any size. + </p> + </> + ) : ( + <div className="aspect-square w-full max-w-sm rounded-3xl bg-white/60 ring-1 ring-[#4a6b72]/10" /> + )} + </div> + </div> + ) +} + +function DownloadButton({ onClick, children }: { onClick: () => void; children: ReactNode }) { + return ( + <button + type="button" + onClick={onClick} + className="rounded-full bg-[#138ba0] px-6 py-3 font-semibold text-white transition-colors hover:bg-[#0f7183] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#138ba0]/40" + > + {children} + </button> + ) +} + +const selectClass = + 'w-full appearance-none rounded-xl border border-[#4a6b72]/25 bg-white px-4 py-3 pr-10 text-[#26454c] ' + + 'outline-none transition-colors focus:border-[#138ba0] focus:ring-2 focus:ring-[#138ba0]/25' + +function Select({ + id, + label, + value, + onChange, + children, +}: { + id: string + label: string + value: string + onChange: (value: string) => void + children: ReactNode +}) { + return ( + <div> + <label htmlFor={id} className="block text-sm font-medium text-[#26454c]"> + {label} + </label> + <div className="relative mt-2"> + <select id={id} value={value} onChange={(e) => onChange(e.target.value)} className={selectClass}> + {children} + </select> + <svg + aria-hidden="true" + viewBox="0 0 20 20" + fill="none" + className="pointer-events-none absolute right-4 top-1/2 h-4 w-4 -translate-y-1/2" + style={{ color: MUTED }} + > + <path d="M5 8l5 5 5-5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /> + </svg> + </div> + </div> + ) +} From 5b9c8f7391ed072aa092df11a8c7e9f3a4f36cd0 Mon Sep 17 00:00:00 2001 From: Zaldimmar <Zaldimmar@gmail.com> Date: Sat, 26 Sep 2026 18:26:12 -0500 Subject: [PATCH 03/22] Call the descriptor sync once at boot, and rename the package index.js ran syncDescriptorsWithSchema twice on one line, a paste slip from v1.4. It's idempotent, so the second call only re-read every table's schema; boot now checks once. package.json's name was still "figma-make-app" from the original export; it's "ngu-web-app" now. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- package.json | 2 +- server/src/index.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 16df0d3..b1ca7fd 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "name": "figma-make-app", + "name": "ngu-web-app", "private": true, "version": "1.0.0", "type": "module", diff --git a/server/src/index.js b/server/src/index.js index 2be4ef8..14fdde7 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -36,7 +36,7 @@ const DB_PATH = process.env.DB_PATH ?? "./ngu.db"; const db = await openDatabase(DB_PATH); const version = migrate(db); -syncDescriptorsWithSchema(db, ENTITIES);syncDescriptorsWithSchema(db, ENTITIES); +syncDescriptorsWithSchema(db, ENTITIES); console.log(`db ${DB_PATH} (${db.driverName}, schema v${version})`); From 7eeac6b22f97cd7ffe82f392ffd9f2867c6ffcaf Mon Sep 17 00:00:00 2001 From: Zaldimmar <Zaldimmar@gmail.com> Date: Sat, 26 Sep 2026 18:29:40 -0500 Subject: [PATCH 04/22] Let the hero's photos or brand backdrop sit behind a stream or video MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit hero_mode answered two questions with one value, so a livestream or featured video could only ever sit on the brand backdrop. It's now two settings: Background brand | photos Beside the words nothing | livestream | featured video Any background goes with any feature: the photo slideshow can run behind the stream, with its captions, progress bars and pause button as before. The fallbacks are unchanged: photos with none added shows brand, and a feature with no link set shows nothing beside the words. Migration 025 adds hero_backdrop and hero_feature, maps each row's hero_mode onto them (photos → photos + nothing, livestream/video → brand + that feature, brand → brand + nothing) and drops hero_mode. ADD/DROP COLUMN rather than a rebuild, so front_page's children and touch trigger are untouched. The API's hero sends `backdrop` and `feature` in place of `mode`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- server/src/admin-schema.js | 5 +- .../migrations/025_hero_backdrop_feature.sql | 40 +++++++++++ server/src/routes/home.js | 3 +- src/lib/adminSchema.ts | 20 ++++-- src/lib/useFrontPage.ts | 9 ++- src/pages/sections/home/HeroStage.tsx | 67 ++++++++++--------- 6 files changed, 104 insertions(+), 40 deletions(-) create mode 100644 server/src/migrations/025_hero_backdrop_feature.sql diff --git a/server/src/admin-schema.js b/server/src/admin-schema.js index f292863..30c63f9 100644 --- a/server/src/admin-schema.js +++ b/server/src/admin-schema.js @@ -669,14 +669,15 @@ const frontPage = { concurrency: "updated_at", list: { - columns: ["id", "headline", "hero_mode", "updated_at"], + columns: ["id", "headline", "hero_backdrop", "hero_feature", "updated_at"], filters: [], search: [], order: "id", }, columns: [ - enumeration("hero_mode", ["brand", "photos", "livestream", "video"]), + enumeration("hero_backdrop", ["brand", "photos"]), + enumeration("hero_feature", ["none", "livestream", "video"]), text("eyebrow"), text("headline"), text("subhead"), diff --git a/server/src/migrations/025_hero_backdrop_feature.sql b/server/src/migrations/025_hero_backdrop_feature.sql new file mode 100644 index 0000000..c85e1ff --- /dev/null +++ b/server/src/migrations/025_hero_backdrop_feature.sql @@ -0,0 +1,40 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 025 HERO: BACKDROP AND FEATURE ARE SEPARATE CHOICES +-- +-- hero_mode answered two questions with one value: what fills the +-- background (the brand animation or the photo slideshow) and what +-- sits beside the words (nothing, a livestream or a featured +-- video). A stream or a video could only ever sit on the brand +-- backdrop. Split, any backdrop goes with any feature. +-- +-- hero_backdrop 'brand' | 'photos' +-- hero_feature 'none' | 'livestream' | 'video' +-- +-- Today's modes map across exactly: photos → photos + none; +-- livestream and video → brand + that feature; brand → brand + +-- none. Photos mode still falls back to brand on the page when +-- there are no photos, as before. +-- +-- ADD COLUMN takes a constant DEFAULT and a CHECK, and DROP COLUMN +-- allows a column whose only constraint is its own CHECK, so no +-- rebuild: front_page's children and its touch trigger are never +-- touched. +-- +-- PRAGMA user_version; -- reads 24 before this file +-- ═══════════════════════════════════════════════════════════════ + +ALTER TABLE front_page ADD COLUMN hero_backdrop TEXT NOT NULL DEFAULT 'brand' + CHECK (hero_backdrop IN ('brand', 'photos')); + +ALTER TABLE front_page ADD COLUMN hero_feature TEXT NOT NULL DEFAULT 'none' + CHECK (hero_feature IN ('none', 'livestream', 'video')); + +UPDATE front_page + SET hero_backdrop = CASE hero_mode WHEN 'photos' THEN 'photos' ELSE 'brand' END, + hero_feature = CASE hero_mode + WHEN 'livestream' THEN 'livestream' + WHEN 'video' THEN 'video' + ELSE 'none' + END; + +ALTER TABLE front_page DROP COLUMN hero_mode; diff --git a/server/src/routes/home.js b/server/src/routes/home.js index 2f5da60..90e65ca 100644 --- a/server/src/routes/home.js +++ b/server/src/routes/home.js @@ -159,7 +159,8 @@ home.get("/front-page", (c) => { return json(c, { front_page: { hero: { - mode: page.hero_mode, + backdrop: page.hero_backdrop, + feature: page.hero_feature, eyebrow: page.eyebrow, headline: page.headline, subhead: page.subhead, diff --git a/src/lib/adminSchema.ts b/src/lib/adminSchema.ts index 10f685c..cbb4457 100644 --- a/src/lib/adminSchema.ts +++ b/src/lib/adminSchema.ts @@ -994,16 +994,26 @@ const frontPage = { note: "The first thing a visitor sees. Blank buttons don't render.", fields: [ { - path: "hero_mode", - label: "Mode", + path: "hero_backdrop", + label: "Background", widget: "select", options: [ - ["brand", "Brand — animated colour, no media"], + ["brand", "Brand — animated colour and the dove"], ["photos", "Photos — cycles through the photos below"], - ["livestream", "Livestream — embeds the stream with a LIVE badge"], - ["video", "Featured video — shows the video below, click to play"], ], blankLabel: "— brand —", + help: "Photos with none added shows the brand background", + }, + { + path: "hero_feature", + label: "Beside the words", + widget: "select", + options: [ + ["none", "Nothing — the words fill the hero"], + ["livestream", "Livestream — the stream, with a LIVE badge"], + ["video", "Featured video — click to play"], + ], + blankLabel: "— nothing —", help: "Switch to Livestream when you go live, and back when you're done", }, { path: "eyebrow", label: "Eyebrow", help: "Small line above the headline" }, diff --git a/src/lib/useFrontPage.ts b/src/lib/useFrontPage.ts index 6169ca5..475beea 100644 --- a/src/lib/useFrontPage.ts +++ b/src/lib/useFrontPage.ts @@ -13,7 +13,11 @@ import { useRecord, type Resource } from './useRecord.ts' import type { EventSeries } from './eventSeries.ts' -export type HeroMode = 'brand' | 'photos' | 'livestream' | 'video' +/** What fills the hero's background. */ +export type HeroBackdrop = 'brand' | 'photos' + +/** What sits beside the words, over the backdrop. */ +export type HeroFeature = 'none' | 'livestream' | 'video' /** The CHECK list on front_page_sections.section. */ export type FrontPageSectionKey = @@ -34,7 +38,8 @@ export type HeroSlide = { } export type Hero = { - mode: HeroMode + backdrop: HeroBackdrop + feature: HeroFeature eyebrow?: string | null headline: string subhead?: string | null diff --git a/src/pages/sections/home/HeroStage.tsx b/src/pages/sections/home/HeroStage.tsx index b344c7e..de71fdf 100644 --- a/src/pages/sections/home/HeroStage.tsx +++ b/src/pages/sections/home/HeroStage.tsx @@ -1,24 +1,30 @@ /* ═══════════════════════════════════════════════════════════════ HERO STAGE - The top of the front page, in whichever mode the admin set: + The top of the front page. Two choices the admin makes + separately, so any backdrop goes with any feature: + + Backdrop, what fills the background: brand drifting colour and slow concentric rings — many - circles, one centre — behind the words, with the - dove at that centre + circles, one centre — with the dove at that centre photos the hero photos, crossfading with a slow zoom, a progress bar per photo and a pause button (anything that moves on its own for more than five seconds needs one) - livestream the stream beside the words, with a LIVE badge - video a featured video beside the words, under a - "Featured video" badge. Never autoplays: an embed - waits for play, a file shows the browser's player - A mode that has nothing to show falls back to brand: photos with - no photos, or livestream/video with no link set. A link that - can't be framed still gets a "Watch live" or "Watch the video" - button, so switching the mode on is never a no-op. + Feature, what sits beside the words over that backdrop: + + none nothing; the words take the width + livestream the stream, with a LIVE badge above the headline + video a featured video under a "Featured video" badge. + Never autoplays: an embed waits for play, a file + shows the browser's player + + A choice with nothing to show falls back: photos with no photos + to brand, a feature with no link set to none. A link that can't + be framed still gets a "Watch live" or "Watch the video" button, + so switching a feature on is never a no-op. `hero` is null while the page config loads or when it failed; the stage still draws, empty, so the page doesn't jump when it @@ -31,7 +37,7 @@ import HomeLink from './HomeLink.tsx' import DoveMark from '../../../components/DoveMark.tsx' import { livestreamEmbedUrl, videoSource, type VideoSource } from '../../../lib/embeds.ts' import { heroPhoto } from '../../../lib/media.ts' -import type { Hero, HeroSlide } from '../../../lib/useFrontPage.ts' +import type { Hero, HeroBackdrop, HeroFeature, HeroSlide } from '../../../lib/useFrontPage.ts' const DEEP = '#04262e' @@ -40,17 +46,18 @@ export default function HeroStage({ hero }: { hero: Hero | null }) { const embed = livestreamEmbedUrl(hero?.livestream?.url) const video = videoSource(hero?.video?.url) - const mode = - hero?.mode === 'photos' && slides.length > 0 - ? 'photos' - : hero?.mode === 'livestream' && hero.livestream - ? 'livestream' - : hero?.mode === 'video' && hero.video - ? 'video' - : 'brand' + const backdrop: HeroBackdrop = + hero?.backdrop === 'photos' && slides.length > 0 ? 'photos' : 'brand' - // Livestream and video share a layout: words left, player right. - const beside = mode === 'livestream' || mode === 'video' + const feature: HeroFeature = + hero?.feature === 'livestream' && hero.livestream + ? 'livestream' + : hero?.feature === 'video' && hero.video + ? 'video' + : 'none' + + // Both features share a layout: words left, player right. + const beside = feature !== 'none' return ( <section @@ -58,7 +65,7 @@ export default function HeroStage({ hero }: { hero: Hero | null }) { className="relative isolate flex min-h-[92vh] items-center overflow-hidden pt-24 pb-16" style={{ background: DEEP }} > - {mode === 'photos' ? ( + {backdrop === 'photos' ? ( <PhotoBackdrop slides={slides} seconds={hero?.slide_seconds ?? 7} /> ) : ( <BrandBackdrop /> @@ -66,16 +73,16 @@ export default function HeroStage({ hero }: { hero: Hero | null }) { <div className="relative z-10 mx-auto grid w-full max-w-7xl items-center gap-12 px-6 lg:grid-cols-12"> <div className={beside ? 'lg:col-span-5' : 'lg:col-span-8'}> - {hero && <Words hero={hero} mode={mode} />} + {hero && <Words hero={hero} feature={feature} />} </div> - {mode === 'livestream' && hero?.livestream && ( + {feature === 'livestream' && hero?.livestream && ( <div className="lg:col-span-7"> <LiveFrame src={embed} url={hero.livestream.url} title={hero.livestream.title} /> </div> )} - {mode === 'video' && hero?.video && ( + {feature === 'video' && hero?.video && ( <div className="lg:col-span-7"> <VideoFrame source={video} url={hero.video.url} title={hero.video.title} /> </div> @@ -87,10 +94,10 @@ export default function HeroStage({ hero }: { hero: Hero | null }) { /* ── The words ───────────────────────────────────────────────── */ -function Words({ hero, mode }: { hero: Hero; mode: 'brand' | 'photos' | 'livestream' | 'video' }) { +function Words({ hero, feature }: { hero: Hero; feature: HeroFeature }) { const words = hero.headline.split(/\s+/).filter(Boolean) - const live = mode === 'livestream' - const beside = live || mode === 'video' + const live = feature === 'livestream' + const beside = feature !== 'none' return ( <div className="text-white"> @@ -104,7 +111,7 @@ function Words({ hero, mode }: { hero: Hero; mode: 'brand' | 'photos' | 'livestr </span> )} </p> - ) : mode === 'video' ? ( + ) : feature === 'video' ? ( <p className="mb-6 inline-flex items-center gap-3 rounded-full bg-white/10 px-4 py-1.5 text-sm font-semibold uppercase tracking-[0.2em] backdrop-blur"> <span className="text-[#9fe7d0]" aria-hidden="true">▶</span> Featured video From e35d09b1723f9d34712a56697e1fee93db7b239c Mon Sep 17 00:00:00 2001 From: Zaldimmar <Zaldimmar@gmail.com> Date: Sat, 26 Sep 2026 18:44:35 -0500 Subject: [PATCH 05/22] Add a guide to updating data that isn't in the database docs/updating-data-in-code.md covers content that lives in code rather than SQLite and how to change it: - The two kinds of admin dropdown: filled from records (optionsFrom, change the record) and fixed lists (options, in adminSchema.ts), and that a bare-string option shows its stored value while a [value, label] pair shows the label. - Relabelling a dropdown is adminSchema.ts alone; adding, removing or renaming a stored value is a migration, both descriptor halves and whatever the public site renders it with. - A table of every dropdown in the editor, where its values and labels live, and what on the public site depends on them. - The front page's three kinds of "section name" (the heading the admin sets, the dropdown label, the subnav link) and stat sources. - Every other piece of code-owned content: nav, page section manifests, banner, history decades, map grid, feedback types, public label maps, roles, SITE_ORIGIN. CLAUDE.md points at it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- CLAUDE.md | 1 + docs/updating-data-in-code.md | 296 ++++++++++++++++++++++++++++++++++ 2 files changed, 297 insertions(+) create mode 100644 docs/updating-data-in-code.md diff --git a/CLAUDE.md b/CLAUDE.md index 7d2572c..5cc971b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -52,6 +52,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - `src/data/` holds only hardcoded data shared across multiple section files (e.g. `historyDecades.ts`, map grid). Everything else comes from SQLite. - `navConfig.ts` is the single source of truth for navigation, routes, and actions (header, footer, pages). - `api.ts` is the shared caching client used by frontend data hooks. +- `docs/updating-data-in-code.md`: where content that isn't in the database lives (admin dropdown labels, fixed value lists, nav, banner, decades, map grid) and how to change it. Keep it current when adding a dropdown or code-owned content. - Logos: org logos in `public/org-logos/` (served at `/org-logos/`), event logos in `public/event-logos/`. The `<Logo>` component hides itself on load error. ## Rules and gotchas diff --git a/docs/updating-data-in-code.md b/docs/updating-data-in-code.md new file mode 100644 index 0000000..c82cbe0 --- /dev/null +++ b/docs/updating-data-in-code.md @@ -0,0 +1,296 @@ +# Updating data that isn't in the database + +Most of the site's content lives in SQLite and is edited in the admin +(`/admin`). Some of it deliberately lives in code instead: labels, +navigation, fixed lists, and a few pieces of editorial copy. Changing +those means editing a file, committing it on a branch, and deploying. + +This guide covers where each of those lives and how to change it +safely, starting with the question that comes up most: how to change +what a dropdown in the admin editor says. + +- [Database or code?](#database-or-code) +- [Admin dropdowns](#admin-dropdowns) + - [Two kinds of dropdown](#two-kinds-of-dropdown) + - [Renaming what a dropdown shows](#renaming-what-a-dropdown-shows) + - [Adding, removing or renaming a stored value](#adding-removing-or-renaming-a-stored-value) + - [Every dropdown in the editor](#every-dropdown-in-the-editor) +- [Front page section names](#front-page-section-names) +- [Front page stat sources](#front-page-stat-sources) +- [Other content that lives in code](#other-content-that-lives-in-code) +- [Making the change](#making-the-change) + +--- + +## Database or code? + +| If it's… | It lives in… | Change it by… | +| ------------------------------------------------------------ | ---------------- | ------------------------------------ | +| A record: an event, organization, person, team, award, timeline entry | the database | editing it in the admin | +| The front page's words, photos, bands, stats and paths | the database | Admin → Front page | +| The **label** a dropdown shows in the admin | code | [one file](#renaming-what-a-dropdown-shows) | +| The **list of allowed values** behind a fixed dropdown | database CHECK + code | [a migration and three files](#adding-removing-or-renaming-a-stored-value) | +| Navigation, page section titles, colours, the site banner, history decades, the map grid | code | [the file named below](#other-content-that-lives-in-code) | + +The rule of thumb from `CLAUDE.md`: data belongs in the database, +presentation belongs in code. A dropdown's *values* are data the +database enforces; its *labels* are presentation. + +--- + +## Admin dropdowns + +The admin editor is generated from two descriptor files that describe +each entity: + +| File | What it holds | +| ----------------------------- | ----------------------------------------------------- | +| `src/lib/adminSchema.ts` | The **form**: field labels, help text, dropdown labels, list columns and filters | +| `server/src/admin-schema.js` | What the server **accepts**: columns, types, the allowed values of each `enumeration(...)` | + +And the database itself holds the final word: most fixed lists are a +`CHECK (... IN (...))` constraint on the column (read them in +`server/src/migrations/023_schema.sql` and any later migration). + +### Two kinds of dropdown + +Every dropdown in the editor is one of these: + +**1. Filled from records (`optionsFrom`).** The choices are rows in the +database: organizations, people, events, teams, awards, event scopes, +regions. The label is the record's own name. To change what one of +these shows, **edit the record in the admin**; there's nothing to +change in code. Adding a person adds them to every "Person" dropdown. + +The queries behind them are `OPTION_QUERIES` in +`server/src/admin-schema.js`. Edit a query only to change *which* +records appear or their order, e.g. to put a disambiguating +organization name in the label, as the `awards` query does. + +> Event scopes (National, Regional, Local…) are records in the +> `event_scopes` table, but there's no admin page for them. Their names +> are changed with a migration: `UPDATE event_scopes SET name = '…' WHERE id = '…';` + +**2. A fixed list in code (`options`).** The choices are written in +`src/lib/adminSchema.ts`. Each option is one of two shapes: + +```ts +options: ["speaker", "leader", "host"] // shows: speaker, leader, host +options: [["speaker", "Speaker"], ["leader", "Leader"]] // shows: Speaker, Leader +``` + +A bare string is shown exactly as stored. A `[value, label]` pair +stores the first and shows the second. That difference is what makes +relabelling cheap. + +### Renaming what a dropdown shows + +If the stored value stays the same and you only want the dropdown to +read differently, **only `src/lib/adminSchema.ts` changes**. No +migration, no server change, and every existing row keeps working. + +Find the field (search for its column name) and give the option a +label. For example, to make the event-people Role dropdown read nicely: + +```ts +// before +options: ["speaker", "leader", "facilitator", "host", "musician", "volunteer", "attendee"], + +// after — values unchanged, labels added +options: [ + ["speaker", "Speaker"], + ["leader", "Leader"], + ["facilitator", "Facilitator"], + ["host", "Host"], + ["musician", "Musician"], + ["volunteer", "Volunteer"], + ["attendee", "Attendee (not shown publicly)"], +], +``` + +Things to check while you're there: + +- **The same list often appears twice**: once on the form field and + once in the entity's `list.filters` (the dropdowns above the list + view). Relabel both so they agree. +- **Several lists are shared constants.** Front page sections and stat + sources are `FRONT_PAGE_SECTIONS` and `STAT_SOURCES` near the top of + the front page block; change them there, once. +- **`blankLabel`** is the text of the empty first option + (`"— brand —"`, `"— choose —"`). It's also just a label. +- The value (first item) **must not change**. It's what's stored in + the database and what the server and the CHECK constraint compare + against. + +### Adding, removing or renaming a stored value + +This changes what the database will accept, so four places move +together, in one branch: + +1. **A new migration** (`server/src/migrations/0NN_description.sql`) + that changes the column's CHECK. A CHECK can't be altered in place, + so either: + - add a new column with the new CHECK, copy the data across, and + drop the old one (see `025_hero_backdrop_feature.sql`), or + - rebuild the table (see `024_front_page_video.sql`, and the + rebuild notes in `CLAUDE.md` under Migrations). + + **Renaming** a value also needs an `UPDATE` in the same migration so + existing rows move to the new value. **Removing** one needs you to + decide what existing rows become first. +2. **`server/src/admin-schema.js`**: the `enumeration("column", [...])` + list for that column. +3. **`src/lib/adminSchema.ts`**: the `options` on the form field, and on + the list filter if there is one. +4. **Anywhere the public site renders or relies on the value**, listed in + the table below (for example `EVENT_TYPES` for event types, or the + `SECTIONS` map in `Home.tsx` for front page sections). + +If the server descriptor and the database disagree, the API refuses to +start: `admin-schema-sync.js` compares them at boot and throws with a +message naming the column. That's deliberate. Fix whichever side is +wrong rather than working around it. + +### Every dropdown in the editor + +**Fixed lists** (`options`: labels in `src/lib/adminSchema.ts`, values +also in `admin-schema.js` and a CHECK): + +| Entity → field | Stored values | Labelled? | Also used on the public site by | +| --- | --- | --- | --- | +| Organizations → Kind (+ list filter) | national, region, chapter, partner | no, shows values | `ORG_KIND_LABEL` in `src/lib/hrefs.ts`, and the route each kind uses | +| Organizations → Region → Scope | domestic, international, virtual | no | the Community page groups regions by it | +| Organizations → Region areas → Edge | top, bottom | no | the chapter map (`OrgList-Map.tsx`) | +| Events → Type (+ list filter) | retreat, class, workshop, meeting, other | no | `EVENT_TYPES` in `src/lib/eventTypes.ts` (public labels and plurals) | +| Events → Status (+ list filter) | upcoming, past, cancelled | no | `STATUS_LABEL` in `src/pages/EventDetail.tsx` | +| Events → Series → Repeats | weekly, monthly_date, monthly_weekday | **yes** | `src/lib/eventSeries.ts` | +| Events → People → Role | speaker, leader, facilitator, host, musician, volunteer, attendee | no | `ROLE_LABEL` in `src/pages/EventDetail.tsx` | +| People → Affiliations → Role; Teams → Members → Role | lead, board, staff, volunteer, member | no | `ROLE_LABEL` in `src/pages/PersonDetail.tsx` | +| Links → Kind (on organizations, events, people, teams) | action, social, website, email | no | `splitLinks` in `server/src/shape.js` | +| Content blocks → Slot | card, body | no | `ContentBlocks.tsx` | +| Content blocks → Type | heading, subheading, paragraph, list, links, quote, image, divider | no | `ContentBlocks.tsx` (one renderer per type) | +| Timeline → Kind (+ list filter) | milestone, event, organization, award, people | no | `KIND_NAMES` in `src/pages/sections/history/TimelineEntry.tsx` | +| Timeline → Points at (+ list filter) | event, organization, award, person, team | no | `refHref` in `src/lib/hrefs.ts` | +| Timeline → Precision (and on events/orgs) | year, month, day | no | the history page's grouping | +| Front page → Background | brand, photos | **yes** | `HeroStage.tsx` | +| Front page → Beside the words | none, livestream, video | **yes** | `HeroStage.tsx` | +| Front page → Sections → Section | countdown, retreats, calendar, stats, timeline, connect | **yes**, `FRONT_PAGE_SECTIONS` | `SECTIONS` in `src/pages/Home.tsx`; see [below](#front-page-section-names) | +| Front page → Stats → Where it comes from | manual, years_since, regions, … | **yes**, `STAT_SOURCES` | `STAT_QUERIES` in `server/src/routes/home.js`; see [below](#front-page-stat-sources) | +| Every list → Published / Featured filter | 1, 0 | **yes** | n/a | + +"No, shows values" means the dropdown currently shows the raw value, +so relabelling it is just [adding labels](#renaming-what-a-dropdown-shows). + +**Lists filled from records** (`optionsFrom`: edit the records, not +code): + +| Dropdown | `optionsFrom` | Comes from | +| --- | --- | --- | +| Chapter → Region | `regions` | organizations of kind region | +| Event → Scope (+ list filter) | `event_scopes` | the `event_scopes` table (migration only) | +| Event hosts → Organization; affiliations; team and award "Organization" / "Awarded by"; person → Home organization | `organizations` | organizations, labelled by name | +| Event hosts / event people / team members / timeline people → Person | `people` | people | +| Affiliations → Team | `teams` | teams, filtered to the chosen organization | +| Person awards → Award | `awards` | awards, labelled "Award — Organization" | +| Person awards → Presented at; Front page → Count down to | `events` | events | +| Timeline → Record | `timeline_refs` | all five kinds, filtered by "Points at" | + +--- + +## Front page section names + +"Section name" means three different things on the front page, and +each is changed in a different place: + +| What you see | Where it's set | +| --- | --- | +| **The heading on the page** ("National Retreats", "What's on") | **Admin → Front page → Page sections → Heading.** Blank uses the default below. | +| The default heading when that field is blank | `SECTIONS` in `src/pages/Home.tsx`, the `title` of each entry | +| **The name in the admin's Section dropdown** ("National Retreats carousel") | `FRONT_PAGE_SECTIONS` in `src/lib/adminSchema.ts` | +| The subnav links under the header ("#Retreats", "#Calendar") | `PAGE_SECTIONS["/"]` in `src/navConfig.ts` | + +To rename a band **for visitors**, use the admin. To rename how it +reads **in the editor's dropdown**, edit `FRONT_PAGE_SECTIONS`: + +```ts +const FRONT_PAGE_SECTIONS = [ + ["countdown", "Countdown to the next event"], + ["retreats", "National Retreats carousel"], // ← the right-hand side is the label + ["calendar", "Event calendar"], + ... +]; +``` + +The subnav links jump to each band by its anchor: the `id` passed in +each band's `render` in `Home.tsx` (`#retreats`, `#calendar`, +`#numbers`, `#connect`, and `#hero` for the hero). If you rename a +subnav label in `navConfig.ts`, leave its `hash` alone unless you also +change the band's `id`. + +**Adding a new kind of band** (not just renaming one) is a feature, +not a relabel: it needs a component, an entry in `SECTIONS` in +`Home.tsx`, the key added to `FRONT_PAGE_SECTIONS`, to the +`enumeration("section", …)` in `server/src/admin-schema.js`, to the +`FrontPageSectionKey` type in `src/lib/useFrontPage.ts`, and to the +CHECK on `front_page_sections.section` via a migration. + +--- + +## Front page stat sources + +The numbers band's "Where it comes from" dropdown works the same way: + +- **Relabel a source:** `STAT_SOURCES` in `src/lib/adminSchema.ts`. +- **Change what a count counts:** its query in `STAT_QUERIES` in + `server/src/routes/home.js`. Keep it counting exactly what the + matching public page shows (published rows), or the number and the + page will disagree. +- **Add a source:** the CHECK on `front_page_stats.source` (migration), + the `enumeration("source", …)` in `server/src/admin-schema.js`, + `STAT_SOURCES`, and a query in `STAT_QUERIES`. + +--- + +## Other content that lives in code + +| What | File | Notes | +| --- | --- | --- | +| Header and footer navigation, page subnav links | `src/navConfig.ts` | `PAGE_LINKS`, `PAGE_SECTIONS`, `NAV_ACTIONS`. A new page also needs a route in `src/App.tsx`. | +| Section titles, blurbs and colours on Retreats, Community, Leadership, Resources, Feedback, Privacy, Terms | the page file in `src/pages/` | the `SECTIONS` array at the top. A section's `id` must match its subnav `hash`. | +| Site-wide announcement banner | `src/data/bannerConfig.ts` | `enabled: false` hides it. Bump `id` when the message changes, so people who dismissed the old one see the new one. | +| History page decade headers | `src/data/historyDecades.ts` | Title, tagline and blurb per decade. | +| Chapter map tiles and area names | `src/data/mapGrid.ts` | `AREAS` (tile positions) and `AREA_NAMES`. Which region paints which tile is in the database (Admin → Organizations → a region → Map areas). | +| Feedback form types | `src/data/feedbackTypes.ts` **and** `TYPES` in `server/src/routes/feedback.js` | Keep the ids identical in both; the server stores unknown ids as `general`. Labels and hints are client-only. | +| Event type labels and plurals (public site) | `src/lib/eventTypes.ts` | Also the order of the type filter chips. | +| Event and person role labels (public site) | `ROLE_LABEL` in `src/pages/EventDetail.tsx` and `src/pages/PersonDetail.tsx` | | +| Organization kind labels ("Region", "Chapter") | `ORG_KIND_LABEL` in `src/lib/hrefs.ts` | | +| 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` | | +| 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` | | + +--- + +## Making the change + +1. Branch from `main` (never commit to `main` directly). +2. Edit the file(s). For a stored-value change, write the migration as + well, numbered after the last one in `server/src/migrations/`. +3. Check it: + ```sh + pnpm exec tsc # type-check + pnpm build # the site still builds + ``` + For anything touching the server or a migration, also run it + locally against a scratch database: + ```sh + cd server + DB_PATH=./dev.db pnpm migrate + DB_PATH=./dev.db pnpm dev # boot fails loudly if a descriptor and the schema disagree + ``` + and open the admin editor to see the dropdown. +4. Commit, push the branch, and open a pull request with `tea`. +5. After it's merged, deploy. A migration runs automatically when the + `ngu-api` service restarts; back up `/var/lib/ngu/ngu.db` first if + the change includes one. From 54bf649b8dc5d3f8664b61a08cf320c02f7dc882 Mon Sep 17 00:00:00 2001 From: Zaldimmar <Zaldimmar@gmail.com> Date: Sat, 26 Sep 2026 19:38:24 -0500 Subject: [PATCH 06/22] Tidy the admin editor's text: previews, blank options, no em-dashes Your wording pass on adminSchema.ts and fields.tsx: "Default: ..." blank options, "eg." examples, "URL ID" for slugs, and relabelled front page sections, stat sources and hero fields. On top of it: - Content block row titles end with an ellipsis when the paragraph is cut. preview() in src/lib/text.ts does it for anything that shortens text: it collapses whitespace, cuts on a word and adds "..." only when it actually shortened. - No em-dashes in the editor, front end or server: placeholders ("Internal note: ..."), the Organizations blurb, the URL ID help, empty table cells (now "-"), the Award dropdown ("Torch Award (NGU)" in OPTION_QUERIES), a boot error message, and every comment in the admin files. Also cleared from the files added this branch (QR page, directory route, embeds, hero, migration 024), and the QR page's team labels read "Board (NGU)". - A few comments where removing the dash had run two sentences together get a comma, colon or parentheses back. - docs/updating-data-in-code.md matches the new labels and gains a "Writing text in the editor" section with these conventions; CLAUDE.md lists them under Rules and gotchas. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- CLAUDE.md | 2 + docs/updating-data-in-code.md | 46 +++-- server/src/admin-crud.js | 18 +- server/src/admin-schema-sync.js | 4 +- server/src/admin-schema.js | 18 +- server/src/auth.js | 2 +- .../src/migrations/024_front_page_video.sql | 2 +- server/src/routes/admin-entities.js | 2 +- server/src/routes/admin.js | 2 +- server/src/routes/directory.js | 2 +- server/src/routes/panel.js | 6 +- src/components/QrCode.tsx | 4 +- src/components/admin/fields.tsx | 12 +- src/lib/adminSchema.ts | 161 +++++++++--------- src/lib/adminTitle.tsx | 4 +- src/lib/embeds.ts | 6 +- src/lib/roles.ts | 2 +- src/lib/site.ts | 2 +- src/lib/text.ts | 23 +++ src/lib/useFrontPage.ts | 4 +- src/pages/QrCodes.tsx | 2 +- src/pages/admin/AdminFeedback.tsx | 8 +- src/pages/admin/AdminHome.tsx | 8 +- src/pages/admin/AdminLayout.tsx | 8 +- src/pages/admin/AdminPanel.tsx | 18 +- src/pages/admin/EntityEdit.tsx | 24 +-- src/pages/admin/EntityList.tsx | 12 +- src/pages/admin/RequireRole.tsx | 4 +- src/pages/admin/adminNav.ts | 14 +- src/pages/sections/QrCodeMaker.tsx | 2 +- src/pages/sections/home/HeroStage.tsx | 4 +- 31 files changed, 239 insertions(+), 187 deletions(-) create mode 100644 src/lib/text.ts diff --git a/CLAUDE.md b/CLAUDE.md index 5cc971b..06fe51f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -60,6 +60,8 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - **Imports need explicit extensions** (`.ts`, `.tsx`, `.js`) everywhere. - **Vite resolves `.js` before `.ts`**, so a `.js` and `.ts` file with the same base name will import the wrong one. Give new hooks distinct names. - **Don't use `fallback: EMPTY` in api.ts hooks.** It silently returns empty arrays and hides server errors; let the error state surface. +- **No em-dashes** (U+2014) anywhere: UI text, help text, comments, docs, commit messages. Use a colon, comma or parentheses. An empty table cell shows `-`. +- **Admin editor text:** blank select options read `Default: …` (what blank means), examples in help text start with `eg.`, and record ids are called "URL ID". Cut-off preview text uses `preview()` from `src/lib/text.ts`, which ends it with an ellipsis. See `docs/updating-data-in-code.md`. ## Admin CRUD engine Descriptor-driven: `server/admin-crud.js` and `admin-schema.js` (server) and `adminSchema.ts` (client) generate SQL and form fields from declarative entity configs. Adding an entity should mean adding a descriptor, not new CRUD code. diff --git a/docs/updating-data-in-code.md b/docs/updating-data-in-code.md index c82cbe0..54d1dc3 100644 --- a/docs/updating-data-in-code.md +++ b/docs/updating-data-in-code.md @@ -18,6 +18,7 @@ what a dropdown in the admin editor says. - [Front page section names](#front-page-section-names) - [Front page stat sources](#front-page-stat-sources) - [Other content that lives in code](#other-content-that-lives-in-code) +- [Writing text in the editor](#writing-text-in-the-editor) - [Making the change](#making-the-change) --- @@ -96,7 +97,7 @@ label. For example, to make the event-people Role dropdown read nicely: // before options: ["speaker", "leader", "facilitator", "host", "musician", "volunteer", "attendee"], -// after — values unchanged, labels added +// after: values unchanged, labels added options: [ ["speaker", "Speaker"], ["leader", "Leader"], @@ -116,8 +117,11 @@ Things to check while you're there: - **Several lists are shared constants.** Front page sections and stat sources are `FRONT_PAGE_SECTIONS` and `STAT_SOURCES` near the top of the front page block; change them there, once. -- **`blankLabel`** is the text of the empty first option - (`"— brand —"`, `"— choose —"`). It's also just a label. +- **`blankLabel`** is the text of the empty first option, written as + `Default: …` saying what happens when it's left blank + (`"Default: brand"`, `"Default: none"`). It's also just a label. A + select with no `blankLabel` shows `- Please choose from the list -` + (set in `src/components/admin/fields.tsx`). - The value (first item) **must not change**. It's what's stored in the database and what the server and the CHECK constraint compare against. @@ -173,9 +177,9 @@ also in `admin-schema.js` and a CHECK): | Timeline → Points at (+ list filter) | event, organization, award, person, team | no | `refHref` in `src/lib/hrefs.ts` | | Timeline → Precision (and on events/orgs) | year, month, day | no | the history page's grouping | | Front page → Background | brand, photos | **yes** | `HeroStage.tsx` | -| Front page → Beside the words | none, livestream, video | **yes** | `HeroStage.tsx` | +| Front page → Feature | none, livestream, video | **yes** | `HeroStage.tsx` | | Front page → Sections → Section | countdown, retreats, calendar, stats, timeline, connect | **yes**, `FRONT_PAGE_SECTIONS` | `SECTIONS` in `src/pages/Home.tsx`; see [below](#front-page-section-names) | -| Front page → Stats → Where it comes from | manual, years_since, regions, … | **yes**, `STAT_SOURCES` | `STAT_QUERIES` in `server/src/routes/home.js`; see [below](#front-page-stat-sources) | +| Front page → Stats → Number Source | manual, years_since, regions, … | **yes**, `STAT_SOURCES` | `STAT_QUERIES` in `server/src/routes/home.js`; see [below](#front-page-stat-sources) | | Every list → Published / Featured filter | 1, 0 | **yes** | n/a | "No, shows values" means the dropdown currently shows the raw value, @@ -191,7 +195,7 @@ code): | Event hosts → Organization; affiliations; team and award "Organization" / "Awarded by"; person → Home organization | `organizations` | organizations, labelled by name | | Event hosts / event people / team members / timeline people → Person | `people` | people | | Affiliations → Team | `teams` | teams, filtered to the chosen organization | -| Person awards → Award | `awards` | awards, labelled "Award — Organization" | +| Person awards → Award | `awards` | awards, labelled "Award (Organization)" | | Person awards → Presented at; Front page → Count down to | `events` | events | | Timeline → Record | `timeline_refs` | all five kinds, filtered by "Points at" | @@ -206,7 +210,7 @@ each is changed in a different place: | --- | --- | | **The heading on the page** ("National Retreats", "What's on") | **Admin → Front page → Page sections → Heading.** Blank uses the default below. | | The default heading when that field is blank | `SECTIONS` in `src/pages/Home.tsx`, the `title` of each entry | -| **The name in the admin's Section dropdown** ("National Retreats carousel") | `FRONT_PAGE_SECTIONS` in `src/lib/adminSchema.ts` | +| **The name in the admin's Section dropdown** ("Events Carousel (National Retreats)") | `FRONT_PAGE_SECTIONS` in `src/lib/adminSchema.ts` | | The subnav links under the header ("#Retreats", "#Calendar") | `PAGE_SECTIONS["/"]` in `src/navConfig.ts` | To rename a band **for visitors**, use the admin. To rename how it @@ -214,9 +218,9 @@ reads **in the editor's dropdown**, edit `FRONT_PAGE_SECTIONS`: ```ts const FRONT_PAGE_SECTIONS = [ - ["countdown", "Countdown to the next event"], - ["retreats", "National Retreats carousel"], // ← the right-hand side is the label - ["calendar", "Event calendar"], + ["countdown", "Event Countdown"], + ["retreats", "Events Carousel (National Retreats)"], // ← the right-hand side is the label + ["calendar", "Event Calendar"], ... ]; ``` @@ -238,7 +242,7 @@ CHECK on `front_page_sections.section` via a migration. ## Front page stat sources -The numbers band's "Where it comes from" dropdown works the same way: +The numbers band's "Number Source" dropdown works the same way: - **Relabel a source:** `STAT_SOURCES` in `src/lib/adminSchema.ts`. - **Change what a count counts:** its query in `STAT_QUERIES` in @@ -272,6 +276,26 @@ The numbers band's "Where it comes from" dropdown works the same way: --- +## Writing text in the editor + +Conventions for any label, help text or option added to the admin, so +the editor reads consistently: + +- **Blank options say what blank means:** `Default: none`, + `Default: weekly`, `Default: the next upcoming event`. +- **Examples in help text start with `eg.`:** `eg. Board Chair, Team Lead`. +- **Record ids are called "URL ID"**, not slug, in anything the editor + shows. +- **Cut-off text ends with an ellipsis.** Anywhere a paragraph is + shortened for a row title, list cell or card, use `preview(text, max)` + from `src/lib/text.ts` rather than `.slice()`. It cuts on a word and + adds `…`, and only when it actually shortened something. +- **No em-dashes** (the long dash, U+2014), in the editor or anywhere else: labels, help + text, placeholders, code comments and docs. Use a colon, a comma or + parentheses instead. An empty value in a table shows `-`. + +--- + ## Making the change 1. Branch from `main` (never commit to `main` directly). diff --git a/server/src/admin-crud.js b/server/src/admin-crud.js index 732d154..2dd977d 100644 --- a/server/src/admin-crud.js +++ b/server/src/admin-crud.js @@ -10,7 +10,7 @@ it wants to exist, the engine deletes and reinserts in array order, and sort_order becomes the index. That makes drag-to- reorder free and removes a whole class of "which row is this" - bugs, at the cost of churning autoincrement ids — which is fine + bugs, at the cost of churning autoincrement ids, which is fine precisely because nothing references them. A column that isn't present in the payload at all is left out of @@ -51,7 +51,7 @@ function coerceValue(column, raw, errors, prefix = "") { // Absent from the payload. Fall back to the descriptor default // if it declares one, otherwise let the column's own DEFAULT do - // the work — which needs the column omitted, not nulled. + // the work, which needs the column omitted, not nulled. if (raw === undefined) { if (column.default !== undefined) return column.default; if (column.required) errors[key] = "Required."; @@ -183,8 +183,8 @@ export function readRow(db, entity, rawId) { /* A 1:1 side table is found one of two ways. `idColumn` is the original: the side table's key IS the parent's id, which is how regions and person_private work. `owner` is the same block children - already use — a foreign key column plus an optional kind discriminator - — and it exists because a timeline entry is keyed by (ref_kind, + already use (a foreign key column plus an optional kind discriminator), + and it exists because a timeline entry is keyed by (ref_kind, ref_id) rather than by the event's own slug. Same upsert either way; only the WHERE differs. */ function extensionWhere(ext, id) { @@ -257,7 +257,7 @@ export function createRow(db, entity, payload) { // idKind "auto": the table assigns the id, so there is nothing to // validate, nothing to check for collisions, and nothing for the - // client to have sent. Timeline entries use this — they have no + // client to have sent. Timeline entries use this: they have no // natural name to slug, and one gets created every time somebody // ticks a checkbox on an event. const auto = entity.idKind === "auto"; @@ -390,8 +390,8 @@ export function deleteRow(db, entity, rawId) { function writeExtensions(db, entity, id, payload, parentValues) { for (const ext of entity.extensions ?? []) { if (!applies(ext.when, parentValues)) { - // The gate closed — the kind changed away from this side - // table, or a checkbox was unticked — so its row (and anything + // The gate closed (the kind changed away from this side + // table, or a checkbox was unticked), so its row (and anything // cascading off it) goes. const gone = extensionWhere(ext, id); db.prepare(`DELETE FROM ${ext.table} WHERE ${gone.sql}`).run(...gone.params); @@ -587,7 +587,7 @@ function deleteChildren(db, child, ownerId) { /* SQLite's constraint messages are accurate and unreadable. Turn the ones that users actually cause into something actionable, - and name the column wherever the message carries it — a missing + and name the column wherever the message carries it: a missing field is the client's problem to fix, not a 500. The descriptor and the schema agreeing (see admin-schema-sync.js) @@ -635,7 +635,7 @@ function wrapDbErrors(fn) { // The polymorphic tables stand in for a foreign key with a // BEFORE INSERT trigger, and a trigger's RAISE(ABORT) matches none - // of the patterns above — so without this, pointing a content + // of the patterns above, so without this, pointing a content // block, link or timeline entry at a row that isn't there is a 500 // rather than something the form can show. const ghost = /^(\w+): no such (\w+)$/.exec(message); diff --git a/server/src/admin-schema-sync.js b/server/src/admin-schema-sync.js index f91edc3..6487d0c 100644 --- a/server/src/admin-schema-sync.js +++ b/server/src/admin-schema-sync.js @@ -14,7 +14,7 @@ field instead of SQLite catching it as a 500; - reports a descriptor column the table doesn't have; - reports a NOT NULL, no-DEFAULT column that no descriptor - column and no engine-supplied column covers — nothing can + column and no engine-supplied column covers: nothing can ever set it, so every insert through the admin will fail. The first is a silent repair. The other two are deployment bugs, @@ -122,7 +122,7 @@ export function syncDescriptorsWithSchema(db, entities, { strict = true } = {}) if (group.engineSupplied.includes(columnName)) continue; problems.push( `${name}: ${group.table}.${columnName} is NOT NULL with no default, ` + - `but no descriptor column covers it — every insert will fail.`, + `but no descriptor column covers it, so every insert will fail.`, ); } } diff --git a/server/src/admin-schema.js b/server/src/admin-schema.js index 30c63f9..29561dd 100644 --- a/server/src/admin-schema.js +++ b/server/src/admin-schema.js @@ -2,7 +2,7 @@ ADMIN ENTITY DESCRIPTORS One object per editable entity. Everything the CRUD handlers do - — validation, SQL, nesting — is read from here, so adding a + (validation, SQL, nesting) is read from here, so adding a table later is a descriptor rather than another set of hand-written statements to keep in step with the schema. @@ -28,7 +28,7 @@ owner by free-text owner_id, so renaming a slug in place would silently orphan every link and content block attached to it. - affiliations is edited from both ends — a person's roles, and a + affiliations is edited from both ends: a person's roles, and a team's members. Each side deletes and reinserts only its own slice (WHERE person_id = ?, WHERE team_id = ?) and declares every column of the row, so a save from one side round-trips @@ -81,7 +81,7 @@ const affiliationRole = [ editor and by the in_timeline extension on events and organizations. occurred_on is text, not date. "2012" and "2025-07" are legitimate - values — a backfilled entry often knows the year and nothing more — + values (a backfilled entry often knows the year and nothing more), and the date coercion would reject both. `precision` is what says how much of it to believe. */ const timelineFields = [ @@ -180,7 +180,7 @@ const blocksChild = (ownerKind) => ({ }); /* Hosts. One row is one host, ordered, each either an organization - or a person — the CHECK on event_hosts rejects both and the blank + or a person. The CHECK on event_hosts rejects both and the blank filter drops neither, so the only bad row that reaches SQLite is one with both selects filled, and that comes back keyed to the row like any other field error. @@ -496,7 +496,7 @@ const people = { // · org_id cannot be changed once anyone is filed under the // team. The composite foreign key has no ON UPDATE CASCADE, so // SQLite aborts the UPDATE. That surfaces as a constraint -// error, which is the correct answer — reassign the members +// error, which is the correct answer: reassign the members // first. // // · deleting a team with members fails the same way, rather than @@ -655,8 +655,8 @@ const timeline = { row impossible even without it. Every collection here is owned by page_id and replaced wholesale. - That is safe for the same reason it is for links and blocks — - nothing has a foreign key into these tables — and paths carry + That is safe for the same reason it is for links and blocks + (nothing has a foreign key into these tables), and paths carry their actions as a nested collection, the shape content blocks and their items already use. */ @@ -811,13 +811,13 @@ export const OPTION_QUERIES = { ORDER BY kind, label`, // The awarding organization is folded into the label instead, - // because a person can receive an award from any organization — + // because a person can receive an award from any organization: // there is nothing to filter on, only something to disambiguate // when two orgs name an award the same thing. awards: ` SELECT a.id, CASE WHEN o.name IS NULL THEN a.name - ELSE a.name || ' — ' || o.name END AS label, + ELSE a.name || ' (' || o.name || ')' END AS label, a.org_id FROM awards a LEFT JOIN organizations o ON o.id = a.org_id diff --git a/server/src/auth.js b/server/src/auth.js index 4e7f000..9a8a181 100644 --- a/server/src/auth.js +++ b/server/src/auth.js @@ -4,7 +4,7 @@ Everything that decides who someone is. Routes decide what they may do. - Password storage is scrypt from node:crypto — no native module, + Password storage is scrypt from node:crypto: no native module, nothing to compile, nothing for pnpm to get wrong. The stored string carries its own parameters, so raising the cost later doesn't invalidate existing hashes. diff --git a/server/src/migrations/024_front_page_video.sql b/server/src/migrations/024_front_page_video.sql index 9fe43fa..2637b43 100644 --- a/server/src/migrations/024_front_page_video.sql +++ b/server/src/migrations/024_front_page_video.sql @@ -3,7 +3,7 @@ -- -- A fourth hero mode, 'video': a recorded video beside the words, -- the way 'livestream' puts a stream there, but without the LIVE --- badge and without autoplay — a visitor presses play. +-- badge and without autoplay: a visitor presses play. -- -- Its own two columns rather than reusing the livestream's, so a -- featured video and a stream can both be set up ahead of time and diff --git a/server/src/routes/admin-entities.js b/server/src/routes/admin-entities.js index 98a7b66..9b700aa 100644 --- a/server/src/routes/admin-entities.js +++ b/server/src/routes/admin-entities.js @@ -12,7 +12,7 @@ feedback routes. Both sit under the same requireAuth. :entity is matched against the descriptor map, never - interpolated into SQL from the URL — an unknown name is a 404 + interpolated into SQL from the URL; an unknown name is a 404 before anything touches the database. ═══════════════════════════════════════════════════════════════ */ diff --git a/server/src/routes/admin.js b/server/src/routes/admin.js index 2bcd7c0..1479050 100644 --- a/server/src/routes/admin.js +++ b/server/src/routes/admin.js @@ -90,7 +90,7 @@ admin.get("/feedback", (c) => { }); /* ── PATCH /api/admin/feedback/:id ─────────────────────────────── - { status?, admin_note? } — either, both, partial. + { status?, admin_note? }: either, both, partial. ───────────────────────────────────────────────────────────── */ admin.patch("/feedback/:id", requireRole("editor"), async (c) => { diff --git a/server/src/routes/directory.js b/server/src/routes/directory.js index 1d55a93..680a26f 100644 --- a/server/src/routes/directory.js +++ b/server/src/routes/directory.js @@ -1,5 +1,5 @@ /* ═══════════════════════════════════════════════════════════════ - DIRECTORY ROUTE — read-only, mounted under /api + DIRECTORY ROUTE: read-only, mounted under /api GET /directory every public record that has a page diff --git a/server/src/routes/panel.js b/server/src/routes/panel.js index 394da02..8aefbce 100644 --- a/server/src/routes/panel.js +++ b/server/src/routes/panel.js @@ -1,12 +1,12 @@ /* ═══════════════════════════════════════════════════════════════ - PANEL ROUTES — server/src/routes/panel.js + PANEL ROUTES: server/src/routes/panel.js GET /api/admin/panel/overview PATCH /api/admin/panel/users/:id role, is_active DELETE /api/admin/panel/users/:id/sessions sign out everywhere Everything here is superadmin-only, enforced once at the top - rather than per route — there's no read here that an ordinary + rather than per route; there's no read here that an ordinary admin should have either. Account records and live session counts are a different class of thing from content. @@ -88,7 +88,7 @@ panel.get("/overview", (c) => { }); /* A table that hasn't been created yet shouldn't take the whole - page down — the panel is where you go when something is wrong. */ + page down: the panel is where you go when something is wrong. */ function count(db, table, where) { try { const sql = `SELECT COUNT(*) AS n FROM ${table}${where ? ` WHERE ${where}` : ""}`; diff --git a/src/components/QrCode.tsx b/src/components/QrCode.tsx index 80a7da2..e5f92d1 100644 --- a/src/components/QrCode.tsx +++ b/src/components/QrCode.tsx @@ -8,8 +8,8 @@ under 6% of the code, well inside what 'H' repairs, and never reaches the three corner finder patterns. - Everything is drawn in the SVG itself — no CSS, no external - references — so the element serialises to a file that looks the + Everything is drawn in the SVG itself (no CSS, no external + references), so the element serialises to a file that looks the same outside the page. `ref` reaches the <svg> for exactly that. ═══════════════════════════════════════════════════════════════ */ diff --git a/src/components/admin/fields.tsx b/src/components/admin/fields.tsx index c0fa4d2..d202c53 100644 --- a/src/components/admin/fields.tsx +++ b/src/components/admin/fields.tsx @@ -5,8 +5,8 @@ an ordered collection of them, and nests one level for content blocks and their items. - Ordering is array position — the server writes sort_order from - the index — so moving a row is a splice, not a number to + Ordering is array position (the server writes sort_order from + the index), so moving a row is a splice, not a number to hand-edit. Rows can be dragged by the handle or moved with the arrow buttons; the arrows are the keyboard path and stay whether or not a pointer is in use. @@ -135,7 +135,7 @@ export function Field({ field, value, row, options, error, onChange }: any) { /> ) : widget === "select" ? ( // A select has no readOnly, so this one really does have - // to be disabled — there's no way to keep it focusable + // to be disabled: there's no way to keep it focusable // and still refuse a new choice. <select {...common} @@ -144,8 +144,8 @@ export function Field({ field, value, row, options, error, onChange }: any) { orphaned && !locked ? inputError : "" }`} > - <option value="">{field.blankLabel ?? "— choose —"}</option> - {orphaned && <option value={value}>{value} — no longer exists</option>} + <option value="">{field.blankLabel ?? "- Please choose from the list -"}</option> + {orphaned && <option value={value}>{value} no longer exists</option>} {list.map(([id2, label]) => ( <option key={id2} value={id2}> {label} @@ -294,7 +294,7 @@ export function Repeater({ spec, rows, options, errors, errorPrefix, onChange }) }} onDragOver={(e) => { // A null dragIndex means the drag started in some - // other collection — leave it to whoever owns it. + // other collection; leave it to whoever owns it. if (dragIndex === null) return; e.preventDefault(); e.stopPropagation(); diff --git a/src/lib/adminSchema.ts b/src/lib/adminSchema.ts index cbb4457..2a19223 100644 --- a/src/lib/adminSchema.ts +++ b/src/lib/adminSchema.ts @@ -8,13 +8,15 @@ nested paths ('region.scope') match the side-table keys. Adding a field is one entry. Adding an entity is one object here - plus one descriptor on the server — no new page component. + plus one descriptor on the server, with no new page component. A value seeded in a repeater's `blank` must also be declared as a default: on the matching server column, or a row the user adds and never fills in reads as real input instead of being skipped. ═══════════════════════════════════════════════════════════════ */ +import { preview } from "./text.ts"; + const PLACE_FIELDS = [ { path: "venue", label: "Venue" }, { path: "address", label: "Address", full: true }, @@ -36,17 +38,17 @@ const PUBLISH_FIELDS = [ { path: "sort_order", label: "Sort order", widget: "number" }, ]; -/* The parts of an affiliation that read the same from either end — +/* The parts of an affiliation that read the same from either end: the person's list of roles, and the team's list of members. */ const AFFILIATION_ROLE_FIELDS = [ - { path: "title", label: "Title", help: "Board Chair, Chapter Lead" }, + { path: "title", label: "Title", help: "eg. Board Chair, Team Lead" }, { path: "role", label: "Role", widget: "select", options: ["lead", "board", "staff", "volunteer", "member"], }, - { path: "is_owner", label: "Owner", widget: "checkbox", help: "Listed first" }, + { path: "is_owner", label: "Owner", widget: "checkbox", help: "Listed first (can be more than one)" }, { path: "started_on", label: "Started", widget: "date" }, { path: "ended_on", label: "Ended", widget: "date", help: "Blank means current" }, { path: "is_public", label: "Public", widget: "checkbox" }, @@ -57,7 +59,7 @@ const AFFILIATION_ROLE_FIELDS = [ 'region.scope' and 'private.notes' are. Everything here is an override. Left blank, the history page falls - back to the record's own title, date and logo through v_timeline — + back to the record's own title, date and logo through v_timeline, which is the point of referencing rather than copying. */ const timelineExtensionFields = (noun) => [ { @@ -105,7 +107,7 @@ const timelineExtensionFields = (noun) => [ const timelineGroup = (noun) => ({ legend: "Timeline", note: - `Adds this ${noun} to the history page. Nothing is copied — the entry ` + + `Adds this ${noun} to the history page. Nothing is copied, the entry ` + `reads this record, so editing it here updates the timeline too.`, fields: [ { @@ -146,7 +148,7 @@ const linksChild = { }; /* Hosts. One row is one host, ordered, and each is either an - organization or a person — never both, which the CHECK on + organization or a person, never both, which the CHECK on event_hosts enforces and this form can only ask nicely about. The first row supplies the logo and colour when the event sets @@ -169,15 +171,16 @@ const hostsChild = { label: "Organization", widget: "select", optionsFrom: "organizations", - blankLabel: "— none —", + blankLabel: "Default: none", + help: "Host Organization" }, { path: "person_id", label: "Person", widget: "select", optionsFrom: "people", - blankLabel: "— none —", - help: "One or the other, not both. First host supplies the logo and colour.", + blankLabel: "Default: none", + help: "Use if the host is an individual, choose between person and org host, not both.", }, ], }; @@ -186,7 +189,7 @@ const blocksChild = { key: "content_blocks", label: "Content blocks", addLabel: "Add block", - title: (row) => `${row.type ?? "block"} — ${(row.text ?? "").slice(0, 40) || "empty"}`, + title: (row) => `${row.type ?? "block"}: ${preview(row.text, 40) || "empty"}`, blank: { slot: "body", type: "paragraph", text: "" }, fields: [ { path: "slot", label: "Slot", widget: "select", options: ["card", "body"] }, @@ -231,7 +234,7 @@ const organizations = { key: "organizations", label: "Organizations", singular: "organization", - idLabel: "Slug", + idLabel: "URL ID", slugFrom: "name", list: { @@ -264,7 +267,7 @@ const organizations = { { path: "short_name", label: "Short name" }, { path: "tagline", label: "Tagline", full: true }, { path: "color", label: "Colour", widget: "color" }, - { path: "logo", label: "Logo", help: "Filename in public/org-logos/" }, + { path: "logo", label: "Logo", help: "Filename in /org-logos/" }, ], }, { @@ -290,7 +293,7 @@ const organizations = { label: "Region", widget: "select", optionsFrom: "regions", - blankLabel: "— none —", + blankLabel: "Default: none", }, { path: "chapter.meets", label: "Meets", help: "2nd Sundays, 6:00pm" }, { path: "chapter.started", label: "Started", help: "Since 2021" }, @@ -311,16 +314,16 @@ const organizations = { title: (row) => row.area_code || "New area", blank: { area_code: "", share: 1 }, fields: [ - { path: "area_code", label: "Area code", required: true, help: "WA, CA, CANADA" }, + { path: "area_code", label: "Area code", required: true, help: "Two letter state code or Country name" }, { path: "share", label: "Share", widget: "number", help: "1 for the whole tile, 0.5 for half" }, { path: "edge", label: "Edge", widget: "select", options: ["top", "bottom"], - blankLabel: "— whole tile —", + blankLabel: "Default: whole tile", }, - { path: "note", label: "Note", help: "north, Salt Lake City area" }, + { path: "note", label: "Note", help: "details to explain why it's half or other note" }, ], }, linksChild, @@ -331,8 +334,8 @@ const organizations = { /* ── Events ──────────────────────────────────────────────────── */ /* The panel the Series checkbox opens. Starts and Ends above stay - the series' bounds — the first meeting and the last day it can - meet — so nothing here repeats them. */ + the series' bounds (the first meeting and the last day it can + meet), so nothing here repeats them. */ const SERIES_WEEKDAYS = [ ["sun", "Sunday"], ["mon", "Monday"], @@ -358,10 +361,10 @@ const seriesGroup = { widget: "select", options: [ ["weekly", "Weekly, on the days ticked below"], - ["monthly_date", "Monthly, on the start date's day (the 13th)"], - ["monthly_weekday", "Monthly, on the start date's weekday (2nd Tuesday)"], + ["monthly_date", "Monthly, on the day of the start date (eg. the 13th)"], + ["monthly_weekday", "Monthly, on the weekday of the start date (eg. 2nd Tuesday)"], ], - blankLabel: "— weekly —", + blankLabel: "Default: weekly", }, { path: "series_interval", @@ -390,7 +393,7 @@ const events = { key: "events", label: "Events", singular: "event", - idLabel: "Slug", + idLabel: "URL ID", slugFrom: "title", list: { @@ -424,7 +427,7 @@ const events = { widget: "select", optionsFrom: "event_scopes", required: true, - help: "Whose gathering this is. Only national, regional and partner appear on the Retreats page", + help: "Whose gathering this is.", }, { path: "event_type", @@ -447,20 +450,20 @@ const events = { { path: "date_label", label: "Date label", - help: "What the card shows — 'March/April 2026' is fine here", + help: "Text override of what the card shows (eg. March/April 2026)", }, { path: "status", label: "Status", widget: "select", options: ["upcoming", "past", "cancelled"], - blankLabel: "— derive from end date —", + blankLabel: "Default: derive from end date", }, { path: "is_series", label: "Series", widget: "checkbox", - help: "Repeats on a schedule — a weekly class, a monthly meeting", + help: "Repeats on a schedule, such as a weekly class, a monthly meeting", }, ], }, @@ -469,7 +472,7 @@ const events = { { legend: "Appearance", fields: [ - { path: "event_logo", label: "Event logo", help: "Filename in public/event-logos/" }, + { path: "event_logo", label: "Event logo", help: "Filename in /event-logos/" }, { path: "org_logo", label: "Org logo override" }, { path: "color", label: "Colour", widget: "color" }, { path: "gradient", label: "Gradient", full: true }, @@ -511,7 +514,7 @@ const events = { "attendee", ], }, - { path: "title", label: "Title", help: "Keynote Speaker" }, + { path: "title", label: "Title", help: "eg. Keynote Speaker" }, { path: "is_public", label: "Show on the site", widget: "checkbox" }, ], }, @@ -526,7 +529,7 @@ const people = { key: "people", label: "People", singular: "person", - idLabel: "Slug", + idLabel: "URL ID", slugFrom: "display_name", list: { @@ -549,13 +552,13 @@ const people = { { path: "sort_name", label: "Sort name", help: "Doe, Jane" }, { path: "pronouns", label: "Pronouns" }, { path: "tagline", label: "Tagline", full: true }, - { path: "photo", label: "Photo", help: "Filename in public/people/" }, + { path: "photo", label: "Photo", help: "Filename in /people/" }, { path: "primary_org_id", label: "Home organization", widget: "select", optionsFrom: "organizations", - blankLabel: "— none —", + blankLabel: "Default: none", help: "Optional. Shown above their bio", }, { @@ -591,7 +594,7 @@ const people = { }, { legend: "Publishing", - note: "Unpublished people are invisible everywhere, including as chapter leads.", + note: "Unpublished people are invisible everywhere.", fields: [PUBLISHED_FIELD], }, ], @@ -622,7 +625,7 @@ const people = { label: "Team", widget: "select", optionsFrom: "teams", - blankLabel: "— none —", + blankLabel: "Default: none", // A team belongs to an org; offering one from another // org would fail the composite foreign key on save. filterBy: (option, row) => option.org_id === row.org_id, @@ -652,7 +655,7 @@ const people = { label: "Presented at", widget: "select", optionsFrom: "events", - blankLabel: "— none —", + blankLabel: "Default: none", }, { path: "awarded_on", label: "Date", widget: "date" }, { path: "citation", label: "Citation", widget: "textarea", full: true }, @@ -670,7 +673,7 @@ const teams = { key: "teams", label: "Teams", singular: "team", - idLabel: "Slug", + idLabel: "URL ID", // teams.id is a global primary key, not scoped to the org, so // 'board' can only exist once across the whole site. Composing // the slug from both fields is what keeps NGU's board and the @@ -694,7 +697,7 @@ const teams = { { legend: "Identity", note: - "Pick the organization first: the slug is built from it, " + + "Pick the organization first: the id is built from it, " + "and it can't be changed once anyone is filed under this team.", fields: [ { @@ -708,7 +711,7 @@ const teams = { { path: "name", label: "Name", required: true, help: "Board, Leadership Team" }, { path: "tagline", label: "Tagline", full: true }, { path: "color", label: "Colour", widget: "color" }, - { path: "logo", label: "Logo", help: "Filename in public/org-logos/" }, + { path: "logo", label: "Logo", help: "Filename in /org-logos/" }, ], }, { legend: "Publishing", fields: PUBLISH_FIELDS }, @@ -749,7 +752,7 @@ const awards = { key: "awards", label: "Awards", singular: "award", - idLabel: "Slug", + idLabel: "URL ID", slugFrom: "name", list: { @@ -777,7 +780,7 @@ const awards = { label: "Awarded by", widget: "select", optionsFrom: "organizations", - blankLabel: "— unattributed —", + blankLabel: "- unattributed -", help: "The organization that gives this award", }, { path: "name", label: "Name", required: true }, @@ -843,7 +846,7 @@ const timeline = { note: "An entry either points at a record or stands on its own. " + "Pointing at one means its title, date and logo come from that " + - "record \u2014 nothing is copied, so editing the record updates this.", + "record and nothing is copied, so editing the record updates this.", fields: [ { path: "kind", @@ -858,15 +861,15 @@ const timeline = { label: "Points at", widget: "select", options: ["event", "organization", "award", "person", "team"], - blankLabel: "\u2014 nothing, this stands alone \u2014", - help: "Changing this leaves the record below orphaned \u2014 pick a new one", + blankLabel: "Default: nothing", + help: "Changing this leaves the record below orphaned, pick a new one", }, { path: "ref_id", label: "Record", widget: "select", optionsFrom: "timeline_refs", - blankLabel: "\u2014 none \u2014", + blankLabel: "Default: none", // One flat list of every referenceable row, narrowed to the // kind chosen above. Five dropdowns of which four are always // wrong would be worse. @@ -879,7 +882,7 @@ const timeline = { legend: "When", note: "Blank takes the referenced record's own date. Precision is what " + - "says how much of the date to believe \u2014 a backfilled entry that " + + "says how much of the date to believe, a backfilled entry that " + "only knows the year should say so.", fields: [ { @@ -927,7 +930,7 @@ const timeline = { addLabel: "Add person", note: "For an entry about people. A 'people' entry pointing at a team " + - "already shows that team's members \u2014 this is for the cases where " + + "already shows that team's members, this is for the cases where " + "the list is editorial rather than structural.", title: (row, options) => options?.people?.find((p) => p.id === row.person_id)?.label ?? "New person", @@ -959,23 +962,23 @@ const timeline = { what the page and the API key on. */ const FRONT_PAGE_SECTIONS = [ - ["countdown", "Countdown to the next event"], - ["retreats", "National Retreats carousel"], - ["calendar", "Event calendar"], - ["stats", "Numbers"], - ["timeline", "Featured timeline"], - ["connect", "Find your way in"], + ["countdown", "Event Countdown"], + ["retreats", "Events Carousel (National Retreats)"], + ["calendar", "Event Calendar"], + ["stats", "Stats"], + ["timeline", "Featured Timeline"], + ["connect", "Connect Nav"], ]; const STAT_SOURCES = [ - ["manual", "Typed in — shows Value"], - ["years_since", "Years since — Value is the year"], - ["regions", "Count: published regions"], - ["chapters", "Count: published chapters"], - ["partners", "Count: published partners"], + ["manual", "Print Value Field"], + ["years_since", "Years Since Value"], + ["regions", "Count: regions"], + ["chapters", "Count: chapters"], + ["partners", "Count: partners"], ["events_held", "Count: past events"], ["retreats_held", "Count: past retreats"], - ["people", "Count: published people"], + ["people", "Count: people in database"], ["awards_given", "Count: public awards given"], ]; @@ -990,7 +993,7 @@ const frontPage = { groups: [ { - legend: "Hero", + legend: "Hero - Primary Section", note: "The first thing a visitor sees. Blank buttons don't render.", fields: [ { @@ -998,29 +1001,29 @@ const frontPage = { label: "Background", widget: "select", options: [ - ["brand", "Brand — animated colour and the dove"], - ["photos", "Photos — cycles through the photos below"], + ["brand", "Brand: animated colour and the dove"], + ["photos", "Photos: cycles through the photos below"], ], - blankLabel: "— brand —", + blankLabel: "Default: brand", help: "Photos with none added shows the brand background", }, { path: "hero_feature", - label: "Beside the words", + label: "Feature", widget: "select", options: [ - ["none", "Nothing — the words fill the hero"], - ["livestream", "Livestream — the stream, with a LIVE badge"], - ["video", "Featured video — click to play"], + ["none", "Nothing: No additional overlay"], + ["livestream", "Livestream: the stream, with a LIVE badge"], + ["video", "Featured video: click to play"], ], - blankLabel: "— nothing —", + blankLabel: "Default: nothing", help: "Switch to Livestream when you go live, and back when you're done", }, { path: "eyebrow", label: "Eyebrow", help: "Small line above the headline" }, { path: "headline", label: "Headline", full: true }, { path: "subhead", label: "Subhead", widget: "textarea", full: true }, { path: "primary_label", label: "Main button label" }, - { path: "primary_url", label: "Main button link", help: "/retreats, #connect or a full URL" }, + { path: "primary_url", label: "Main button link", help: "/page, #section-id or a full URL" }, { path: "secondary_label", label: "Second button label" }, { path: "secondary_url", label: "Second button link" }, ], @@ -1032,7 +1035,7 @@ const frontPage = { path: "slide_seconds", label: "Seconds per photo", widget: "number", - help: "Photos mode. 3 to 60", + help: "Photos Background. Set from 3 to 60 seconds", }, { path: "livestream_url", @@ -1047,7 +1050,7 @@ const frontPage = { full: true, help: "A YouTube, Vimeo or Facebook link, or a video file: a filename in " + - "public/front-page/ or a link ending in .mp4 or .webm", + "/front-page/ or a link ending in .mp4 or .webm", }, { path: "video_title", label: "Video title", full: true, help: "Shown after \"Featured video\" above the headline" }, ], @@ -1060,7 +1063,7 @@ const frontPage = { label: "Count down to", widget: "select", optionsFrom: "events", - blankLabel: "— the next upcoming event —", + blankLabel: "Default: the next upcoming event ", help: "Leave blank almost always. A pinned event that's over falls back to the next one", }, ], @@ -1084,7 +1087,7 @@ const frontPage = { options: FRONT_PAGE_SECTIONS, required: true, }, - { path: "title", label: "Heading", help: "Blank for the section's own" }, + { path: "title", label: "Heading", help: "Heading Override" }, { path: "blurb", label: "Blurb", full: true }, { path: "is_hidden", label: "Hidden", widget: "checkbox", help: "Hide for now" }, ], @@ -1097,7 +1100,7 @@ const frontPage = { title: (row) => row.caption || row.media || "New photo", blank: { media: "", alt: "", caption: "" }, fields: [ - { path: "media", label: "Photo", required: true, help: "Filename in public/front-page/, or a URL" }, + { path: "media", label: "Photo", required: true, help: "Filename in /front-page/, or a URL" }, { path: "alt", label: "Description", help: "For screen readers" }, { path: "caption", label: "Caption", full: true }, { path: "link_url", label: "Link", help: "Optional; makes the caption a link" }, @@ -1114,26 +1117,26 @@ const frontPage = { { path: "label", label: "Label", required: true }, { path: "source", - label: "Where it comes from", + label: "Number Source", widget: "select", options: STAT_SOURCES, - blankLabel: "— typed in —", + blankLabel: "Default: Print Value", }, - { path: "value", label: "Value", help: "Typed in: the number. Years since: the year" }, + { path: "value", label: "Value", help: "The number thats printed" }, { path: "suffix", label: "Suffix", help: "+, k, % …" }, { path: "note", label: "Note", full: true }, ], }, { key: "paths", - label: "Find your way in", + label: "Connect Nav", note: "Each path is a choice a visitor can pick; its actions appear when they do.", addLabel: "Add path", title: (row) => [row.icon, row.label].filter(Boolean).join(" ") || "New path", blank: { label: "", icon: "", blurb: "" }, fields: [ - { path: "label", label: "Label", required: true, help: "Attend, Serve…" }, - { path: "icon", label: "Icon", help: "One emoji" }, + { path: "label", label: "Label", required: true, help: "eg. Attend, Serve…" }, + { path: "icon", label: "Icon", help: "Emoji" }, { path: "blurb", label: "Blurb", full: true }, ], children: [ diff --git a/src/lib/adminTitle.tsx b/src/lib/adminTitle.tsx index f4dc675..8adcd71 100644 --- a/src/lib/adminTitle.tsx +++ b/src/lib/adminTitle.tsx @@ -3,9 +3,9 @@ The layout knows which section you're in; only the page knows which record is on screen. Rather than have both write - document.title and race — child effects run before parent + document.title and race (child effects run before parent effects, so the layout would win and the record name would - never survive — the page publishes a string and the layout is + never survive), the page publishes a string and the layout is the single writer. Null is the normal state. A page that publishes nothing, or one diff --git a/src/lib/embeds.ts b/src/lib/embeds.ts index 306e658..cdcc86b 100644 --- a/src/lib/embeds.ts +++ b/src/lib/embeds.ts @@ -2,8 +2,8 @@ EMBEDS Turns the link an admin pastes into the URL an <iframe> can - load. People paste the page they're looking at — a YouTube watch - or live link, a Facebook video, a Vimeo page — not the embed + load. People paste the page they're looking at (a YouTube watch + or live link, a Facebook video, a Vimeo page), not the embed form, so those are recognised and rewritten. Anything else that is https is assumed to already be an embed URL and passed through; anything that isn't https is refused, so the hero never @@ -11,7 +11,7 @@ Streams start playing, muted: browsers only autoplay muted video, and a hero that starts shouting is worse than one that - asks. A featured video doesn't start at all — it's a recording, + asks. A featured video doesn't start at all: it's a recording, so the visitor presses play. A featured video can also be a file rather than a link: a diff --git a/src/lib/roles.ts b/src/lib/roles.ts index 2150282..794b12f 100644 --- a/src/lib/roles.ts +++ b/src/lib/roles.ts @@ -1,5 +1,5 @@ /* ═══════════════════════════════════════════════════════════════ - ROLES — src/lib/roles.ts + ROLES: src/lib/roles.ts The same ladder as server/src/auth.js, and it has to stay the same ladder. This copy exists to decide what to draw; the diff --git a/src/lib/site.ts b/src/lib/site.ts index a7668e3..75bce26 100644 --- a/src/lib/site.ts +++ b/src/lib/site.ts @@ -2,7 +2,7 @@ SITE The public address of the live site. Used where a URL has to - leave the browser and still work — a printed QR code made on + leave the browser and still work: a printed QR code made on localhost or a preview has to point here, not at wherever it was generated. Everything inside the site links by path, not this. ═══════════════════════════════════════════════════════════════ */ diff --git a/src/lib/text.ts b/src/lib/text.ts new file mode 100644 index 0000000..9e435c7 --- /dev/null +++ b/src/lib/text.ts @@ -0,0 +1,23 @@ +/* ═══════════════════════════════════════════════════════════════ + TEXT + + Shared helpers for showing a short piece of longer text. + + preview() is for anywhere a paragraph is cut to fit a row title, + a list cell or a card: it collapses whitespace and, when it has + to cut, stops at the last whole word and ends with an ellipsis, + so a shortened line always reads as shortened. Text that already + fits comes back unchanged, with no ellipsis. + ═══════════════════════════════════════════════════════════════ */ + +export function preview(text: string | null | undefined, max: number): string { + const flat = (text ?? '').replace(/\s+/g, ' ').trim() + if (flat.length <= max) return flat + + const cut = flat.slice(0, max) + const lastSpace = cut.lastIndexOf(' ') + // Break on a word if one ends in the back half; otherwise a single + // long word would leave almost nothing. + const clean = lastSpace > max / 2 ? cut.slice(0, lastSpace) : cut + return `${clean.replace(/[\s.,;:!?]+$/, '')}…` +} diff --git a/src/lib/useFrontPage.ts b/src/lib/useFrontPage.ts index 475beea..e43c6e2 100644 --- a/src/lib/useFrontPage.ts +++ b/src/lib/useFrontPage.ts @@ -5,7 +5,7 @@ visible sections in order, counted stats, paths with actions, and the countdown's event. Edited in the admin under Front page. - No fallback content. If the request fails the page says so — a + No fallback content. If the request fails the page says so: a plausible default home page would hide a broken server behind something that looks fine. ═══════════════════════════════════════════════════════════════ */ @@ -61,7 +61,7 @@ export type FrontPageSection = { export type FrontPageStat = { label: string - /** Already counted or typed; never null — the API drops those. */ + /** Already counted or typed; never null, since the API drops those. */ value: string suffix?: string | null note?: string | null diff --git a/src/pages/QrCodes.tsx b/src/pages/QrCodes.tsx index 1341b5d..a0173d7 100644 --- a/src/pages/QrCodes.tsx +++ b/src/pages/QrCodes.tsx @@ -2,7 +2,7 @@ import PageShell from '../components/PageShell.tsx' import QrCodeMaker from './sections/QrCodeMaker.tsx' /* ═══════════════════════════════════════════════════════════════ - QR CODES PAGE — /qr + QR CODES PAGE: /qr A QR code for any page on the site, for flyers, slides and signs. Unlisted: not in navConfig, so neither the header nor the diff --git a/src/pages/admin/AdminFeedback.tsx b/src/pages/admin/AdminFeedback.tsx index 2bcf1d8..55475eb 100644 --- a/src/pages/admin/AdminFeedback.tsx +++ b/src/pages/admin/AdminFeedback.tsx @@ -1,5 +1,5 @@ /* ═══════════════════════════════════════════════════════════════ - ADMIN — FEEDBACK TRIAGE + ADMIN: FEEDBACK TRIAGE Reads /api/admin/feedback, writes status and notes back through PATCH, and deletes through DELETE. Deliberately a flat list @@ -9,7 +9,7 @@ Two capabilities, two ranks. Editors and above can change a status or leave a note; deleting is admin and above, matching requireRole on the server. Both come from the roles ladder - rather than an equality check — a superadmin is not role === + rather than an equality check: a superadmin is not role === "admin", and reading it that way is what hid these controls. Every read passes ttl: 0. The api cache exists for public @@ -156,7 +156,7 @@ function FeedbackCard({ row, onChange, onRemove, canWrite, canRemove }) { rows={2} value={note} disabled={busy} - placeholder="Internal note — who's handling it, what was done" + placeholder="Internal note: who's handling it, what was done" onChange={(e) => setNote(e.target.value)} className="mt-3 w-full resize-y rounded-lg border border-[#4a6b72]/25 bg-white px-3 py-2 text-sm text-[#26454c] outline-none focus:border-[#138ba0] focus:ring-2 focus:ring-[#138ba0]/25" /> @@ -238,7 +238,7 @@ export default function AdminFeedback() { const [loading, setLoading] = useState(true); const [error, setError] = useState<any>(null); - // Minimums, not equality — see lib/roles.ts. + // Minimums, not equality; see lib/roles.ts. const canWrite = roleCanWrite(user); const canRemove = canDelete(user); diff --git a/src/pages/admin/AdminHome.tsx b/src/pages/admin/AdminHome.tsx index e281f67..7e15f8c 100644 --- a/src/pages/admin/AdminHome.tsx +++ b/src/pages/admin/AdminHome.tsx @@ -1,9 +1,9 @@ /* ═══════════════════════════════════════════════════════════════ ADMIN HOME - Where login lands. Two columns: the cards are the navigation — - the header deliberately drops its tab row here so the same links - aren't drawn twice — and a standing info panel on the right. + Where login lands. Two columns: the cards are the navigation + (the header deliberately drops its tab row here so the same links + aren't drawn twice), and a standing info panel on the right. The cards come from adminNav.ts, the same list the CMS header reads, so a new entity shows up here the moment it's registered. @@ -31,7 +31,7 @@ import { CMS_NAV, FORMS_NAV, PANEL_NAV, target } from "./adminNav.ts"; function NavCard({ item }) { const to = target(item); - // Drop the child that just repeats the card's own destination — + // Drop the child that just repeats the card's own destination: // "All organizations" under Organizations. const extras = (item.children ?? []).filter((child) => child.to !== to); diff --git a/src/pages/admin/AdminLayout.tsx b/src/pages/admin/AdminLayout.tsx index 2e0120b..7bd1932 100644 --- a/src/pages/admin/AdminLayout.tsx +++ b/src/pages/admin/AdminLayout.tsx @@ -2,7 +2,7 @@ ADMIN LAYOUT Bare on purpose. No PageShell, no announcement banner, no - footer site map — none of that belongs around a staff tool, and + footer site map. None of that belongs around a staff tool, and /admin should never appear in navConfig. Three areas share this chrome: Home, the CMS and the Panel. The @@ -11,8 +11,8 @@ The tab row is drawn everywhere except Home, where the card grid is the navigation and drawing both would say the same thing - twice. Which tabs appear depends on the signed-in user — - navFor() drops the superadmin-only ones — but that's cosmetics. + twice. Which tabs appear depends on the signed-in user + (navFor() drops the superadmin-only ones), but that's cosmetics. The route guard and the API are what actually say no. ═══════════════════════════════════════════════════════════════ */ @@ -53,7 +53,7 @@ export default function AdminLayout() { matches(pathname, child.to), ); - // What the page below has published about itself — a record + // What the page below has published about itself: a record // name, or null on a list. setDetail is stable so publishing // can't loop. const [detail, setDetail] = useState<any>(null); diff --git a/src/pages/admin/AdminPanel.tsx b/src/pages/admin/AdminPanel.tsx index 6b24b23..e34493e 100644 --- a/src/pages/admin/AdminPanel.tsx +++ b/src/pages/admin/AdminPanel.tsx @@ -8,13 +8,13 @@ Three blocks, deliberately boring: - System — what's actually running, for when something is off - Content — row counts, the cheapest "is the database there" - Accounts — roles, access and live sessions + System what's actually running, for when something is off + Content row counts, the cheapest "is the database there" + Accounts roles, access and live sessions The role select is driven by ROLES from lib/roles.ts, so a new rung on the ladder appears here without this file changing. The - legend beside it is the same list — four roles is past the + legend beside it is the same list: four roles is past the point where "Editor" explains itself. Every account write signs that person out, which the server @@ -30,18 +30,18 @@ import { isUnauthorized, useAuth } from "../../lib/auth.tsx"; import { useNavigate } from "react-router-dom"; import { ROLES, ROLE_LABELS, ROLE_NOTES } from "../../lib/roles.ts"; -/* SQLite hands back "2026-09-22 04:11:07" — UTC, but without the +/* SQLite hands back "2026-09-22 04:11:07": UTC, but without the marker that says so. Left alone, browsers read it as local time and last-login drifts by the timezone offset. */ function when(value) { - if (!value) return "—"; + if (!value) return "-"; const iso = value.includes("T") ? value : `${value.replace(" ", "T")}Z`; const date = new Date(iso); return Number.isNaN(date.getTime()) ? value : date.toLocaleString(); } function uptime(seconds) { - if (seconds == null) return "—"; + if (seconds == null) return "-"; const d = Math.floor(seconds / 86400); const h = Math.floor((seconds % 86400) / 3600); const m = Math.floor((seconds % 3600) / 60); @@ -104,7 +104,7 @@ export default function AdminPanel() { }, [load]); /* Replace the one row the server returns rather than refetching - the whole overview — the counts didn't change. */ + the whole overview; the counts didn't change. */ function mergeUser(updated) { setData((current) => current @@ -199,7 +199,7 @@ export default function AdminPanel() { > {row.label}{" "} <strong className="font-semibold text-[#0f2f36]"> - {row.count ?? "—"} + {row.count ?? "-"} </strong> </span> ))} diff --git a/src/pages/admin/EntityEdit.tsx b/src/pages/admin/EntityEdit.tsx index d451a66..5511ce8 100644 --- a/src/pages/admin/EntityEdit.tsx +++ b/src/pages/admin/EntityEdit.tsx @@ -1,9 +1,9 @@ /* ═══════════════════════════════════════════════════════════════ - ADMIN — ENTITY EDIT + ADMIN: ENTITY EDIT Create and edit for every entity in the manifest. The form holds - the whole nested object — parent row, side tables, child - collections — and PATCH sends the lot. The server replaces + the whole nested object (parent row, side tables, child + collections) and PATCH sends the lot. The server replaces children wholesale, so what you see here is exactly what will exist afterwards. @@ -14,7 +14,7 @@ A field the form never sets is left out of the payload entirely, and the server lets the column's own DEFAULT apply. So a blank - new-record form is deliberate, not lazy — writing "" into every + new-record form is deliberate, not lazy: writing "" into every field is what used to turn a default into a constraint failure. updated_at rides along untouched. If someone else saved while @@ -26,7 +26,7 @@ Two capabilities, not one role. An editor may create and update but not delete, so the action bar asks canWrite/canDelete rather than comparing user.role to a string. The comparison this - replaced — role === "admin" — locked superadmins out of saving + replaced (role === "admin") locked superadmins out of saving the moment a rank above admin existed, which is what an equality test against a ladder always eventually does. @@ -35,8 +35,8 @@ slugFrom may name one field or several. Most ids are unique because the name is: two organizations aren't both called - Northwest. Team ids are the exception — teams.id is a global - primary key, so every org's 'Board' would collide — which is + Northwest. Team ids are the exception: teams.id is a global + primary key, so every org's 'Board' would collide, which is why the array form exists and teams uses it. ═══════════════════════════════════════════════════════════════ */ @@ -72,7 +72,7 @@ export default function EntityEdit() { // Some entities have no slug: the table assigns an integer id, so // there is nothing to type on create and nothing to compose from - // other fields. Timeline entries are the first — an entry that + // other fields. Timeline entries are the first: an entry that // references an event has no name of its own. const autoId = manifest?.idKind === "auto"; @@ -224,7 +224,7 @@ export default function EntityEdit() { setForm((prev) => { let next = setPath(prev, path, value); // Recompose the id whenever one of its sources moves. The - // prefix always follows the organization — picking a + // prefix always follows the organization; picking a // different one has to change the slug, or it would claim a // team belongs somewhere it doesn't. The tail only follows // the name until someone types over it. @@ -319,7 +319,7 @@ export default function EntityEdit() { </h1> {/* Slug. An auto-id entity has nothing to ask for on create, and - nothing editable afterwards — so it gets a plain line rather + nothing editable afterwards, so it gets a plain line rather than a disabled box pretending to be a field. */} {singleton ? ( updatedAt && ( @@ -347,7 +347,7 @@ export default function EntityEdit() { placeholder: isNew && qualifierPaths.length ? "board" : undefined, readOnly: !isNew, help: !isNew - ? "Fixed once created — links and content blocks reference it." + ? "Fixed once created, since links and content blocks reference it." : qualifierPaths.length ? "The prefix comes from the organization. Type the rest." : "Lowercase, hyphens, no spaces. Can't be changed later.", @@ -394,7 +394,7 @@ export default function EntityEdit() { ))} {/* Child collections. Awards own none, so the panel would be - an empty white box — skip it rather than render it. */} + an empty white box; skip it rather than render it. */} {children.some((child) => visible(child.when)) && ( <div className="mt-6 rounded-2xl border border-[#138ba0]/20 bg-white p-5"> {children diff --git a/src/pages/admin/EntityList.tsx b/src/pages/admin/EntityList.tsx index 209d965..ed74ffe 100644 --- a/src/pages/admin/EntityList.tsx +++ b/src/pages/admin/EntityList.tsx @@ -1,5 +1,5 @@ /* ═══════════════════════════════════════════════════════════════ - ADMIN — ENTITY LIST + ADMIN: ENTITY LIST One component for organizations, events and people. The :entity route param picks the manifest; nothing here knows what a @@ -7,8 +7,8 @@ The "New X" link follows the same rule as EntityEdit's save button: atLeast(user, "editor"), matching requireRole("editor") - on POST /api/admin/:entity. Drawing it is not permission — the - server decides — it only avoids offering a click that 403s, and + on POST /api/admin/:entity. Drawing it is not permission (the + server decides); it only avoids offering a click that 403s, and avoids hiding one that wouldn't. ═══════════════════════════════════════════════════════════════ */ @@ -34,7 +34,7 @@ export default function EntityList() { const [query, setQuery] = useState(params.get("q") ?? ""); // Minimum rank, never equality. POST /api/admin/:entity is gated - // at "editor", so anyone from editor upward may create — and the + // at "editor", so anyone from editor upward may create, and the // equality test this replaced hid the button from superadmins as // well as editors, which is the failure mode an == against a // ladder always produces once a rank is added above it. @@ -178,8 +178,8 @@ export default function EntityList() { {column.widget === "bool" ? row[column.key] ? "Yes" - : "—" - : row[column.key] || "—"} + : "-" + : row[column.key] || "-"} </td> ))} <td className="px-4 py-3 font-mono text-xs text-[#4a6b72]">{row.id}</td> diff --git a/src/pages/admin/RequireRole.tsx b/src/pages/admin/RequireRole.tsx index 7f63742..9167fed 100644 --- a/src/pages/admin/RequireRole.tsx +++ b/src/pages/admin/RequireRole.tsx @@ -1,11 +1,11 @@ /* ═══════════════════════════════════════════════════════════════ - ROLE GUARD — src/pages/admin/RequireRole.tsx + ROLE GUARD: src/pages/admin/RequireRole.tsx Sits inside RequireAuth, never instead of it: by the time this renders, the session question has already been answered. All this decides is whether the answer was good enough. - Same caveat as RequireAuth — this hides the interface, not the + Same caveat as RequireAuth: this hides the interface, not the data. /api/admin/panel/* is superadmin-only on the server, and that's the part that matters. Without it, a bookmarked URL and a disabled select would be the only thing between a viewer and diff --git a/src/pages/admin/adminNav.ts b/src/pages/admin/adminNav.ts index 4b034ec..01e9648 100644 --- a/src/pages/admin/adminNav.ts +++ b/src/pages/admin/adminNav.ts @@ -1,9 +1,9 @@ /* ═══════════════════════════════════════════════════════════════ - ADMIN NAVIGATION — src/pages/admin/adminNav.ts + ADMIN NAVIGATION: src/pages/admin/adminNav.ts Lifted out of AdminLayout because two things read it now: the header tabs and the card grid on the home page. Adding an entity - stays one entry here plus a descriptor — there's still no second + stays one entry here plus a descriptor; there's still no second list to keep in step, it just isn't inside the layout file any more. @@ -32,8 +32,8 @@ export const AREA_TITLES = { }; /* The CMS tabs. Teams and Awards live under Organizations because - that's where they belong conceptually — a team is part of an org, - an award is given by one — even though each is its own table and + that's where they belong conceptually (a team is part of an org, + an award is given by one), even though each is its own table and its own page. */ export const CMS_NAV = [ { @@ -44,7 +44,7 @@ export const CMS_NAV = [ { to: "/admin/organizations", label: "Organizations", - blurb: "Regions, chapters and partners — plus the teams and awards they own.", + blurb: "Regions, chapters and partners, plus the teams and awards they own.", children: [ { to: "/admin/organizations", label: "All organizations" }, { to: "/admin/teams", label: "Teams" }, @@ -64,7 +64,7 @@ export const CMS_NAV = [ label: "Timeline", blurb: "What the history page shows, and the order it shows it in.", }, - // One record, not a list — the tab opens it directly. + // One record, not a list: the tab opens it directly. { to: "/admin/front_page", label: "Front page", @@ -89,7 +89,7 @@ export const FORMS_NAV = { ], }; -/* Accounts and server state, not content — which is why it sits +/* Accounts and server state, not content, which is why it sits outside the CMS rather than as another tab within it. */ export const PANEL_NAV = { to: ADMIN_PANEL, diff --git a/src/pages/sections/QrCodeMaker.tsx b/src/pages/sections/QrCodeMaker.tsx index 25b53e1..8495f37 100644 --- a/src/pages/sections/QrCodeMaker.tsx +++ b/src/pages/sections/QrCodeMaker.tsx @@ -98,7 +98,7 @@ function groupsFor(kind: Kind, directory: Directory | null): Group[] { { choices: directory.teams.map((t) => ({ path: teamHref(t.id), - label: `${t.name} — ${t.org_name}`, + label: `${t.name} (${t.org_name})`, })), }, ] diff --git a/src/pages/sections/home/HeroStage.tsx b/src/pages/sections/home/HeroStage.tsx index de71fdf..172f585 100644 --- a/src/pages/sections/home/HeroStage.tsx +++ b/src/pages/sections/home/HeroStage.tsx @@ -6,8 +6,8 @@ Backdrop, what fills the background: - brand drifting colour and slow concentric rings — many - circles, one centre — with the dove at that centre + brand drifting colour and slow concentric rings (many + circles, one centre) with the dove at that centre photos the hero photos, crossfading with a slow zoom, a progress bar per photo and a pause button (anything that moves on its own for more than five seconds From 68f08b633ce65261139faf5e935153b8f1bd2ecb Mon Sep 17 00:00:00 2001 From: Zaldimmar <Zaldimmar@gmail.com> Date: Sat, 26 Sep 2026 19:59:29 -0500 Subject: [PATCH 07/22] Let the front page countdown filter by event scope and type Admin > Front page > Countdown gains two optional dropdowns, "Only this scope" and "Only this type", each defaulting to any. They narrow which event counts as "the next one": National + Retreat counts down to the next national retreat and skips a sooner regional class. A pinned event still wins over both. When nothing matches, the countdown band doesn't render, as before. Migration 026 adds front_page.countdown_scope_id, a foreign key to event_scopes (ON DELETE SET NULL, so removing a scope returns it to "any"), and countdown_event_type, checked against the same values as events.event_type. Adding an event type now widens both CHECKs; the note in eventTypes.ts and the guide say so. Also clears the older em-dashes from home.js and eventTypes.ts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/updating-data-in-code.md | 3 +- server/src/admin-schema.js | 2 ++ .../src/migrations/026_countdown_filters.sql | 29 +++++++++++++++++++ server/src/routes/home.js | 24 ++++++++++++--- src/lib/adminSchema.ts | 24 ++++++++++++++- src/lib/eventTypes.ts | 12 ++++---- 6 files changed, 83 insertions(+), 11 deletions(-) create mode 100644 server/src/migrations/026_countdown_filters.sql diff --git a/docs/updating-data-in-code.md b/docs/updating-data-in-code.md index 54d1dc3..b03c2b5 100644 --- a/docs/updating-data-in-code.md +++ b/docs/updating-data-in-code.md @@ -176,6 +176,7 @@ also in `admin-schema.js` and a CHECK): | Timeline → Kind (+ list filter) | milestone, event, organization, award, people | no | `KIND_NAMES` in `src/pages/sections/history/TimelineEntry.tsx` | | Timeline → Points at (+ list filter) | event, organization, award, person, team | no | `refHref` in `src/lib/hrefs.ts` | | Timeline → Precision (and on events/orgs) | year, month, day | no | the history page's grouping | +| Front page → Countdown → Only this type | retreat, class, workshop, meeting, other | **yes** | `server/src/routes/home.js` (picks the countdown event). The same values as Events → Type, so adding a type widens both CHECKs. | | Front page → Background | brand, photos | **yes** | `HeroStage.tsx` | | Front page → Feature | none, livestream, video | **yes** | `HeroStage.tsx` | | Front page → Sections → Section | countdown, retreats, calendar, stats, timeline, connect | **yes**, `FRONT_PAGE_SECTIONS` | `SECTIONS` in `src/pages/Home.tsx`; see [below](#front-page-section-names) | @@ -191,7 +192,7 @@ code): | Dropdown | `optionsFrom` | Comes from | | --- | --- | --- | | Chapter → Region | `regions` | organizations of kind region | -| Event → Scope (+ list filter) | `event_scopes` | the `event_scopes` table (migration only) | +| Event → Scope (+ list filter); Front page → Countdown → Only this scope | `event_scopes` | the `event_scopes` table (migration only) | | Event hosts → Organization; affiliations; team and award "Organization" / "Awarded by"; person → Home organization | `organizations` | organizations, labelled by name | | Event hosts / event people / team members / timeline people → Person | `people` | people | | Affiliations → Team | `teams` | teams, filtered to the chosen organization | diff --git a/server/src/admin-schema.js b/server/src/admin-schema.js index 29561dd..ee36e78 100644 --- a/server/src/admin-schema.js +++ b/server/src/admin-schema.js @@ -691,6 +691,8 @@ const frontPage = { text("video_url"), text("video_title"), text("countdown_event_id"), + text("countdown_scope_id"), + enumeration("countdown_event_type", ["retreat", "class", "workshop", "meeting", "other"]), ], children: [ diff --git a/server/src/migrations/026_countdown_filters.sql b/server/src/migrations/026_countdown_filters.sql new file mode 100644 index 0000000..b859265 --- /dev/null +++ b/server/src/migrations/026_countdown_filters.sql @@ -0,0 +1,29 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 026 COUNTDOWN: FILTER BY SCOPE AND TYPE +-- +-- The countdown counts to the pinned event, or else to the next +-- published event that hasn't ended. These two narrow "the next +-- event": National + Retreat counts down to the next national +-- retreat and skips a regional class that happens sooner. Either or +-- both can be left null, meaning any. A pinned event still wins +-- whatever they say; the admin chose it by name. +-- +-- countdown_scope_id an event_scopes id. A real foreign key, +-- so it can't name a scope that doesn't +-- exist; ON DELETE SET NULL puts it back to +-- "any" if a scope is ever removed. +-- countdown_event_type the same values as events.event_type. +-- Adding an event type now means widening +-- this CHECK too. +-- +-- Plain ADD COLUMN: a REFERENCES column is allowed when its default +-- is NULL, and a CHECK is allowed on any. No rebuild. +-- +-- PRAGMA user_version; -- reads 25 before this file +-- ═══════════════════════════════════════════════════════════════ + +ALTER TABLE front_page ADD COLUMN countdown_scope_id TEXT + REFERENCES event_scopes (id) ON DELETE SET NULL; + +ALTER TABLE front_page ADD COLUMN countdown_event_type TEXT + CHECK (countdown_event_type IN ('retreat', 'class', 'workshop', 'meeting', 'other')); diff --git a/server/src/routes/home.js b/server/src/routes/home.js index 90e65ca..cf560e8 100644 --- a/server/src/routes/home.js +++ b/server/src/routes/home.js @@ -1,5 +1,5 @@ /* ═══════════════════════════════════════════════════════════════ - FRONT PAGE ROUTE — read-only, mounted under /api + FRONT PAGE ROUTE: read-only, mounted under /api GET /front-page the home page's configuration, resolved @@ -26,6 +26,11 @@ ended. "Hasn't ended" is COALESCE(ends_on, starts_on) >= today, so a running series with a start date in the past still counts. The client works out the next meeting of a series from `series`. + + countdown_scope_id and countdown_event_type narrow "the next + event" (National + Retreat skips a sooner regional class). Null + means any. They don't apply to a pinned event: the admin chose + that one by name. ═══════════════════════════════════════════════════════════════ */ import { Hono } from "hono"; @@ -57,7 +62,7 @@ const STAT_QUERIES = { WHERE pa.is_public = 1`, }; -/* The number as a string, or null when there's nothing to print — +/* The number as a string, or null when there's nothing to print: a manual stat nobody filled in, or a year that isn't one. */ function statValue(db, row) { if (row.source === "manual") return row.value || null; @@ -145,16 +150,27 @@ home.get("/front-page", (c) => { .get(page.countdown_event_id) : null; + const filters = []; + const params = []; + if (page.countdown_scope_id) { + filters.push("AND scope_id = ?"); + params.push(page.countdown_scope_id); + } + if (page.countdown_event_type) { + filters.push("AND event_type = ?"); + params.push(page.countdown_event_type); + } + const next = pinned ?? db .prepare( `SELECT * FROM v_events - WHERE ${notOver} + WHERE ${notOver} ${filters.join(" ")} ORDER BY starts_on, title LIMIT 1`, ) - .get(); + .get(...params); return json(c, { front_page: { diff --git a/src/lib/adminSchema.ts b/src/lib/adminSchema.ts index 2a19223..9fd0bfe 100644 --- a/src/lib/adminSchema.ts +++ b/src/lib/adminSchema.ts @@ -1063,9 +1063,31 @@ const frontPage = { label: "Count down to", widget: "select", optionsFrom: "events", - blankLabel: "Default: the next upcoming event ", + blankLabel: "Default: the next upcoming event", help: "Leave blank almost always. A pinned event that's over falls back to the next one", }, + { + path: "countdown_scope_id", + label: "Only this scope", + widget: "select", + optionsFrom: "event_scopes", + blankLabel: "Default: any scope", + help: "Narrows the next upcoming event. Ignored when an event is pinned above", + }, + { + path: "countdown_event_type", + label: "Only this type", + widget: "select", + options: [ + ["retreat", "Retreat"], + ["class", "Class"], + ["workshop", "Workshop"], + ["meeting", "Meeting"], + ["other", "Other"], + ], + blankLabel: "Default: any type", + help: "Combines with the scope: National + Retreat counts down to the next national retreat", + }, ], }, ], diff --git a/src/lib/eventTypes.ts b/src/lib/eventTypes.ts index 91f8898..a4f3e49 100644 --- a/src/lib/eventTypes.ts +++ b/src/lib/eventTypes.ts @@ -2,18 +2,20 @@ EVENT TYPES The client half of the CHECK on events.event_type. Order here is - display order — the filter chips read it straight off this array, + display order: the filter chips read it straight off this array, so moving a line moves a chip. - What this is not: event_scopes. A scope owns presentation — + What this is not: event_scopes. A scope owns presentation: Retreats.tsx keys its title, accent and background on the id, so an unrecognised scope_id makes an event vanish with no error, which is why that one is a real table with a real foreign key. A type carries no presentation of its own and an unknown value renders as its own name, so a CHECK is enough. - Adding a type is three edits: the CHECK in a migration, the enum - in both descriptor halves, and this list. Adding it here alone + Adding a type is three edits: the CHECKs in a migration (on + events.event_type and front_page.countdown_event_type), the enums + in both descriptor halves (the event's type and the front page's + countdown type), and this list. Adding it here alone means the site offers a filter the database will refuse to store. ═══════════════════════════════════════════════════════════════ */ @@ -37,7 +39,7 @@ const capitalize = (word: string) => word ? word.charAt(0).toUpperCase() + word.slice(1) : '' /* A value the CHECK has gained since this file was written renders - as itself rather than vanishing — the same rule EventDetail's + as itself rather than vanishing, the same rule EventDetail's ROLE_ORDER follows for billing roles. */ export const eventTypeLabel = (id?: string | null): string => (id ? BY_ID.get(id)?.label : null) ?? capitalize(id ?? '') From c4970af3b8bb895ee5520490353031164f795be6 Mon Sep 17 00:00:00 2001 From: Zaldimmar <Zaldimmar@gmail.com> Date: Sat, 26 Sep 2026 20:20:51 -0500 Subject: [PATCH 08/22] Colour event card buttons, add address to the footer, steady the map list - Event cards: the link buttons (Register and the like) and "Event details" now take the card's colour for their text as well as their border: the event's own colour, or the band's default (teal unless the page sets one). They were falling back to the card's black. The two "no registration" notices lose their em-dashes. - Footer: the logo moves above the site map, a size larger, with the street address (marked as physical, not for mail) and the 501(c)(3) statement and tax ID under it. The site map spreads across the full width below, six columns on large screens. The details are one constant at the top of Footer.tsx. - Chapter map: hovering a region in the list no longer scrolls the list. The list still follows hovers and clicks on the map and the legend; a hover inside the list only highlights. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/components/Footer.tsx | 38 ++++++++++++++++++++------ src/pages/sections/EventList-Cards.tsx | 11 +++++--- src/pages/sections/OrgList-Map.tsx | 21 ++++++++++++-- 3 files changed, 55 insertions(+), 15 deletions(-) diff --git a/src/components/Footer.tsx b/src/components/Footer.tsx index ce2346c..f3db5f8 100644 --- a/src/components/Footer.tsx +++ b/src/components/Footer.tsx @@ -50,6 +50,16 @@ const Get_In_Touch: TouchLink[] = [ { label: "Contact Us", to: "/leadership#contact" }, ]; +/* Under the logo. The street address is where NGU is, not where + to send post, and says so. */ +const Organization_Details = { + street: "1901 NW Blue Parkway", + cityLine: "Unity Village, MO 64065", + addressNote: "Physical address, not for mail", + nonprofit: "Next Generation of Unity is a qualified 501(c)(3) nonprofit organization.", + taxId: "33-2819320", +}; + const Footer_Links = [ { label: "Privacy Policy", to: "/privacy" }, { label: "Terms of Service", to: "/terms" }, @@ -71,18 +81,28 @@ export default function Footer() { <footer className="py-16 px-6" style={{ background: "rgba(0, 47, 58, 0.92)" }}> <div className="max-w-6xl mx-auto"> <div className="grid grid-cols-1 md:grid-cols-12 gap-10 md:gap-8 mb-12"> - {/* Brand */} - <div className="md:col-span-3 flex justify-center md:justify-start"> - <Link to="/"> - <img src={nguLogo} alt="Next Generation of Unity" className="h-10 w-auto" /> + {/* Brand and details on top, the site map across the full + width below them. */} + <div className="md:col-span-9 text-center md:text-left"> + <Link to="/" className="inline-block"> + <img src={nguLogo} alt="Next Generation of Unity" className="h-14 w-auto" /> </Link> - </div> - {/* Site map — mirrors both nav tiers */} - <div className="md:col-span-6 text-center md:text-left"> - <nav aria-label="Site map"> + <address className="mt-5 not-italic text-sm leading-relaxed text-white/60"> + {Organization_Details.street} + <br /> + {Organization_Details.cityLine} + <br /> + <span className="text-white/40">({Organization_Details.addressNote})</span> + </address> + <p className="mt-3 max-w-xl text-sm leading-relaxed text-white/60"> + {Organization_Details.nonprofit} Tax ID: {Organization_Details.taxId}. + </p> + + {/* Site map: mirrors both nav tiers */} + <nav aria-label="Site map" className="mt-10"> <h2 className={headingClass}>Site Map</h2> - <ul className="grid grid-cols-2 sm:grid-cols-3 gap-x-6 gap-y-6"> + <ul className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-x-6 gap-y-6"> {PAGE_LINKS.map((page) => { const sections = PAGE_SECTIONS[page.path] ?? []; return ( diff --git a/src/pages/sections/EventList-Cards.tsx b/src/pages/sections/EventList-Cards.tsx index 00f1068..80f8fbb 100644 --- a/src/pages/sections/EventList-Cards.tsx +++ b/src/pages/sections/EventList-Cards.tsx @@ -283,10 +283,10 @@ export function Card({ {links.length === 0 && ( <p className="text-center font-600" style={{ color: accent }}> {past - ? "This event has concluded — thank you to everyone who joined us!" + ? "This event has concluded. Thank you to everyone who joined us!" : igHandle ? "Registration has not opened yet, follow our instagram for more details." - : "Registration has not opened yet — check back soon for more details."} + : "Registration has not opened yet, check back soon for more details."} </p> )} @@ -295,6 +295,9 @@ export function Card({ compact ? "gap-2" : "gap-3" } ${links.length === 0 ? "mt-4" : ""}`} > + {/* Button text takes the card's colour (the event's own, + or the band's default, teal unless the page sets one), + the same as the border, rather than the card's black. */} {links.map(item => ( <a key={item.label} @@ -302,7 +305,7 @@ export function Card({ className={`rounded-xl font-700 transition-all duration-200 hover:scale-105 text-center ${ compact ? "py-2.5 px-5" : "py-2.5 px-6" }`} - style={{ border: `1px solid ${color}` }} + style={{ border: `1px solid ${color}`, color }} > {item.label} </a> @@ -333,7 +336,7 @@ export function Card({ className={`rounded-xl font-700 transition-all duration-200 hover:scale-105 text-center ${ compact ? "py-2.5 px-5" : "py-2.5 px-6" }`} - style={{ border: `1px solid ${color}` }} + style={{ border: `1px solid ${color}`, color }} > Event details </Link> diff --git a/src/pages/sections/OrgList-Map.tsx b/src/pages/sections/OrgList-Map.tsx index 817518f..2eb06c8 100644 --- a/src/pages/sections/OrgList-Map.tsx +++ b/src/pages/sections/OrgList-Map.tsx @@ -778,6 +778,19 @@ export default function OrgListMap({ view = "map", accent = FALLBACK_COLOR }) { const regionRefs = useRef<any>({}); const chapterRefs = useRef<any>({}); + // Where the latest hover came from. The list follows the map and + // the legend, but hovering the list itself must not move it: the + // row would slide out from under the pointer. + const hoverFromList = useRef(false); + const hoverOnMap = id => { + hoverFromList.current = false; + setHovered(id); + }; + const hoverInList = id => { + hoverFromList.current = true; + setHovered(id); + }; + const scrollListTo = el => { const box = listRef.current; if (!box || !el) return; @@ -788,8 +801,11 @@ export default function OrgListMap({ view = "map", accent = FALLBACK_COLOR }) { box.scrollTo({ top: el.offsetTop - 8, behavior: "smooth" }); }; - // Hovering or selecting a region brings that block into view. + // Hovering or selecting a region on the map or legend brings its + // block into view. After a hover in the list, nothing scrolls: not + // on the way in, and not back to the selection on the way out. useEffect(() => { + if (hoverFromList.current) return; const id = hovered || selected; if (id) scrollListTo(regionRefs.current[id]); }, [hovered, selected]); @@ -838,7 +854,7 @@ export default function OrgListMap({ view = "map", accent = FALLBACK_COLOR }) { ); } - const shared = { selected, setSelected, hovered, setHovered }; + const shared = { selected, setSelected, hovered, setHovered: hoverOnMap }; const onMapIds = new Set(regionAreas.map(a => a.region_id)); const block = (region, indent) => ( @@ -851,6 +867,7 @@ export default function OrgListMap({ view = "map", accent = FALLBACK_COLOR }) { regionRefs={regionRefs} chapterRefs={chapterRefs} {...shared} + setHovered={hoverInList} /> ); From 99c3a87c87902205a5624bbdada21ec173d2e8ff Mon Sep 17 00:00:00 2001 From: Zaldimmar <Zaldimmar@gmail.com> Date: Sun, 27 Sep 2026 14:42:12 -0500 Subject: [PATCH 09/22] Add a Tools block to the admin home with the QR code generator Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/pages/admin/AdminHome.tsx | 12 +++++++++--- src/pages/admin/adminNav.ts | 15 +++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/src/pages/admin/AdminHome.tsx b/src/pages/admin/AdminHome.tsx index 7e15f8c..c1312ce 100644 --- a/src/pages/admin/AdminHome.tsx +++ b/src/pages/admin/AdminHome.tsx @@ -9,8 +9,8 @@ reads, so a new entity shows up here the moment it's registered. Forms sit in their own block below: they're submissions coming in rather than content going out, and there'll be more of them - than the feedback queue eventually. The Panel block below that - only exists for superadmins. + than the feedback queue eventually. Tools come next, and the + Panel block below that only exists for superadmins. The right-hand panel is deliberately inert. Nothing here fetches, so the landing page can't be slow or half-broken on @@ -22,7 +22,7 @@ import { Link } from "react-router-dom"; import { useAuth } from "../../lib/auth.tsx"; import { SITE_VERSION } from "../../lib/version.ts"; import { ROLE_LABELS, isSuper } from "../../lib/roles.ts"; -import { CMS_NAV, FORMS_NAV, PANEL_NAV, target } from "./adminNav.ts"; +import { CMS_NAV, FORMS_NAV, PANEL_NAV, TOOLS_NAV, target } from "./adminNav.ts"; /* One card. The title link is stretched over the whole card with `after:absolute`, which makes the card clickable without nesting @@ -129,6 +129,12 @@ export default function AdminHome() { ))} </CardBlock> + <CardBlock title={TOOLS_NAV.label} blurb={TOOLS_NAV.blurb}> + {TOOLS_NAV.children.map((tool) => ( + <NavCard key={tool.to} item={tool} /> + ))} + </CardBlock> + {isSuper(user) && ( <CardBlock title="Superadmin" blurb="Only superadmins see this block."> <NavCard item={PANEL_NAV} /> diff --git a/src/pages/admin/adminNav.ts b/src/pages/admin/adminNav.ts index 01e9648..0748c6c 100644 --- a/src/pages/admin/adminNav.ts +++ b/src/pages/admin/adminNav.ts @@ -89,6 +89,21 @@ export const FORMS_NAV = { ], }; +/* Tools are pages that make something rather than edit a record. + They live on the public site, so they're on the home page only: + a header tab would leave the admin area. */ +export const TOOLS_NAV = { + label: "Tools", + blurb: "Handy pages for making things.", + children: [ + { + to: "/qr", + label: "QR code generator", + blurb: "Codes for flyers, slides and signs, pointing at any page on the site.", + }, + ], +}; + /* Accounts and server state, not content, which is why it sits outside the CMS rather than as another tab within it. */ export const PANEL_NAV = { From 3c02eb8971a300bd06ef4840ebd4bd855c132859 Mon Sep 17 00:00:00 2001 From: Zaldimmar <Zaldimmar@gmail.com> Date: Sun, 27 Sep 2026 14:45:20 -0500 Subject: [PATCH 10/22] Show platform icons on link buttons Links pick their platform from a preset dropdown (PLATFORMS in src/lib/platforms.ts), and every link button draws that platform's icon beside its label. The footer and event cards now share the same PlatformIcon component instead of their own copies. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/updating-data-in-code.md | 1 + src/components/Footer.tsx | 38 ++-------- src/components/PlatformIcon.tsx | 98 +++++++++++++++++++++++++ src/lib/adminSchema.ts | 10 ++- src/lib/platforms.ts | 29 ++++++++ src/pages/EventDetail.tsx | 4 +- src/pages/OrganizationDetail.tsx | 11 ++- src/pages/PersonDetail.tsx | 11 ++- src/pages/TeamDetail.tsx | 4 +- src/pages/sections/EventList-Cards.tsx | 25 +------ src/pages/sections/OrgList-Vertical.tsx | 4 +- 11 files changed, 170 insertions(+), 65 deletions(-) create mode 100644 src/components/PlatformIcon.tsx create mode 100644 src/lib/platforms.ts diff --git a/docs/updating-data-in-code.md b/docs/updating-data-in-code.md index b03c2b5..b1b65e9 100644 --- a/docs/updating-data-in-code.md +++ b/docs/updating-data-in-code.md @@ -171,6 +171,7 @@ also in `admin-schema.js` and a CHECK): | Events → People → Role | speaker, leader, facilitator, host, musician, volunteer, attendee | no | `ROLE_LABEL` in `src/pages/EventDetail.tsx` | | People → Affiliations → Role; Teams → Members → Role | lead, board, staff, volunteer, member | no | `ROLE_LABEL` in `src/pages/PersonDetail.tsx` | | Links → Kind (on organizations, events, people, teams) | action, social, website, email | no | `splitLinks` in `server/src/shape.js` | +| Links → Platform | instagram, facebook, discord, youtube, tiktok, x, substack, spotify, linkedin | **yes**, `PLATFORMS` | `PlatformIcon.tsx` draws the icon on the button. **No CHECK and no `enumeration`**: the column is plain text, so adding one is an entry in `PLATFORMS` (`src/lib/platforms.ts`) and its icon in `src/components/PlatformIcon.tsx`, no migration. | | Content blocks → Slot | card, body | no | `ContentBlocks.tsx` | | Content blocks → Type | heading, subheading, paragraph, list, links, quote, image, divider | no | `ContentBlocks.tsx` (one renderer per type) | | Timeline → Kind (+ list filter) | milestone, event, organization, award, people | no | `KIND_NAMES` in `src/pages/sections/history/TimelineEntry.tsx` | diff --git a/src/components/Footer.tsx b/src/components/Footer.tsx index f3db5f8..21974ea 100644 --- a/src/components/Footer.tsx +++ b/src/components/Footer.tsx @@ -1,38 +1,12 @@ import { Link } from "react-router-dom"; import { PAGE_LINKS, PAGE_SECTIONS, NAV_ACTIONS } from "../navConfig.ts"; import nguLogo from "../assets/NGU_Logo.svg"; - -const InstagramIcon = ({ id = "ig-gradient" }) => ( - <svg viewBox="0 0 24 24" className="w-6 h-6 ig-icon" style={{ "--ig-fill": `url(#${id})` }}> - <defs> - <linearGradient id={id} x1="0%" y1="100%" x2="100%" y2="0%"> - <stop offset="0%" stopColor="#FEDA75" /> - <stop offset="25%" stopColor="#FA7E1E" /> - <stop offset="50%" stopColor="#D62976" /> - <stop offset="75%" stopColor="#962FBF" /> - <stop offset="100%" stopColor="#4F5BD5" /> - </linearGradient> - </defs> - <path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z"/> - </svg> -); - -const FacebookIcon = () => ( - <svg viewBox="0 0 24 24" className="w-6 h-6 fb-icon" fill="currentColor"> - <path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/> - </svg> -); - -const DiscordIcon = () => ( - <svg viewBox="0 0 24 24" className="w-6 h-6 ds-icon" fill="currentColor"> - <path d="M20.317 4.37a19.791 19.791 0 00-4.885-1.515.074.074 0 00-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 00-5.487 0 12.64 12.64 0 00-.617-1.25.077.077 0 00-.079-.037A19.736 19.736 0 003.677 4.37a.07.07 0 00-.032.027C.533 9.046-.32 13.58.099 18.057c.001.022.015.04.033.05a19.81 19.81 0 005.993 3.03.078.078 0 00.084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 00-.041-.106 13.107 13.107 0 01-1.872-.892.077.077 0 01-.008-.128 10.2 10.2 0 00.372-.292.074.074 0 01.077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 01.078.01c.12.098.246.198.373.292a.077.077 0 01-.006.127 12.299 12.299 0 01-1.873.892.077.077 0 00-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 00.084.028 19.839 19.839 0 006.002-3.03.077.077 0 00.032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 00-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z"/> - </svg> -); +import PlatformIcon from "./PlatformIcon.tsx"; const Social_Links = [ - { label: "Instagram", href: "https://www.instagram.com/nextgenerationunity/", Icon: InstagramIcon }, - { label: "Facebook", href: "https://www.facebook.com/NextGenerationofUnity", Icon: FacebookIcon }, - { label: "Discord", href: "https://discord.com/invite/AtngzpqaX5", Icon: DiscordIcon }, + { label: "Instagram", href: "https://www.instagram.com/nextgenerationunity/", platform: "instagram" }, + { label: "Facebook", href: "https://www.facebook.com/NextGenerationofUnity", platform: "facebook" }, + { label: "Discord", href: "https://discord.com/invite/AtngzpqaX5", platform: "discord" }, ]; // Give's destination lives in navConfig so the footer and the nav can't drift. @@ -147,7 +121,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, Icon }) => ( + {Social_Links.map(({ label, href, platform }) => ( <a key={label} href={href} @@ -157,7 +131,7 @@ export default function Footer() { className="footer-icons w-10 h-10 rounded-full flex items-center justify-center text-white/70 transition-colors" style={{ background: "rgba(255,255,255,0.08)", border: "1px solid rgba(255,255,255,0.15)" }} > - {label === "Instagram" ? <InstagramIcon id="ig-footer" /> : <Icon />} + <PlatformIcon platform={platform} className="w-6 h-6" /> </a> ))} </div> diff --git a/src/components/PlatformIcon.tsx b/src/components/PlatformIcon.tsx new file mode 100644 index 0000000..17205b2 --- /dev/null +++ b/src/components/PlatformIcon.tsx @@ -0,0 +1,98 @@ +import { useId } from 'react' + +import type { Platform } from '../lib/platforms.ts' + +/* ═══════════════════════════════════════════════════════════════ + PLATFORM ICON + + The brand mark for a link's platform (links.platform), drawn in + currentColor so it takes the colour of the button it sits in. + Anything that isn't one of PLATFORMS in lib/platforms.ts, blank + included, draws nothing, so a caller can always pass the field + straight through. + + Paths are Simple Icons (CC0), except Instagram, Facebook and + Discord, which came over from the footer unchanged. + + Instagram is the odd one: its hover fill is a gradient, which + has to be an SVG <linearGradient> with an id. useId keeps that + id unique however many cards draw one. The hover itself is CSS + (.ig-icon in index.css), which only switches the fill inside an + .ig-link or .footer-icons parent; the Facebook and Discord + hovers are there too. + ═══════════════════════════════════════════════════════════════ */ + +const PATHS: Record<Exclude<Platform, 'instagram'>, string> = { + facebook: + 'M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z', + discord: + 'M20.317 4.37a19.791 19.791 0 00-4.885-1.515.074.074 0 00-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 00-5.487 0 12.64 12.64 0 00-.617-1.25.077.077 0 00-.079-.037A19.736 19.736 0 003.677 4.37a.07.07 0 00-.032.027C.533 9.046-.32 13.58.099 18.057c.001.022.015.04.033.05a19.81 19.81 0 005.993 3.03.078.078 0 00.084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 00-.041-.106 13.107 13.107 0 01-1.872-.892.077.077 0 01-.008-.128 10.2 10.2 0 00.372-.292.074.074 0 01.077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 01.078.01c.12.098.246.198.373.292a.077.077 0 01-.006.127 12.299 12.299 0 01-1.873.892.077.077 0 00-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 00.084.028 19.839 19.839 0 006.002-3.03.077.077 0 00.032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 00-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z', + youtube: + 'M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z', + tiktok: + 'M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3.94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-.32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1.12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z', + x: 'M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932ZM17.61 20.644h2.039L6.486 3.24H4.298Z', + substack: + 'M22.539 8.242H1.46V5.406h21.08v2.836zM1.46 10.812V24L12 18.11 22.54 24V10.812H1.46zM22.54 0H1.46v2.836h21.08V0z', + spotify: + 'M12 0C5.4 0 0 5.4 0 12s5.4 12 12 12 12-5.4 12-12S18.66 0 12 0zm5.521 17.34c-.24.359-.66.48-1.021.24-2.82-1.74-6.36-2.101-10.561-1.141-.418.122-.779-.179-.899-.539-.12-.421.18-.78.54-.9 4.56-1.021 8.52-.6 11.64 1.32.42.18.479.659.301 1.02zm1.44-3.3c-.301.42-.841.6-1.262.3-3.239-1.98-8.159-2.58-11.939-1.38-.479.12-1.02-.12-1.14-.6-.12-.48.12-1.021.6-1.141C9.6 9.9 15 10.561 18.72 12.84c.361.181.54.78.241 1.2zm.12-3.36C15.24 8.4 8.82 8.16 5.16 9.301c-.6.179-1.2-.181-1.38-.721-.18-.601.18-1.2.72-1.381 4.26-1.26 11.28-1.02 15.721 1.621.539.3.719 1.02.419 1.56-.299.421-1.02.599-1.559.3z', + linkedin: + 'M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z', +} + +/* Hover classes the footer's CSS already keys on. */ +const HOVER_CLASS: Partial<Record<Platform, string>> = { + facebook: 'fb-icon', + discord: 'ds-icon', +} + +const INSTAGRAM_PATH = + 'M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z' + +function InstagramIcon({ className }: { className: string }) { + // useId's output has characters an SVG url() reference won't take. + const id = `ig-${useId().replace(/[^a-zA-Z0-9-]/g, '')}` + return ( + <svg + viewBox="0 0 24 24" + aria-hidden="true" + className={`ig-icon shrink-0 ${className}`} + style={{ '--ig-fill': `url(#${id})` }} + > + <defs> + <linearGradient id={id} x1="0%" y1="100%" x2="100%" y2="0%"> + <stop offset="0%" stopColor="#FEDA75" /> + <stop offset="25%" stopColor="#FA7E1E" /> + <stop offset="50%" stopColor="#D62976" /> + <stop offset="75%" stopColor="#962FBF" /> + <stop offset="100%" stopColor="#4F5BD5" /> + </linearGradient> + </defs> + <path d={INSTAGRAM_PATH} /> + </svg> + ) +} + +export default function PlatformIcon({ + platform, + className = 'h-4 w-4', +}: { + platform?: string | null + className?: string +}) { + if (platform === 'instagram') return <InstagramIcon className={className} /> + + const path = platform ? PATHS[platform as keyof typeof PATHS] : undefined + if (!path) return null + + return ( + <svg + viewBox="0 0 24 24" + aria-hidden="true" + fill="currentColor" + className={`shrink-0 ${HOVER_CLASS[platform as Platform] ?? ''} ${className}`} + > + <path d={path} /> + </svg> + ) +} diff --git a/src/lib/adminSchema.ts b/src/lib/adminSchema.ts index 9fd0bfe..27c4c3c 100644 --- a/src/lib/adminSchema.ts +++ b/src/lib/adminSchema.ts @@ -16,6 +16,7 @@ ═══════════════════════════════════════════════════════════════ */ import { preview } from "./text.ts"; +import { PLATFORMS } from "./platforms.ts"; const PLACE_FIELDS = [ { path: "venue", label: "Venue" }, @@ -140,7 +141,14 @@ const linksChild = { widget: "select", options: ["action", "social", "website", "email"], }, - { path: "platform", label: "Platform", help: "instagram, discord…" }, + { + path: "platform", + label: "Platform", + widget: "select", + options: PLATFORMS.map((platform) => [platform.id, platform.label]), + blankLabel: "Default: no icon", + help: "Shows the platform's icon on the button.", + }, { path: "label", label: "Label", required: true }, { path: "url", label: "URL", required: true, full: true }, { path: "is_primary", label: "Primary", widget: "checkbox" }, diff --git a/src/lib/platforms.ts b/src/lib/platforms.ts new file mode 100644 index 0000000..1080590 --- /dev/null +++ b/src/lib/platforms.ts @@ -0,0 +1,29 @@ +/* ═══════════════════════════════════════════════════════════════ + LINK PLATFORMS + + The preset values for links.platform. Order here is the order + the admin's Platform dropdown lists them in. + + links.platform is a plain TEXT column with no CHECK: a platform + carries nothing but an icon, and an unknown value just draws a + button without one. So adding a platform is two edits, both in + code: an entry here and its icon in PlatformIcon.tsx. The type + below makes the icon list refuse to compile without it. + + 'instagram' is also read by splitLinks in server/src/shape.js, + which lifts the handle out for the event cards' follow button. + ═══════════════════════════════════════════════════════════════ */ + +export const PLATFORMS = [ + { id: 'instagram', label: 'Instagram' }, + { id: 'facebook', label: 'Facebook' }, + { id: 'discord', label: 'Discord' }, + { id: 'youtube', label: 'YouTube' }, + { id: 'tiktok', label: 'TikTok' }, + { id: 'x', label: 'X (Twitter)' }, + { id: 'substack', label: 'Substack' }, + { id: 'spotify', label: 'Spotify' }, + { id: 'linkedin', label: 'LinkedIn' }, +] as const + +export type Platform = (typeof PLATFORMS)[number]['id'] diff --git a/src/pages/EventDetail.tsx b/src/pages/EventDetail.tsx index f1fe27d..c412eef 100644 --- a/src/pages/EventDetail.tsx +++ b/src/pages/EventDetail.tsx @@ -20,6 +20,7 @@ import { Link, useParams } from 'react-router-dom' import PageShell, { type ShellSection } from '../components/PageShell.tsx' import PageState from '../components/PageState.tsx' +import PlatformIcon from '../components/PlatformIcon.tsx' import ContentBlocks from '../components/ContentBlocks.tsx' import PeopleTiles, { type PeopleGroupInput } from '../components/PeopleTiles.tsx' import { @@ -115,9 +116,10 @@ export default function EventDetail() { href={link.url} target="_blank" rel="noreferrer" - className="rounded-full px-5 py-2 text-sm font-semibold text-white transition-transform hover:scale-105" + className="inline-flex items-center gap-2 rounded-full px-5 py-2 text-sm font-semibold text-white transition-transform hover:scale-105" style={{ background: accent }} > + <PlatformIcon platform={link.platform} /> {link.label} </a> ))} diff --git a/src/pages/OrganizationDetail.tsx b/src/pages/OrganizationDetail.tsx index e427a39..582c5df 100644 --- a/src/pages/OrganizationDetail.tsx +++ b/src/pages/OrganizationDetail.tsx @@ -20,6 +20,7 @@ import { Link, Navigate, useLocation, useParams } from 'react-router-dom' import PageShell from '../components/PageShell.tsx' import PageState from '../components/PageState.tsx' +import PlatformIcon from '../components/PlatformIcon.tsx' import ContentBlocks from '../components/ContentBlocks.tsx' import PeopleTiles from '../components/PeopleTiles.tsx' import EventListCards from './sections/EventList-Cards.tsx' @@ -324,9 +325,10 @@ function Contact({ org, accent }: { org: OrganizationRecord; accent: string }) { href={link.url} target="_blank" rel="noreferrer" - className="rounded-full px-5 py-2 text-sm font-semibold text-white transition-transform hover:scale-105" + className="inline-flex items-center gap-2 rounded-full px-5 py-2 text-sm font-semibold text-white transition-transform hover:scale-105" style={{ background: accent }} > + <PlatformIcon platform={link.platform} /> {link.label} </a> ))} @@ -334,8 +336,8 @@ function Contact({ org, accent }: { org: OrganizationRecord; accent: string }) { {/* website and email arrive as bare strings (splitLinks in shape.js); socials are whole link rows. */} {[ - org.website ? { url: org.website, label: 'Website' } : null, - org.email ? { url: `mailto:${org.email}`, label: org.email } : null, + org.website ? { url: org.website, label: 'Website', platform: null } : null, + org.email ? { url: `mailto:${org.email}`, label: org.email, platform: null } : null, ...org.socials, ] .filter((link): link is NonNullable<typeof link> => Boolean(link)) @@ -345,9 +347,10 @@ function Contact({ org, accent }: { org: OrganizationRecord; accent: string }) { href={link.url} target="_blank" rel="noreferrer" - className="rounded-full border px-4 py-1.5 text-sm font-medium transition-colors hover:bg-[#eef9fb]" + className="inline-flex items-center gap-2 rounded-full border px-4 py-1.5 text-sm font-medium transition-colors hover:bg-[#eef9fb]" style={{ borderColor: accent, color: accent }} > + <PlatformIcon platform={link.platform} /> {link.label} </a> ))} diff --git a/src/pages/PersonDetail.tsx b/src/pages/PersonDetail.tsx index ecf4e55..5b7a65e 100644 --- a/src/pages/PersonDetail.tsx +++ b/src/pages/PersonDetail.tsx @@ -22,6 +22,7 @@ import { Link, useParams } from 'react-router-dom' import PageShell, { type ShellSection } from '../components/PageShell.tsx' import PageState from '../components/PageState.tsx' +import PlatformIcon from '../components/PlatformIcon.tsx' import ContentBlocks from '../components/ContentBlocks.tsx' import { usePerson, @@ -243,9 +244,9 @@ function Facts({ person, accent }: { person: PersonRecord; accent: string }) { function Contact({ person, accent }: { person: PersonRecord; accent: string }) { const outlined = [ - person.website ? { url: person.website, label: 'Website' } : null, + person.website ? { url: person.website, label: 'Website', platform: null } : null, person.public_email - ? { url: `mailto:${person.public_email}`, label: person.public_email } + ? { url: `mailto:${person.public_email}`, label: person.public_email, platform: null } : null, ...person.socials, ].filter((link): link is NonNullable<typeof link> => Boolean(link)) @@ -260,9 +261,10 @@ function Contact({ person, accent }: { person: PersonRecord; accent: string }) { href={link.url} target="_blank" rel="noreferrer" - className="rounded-full px-5 py-2 text-sm font-semibold text-white transition-transform hover:scale-105" + className="inline-flex items-center gap-2 rounded-full px-5 py-2 text-sm font-semibold text-white transition-transform hover:scale-105" style={{ background: accent }} > + <PlatformIcon platform={link.platform} /> {link.label} </a> ))} @@ -273,9 +275,10 @@ function Contact({ person, accent }: { person: PersonRecord; accent: string }) { href={link.url} target="_blank" rel="noreferrer" - className="rounded-full border px-4 py-1.5 text-sm font-medium transition-colors hover:bg-[#eef9fb]" + className="inline-flex items-center gap-2 rounded-full border px-4 py-1.5 text-sm font-medium transition-colors hover:bg-[#eef9fb]" style={{ borderColor: accent, color: accent }} > + <PlatformIcon platform={link.platform} /> {link.label} </a> ))} diff --git a/src/pages/TeamDetail.tsx b/src/pages/TeamDetail.tsx index 8bfc9d2..81455d6 100644 --- a/src/pages/TeamDetail.tsx +++ b/src/pages/TeamDetail.tsx @@ -15,6 +15,7 @@ import { Link, useParams } from 'react-router-dom' import PageShell from '../components/PageShell.tsx' import PageState from '../components/PageState.tsx' +import PlatformIcon from '../components/PlatformIcon.tsx' import ContentBlocks from '../components/ContentBlocks.tsx' import PeopleTiles from '../components/PeopleTiles.tsx' import { useTeam } from '../lib/useContent.ts' @@ -75,9 +76,10 @@ export default function TeamDetail() { href={link.url} target="_blank" rel="noreferrer" - className="rounded-full px-5 py-2 text-sm font-semibold text-white transition-transform hover:scale-105" + className="inline-flex items-center gap-2 rounded-full px-5 py-2 text-sm font-semibold text-white transition-transform hover:scale-105" style={{ background: accent }} > + <PlatformIcon platform={link.platform} /> {link.label} </a> ))} diff --git a/src/pages/sections/EventList-Cards.tsx b/src/pages/sections/EventList-Cards.tsx index 80f8fbb..2a7f3e6 100644 --- a/src/pages/sections/EventList-Cards.tsx +++ b/src/pages/sections/EventList-Cards.tsx @@ -4,6 +4,7 @@ import { splitByStatus, typesPresent, useEvents } from "../../data/eventData.ts" import { eventHref } from "../../lib/hrefs.ts"; import { EVENT_TYPES, eventTypeLabel } from "../../lib/eventTypes.ts"; import { seriesLabel } from "../../lib/eventSeries.ts"; +import PlatformIcon from "../../components/PlatformIcon.tsx"; /* ═══════════════════════════════════════════════════════════════ EVENT LIST — CARDS @@ -96,25 +97,6 @@ const EDGE_FADE = `linear-gradient(to right, /* Card layout CSS lives in index.css under the .ev- prefix. */ -const InstagramIcon = ({ id = "ig-gradient" }) => ( - <svg - viewBox="0 0 24 24" - className="ig-icon w-6 h-6" - style={{ "--ig-fill": `url(#${id})` }} - > - <defs> - <linearGradient id={id} x1="0%" y1="100%" x2="100%" y2="0%"> - <stop offset="0%" stopColor="#FEDA75" /> - <stop offset="25%" stopColor="#FA7E1E" /> - <stop offset="50%" stopColor="#D62976" /> - <stop offset="75%" stopColor="#962FBF" /> - <stop offset="100%" stopColor="#4F5BD5" /> - </linearGradient> - </defs> - <path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z" /> - </svg> -); - /* The title is the way into the event's own page. A link on the title rather than a wrapper around the whole card: @@ -302,11 +284,12 @@ export function Card({ <a key={item.label} href={item.url} - className={`rounded-xl font-700 transition-all duration-200 hover:scale-105 text-center ${ + className={`inline-flex items-center justify-center gap-2 rounded-xl font-700 transition-all duration-200 hover:scale-105 text-center ${ compact ? "py-2.5 px-5" : "py-2.5 px-6" }`} style={{ border: `1px solid ${color}`, color }} > + <PlatformIcon platform={item.platform} /> {item.label} </a> ))} @@ -324,7 +307,7 @@ export function Card({ }`} style={{ border: `1px solid ${accent}`, color: accent }} > - <InstagramIcon id={`ig-${ev.id}`} /> + <PlatformIcon platform="instagram" className="w-6 h-6" /> {igHandle} </a> )} diff --git a/src/pages/sections/OrgList-Vertical.tsx b/src/pages/sections/OrgList-Vertical.tsx index 23a057d..5f3f0f3 100644 --- a/src/pages/sections/OrgList-Vertical.tsx +++ b/src/pages/sections/OrgList-Vertical.tsx @@ -1,5 +1,6 @@ import { useId, useState } from "react"; import ArrowLink from "../../components/ArrowLink.tsx"; +import PlatformIcon from "../../components/PlatformIcon.tsx"; import { areasSentence, initialsFor, @@ -50,7 +51,7 @@ const FALLBACK_COLOR = "#4a6b72"; function RowButton({ as: As = "button", color, children, ...rest }: any) { return ( <As - className="shrink-0 whitespace-nowrap py-2 px-4 rounded-xl font-700 text-sm transition-transform duration-200 hover:scale-105" + className="inline-flex shrink-0 items-center gap-2 whitespace-nowrap py-2 px-4 rounded-xl font-700 text-sm transition-transform duration-200 hover:scale-105" style={{ border: `1px solid ${color}`, color }} {...rest} > @@ -233,6 +234,7 @@ function OrgRow({ org, pageLabel, siteLabel }) { rel="noopener noreferrer" color={color} > + <PlatformIcon platform={link.platform} /> {link.label} </RowButton> ))} From cd393e4ab21ebed548c3dd6dd3f95433e397a0e2 Mon Sep 17 00:00:00 2001 From: Zaldimmar <Zaldimmar@gmail.com> Date: Sun, 27 Sep 2026 14:50:41 -0500 Subject: [PATCH 11/22] Add a Listed flag: published records reachable only by their link is_listed (migration 027) sits beside is_published on organizations, events, people, teams and awards. Unticked, the record's own page still works, but the site's lists leave it out: the list routes, a region's chapters, an organization's events, teams and awards, the QR page's directory, and the front page's counts and countdown. Places where someone attached it by hand (rosters, hosts, billed people, recipients, timeline, a pinned countdown) still show it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/updating-data-in-code.md | 2 +- server/src/admin-schema.js | 22 +++++++++----- server/src/migrations/027_listed.sql | 43 ++++++++++++++++++++++++++++ server/src/routes/content.js | 25 +++++++++------- server/src/routes/directory.js | 13 +++++---- server/src/routes/home.js | 26 +++++++++-------- src/lib/adminSchema.ts | 27 +++++++++++++++-- 7 files changed, 120 insertions(+), 38 deletions(-) create mode 100644 server/src/migrations/027_listed.sql diff --git a/docs/updating-data-in-code.md b/docs/updating-data-in-code.md index b1b65e9..6f14402 100644 --- a/docs/updating-data-in-code.md +++ b/docs/updating-data-in-code.md @@ -182,7 +182,7 @@ also in `admin-schema.js` and a CHECK): | Front page → Feature | none, livestream, video | **yes** | `HeroStage.tsx` | | Front page → Sections → Section | countdown, retreats, calendar, stats, timeline, connect | **yes**, `FRONT_PAGE_SECTIONS` | `SECTIONS` in `src/pages/Home.tsx`; see [below](#front-page-section-names) | | Front page → Stats → Number Source | manual, years_since, regions, … | **yes**, `STAT_SOURCES` | `STAT_QUERIES` in `server/src/routes/home.js`; see [below](#front-page-stat-sources) | -| Every list → Published / Featured filter | 1, 0 | **yes** | n/a | +| Every list → Published / Listed / Featured filter | 1, 0 | **yes** | n/a | "No, shows values" means the dropdown currently shows the raw value, so relabelling it is just [adding labels](#renaming-what-a-dropdown-shows). diff --git a/server/src/admin-schema.js b/server/src/admin-schema.js index ee36e78..aae1e31 100644 --- a/server/src/admin-schema.js +++ b/server/src/admin-schema.js @@ -217,10 +217,11 @@ const organizations = { "locality", "state_code", "is_published", + "is_listed", "sort_order", "updated_at", ], - filters: ["kind", "is_published"], + filters: ["kind", "is_published", "is_listed"], search: ["name", "id", "locality"], order: "kind, sort_order, name", }, @@ -236,6 +237,7 @@ const organizations = { text("logo"), ...placeColumns, bool("is_published"), + bool("is_listed"), int("sort_order"), bool("in_timeline"), ], @@ -305,12 +307,13 @@ const events = { "starts_on", "status", "is_published", + "is_listed", "updated_at", ], // No host filter: hosts are rows in another table now, and the // engine's filters are columns on this one. The events a host // owns are on that host's own page. - filters: ["scope_id", "event_type", "status", "is_published"], + filters: ["scope_id", "event_type", "status", "is_published", "is_listed"], search: ["title", "id", "theme"], order: "starts_on IS NULL, starts_on DESC, title", }, @@ -343,6 +346,7 @@ const events = { text("color"), text("gradient"), bool("is_published"), + bool("is_listed"), bool("in_timeline"), // A repeating schedule. Columns rather than a side table: the @@ -409,9 +413,10 @@ const people = { "tagline", "locality", "is_published", + "is_listed", "updated_at", ], - filters: ["is_published"], + filters: ["is_published", "is_listed"], search: ["display_name", "sort_name", "id"], order: "sort_name, display_name", }, @@ -431,6 +436,7 @@ const people = { text("country"), text("location_label"), bool("is_published"), + bool("is_listed"), ], extensions: [ @@ -510,8 +516,8 @@ const teams = { concurrency: "updated_at", list: { - columns: ["id", "org_id", "name", "tagline", "is_published", "sort_order", "updated_at"], - filters: ["org_id", "is_published"], + columns: ["id", "org_id", "name", "tagline", "is_published", "is_listed", "sort_order", "updated_at"], + filters: ["org_id", "is_published", "is_listed"], search: ["name", "id", "tagline"], order: "org_id, sort_order, name", }, @@ -523,6 +529,7 @@ const teams = { text("color"), text("logo"), bool("is_published"), + bool("is_listed"), int("sort_order"), ], @@ -569,8 +576,8 @@ const awards = { idKind: "slug", list: { - columns: ["id", "org_id", "name", "description", "is_published", "sort_order"], - filters: ["org_id", "is_published"], + columns: ["id", "org_id", "name", "description", "is_published", "is_listed", "sort_order"], + filters: ["org_id", "is_published", "is_listed"], search: ["name", "id", "description"], order: "org_id, sort_order, name", }, @@ -581,6 +588,7 @@ const awards = { text("description"), text("logo"), bool("is_published"), + bool("is_listed"), int("sort_order"), ], }; diff --git a/server/src/migrations/027_listed.sql b/server/src/migrations/027_listed.sql new file mode 100644 index 0000000..12a9f79 --- /dev/null +++ b/server/src/migrations/027_listed.sql @@ -0,0 +1,43 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 027 LISTED: PUBLISHED BUT ONLY BY LINK +-- +-- is_published stays the hard gate: 0 is a draft (or, for people, +-- private), off the site entirely and a 404 at its own URL. +-- is_listed only means anything on a published row. 0 keeps the +-- record's own page working but leaves it out of every list the +-- site gathers by itself: +-- +-- the /events, /organizations, /teams and /awards lists (and so +-- every band, calendar, map and card grid built on them), a +-- region's chapters, an organization's events, teams and awards, +-- the /directory the QR page reads, and the front page's counts +-- and next-event countdown. +-- +-- It still appears wherever someone attached it by hand: rosters, +-- billed people, hosts, award recipients, timeline entries, and a +-- countdown pinned to it by name. Each of those rows has its own +-- is_public (or is_published) to hide it there. +-- +-- Defaults to 1, so every existing row stays listed. +-- +-- Plain ADD COLUMN: NOT NULL with a constant default and a CHECK is +-- allowed without a rebuild, STRICT tables included. v_events reads +-- e.*, so it picks the column up with no change of its own. +-- +-- PRAGMA user_version; -- reads 26 before this file +-- ═══════════════════════════════════════════════════════════════ + +ALTER TABLE organizations ADD COLUMN is_listed INTEGER NOT NULL DEFAULT 1 + CHECK (is_listed IN (0, 1)); + +ALTER TABLE events ADD COLUMN is_listed INTEGER NOT NULL DEFAULT 1 + CHECK (is_listed IN (0, 1)); + +ALTER TABLE people ADD COLUMN is_listed INTEGER NOT NULL DEFAULT 1 + CHECK (is_listed IN (0, 1)); + +ALTER TABLE teams ADD COLUMN is_listed INTEGER NOT NULL DEFAULT 1 + CHECK (is_listed IN (0, 1)); + +ALTER TABLE awards ADD COLUMN is_listed INTEGER NOT NULL DEFAULT 1 + CHECK (is_listed IN (0, 1)); diff --git a/server/src/routes/content.js b/server/src/routes/content.js index 5000a90..7c827dd 100644 --- a/server/src/routes/content.js +++ b/server/src/routes/content.js @@ -15,6 +15,11 @@ `details` rather than as separate routes — that's what lets a list component be written once and pointed at any kind. + The lists leave out unlisted records (is_listed = 0); the + detail routes don't, since reaching one by its link is the + point. A region's chapters and an organization's events, teams + and awards are lists too. See 027_listed.sql. + Responses carry their fallbacks already resolved: an event's `color` is its own or its first host's, and `status` is derived from the dates when it isn't set. Components read one field and @@ -266,7 +271,7 @@ function attachRegionDetails(db, orgs) { .prepare( `SELECT c.region_id, o.id, o.name, o.location_label, o.logo FROM chapters c - JOIN organizations o ON o.id = c.id AND o.is_published = 1 + JOIN organizations o ON o.id = c.id AND o.is_published = 1 AND o.is_listed = 1 WHERE c.region_id IN (${marks(ids.length)}) ORDER BY o.sort_order, o.name`, ) @@ -377,7 +382,7 @@ function attachTeams(db, orgs) { .prepare( `SELECT id, org_id, name, tagline, color, logo FROM teams - WHERE org_id IN (${marks(ids.length)}) AND is_published = 1 + WHERE org_id IN (${marks(ids.length)}) AND is_published = 1 AND is_listed = 1 ORDER BY sort_order, name`, ) .all(...ids); @@ -412,7 +417,7 @@ function attachAwards(db, orgs) { JOIN people p ON p.id = pa.person_id AND p.is_published = 1 WHERE pa.award_id = a.id AND pa.is_public = 1) AS recipient_count FROM awards a - WHERE a.org_id IN (${marks(ids.length)}) AND a.is_published = 1 + WHERE a.org_id IN (${marks(ids.length)}) AND a.is_published = 1 AND a.is_listed = 1 ORDER BY a.sort_order, a.name`, ) .all(...ids); @@ -457,7 +462,7 @@ content.get("/events", (c) => { const rows = db .prepare( `SELECT * FROM v_events - WHERE is_published = 1 + WHERE is_published = 1 AND is_listed = 1 ORDER BY ${EVENT_ORDER}`, ) .all(); @@ -538,7 +543,7 @@ content.get("/events/:id", (c) => { /* ── Organizations ───────────────────────────────────────────── - GET /organizations every published org + GET /organizations every published, listed org GET /organizations?kind=region one kind GET /organizations?kind=region,chapter @@ -565,7 +570,7 @@ content.get("/organizations", (c) => { const rows = db .prepare( `SELECT * FROM organizations - WHERE is_published = 1 ${filter} + WHERE is_published = 1 AND is_listed = 1 ${filter} ORDER BY kind, sort_order, name`, ) .all(...kinds); @@ -627,7 +632,7 @@ content.get("/organizations/:id", (c) => { e.effective_color AS color FROM v_events e JOIN event_hosts eh ON eh.event_id = e.id AND eh.org_id = ? - WHERE e.is_published = 1 + WHERE e.is_published = 1 AND e.is_listed = 1 ORDER BY ${EVENT_ORDER}`, ) .all(id); @@ -637,7 +642,7 @@ content.get("/organizations/:id", (c) => { /* ── Teams ───────────────────────────────────────────────────── - GET /teams every published team + GET /teams every published, listed team GET /teams?org=mid-atlantic one organization's teams GET /teams/:id one team's page @@ -655,7 +660,7 @@ content.get("/teams", (c) => { `SELECT t.*, o.name AS org_name, o.kind AS org_kind FROM teams t JOIN organizations o ON o.id = t.org_id AND o.is_published = 1 - WHERE t.is_published = 1 ${org ? "AND t.org_id = ?" : ""} + WHERE t.is_published = 1 AND t.is_listed = 1 ${org ? "AND t.org_id = ?" : ""} ORDER BY o.sort_order, t.sort_order, t.name`, ) .all(...(org ? [org] : [])); @@ -720,7 +725,7 @@ content.get("/awards", (c) => { WHERE pa.award_id = a.id AND pa.is_public = 1) AS recipient_count FROM awards a LEFT JOIN organizations o ON o.id = a.org_id AND o.is_published = 1 - WHERE a.is_published = 1 ${org ? "AND a.org_id = ?" : ""} + WHERE a.is_published = 1 AND a.is_listed = 1 ${org ? "AND a.org_id = ?" : ""} ORDER BY a.sort_order, a.name`, ) .all(...(org ? [org] : [])); diff --git a/server/src/routes/directory.js b/server/src/routes/directory.js index 680a26f..71b315f 100644 --- a/server/src/routes/directory.js +++ b/server/src/routes/directory.js @@ -19,6 +19,9 @@ awards published people published + and each leaves out unlisted records (is_listed = 0): the QR page + is public, and listing them here would undo the point of them. + The site already serves each of these at its own URL; this only lists them in one place. ═══════════════════════════════════════════════════════════════ */ @@ -39,32 +42,32 @@ directory.get("/directory", (c) => { events: all( `SELECT id, title AS name, starts_on FROM events - WHERE is_published = 1 + WHERE is_published = 1 AND is_listed = 1 ORDER BY starts_on IS NULL, starts_on DESC, title`, ), organizations: all( `SELECT id, name, kind FROM organizations - WHERE is_published = 1 + WHERE is_published = 1 AND is_listed = 1 ORDER BY kind, name`, ), teams: all( `SELECT t.id, t.name, o.name AS org_name FROM teams t JOIN organizations o ON o.id = t.org_id AND o.is_published = 1 - WHERE t.is_published = 1 + WHERE t.is_published = 1 AND t.is_listed = 1 ORDER BY o.name, t.sort_order, t.name`, ), awards: all( `SELECT id, name FROM awards - WHERE is_published = 1 + WHERE is_published = 1 AND is_listed = 1 ORDER BY name`, ), people: all( `SELECT id, display_name AS name FROM people - WHERE is_published = 1 + WHERE is_published = 1 AND is_listed = 1 ORDER BY COALESCE(sort_name, display_name)`, ), }, diff --git a/server/src/routes/home.js b/server/src/routes/home.js index cf560e8..9173b54 100644 --- a/server/src/routes/home.js +++ b/server/src/routes/home.js @@ -15,15 +15,17 @@ ── Stats ── A stat's source picks a query from STAT_QUERIES. Each counts - exactly what the matching public page shows: published rows, and - for awards only public citations to published people. A count + exactly what the matching public page shows: published, listed + rows, and for awards only public citations to published people + (an award's page names its recipients whether they're listed or + not, so the count does too). A count that disagreed with the page it summarises would be worse than none. 'manual' and 'years_since' read the row's own value. ── Countdown ── - The pinned event if it is still published and not over; - otherwise the next published, non-cancelled event that hasn't - ended. "Hasn't ended" is COALESCE(ends_on, starts_on) >= today, + The pinned event if it is still published and not over, listed + or not; otherwise the next published, listed, non-cancelled + event that hasn't ended. "Hasn't ended" is COALESCE(ends_on, starts_on) >= today, so a running series with a start date in the past still counts. The client works out the next meeting of a series from `series`. @@ -46,15 +48,15 @@ const json = (c, body) => c.json(body, 200, { "Cache-Control": CACHE }); const PAGE_ID = "home"; const STAT_QUERIES = { - regions: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'region' AND is_published = 1`, - chapters: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'chapter' AND is_published = 1`, - partners: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'partner' AND is_published = 1`, + regions: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'region' AND is_published = 1 AND is_listed = 1`, + chapters: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'chapter' AND is_published = 1 AND is_listed = 1`, + partners: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'partner' AND is_published = 1 AND is_listed = 1`, events_held: `SELECT COUNT(*) AS n FROM v_events - WHERE is_published = 1 AND effective_status = 'past'`, + WHERE is_published = 1 AND is_listed = 1 AND effective_status = 'past'`, retreats_held: `SELECT COUNT(*) AS n FROM v_events - WHERE is_published = 1 AND effective_status = 'past' + WHERE is_published = 1 AND is_listed = 1 AND effective_status = 'past' AND event_type = 'retreat'`, - people: `SELECT COUNT(*) AS n FROM people WHERE is_published = 1`, + people: `SELECT COUNT(*) AS n FROM people WHERE is_published = 1 AND is_listed = 1`, awards_given: `SELECT COUNT(*) AS n FROM person_awards pa JOIN people p ON p.id = pa.person_id AND p.is_published = 1 @@ -166,7 +168,7 @@ home.get("/front-page", (c) => { db .prepare( `SELECT * FROM v_events - WHERE ${notOver} ${filters.join(" ")} + WHERE ${notOver} AND is_listed = 1 ${filters.join(" ")} ORDER BY starts_on, title LIMIT 1`, ) diff --git a/src/lib/adminSchema.ts b/src/lib/adminSchema.ts index 27c4c3c..c5a794b 100644 --- a/src/lib/adminSchema.ts +++ b/src/lib/adminSchema.ts @@ -32,10 +32,21 @@ const PLACE_FIELDS = [ const PUBLISHED_FIELD = { path: "is_published", label: "Published", widget: "checkbox" }; +/* Only means anything on a published record. Unticked, its own page + still works but the site's lists, counts and the QR page leave it + out. See 027_listed.sql for exactly which. */ +const LISTED_FIELD = { + path: "is_listed", + label: "Listed", + widget: "checkbox", + help: "Unticked: only reachable by its link", +}; + /* For entities whose lists the site orders by hand. Events sort by - date and people by sort_name, so they take PUBLISHED_FIELD alone. */ + date and people by sort_name, so they take the first two alone. */ const PUBLISH_FIELDS = [ PUBLISHED_FIELD, + LISTED_FIELD, { path: "sort_order", label: "Sort order", widget: "number" }, ]; @@ -252,10 +263,12 @@ const organizations = { { key: "locality", label: "City" }, { key: "state_code", label: "State" }, { key: "is_published", label: "Live", widget: "bool" }, + { key: "is_listed", label: "Listed", widget: "bool" }, ], filters: [ { key: "kind", label: "Kind", options: ["national", "region", "chapter", "partner"] }, { key: "is_published", label: "Published", options: [["1", "Live"], ["0", "Hidden"]] }, + { key: "is_listed", label: "Listed", options: [["1", "Listed"], ["0", "Link only"]] }, ], }, @@ -412,6 +425,7 @@ const events = { { key: "date_label", label: "Dates" }, { key: "status", label: "Status" }, { key: "is_published", label: "Live", widget: "bool" }, + { key: "is_listed", label: "Listed", widget: "bool" }, ], filters: [ { key: "scope_id", label: "Scope", optionsFrom: "event_scopes" }, @@ -422,6 +436,7 @@ const events = { }, { key: "status", label: "Status", options: ["upcoming", "past", "cancelled"] }, { key: "is_published", label: "Published", options: [["1", "Live"], ["0", "Hidden"]] }, + { key: "is_listed", label: "Listed", options: [["1", "Listed"], ["0", "Link only"]] }, ], }, @@ -488,7 +503,7 @@ const events = { }, timelineGroup("event"), timelineDetailGroup("event"), - { legend: "Publishing", fields: [PUBLISHED_FIELD] }, + { legend: "Publishing", fields: [PUBLISHED_FIELD, LISTED_FIELD] }, ], children: [ @@ -546,9 +561,11 @@ const people = { { key: "tagline", label: "Tagline" }, { key: "locality", label: "City" }, { key: "is_published", label: "Live", widget: "bool" }, + { key: "is_listed", label: "Listed", widget: "bool" }, ], filters: [ { key: "is_published", label: "Published", options: [["1", "Live"], ["0", "Hidden"]] }, + { key: "is_listed", label: "Listed", options: [["1", "Listed"], ["0", "Link only"]] }, ], }, @@ -603,7 +620,7 @@ const people = { { legend: "Publishing", note: "Unpublished people are invisible everywhere.", - fields: [PUBLISHED_FIELD], + fields: [PUBLISHED_FIELD, LISTED_FIELD], }, ], @@ -694,10 +711,12 @@ const teams = { { key: "org_id", label: "Organization" }, { key: "tagline", label: "Tagline" }, { key: "is_published", label: "Live", widget: "bool" }, + { key: "is_listed", label: "Listed", widget: "bool" }, ], filters: [ { key: "org_id", label: "Organization", optionsFrom: "organizations" }, { key: "is_published", label: "Published", options: [["1", "Live"], ["0", "Hidden"]] }, + { key: "is_listed", label: "Listed", options: [["1", "Listed"], ["0", "Link only"]] }, ], }, @@ -769,10 +788,12 @@ const awards = { { key: "org_id", label: "Awarded by" }, { key: "description", label: "Description" }, { key: "is_published", label: "Live", widget: "bool" }, + { key: "is_listed", label: "Listed", widget: "bool" }, ], filters: [ { key: "org_id", label: "Awarded by", optionsFrom: "organizations" }, { key: "is_published", label: "Published", options: [["1", "Live"], ["0", "Hidden"]] }, + { key: "is_listed", label: "Listed", options: [["1", "Listed"], ["0", "Link only"]] }, ], }, From eaff23839f272ac925df7da1eeb04d4e432111e0 Mon Sep 17 00:00:00 2001 From: Zaldimmar <Zaldimmar@gmail.com> Date: Sun, 27 Sep 2026 15:04:45 -0500 Subject: [PATCH 12/22] Add image uploads with a media library, and event card backgrounds Uploads (migration 028, server/src/media.js, routes/media.js): editors and up upload JPEG, PNG, GIF, WebP or SVG. Photos are resized to 2400px and saved as WebP by default, or kept as uploaded on request. Files live in UPLOADS_DIR, served by nginx in production and by the API in dev. Admins and up delete, after seeing what still uses the file. Every image field in the editor is now an image widget: preview, the path as text, Upload and Choose from library. A new Media page lists the library. Org lists and event cards now resolve logos through media.ts, so uploaded paths work there. Events get a card_image (migration 029): a photo behind the card under a light veil so the text stays readable. The card's size is unchanged. Setup for production is in docs/media-uploads.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .gitignore | 7 +- CLAUDE.md | 3 +- docs/media-uploads.md | 71 +++ docs/updating-data-in-code.md | 1 + server/package.json | 3 +- server/src/admin-schema.js | 1 + server/src/index.js | 29 ++ server/src/media.js | 184 ++++++++ server/src/migrations/028_media.sql | 41 ++ .../src/migrations/029_event_card_image.sql | 15 + server/src/routes/content.js | 1 + server/src/routes/media.js | 181 ++++++++ src/App.tsx | 2 + src/components/admin/MediaLibrary.tsx | 407 ++++++++++++++++++ src/components/admin/fields.tsx | 16 + src/lib/adminSchema.ts | 34 +- src/lib/api.ts | 6 + src/lib/media.ts | 5 + src/lib/useContent.ts | 2 + src/pages/admin/AdminMedia.tsx | 193 +++++++++ src/pages/admin/adminNav.ts | 7 + src/pages/sections/EventList-Cards.tsx | 26 +- src/pages/sections/OrgList-Card.tsx | 5 +- src/pages/sections/OrgList-Map.tsx | 5 +- src/pages/sections/OrgList-Vertical.tsx | 5 +- vite.config.ts | 6 + 26 files changed, 1234 insertions(+), 22 deletions(-) create mode 100644 docs/media-uploads.md create mode 100644 server/src/media.js create mode 100644 server/src/migrations/028_media.sql create mode 100644 server/src/migrations/029_event_card_image.sql create mode 100644 server/src/routes/media.js create mode 100644 src/components/admin/MediaLibrary.tsx create mode 100644 src/pages/admin/AdminMedia.tsx diff --git a/.gitignore b/.gitignore index a0d338c..deebeec 100644 --- a/.gitignore +++ b/.gitignore @@ -18,4 +18,9 @@ build/ .vscode/* !.vscode/extensions.json .DS_Store -Thumbs.db \ No newline at end of file +Thumbs.db + +# plain txt files +.txt +# uploaded media (local dev) +server/uploads/ diff --git a/CLAUDE.md b/CLAUDE.md index 06fe51f..977fbfb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -18,7 +18,7 @@ Frontend (repo root): - `pnpm exec tsc`: type-check (`noEmit`; there is no separate lint or typecheck script) - There is no test suite. -Backend (`server/`, Node >= 22). The server reads `HOST` (default `127.0.0.1`), `PORT` (default `3001`) and `DB_PATH` (default `./ngu.db`); locally, use `DB_PATH=./dev.db`: +Backend (`server/`, Node >= 22). The server reads `HOST` (default `127.0.0.1`), `PORT` (default `3001`), `DB_PATH` (default `./ngu.db`) and `UPLOADS_DIR` (default `./uploads`); locally, use `DB_PATH=./dev.db`: - `DB_PATH=./dev.db pnpm dev`: run with `node --watch` - `DB_PATH=./dev.db pnpm migrate`: apply migrations without starting the server - `DB_PATH=./dev.db node src/admin-cli.js add|list|passwd|role|disable|enable ...`: the only way accounts are created @@ -30,6 +30,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - App deployed to `/srv/ngu-api`; database at `/var/lib/ngu/ngu.db` - Debugging: check `journalctl -u ngu-api -n 40 --no-pager` first. Make sure rsync ran from the repo (not the deployed copy) before restarting the service. - Never run commands against the production server or database unless explicitly asked. +- Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`. ## Git workflow - Remote is a self-hosted Forgejo server, not GitHub. Do not use `gh`. diff --git a/docs/media-uploads.md b/docs/media-uploads.md new file mode 100644 index 0000000..d548e27 --- /dev/null +++ b/docs/media-uploads.md @@ -0,0 +1,71 @@ +# Media uploads + +Images uploaded in the admin (Media page, or the Upload and Choose +from library buttons on any image field) are stored on disk and listed +in the `media` table (`server/src/migrations/028_media.sql`). + +## How files are stored + +- An image field stores the file's public path, `/uploads/<file>`. It + still accepts a bare filename in that field's `public/` directory or a + full URL, as before. +- By default a photo is turned upright, shrunk to fit 2400px on its + longest side, and saved as WebP. This also strips its metadata, + camera location included. Limit: 25 MB per file. +- **Keep original** stores the file exactly as uploaded (up to 10 MB), + metadata and all. +- SVGs are always kept as they are. +- Accepted types: JPEG, PNG, GIF, WebP, SVG. The type is read from the + file's contents, not its name. +- Editors and up can upload. Admins and up can delete. The Media page + shows which tables still use a file before deleting it, because + nothing stops a file a record uses from being deleted. + +Limits and sizes are constants at the top of `server/src/media.js`. + +## Local development + +The API reads `UPLOADS_DIR` (default `./uploads`, so `server/uploads/`, +which git ignores). The API serves `/uploads/` itself, and Vite proxies +`/uploads` to the same target as `/api`. + +## Production + +1. Create the directory, owned by the service user: + + ```sh + sudo mkdir -p /var/lib/ngu/uploads + sudo chown <ngu-api user>: /var/lib/ngu/uploads + ``` + +2. Set it in the `ngu-api` unit (`systemctl edit ngu-api`): + + ```ini + [Service] + Environment=UPLOADS_DIR=/var/lib/ngu/uploads + ``` + + It lives outside `/srv/ngu-api` so an rsync deploy never deletes it. + Back it up alongside the database. + +3. In the nginx site, let uploads through and serve them from disk: + + ```nginx + # In the server block. nginx's default is 1 MB. + client_max_body_size 26m; + + location /uploads/ { + alias /var/lib/ngu/uploads/; + expires 30d; + add_header Cache-Control "public, immutable"; + add_header X-Content-Type-Options nosniff; + # An uploaded SVG opened on its own can't run script. + add_header Content-Security-Policy "default-src 'none'; style-src 'unsafe-inline'; sandbox"; + } + ``` + + Filenames are random and never reused, so `immutable` is safe. + +4. `sharp` is a server dependency now: run `pnpm install` in + `/srv/ngu-api` after the deploy. It ships prebuilt Linux binaries, + so no build tools are needed. diff --git a/docs/updating-data-in-code.md b/docs/updating-data-in-code.md index 6f14402..b473c46 100644 --- a/docs/updating-data-in-code.md +++ b/docs/updating-data-in-code.md @@ -32,6 +32,7 @@ what a dropdown in the admin editor says. | The **label** a dropdown shows in the admin | code | [one file](#renaming-what-a-dropdown-shows) | | The **list of allowed values** behind a fixed dropdown | database CHECK + code | [a migration and three files](#adding-removing-or-renaming-a-stored-value) | | Navigation, page section titles, colours, the site banner, history decades, the map grid | code | [the file named below](#other-content-that-lives-in-code) | +| Uploaded images | disk + the `media` table | Admin → Media, or any image field. See `docs/media-uploads.md` | The rule of thumb from `CLAUDE.md`: data belongs in the database, presentation belongs in code. A dropdown's *values* are data the diff --git a/server/package.json b/server/package.json index f898f59..9f206bf 100644 --- a/server/package.json +++ b/server/package.json @@ -13,6 +13,7 @@ }, "dependencies": { "@hono/node-server": "^1.0.0", - "hono": "^4.0.0" + "hono": "^4.0.0", + "sharp": "^0.35.4" } } diff --git a/server/src/admin-schema.js b/server/src/admin-schema.js index aae1e31..95d227b 100644 --- a/server/src/admin-schema.js +++ b/server/src/admin-schema.js @@ -345,6 +345,7 @@ const events = { text("event_logo"), text("color"), text("gradient"), + text("card_image"), bool("is_published"), bool("is_listed"), bool("in_timeline"), diff --git a/server/src/index.js b/server/src/index.js index 14fdde7..1fde53f 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -8,7 +8,10 @@ there too. ═══════════════════════════════════════════════════════════════ */ +import { mkdir } from "node:fs/promises"; + import { serve } from "@hono/node-server"; +import { serveStatic } from "@hono/node-server/serve-static"; import { Hono } from "hono"; import { logger } from "hono/logger"; @@ -24,6 +27,8 @@ import auth from "./routes/auth.js"; import admin from "./routes/admin.js"; import panel from "./routes/panel.js"; import adminEntities from "./routes/admin-entities.js"; +import media from "./routes/media.js"; +import { UPLOADS_DIR } from "./media.js"; import { startSessionSweeper } from "./auth.js"; import { syncDescriptorsWithSchema } from "./admin-schema-sync.js"; import { ENTITIES } from "./admin-schema.js"; @@ -39,6 +44,8 @@ const version = migrate(db); syncDescriptorsWithSchema(db, ENTITIES); console.log(`db ${DB_PATH} (${db.driverName}, schema v${version})`); +await mkdir(UPLOADS_DIR, { recursive: true }); +console.log(`uploads ${UPLOADS_DIR}`); /* ── App ─────────────────────────────────────────────────────── */ @@ -69,8 +76,30 @@ app.use("/api/auth/login", rateLimit({ windowMs: 15 * 60_000, max: 10 })); app.route("/api/admin/panel", panel); app.route("/api/auth", auth); app.route("/api/admin", admin); +// Before the entity routes, whose /:entity would claim /media. +app.route("/api/admin", media); app.route("/api/admin", adminEntities); +/* ── Uploads ─────────────────────────────────────────────────── + In production nginx serves /uploads/ straight from disk and + never passes it here. This is for development, where Vite + proxies /uploads to the API. The headers match the nginx + block's: an uploaded SVG opened on its own can't run script. + ───────────────────────────────────────────────────────────── */ + +app.use("/uploads/*", async (c, next) => { + await next(); + c.header("X-Content-Type-Options", "nosniff"); + c.header("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; sandbox"); +}); +app.use( + "/uploads/*", + serveStatic({ + root: UPLOADS_DIR, + rewriteRequestPath: (p) => p.replace(/^\/uploads/, ""), + }), +); + startSessionSweeper(db); app.notFound((c) => c.json({ error: "Not found" }, 404)); diff --git a/server/src/media.js b/server/src/media.js new file mode 100644 index 0000000..c4a5b91 --- /dev/null +++ b/server/src/media.js @@ -0,0 +1,184 @@ +/* ═══════════════════════════════════════════════════════════════ + MEDIA STORAGE + + Where uploads go and what happens to them on the way. The routes + in routes/media.js are HTTP around this; the rules are here. + + ── Where ── + UPLOADS_DIR, default ./uploads (next to dev.db when run from + server/). Production sets /var/lib/ngu/uploads, beside the + database and outside /srv/ngu-api, so a deploy's rsync never + deletes anyone's photos. Every file is served at + /uploads/<filename>: by nginx in production, by the API in + development (see index.js). + + ── What ── + The type is read from the file's first bytes, never from its + name or the browser's Content-Type, both of which the uploader + controls. JPEG, PNG, GIF, WebP and SVG are accepted; anything + else is refused. + + ── Processing ── + By default a raster image is turned upright (EXIF orientation), + shrunk to fit MAX_EDGE on its longest side, and saved as WebP, + which also drops its metadata, camera location included. + `keepOriginal` stores the bytes exactly as uploaded instead, + under the tighter KEEP_MAX_BYTES. An SVG is always kept as it + is: it's already small, and rasterising it would lose the point + of it. + + Names are random, so two uploads of "logo.png" can't collide + and a filename says nothing about what's in it. + ═══════════════════════════════════════════════════════════════ */ + +import { randomBytes } from "node:crypto"; +import { mkdir, rename, unlink, writeFile } from "node:fs/promises"; +import path from "node:path"; + +import sharp from "sharp"; + +export const UPLOADS_DIR = path.resolve(process.env.UPLOADS_DIR ?? "./uploads"); + +/* The public path an image field stores. media.ts passes anything + starting with "/" through untouched. */ +export const PUBLIC_PREFIX = "/uploads/"; + +const MB = 1024 * 1024; + +/* The largest file accepted at all, before processing: room for a + full-size phone photo. */ +export const MAX_UPLOAD_BYTES = 25 * MB; + +/* The largest file kept as uploaded, unprocessed. */ +export const KEEP_MAX_BYTES = 10 * MB; + +/* Longest side after processing, in pixels. Wide enough for a + full-bleed hero on a large screen. */ +const MAX_EDGE = 2400; + +const WEBP_QUALITY = 82; + +export class MediaError extends Error { + constructor(status, message) { + super(message); + this.status = status; + } +} + +/* ── Sniffing ──────────────────────────────────────────────── */ + +const TYPES = { + jpeg: { mime: "image/jpeg", ext: ".jpg" }, + png: { mime: "image/png", ext: ".png" }, + gif: { mime: "image/gif", ext: ".gif" }, + webp: { mime: "image/webp", ext: ".webp" }, + svg: { mime: "image/svg+xml", ext: ".svg" }, +}; + +function startsWith(buf, bytes, offset = 0) { + return bytes.every((byte, i) => buf[offset + i] === byte); +} + +function sniff(buf) { + if (startsWith(buf, [0xff, 0xd8, 0xff])) return "jpeg"; + if (startsWith(buf, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return "png"; + if (startsWith(buf, [0x47, 0x49, 0x46, 0x38])) return "gif"; + if (startsWith(buf, [0x52, 0x49, 0x46, 0x46]) && startsWith(buf, [0x57, 0x45, 0x42, 0x50], 8)) { + return "webp"; + } + + // SVG is text: an optional BOM, XML declaration, comments or a + // doctype, then an <svg> element. Look at the head only. + const head = buf.subarray(0, 1024).toString("utf8").replace(/^/, "").trimStart(); + if (/^(<\?xml[\s\S]*?\?>\s*)?(<!--[\s\S]*?-->\s*|<!DOCTYPE[^>]*>\s*)*<svg[\s>]/i.test(head)) { + return "svg"; + } + + return null; +} + +/* ── Store ───────────────────────────────────────────────────── + Writes the file and returns what the media row needs. The row + itself is the caller's, so a failed insert can call remove() + and leave nothing behind. + ───────────────────────────────────────────────────────────── */ + +export async function store(buf, { keepOriginal = false } = {}) { + if (buf.length === 0) throw new MediaError(400, "The file is empty."); + if (buf.length > MAX_UPLOAD_BYTES) { + throw new MediaError(413, `Files can be at most ${MAX_UPLOAD_BYTES / MB} MB.`); + } + + const kind = sniff(buf); + if (!kind) { + throw new MediaError(415, "Only JPEG, PNG, GIF, WebP and SVG images can be uploaded."); + } + + const convert = kind !== "svg" && !keepOriginal; + + if (!convert && buf.length > KEEP_MAX_BYTES) { + throw new MediaError( + 413, + `Files kept as uploaded can be at most ${KEEP_MAX_BYTES / MB} MB. ` + + "Leave the original unticked to have it shrunk instead.", + ); + } + + let out = buf; + let type = TYPES[kind]; + let width = null; + let height = null; + + try { + if (convert) { + // animated keeps every frame of a GIF or an animated WebP. + const { data, info } = await sharp(buf, { animated: true }) + .rotate() + .resize({ width: MAX_EDGE, height: MAX_EDGE, fit: "inside", withoutEnlargement: true }) + .webp({ quality: WEBP_QUALITY }) + .toBuffer({ resolveWithObject: true }); + out = data; + type = TYPES.webp; + width = info.width; + // An animated image reports the whole strip's height. + height = info.pageHeight ?? info.height; + } else if (kind !== "svg") { + const meta = await sharp(buf).metadata(); + width = meta.width ?? null; + height = meta.pageHeight ?? meta.height ?? null; + } + } catch { + throw new MediaError(415, "That image couldn't be read. It may be damaged."); + } + + const filename = `${randomBytes(12).toString("hex")}${type.ext}`; + + await mkdir(UPLOADS_DIR, { recursive: true }); + // Written under a temporary name and renamed, so a half-written + // file is never served under its real one. + const tmp = path.join(UPLOADS_DIR, `.${filename}.tmp`); + await writeFile(tmp, out); + await rename(tmp, path.join(UPLOADS_DIR, filename)); + + return { + filename, + content_type: type.mime, + bytes: out.length, + width, + height, + processed: convert ? 1 : 0, + }; +} + +/* Deletes one stored file. 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; + } +} diff --git a/server/src/migrations/028_media.sql b/server/src/migrations/028_media.sql new file mode 100644 index 0000000..09ca066 --- /dev/null +++ b/server/src/migrations/028_media.sql @@ -0,0 +1,41 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 028 MEDIA: UPLOADED IMAGES +-- +-- One row per file in UPLOADS_DIR (/var/lib/ngu/uploads in +-- production, outside the deployed app so an rsync can't touch +-- it). nginx serves the directory at /uploads/; the API only +-- writes and deletes. +-- +-- An image field stores the file's public path, '/uploads/<file>', +-- not this row's id. That keeps every image column a plain TEXT +-- that also takes a filename in public/ or a full URL, as before, +-- and means media.ts needs no lookup. The cost is no foreign key: +-- deleting a file a record still names leaves that record showing +-- nothing (the <Logo> and <img> fallbacks already handle a missing +-- file), so the Media page warns before a delete. +-- +-- filename the stored name: random, so it can't collide or +-- be guessed from the original. '3f9c…e1.webp' +-- original_name what the uploader's file was called, for the +-- library's search and display +-- processed 1 when resized and converted to WebP, 0 when +-- kept as uploaded +-- width, height null for an SVG, which has no pixel size +-- +-- PRAGMA user_version; -- reads 27 before this file +-- ═══════════════════════════════════════════════════════════════ + +CREATE TABLE media ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + filename TEXT NOT NULL UNIQUE, + original_name TEXT NOT NULL, + content_type TEXT NOT NULL, + bytes INTEGER NOT NULL CHECK (bytes >= 0), + width INTEGER, + height INTEGER, + processed INTEGER NOT NULL DEFAULT 1 CHECK (processed IN (0, 1)), + uploaded_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL, + created_at TEXT NOT NULL DEFAULT (datetime('now')) +) STRICT; + +CREATE INDEX media_created_idx ON media (created_at DESC); diff --git a/server/src/migrations/029_event_card_image.sql b/server/src/migrations/029_event_card_image.sql new file mode 100644 index 0000000..82cac9a --- /dev/null +++ b/server/src/migrations/029_event_card_image.sql @@ -0,0 +1,15 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 029 EVENTS: CARD BACKGROUND IMAGE +-- +-- A photo behind an event's card. The card keeps its size and its +-- layout; the image covers it, under a light veil (CARD_IMAGE_VEIL +-- in EventList-Cards.tsx) so the text on top stays readable. +-- +-- Like every image column, it holds a path: '/uploads/<file>' from +-- the media library, a bare filename in public/event-backgrounds/, +-- or a full URL. Null draws the card as before. +-- +-- PRAGMA user_version; -- reads 28 before this file +-- ═══════════════════════════════════════════════════════════════ + +ALTER TABLE events ADD COLUMN card_image TEXT; diff --git a/server/src/routes/content.js b/server/src/routes/content.js index 7c827dd..1e56055 100644 --- a/server/src/routes/content.js +++ b/server/src/routes/content.js @@ -148,6 +148,7 @@ function shapeEvent(row, links, cardBlocks, hosts = []) { event_logo: row.event_logo, color: row.effective_color, gradient: row.gradient, + card_image: row.card_image, hosts: hosts.map(shapeHost), diff --git a/server/src/routes/media.js b/server/src/routes/media.js new file mode 100644 index 0000000..a0df5fa --- /dev/null +++ b/server/src/routes/media.js @@ -0,0 +1,181 @@ +/* ═══════════════════════════════════════════════════════════════ + MEDIA ROUTES: mounted under /api/admin + + GET /media the library, newest first, ?q=name + POST /media upload one image (multipart: file, + keep_original) + GET /media/:id/uses which records name this file + DELETE /media/:id remove the row and the file + + Reading needs a session, uploading needs editor, deleting needs + admin: the same ladder the entity routes use, so an editor can + add images to what they edit but not take one out from under + somebody else's page. + + Mounted before the entity routes, whose /:entity would otherwise + claim /media and answer "Unknown entity." + ═══════════════════════════════════════════════════════════════ */ + +import { Hono } from "hono"; +import { bodyLimit } from "hono/body-limit"; + +import { requireAuth, requireRole } from "../auth.js"; +import { MAX_UPLOAD_BYTES, MediaError, PUBLIC_PREFIX, remove, store } from "../media.js"; + +const media = new Hono(); + +media.use("*", requireAuth); + +const NO_STORE = { "Cache-Control": "no-store" }; + +const MAX_LIST = 500; + +/* Tables that can't hold an image path, or mustn't be searched. */ +const NOT_CONTENT = new Set(["media", "admin_users", "sessions", "feedback", "sqlite_sequence"]); + +function shape(row) { + return { + id: row.id, + url: `${PUBLIC_PREFIX}${row.filename}`, + original_name: row.original_name, + content_type: row.content_type, + bytes: row.bytes, + width: row.width, + height: row.height, + processed: row.processed === 1, + uploaded_by: row.uploaded_by_name ?? row.uploaded_by_email ?? null, + created_at: row.created_at, + }; +} + +const SELECT = `SELECT m.*, u.name AS uploaded_by_name, u.email AS uploaded_by_email + FROM media m + LEFT JOIN admin_users u ON u.id = m.uploaded_by`; + +media.get("/media", (c) => { + const q = (c.req.query("q") ?? "").trim().slice(0, 100); + const rows = c + .get("db") + .prepare( + `${SELECT} + ${q ? "WHERE m.original_name LIKE ?" : ""} + ORDER BY m.created_at DESC, m.id DESC + LIMIT ${MAX_LIST}`, + ) + .all(...(q ? [`%${q}%`] : [])); + return c.json({ media: rows.map(shape) }, 200, NO_STORE); +}); + +media.post( + "/media", + requireRole("editor"), + // A little over the file limit, for the multipart framing. + bodyLimit({ + maxSize: MAX_UPLOAD_BYTES + 64 * 1024, + onError: (c) => c.json({ error: "That file is too large." }, 413), + }), + async (c) => { + const db = c.get("db"); + const user = c.get("user"); + + let body; + try { + body = await c.req.parseBody(); + } catch { + return c.json({ error: "Expected a file upload." }, 400); + } + + const file = body.file; + if (!(file instanceof File)) return c.json({ error: "No file was sent." }, 400); + + const stored = await store(Buffer.from(await file.arrayBuffer()), { + keepOriginal: body.keep_original === "1", + }); + + let row; + try { + const { lastInsertRowid } = db + .prepare( + `INSERT INTO media + (filename, original_name, content_type, bytes, width, height, processed, uploaded_by) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + ) + .run( + stored.filename, + (file.name || "upload").slice(0, 200), + stored.content_type, + stored.bytes, + stored.width, + stored.height, + stored.processed, + user.id, + ); + row = db.prepare(`${SELECT} WHERE m.id = ?`).get(lastInsertRowid); + } catch (err) { + await remove(stored.filename); + throw err; + } + + console.log(`media ${stored.filename} uploaded by ${user.email}`); + return c.json({ media: shape(row) }, 201, NO_STORE); + }, +); + +/* Every TEXT column of every content table, searched for the exact + path. Read from the live schema rather than a list of image + columns, so a new image field is covered the day it's added. */ +function usesOf(db, url) { + const tables = db + .prepare(`SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`) + .all() + .map((t) => t.name) + .filter((name) => !NOT_CONTENT.has(name)); + + const uses = []; + for (const table of tables) { + const columns = db + .prepare(`SELECT name, type FROM pragma_table_info(?)`) + .all(table) + .filter((col) => col.type.toUpperCase() === "TEXT") + .map((col) => col.name); + if (columns.length === 0) continue; + + // Names come from the schema, not the request; quoted anyway. + const where = columns.map((col) => `"${col}" = ?`).join(" OR "); + const { n } = db + .prepare(`SELECT COUNT(*) AS n FROM "${table}" WHERE ${where}`) + .get(...columns.map(() => url)); + if (n > 0) uses.push({ table, count: n }); + } + return uses; +} + +function findOr404(c) { + const id = Number(c.req.param("id")); + const row = Number.isInteger(id) + ? c.get("db").prepare(`SELECT * FROM media WHERE id = ?`).get(id) + : null; + if (!row) throw new MediaError(404, "No such file."); + return row; +} + +media.get("/media/:id/uses", (c) => { + const row = findOr404(c); + return c.json({ uses: usesOf(c.get("db"), `${PUBLIC_PREFIX}${row.filename}`) }, 200, NO_STORE); +}); + +media.delete("/media/:id", requireRole("admin"), async (c) => { + const row = findOr404(c); + c.get("db").prepare(`DELETE FROM media WHERE id = ?`).run(row.id); + await remove(row.filename); + console.log(`media ${row.filename} deleted by ${c.get("user").email}`); + return c.body(null, 204); +}); + +media.onError((err, c) => { + if (err instanceof MediaError) return c.json({ error: err.message }, err.status, NO_STORE); + console.error(err); + return c.json({ error: "Something went wrong." }, 500); +}); + +export default media; diff --git a/src/App.tsx b/src/App.tsx index c72c0f2..8a8df02 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -32,6 +32,7 @@ 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 EntityList from "./pages/admin/EntityList.tsx"; import EntityEdit from "./pages/admin/EntityEdit.tsx"; @@ -80,6 +81,7 @@ export default function App() { <Route path="panel" element={<AdminPanel />} /> </Route> <Route path="feedback" element={<AdminFeedback />} /> + <Route path="media" element={<AdminMedia />} /> <Route path=":entity" element={<EntityList />} /> <Route path=":entity/:id" element={<EntityEdit />} /> </Route> diff --git a/src/components/admin/MediaLibrary.tsx b/src/components/admin/MediaLibrary.tsx new file mode 100644 index 0000000..8bb3b55 --- /dev/null +++ b/src/components/admin/MediaLibrary.tsx @@ -0,0 +1,407 @@ +/* ═══════════════════════════════════════════════════════════════ + MEDIA LIBRARY + + Everything the admin does with uploaded images, in one file: + + ImageInput the `widget: "image"` form field. A preview, the + stored value as editable text, and buttons to + upload a new file or pick an earlier one. + MediaPicker the dialog behind "Choose from library". + MediaGrid the thumbnails both the picker and the Media page + (pages/admin/AdminMedia.tsx) draw. + UploadButton a file input dressed as a button, with the + "keep original" choice beside it. + + An image field stores a path, not a media id: '/uploads/<file>' + for an upload, or, as before, a bare filename in the field's + public/ directory or a full URL. So the text box stays: old + values keep working, and a URL from elsewhere can be pasted in. + `resolve` on the field (a media.ts helper) turns a bare filename + into something the preview can load. + + Uploading is editor and up; the server says the same. Reads use + ttl: 0 because two people uploading at once is exactly when a + cached list would lie. + ═══════════════════════════════════════════════════════════════ */ + +import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from "react"; + +import { ApiError, get, upload } from "../../lib/api.ts"; +import { useAuth } from "../../lib/auth.tsx"; +import { canWrite as roleCanWrite } from "../../lib/roles.ts"; + +export type MediaItem = { + id: number; + url: string; + original_name: string; + content_type: string; + bytes: number; + width: number | null; + height: number | null; + processed: boolean; + uploaded_by: string | null; + created_at: string; +}; + +const button = + "rounded-full border border-[#138ba0] px-3 py-1 text-sm font-medium text-[#138ba0] " + + "transition-colors hover:bg-[#eef9fb] disabled:cursor-default disabled:opacity-50"; + +/* A light checkerboard, so a white logo on a transparent background + is still visible in its thumbnail. */ +const CHECKER = { + backgroundColor: "#fff", + backgroundImage: + "linear-gradient(45deg,#e6eef0 25%,transparent 25%),linear-gradient(-45deg,#e6eef0 25%,transparent 25%)," + + "linear-gradient(45deg,transparent 75%,#e6eef0 75%),linear-gradient(-45deg,transparent 75%,#e6eef0 75%)", + backgroundSize: "12px 12px", + backgroundPosition: "0 0,0 6px,6px -6px,-6px 0", +}; + +export function formatBytes(bytes: number) { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`; + return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; +} + +export function mediaSize(item: MediaItem) { + const dims = item.width && item.height ? `${item.width} × ${item.height}, ` : ""; + return `${dims}${formatBytes(item.bytes)}`; +} + +/* ── Data ────────────────────────────────────────────────────── */ + +export function uploadImage(file: File, keepOriginal: boolean): Promise<MediaItem> { + const form = new FormData(); + form.append("file", file); + if (keepOriginal) form.append("keep_original", "1"); + return upload("/admin/media", form).then((data) => data.media); +} + +export function useMediaLibrary(query: string) { + const [items, setItems] = useState<MediaItem[] | null>(null); + const [error, setError] = useState<string | null>(null); + + const reload = useCallback(() => { + const q = query.trim(); + setError(null); + get(`/admin/media${q ? `?q=${encodeURIComponent(q)}` : ""}`, { ttl: 0 }) + .then((data) => setItems(data.media)) + .catch((err) => + setError(err instanceof ApiError ? err.message : "Couldn't load the library."), + ); + }, [query]); + + useEffect(reload, [reload]); + + return { items, error, reload, setItems }; +} + +/* ── Upload button ───────────────────────────────────────────── */ + +export function UploadButton({ + onUploaded, + multiple = false, + label = "Upload", +}: { + onUploaded: (item: MediaItem) => void; + multiple?: boolean; + label?: string; +}) { + const inputRef = useRef<HTMLInputElement>(null); + const keepId = useId(); + const [keepOriginal, setKeepOriginal] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + + async function send(files: FileList | null) { + if (!files || files.length === 0) return; + setBusy(true); + setError(null); + try { + // One at a time: each is up to 25 MB, and a failure should + // name the file it happened to. + for (const file of Array.from(files)) { + try { + onUploaded(await uploadImage(file, keepOriginal)); + } catch (err) { + const why = err instanceof ApiError ? err.message : "Upload failed."; + setError(files.length > 1 ? `${file.name}: ${why}` : why); + break; + } + } + } finally { + setBusy(false); + if (inputRef.current) inputRef.current.value = ""; + } + } + + return ( + <div> + <div className="flex flex-wrap items-center gap-3"> + <button + type="button" + className={button} + disabled={busy} + onClick={() => inputRef.current?.click()} + > + {busy ? "Uploading…" : label} + </button> + <input + ref={inputRef} + type="file" + accept="image/jpeg,image/png,image/gif,image/webp,image/svg+xml" + multiple={multiple} + className="hidden" + onChange={(e) => send(e.target.files)} + /> + <label htmlFor={keepId} className="flex items-center gap-1.5 text-xs text-[#4a6b72]"> + <input + id={keepId} + type="checkbox" + checked={keepOriginal} + onChange={(e) => setKeepOriginal(e.target.checked)} + className="h-3.5 w-3.5 rounded border-[#4a6b72]/40 text-[#138ba0]" + /> + Keep original + </label> + </div> + {error && <p className="mt-1 text-xs text-[#b3261e]">{error}</p>} + </div> + ); +} + +export const UPLOAD_HELP = + "Photos are shrunk to 2400px and saved as WebP, which also removes their location data. " + + "Keep original stores the file exactly as it is (up to 10 MB). SVGs are always kept as they are."; + +/* ── Grid ────────────────────────────────────────────────────── */ + +export function MediaGrid({ + items, + selected, + onPick, + renderActions, +}: { + items: MediaItem[]; + selected?: string | null; + onPick?: (item: MediaItem) => void; + renderActions?: (item: MediaItem) => ReactNode; +}) { + if (items.length === 0) { + return <p className="text-sm text-[#4a6b72]">Nothing here yet.</p>; + } + + return ( + <ul className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4"> + {items.map((item) => { + const isSelected = selected === item.url; + const thumb = ( + <> + <div className="aspect-[4/3] overflow-hidden rounded-lg" style={CHECKER}> + <img + src={item.url} + alt="" + loading="lazy" + className="h-full w-full object-contain" + /> + </div> + <p className="mt-1.5 truncate text-xs font-medium text-[#26454c]" title={item.original_name}> + {item.original_name} + </p> + <p className="text-xs text-[#4a6b72]/80">{mediaSize(item)}</p> + </> + ); + + return ( + <li + key={item.id} + className={`rounded-xl border bg-white p-2 ${ + isSelected ? "border-[#138ba0] ring-2 ring-[#138ba0]/30" : "border-[#4a6b72]/20" + }`} + > + {onPick ? ( + <button + type="button" + onClick={() => onPick(item)} + className="block w-full text-left" + aria-pressed={isSelected} + > + {thumb} + </button> + ) : ( + thumb + )} + {renderActions && <div className="mt-2">{renderActions(item)}</div>} + </li> + ); + })} + </ul> + ); +} + +/* ── Picker dialog ───────────────────────────────────────────── */ + +export function MediaPicker({ + selected, + onPick, + onClose, +}: { + selected?: string | null; + onPick: (item: MediaItem) => void; + onClose: () => void; +}) { + const { user } = useAuth(); + const [query, setQuery] = useState(""); + const { items, error, setItems } = useMediaLibrary(query); + const dialogRef = useRef<HTMLDialogElement>(null); + + // showModal gives focus trapping, Escape and the backdrop for free. + useEffect(() => { + dialogRef.current?.showModal(); + }, []); + + return ( + <dialog + ref={dialogRef} + onClose={onClose} + onClick={(e) => { + // A click on the backdrop lands on the dialog itself. + if (e.target === dialogRef.current) dialogRef.current?.close(); + }} + className="w-[min(56rem,calc(100vw-2rem))] rounded-2xl p-0 backdrop:bg-[#0f2f36]/40" + > + <div className="flex max-h-[85vh] flex-col"> + <div className="flex flex-wrap items-center gap-3 border-b border-[#138ba0]/15 px-5 py-4"> + <h2 className="text-lg font-semibold text-[#138ba0]">Choose an image</h2> + <input + type="search" + value={query} + onChange={(e) => setQuery(e.target.value)} + placeholder="Search by file name" + className="ml-auto w-56 rounded-lg border border-[#4a6b72]/25 px-3 py-1.5 text-sm outline-none focus:border-[#138ba0]" + /> + <button + type="button" + onClick={() => dialogRef.current?.close()} + aria-label="Close" + className="h-8 w-8 rounded-full text-[#4a6b72] hover:bg-[#eef9fb]" + > + ✕ + </button> + </div> + + {roleCanWrite(user) && ( + <div className="border-b border-[#138ba0]/10 px-5 py-3"> + <UploadButton + label="Upload new" + onUploaded={(item) => { + setItems((current) => [item, ...(current ?? [])]); + onPick(item); + dialogRef.current?.close(); + }} + /> + <p className="mt-1 text-xs text-[#4a6b72]">{UPLOAD_HELP}</p> + </div> + )} + + <div className="overflow-y-auto px-5 py-4"> + {error ? ( + <p className="text-sm text-[#b3261e]">{error}</p> + ) : items === null ? ( + <p className="text-sm text-[#4a6b72]">Loading…</p> + ) : ( + <MediaGrid + items={items} + selected={selected} + onPick={(item) => { + onPick(item); + dialogRef.current?.close(); + }} + /> + )} + </div> + </div> + </dialog> + ); +} + +/* ── The form field ──────────────────────────────────────────── */ + +export function ImageInput({ + id, + value, + resolve, + locked, + className, + onChange, +}: { + id: string; + value: string | null | undefined; + resolve?: (file?: string | null) => string | null; + locked: boolean; + className: string; + onChange: (value: string) => void; +}) { + const { user } = useAuth(); + const [picking, setPicking] = useState(false); + const [broken, setBroken] = useState(false); + + const src = value ? (resolve ? resolve(value) : value) : null; + useEffect(() => setBroken(false), [src]); + + const editable = !locked && roleCanWrite(user); + + return ( + <div className="flex gap-3"> + <div + className="flex h-20 w-20 shrink-0 items-center justify-center overflow-hidden rounded-lg border border-[#4a6b72]/20" + style={CHECKER} + > + {src && !broken ? ( + <img src={src} alt="" className="h-full w-full object-contain" onError={() => setBroken(true)} /> + ) : ( + <span className="px-1 text-center text-[10px] text-[#4a6b72]/70"> + {src ? "Not found" : "No image"} + </span> + )} + </div> + + <div className="min-w-0 flex-1 space-y-2"> + <input + id={id} + type="text" + value={value ?? ""} + readOnly={locked} + onChange={(e) => onChange(e.target.value)} + className={className} + /> + {editable && ( + <div className="flex flex-wrap items-start gap-2"> + <UploadButton onUploaded={(item) => onChange(item.url)} /> + <button type="button" className={button} onClick={() => setPicking(true)}> + Choose from library + </button> + {value && ( + <button + type="button" + onClick={() => onChange("")} + className="px-2 py-1 text-sm text-[#4a6b72] hover:text-[#b3261e]" + > + Clear + </button> + )} + </div> + )} + </div> + + {picking && ( + <MediaPicker + selected={value} + onPick={(item) => onChange(item.url)} + onClose={() => setPicking(false)} + /> + )} + </div> + ); +} diff --git a/src/components/admin/fields.tsx b/src/components/admin/fields.tsx index d202c53..8f395d7 100644 --- a/src/components/admin/fields.tsx +++ b/src/components/admin/fields.tsx @@ -18,6 +18,11 @@ that column in the server's admin-schema.js or the row will be saved as real input. + `widget: "image"` is a text box with a preview and upload and + library buttons beside it (ImageInput in MediaLibrary.tsx). Its + `resolve` option is the media.ts helper for the field's public/ + directory, so a bare filename previews from the right place. + Two options change the box itself rather than what goes in it: prefix fixed text inside the box, left of the cursor. The @@ -34,6 +39,8 @@ import { useRef, useState } from "react"; +import { ImageInput } from "./MediaLibrary.tsx"; + const input = "w-full rounded-lg border border-[#4a6b72]/25 bg-white px-3 py-2 text-sm text-[#26454c] " + "outline-none transition-colors focus:border-[#138ba0] focus:ring-2 focus:ring-[#138ba0]/25"; @@ -168,6 +175,15 @@ export function Field({ field, value, row, options, error, onChange }: any) { className={locked ? inputLocked : common.className} /> </div> + ) : widget === "image" ? ( + <ImageInput + id={id} + value={value} + resolve={field.resolve} + locked={locked} + className={locked ? inputLocked : common.className} + onChange={onChange} + /> ) : field.prefix && !locked ? ( // The span is not a form control, so it can't be typed // into, tabbed to, or selected by dragging through the diff --git a/src/lib/adminSchema.ts b/src/lib/adminSchema.ts index c5a794b..2be582b 100644 --- a/src/lib/adminSchema.ts +++ b/src/lib/adminSchema.ts @@ -17,6 +17,16 @@ import { preview } from "./text.ts"; import { PLATFORMS } from "./platforms.ts"; +import { + awardLogo, + blockMedia, + eventBackground, + eventLogo, + heroPhoto, + orgLogo, + personPhoto, + teamLogo, +} from "./media.ts"; const PLACE_FIELDS = [ { path: "venue", label: "Venue" }, @@ -228,7 +238,7 @@ const blocksChild = { ], }, { path: "text", label: "Text", widget: "textarea", full: true }, - { path: "media", label: "Media", help: "Filename or URL" }, + { path: "media", label: "Media", widget: "image", resolve: blockMedia, full: true }, { path: "href", label: "Link" }, ], children: [ @@ -288,7 +298,7 @@ const organizations = { { path: "short_name", label: "Short name" }, { path: "tagline", label: "Tagline", full: true }, { path: "color", label: "Colour", widget: "color" }, - { path: "logo", label: "Logo", help: "Filename in /org-logos/" }, + { path: "logo", label: "Logo", widget: "image", resolve: orgLogo, full: true }, ], }, { @@ -495,10 +505,18 @@ const events = { { legend: "Appearance", fields: [ - { path: "event_logo", label: "Event logo", help: "Filename in /event-logos/" }, - { path: "org_logo", label: "Org logo override" }, + { path: "event_logo", label: "Event logo", widget: "image", resolve: eventLogo, full: true }, + { path: "org_logo", label: "Org logo override", widget: "image", resolve: orgLogo, full: true }, { path: "color", label: "Colour", widget: "color" }, { path: "gradient", label: "Gradient", full: true }, + { + path: "card_image", + label: "Card background", + widget: "image", + resolve: eventBackground, + full: true, + help: "A photo behind the event's card, faded so the text stays readable.", + }, ], }, timelineGroup("event"), @@ -577,7 +595,7 @@ const people = { { path: "sort_name", label: "Sort name", help: "Doe, Jane" }, { path: "pronouns", label: "Pronouns" }, { path: "tagline", label: "Tagline", full: true }, - { path: "photo", label: "Photo", help: "Filename in /people/" }, + { path: "photo", label: "Photo", widget: "image", resolve: personPhoto, full: true }, { path: "primary_org_id", label: "Home organization", @@ -738,7 +756,7 @@ const teams = { { path: "name", label: "Name", required: true, help: "Board, Leadership Team" }, { path: "tagline", label: "Tagline", full: true }, { path: "color", label: "Colour", widget: "color" }, - { path: "logo", label: "Logo", help: "Filename in /org-logos/" }, + { path: "logo", label: "Logo", widget: "image", resolve: teamLogo, full: true }, ], }, { legend: "Publishing", fields: PUBLISH_FIELDS }, @@ -814,7 +832,7 @@ const awards = { }, { path: "name", label: "Name", required: true }, { path: "description", label: "Description", widget: "textarea", full: true }, - { path: "logo", label: "Logo", help: "Filename in public/org-logos/" }, + { path: "logo", label: "Logo", widget: "image", resolve: awardLogo, full: true }, ], }, { @@ -1151,7 +1169,7 @@ const frontPage = { title: (row) => row.caption || row.media || "New photo", blank: { media: "", alt: "", caption: "" }, fields: [ - { path: "media", label: "Photo", required: true, help: "Filename in /front-page/, or a URL" }, + { path: "media", label: "Photo", required: true, widget: "image", resolve: heroPhoto, full: true }, { path: "alt", label: "Description", help: "For screen readers" }, { path: "caption", label: "Caption", full: true }, { path: "link_url", label: "Link", help: "Optional; makes the caption a link" }, diff --git a/src/lib/api.ts b/src/lib/api.ts index 9086e2f..5eeca0a 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -115,3 +115,9 @@ export function patch(path, data) { export function del(path) { return request(path, { method: "DELETE" }); } + +/* A multipart body. No Content-Type here: the browser sets it, + boundary included, from the FormData itself. */ +export function upload(path, form: FormData) { + return request(path, { method: "POST", body: form }); +} diff --git a/src/lib/media.ts b/src/lib/media.ts index 0234c91..df238c8 100644 --- a/src/lib/media.ts +++ b/src/lib/media.ts @@ -17,6 +17,10 @@ const ABSOLUTE = /^(https?:|\/|data:)/ +/* An uploaded file ('/uploads/…'), a path anywhere on the site, or + a full URL: something to use as it is rather than resolve. */ +export const isAbsoluteMedia = (file?: string | null) => Boolean(file && ABSOLUTE.test(file)) + function inDir(dir: string) { return (file?: string | null): string | null => { if (!file) return null @@ -27,6 +31,7 @@ function inDir(dir: string) { export const personPhoto = inDir('/people') // confirmed export const eventLogo = inDir('/event-logos') // confirmed +export const eventBackground = inDir('/event-backgrounds') export const orgLogo = inDir('/org-logos') // ⚠ guess export const teamLogo = inDir('/team-logos') // ⚠ guess export const awardLogo = inDir('/award-logos') // ⚠ guess diff --git a/src/lib/useContent.ts b/src/lib/useContent.ts index 86feaa1..7a6972d 100644 --- a/src/lib/useContent.ts +++ b/src/lib/useContent.ts @@ -101,6 +101,8 @@ export type EventRecord = { event_logo?: string | null color?: string | null gradient?: string | null + /** Behind the card. See 029_event_card_image.sql. */ + card_image?: string | null /* In billing order. The first is the one `color` and `org_logo` fell back to when the event set neither. */ hosts: EventHost[] diff --git a/src/pages/admin/AdminMedia.tsx b/src/pages/admin/AdminMedia.tsx new file mode 100644 index 0000000..379a185 --- /dev/null +++ b/src/pages/admin/AdminMedia.tsx @@ -0,0 +1,193 @@ +/* ═══════════════════════════════════════════════════════════════ + ADMIN: MEDIA + + The uploaded-image library: search it, add to it, copy a file's + path, delete what nothing needs. Image fields in the editors + upload and pick from the same library (MediaLibrary.tsx), so this + page is for housekeeping rather than the way images get in. + + Two ranks, as on the server: editors and up upload, admins and + up delete. A delete first asks the server which records still + name the file, since nothing stops one being removed from under + a page (an image field stores the path, not a foreign key). + ═══════════════════════════════════════════════════════════════ */ + +import { useState } from "react"; + +import { ApiError, del, get } from "../../lib/api.ts"; +import { useAuth } from "../../lib/auth.tsx"; +import { canDelete, canWrite as roleCanWrite } from "../../lib/roles.ts"; +import { + MediaGrid, + UPLOAD_HELP, + UploadButton, + useMediaLibrary, + type MediaItem, +} from "../../components/admin/MediaLibrary.tsx"; + +type Use = { table: string; count: number }; + +function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () => void }) { + const [uses, setUses] = useState<Use[] | null>(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + + async function ask() { + setBusy(true); + setError(null); + try { + const data = await get(`/admin/media/${item.id}/uses`, { ttl: 0 }); + setUses(data.uses); + } catch (err) { + setError(err instanceof ApiError ? err.message : "Couldn't check where it's used."); + } finally { + setBusy(false); + } + } + + async function remove() { + setBusy(true); + setError(null); + try { + await del(`/admin/media/${item.id}`); + onDeleted(); + } catch (err) { + setError(err instanceof ApiError ? err.message : "Couldn't delete that."); + setBusy(false); + } + } + + if (uses === null) { + return ( + <> + <button + type="button" + onClick={ask} + disabled={busy} + className="text-xs text-[#4a6b72] hover:text-[#b3261e]" + > + Delete + </button> + {error && <p className="mt-1 text-xs text-[#b3261e]">{error}</p>} + </> + ); + } + + return ( + <div className="rounded-lg bg-[#fdf3f2] p-2 text-xs text-[#26454c]"> + {uses.length > 0 ? ( + <p> + Still used by{" "} + {uses.map((use) => `${use.count} in ${use.table.replace(/_/g, " ")}`).join(", ")}. Those + will show no image. + </p> + ) : ( + <p>Nothing uses this file.</p> + )} + <div className="mt-2 flex gap-3"> + <button + type="button" + onClick={remove} + disabled={busy} + className="font-medium text-[#b3261e] hover:underline" + > + {busy ? "Deleting…" : "Delete for good"} + </button> + <button type="button" onClick={() => setUses(null)} className="text-[#4a6b72] hover:underline"> + Cancel + </button> + </div> + {error && <p className="mt-1 text-[#b3261e]">{error}</p>} + </div> + ); +} + +function CopyPath({ url }: { url: string }) { + const [copied, setCopied] = useState(false); + return ( + <button + type="button" + onClick={() => { + navigator.clipboard?.writeText(url).then(() => { + setCopied(true); + setTimeout(() => setCopied(false), 1500); + }); + }} + className="text-xs text-[#138ba0] hover:underline" + > + {copied ? "Copied" : "Copy path"} + </button> + ); +} + +export default function AdminMedia() { + const { user } = useAuth(); + const [query, setQuery] = useState(""); + const { items, error, setItems } = useMediaLibrary(query); + + return ( + <div> + <div className="flex flex-wrap items-baseline gap-3"> + <h1 className="text-2xl font-bold text-[#138ba0]">Media</h1> + <p className="text-sm text-[#4a6b72]"> + Uploaded images. Image fields in every editor pick from here. + </p> + </div> + + <div className="mt-6 flex flex-wrap items-start gap-6"> + {roleCanWrite(user) && ( + <div className="max-w-md"> + <UploadButton + multiple + label="Upload images" + onUploaded={(item) => setItems((current) => [item, ...(current ?? [])])} + /> + <p className="mt-1 text-xs text-[#4a6b72]">{UPLOAD_HELP}</p> + </div> + )} + <input + type="search" + value={query} + onChange={(e) => setQuery(e.target.value)} + placeholder="Search by file name" + className="ml-auto w-64 rounded-lg border border-[#4a6b72]/25 px-3 py-2 text-sm outline-none focus:border-[#138ba0]" + /> + </div> + + <div className="mt-6"> + {error ? ( + <p className="text-sm text-[#b3261e]">{error}</p> + ) : items === null ? ( + <p className="text-sm text-[#4a6b72]">Loading…</p> + ) : ( + <MediaGrid + items={items} + renderActions={(item) => ( + <div className="flex flex-wrap items-start gap-x-3 gap-y-1"> + <CopyPath url={item.url} /> + <a + href={item.url} + target="_blank" + rel="noreferrer" + className="text-xs text-[#138ba0] hover:underline" + > + Open + </a> + {canDelete(user) && ( + <div className="w-full"> + <DeleteControl + item={item} + onDeleted={() => + setItems((current) => (current ?? []).filter((m) => m.id !== item.id)) + } + /> + </div> + )} + </div> + )} + /> + )} + </div> + </div> + ); +} diff --git a/src/pages/admin/adminNav.ts b/src/pages/admin/adminNav.ts index 0748c6c..b907f54 100644 --- a/src/pages/admin/adminNav.ts +++ b/src/pages/admin/adminNav.ts @@ -70,6 +70,13 @@ export const CMS_NAV = [ label: "Front page", blurb: "The hero, its photos or livestream, and which bands the home page draws.", }, + // Not an entity: the uploaded-image library every image field + // picks from. Its own page, AdminMedia.tsx. + { + to: "/admin/media", + label: "Media", + blurb: "Uploaded images: logos, photos and backgrounds, ready to reuse.", + }, ]; /* Forms are submissions coming in rather than content going out, so diff --git a/src/pages/sections/EventList-Cards.tsx b/src/pages/sections/EventList-Cards.tsx index 2a7f3e6..238ab43 100644 --- a/src/pages/sections/EventList-Cards.tsx +++ b/src/pages/sections/EventList-Cards.tsx @@ -5,6 +5,7 @@ import { eventHref } from "../../lib/hrefs.ts"; import { EVENT_TYPES, eventTypeLabel } from "../../lib/eventTypes.ts"; import { seriesLabel } from "../../lib/eventSeries.ts"; import PlatformIcon from "../../components/PlatformIcon.tsx"; +import { eventBackground, isAbsoluteMedia } from "../../lib/media.ts"; /* ═══════════════════════════════════════════════════════════════ EVENT LIST — CARDS @@ -35,7 +36,9 @@ const LOGOS = Object.fromEntries( Object.entries(LOGO_FILES).map(([path, src]) => [path.split("/").pop(), src]) ); -const logoSrc = file => (file && LOGOS[file]) || null; +/* A bundled logo by filename, or an upload or URL as it is. */ +const logoSrc = file => + (file && LOGOS[file]) || (isAbsoluteMedia(file) ? file : null); /* Last resort only. The API already falls back to the host organization's logo when an event doesn't name its own, so this @@ -60,6 +63,25 @@ function Logo({ file, alt = "", className }) { const TEAL = "#138ba0"; // last-resort card color const CARD_BG = "#ffffff"; // sits under every card, gradient or not +/* Laid over a card's background image so black text reads on any + photo. Heavier at the top, where the title and dates are, and + lighter lower down so more of the picture shows through. */ +const CARD_IMAGE_VEIL = + "linear-gradient(to bottom, rgba(255,255,255,0.9), rgba(255,255,255,0.78))"; + +/* The card's background layers, top first: its gradient if it has + one, then the veil and photo if it has one, then white. */ +function cardBackground(ev) { + const layers: string[] = []; + if (ev.gradient) layers.push(ev.gradient); + const image = eventBackground(ev.card_image); + if (image) { + layers.push(CARD_IMAGE_VEIL, `url(${JSON.stringify(image)}) center / cover no-repeat`); + } + layers.push(CARD_BG); + return layers.join(", "); +} + /* ── Grid view ──────────────────────────────────────────────── The grid fits as many columns as the screen allows, with no breakpoints: each card is at least CARD_MIN wide, and the @@ -185,7 +207,7 @@ export function Card({ }`} style={{ border: `1px solid ${color}`, - background: ev.gradient ? `${ev.gradient}, ${CARD_BG}` : CARD_BG, + background: cardBackground(ev), filter: past ? "saturate(0.75)" : "none", pointerEvents: interactive ? "auto" : "none", }} diff --git a/src/pages/sections/OrgList-Card.tsx b/src/pages/sections/OrgList-Card.tsx index 7d13ccf..86901b9 100644 --- a/src/pages/sections/OrgList-Card.tsx +++ b/src/pages/sections/OrgList-Card.tsx @@ -1,5 +1,6 @@ import { useState } from "react"; import ArrowLink from "../../components/ArrowLink.tsx"; +import { orgLogo } from "../../lib/media.ts"; import { initialsFor, orgPath, @@ -21,8 +22,6 @@ import { array — only the short card description. ═══════════════════════════════════════════════════════════════ */ -const LOGO_BASE = "/org-logos/"; - const MUTED = "#7a9299"; const INK = "#2c4a50"; const FALLBACK_COLOR = "#4a6b72"; @@ -39,7 +38,7 @@ function OrgMark({ org, color }) { if (org.logo && !failed) { return ( <img - src={`${LOGO_BASE}${org.logo}`} + src={orgLogo(org.logo) ?? undefined} alt="" onError={() => setFailed(true)} className="h-14 w-14 object-contain rounded-xl shrink-0" diff --git a/src/pages/sections/OrgList-Map.tsx b/src/pages/sections/OrgList-Map.tsx index 2eb06c8..eec121c 100644 --- a/src/pages/sections/OrgList-Map.tsx +++ b/src/pages/sections/OrgList-Map.tsx @@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react"; import { useCommunity } from "../../data/chapters.ts"; import { Link } from "react-router-dom"; import ArrowLink from "../../components/ArrowLink.tsx"; +import { orgLogo } from "../../lib/media.ts"; import { initialsFor, orgPath } from "../../data/organizations.ts"; import { AREAS, AREA_NAMES } from "../../data/mapGrid.ts"; @@ -39,8 +40,6 @@ const ROWS = 7; // stays at max-w-6xl, so this deliberately breaks out past it. const CONTENT_MAX = "88rem"; -const LOGO_BASE = "/org-logos/"; - const MUTED = "#7a9299"; const RULE = "#cfe3e7"; const INK = "#2c4a50"; @@ -472,7 +471,7 @@ function OrgLogo({ org, color, size = "h-14 w-14" }) { if (org.logo && !failed) { return ( <img - src={`${LOGO_BASE}${org.logo}`} + src={orgLogo(org.logo) ?? undefined} alt={org.name} onError={() => setFailed(true)} className={`${size} object-contain rounded-xl shrink-0`} diff --git a/src/pages/sections/OrgList-Vertical.tsx b/src/pages/sections/OrgList-Vertical.tsx index 5f3f0f3..f35113d 100644 --- a/src/pages/sections/OrgList-Vertical.tsx +++ b/src/pages/sections/OrgList-Vertical.tsx @@ -1,5 +1,6 @@ import { useId, useState } from "react"; import ArrowLink from "../../components/ArrowLink.tsx"; +import { orgLogo } from "../../lib/media.ts"; import PlatformIcon from "../../components/PlatformIcon.tsx"; import { areasSentence, @@ -36,8 +37,6 @@ import { a partner row simply doesn't have them. ═══════════════════════════════════════════════════════════════ */ -const LOGO_BASE = "/org-logos/"; - const MUTED = "#7a9299"; const RULE = "#cfe3e7"; const INK = "#2c4a50"; @@ -66,7 +65,7 @@ function OrgMark({ org, color }) { if (org.logo && !failed) { return ( <img - src={`${LOGO_BASE}${org.logo}`} + src={orgLogo(org.logo) ?? undefined} alt="" onError={() => setFailed(true)} className="h-8 w-8 object-contain shrink-0" diff --git a/vite.config.ts b/vite.config.ts index cdace2e..c514c7f 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -24,6 +24,12 @@ export default defineConfig({ changeOrigin: false, xfwd: true, }, + // Uploaded images. nginx serves these in production; in dev + // the API does, so they go to the same place as /api. + "/uploads": { + target: "http://127.0.0.1:5173", + changeOrigin: false, + }, }, }, build: { From 8186aff62fae940e09d581396f6d64383fa02f84 Mon Sep 17 00:00:00 2001 From: Zaldimmar <Zaldimmar@gmail.com> Date: Sun, 27 Sep 2026 15:33:14 -0500 Subject: [PATCH 13/22] Add a section nav to the admin editor and fold repeater rows Every record editor gets a sticky "On this page" column listing its field groups and collections (with row counts), lighting the one in view and marking any with a save error. Below lg it becomes a sticky "Jump to" menu. Editor pages widen to fit it through a small layout context; other admin pages keep their width. Each collection now sits in its own card, and repeater rows fold to their title line. Rows start folded, with Expand all and Collapse all; a new row, or one the server rejected, opens itself. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/components/admin/SectionNav.tsx | 141 +++++++++++++++++++++ src/components/admin/fields.tsx | 187 ++++++++++++++++++++++------ src/lib/adminWidth.tsx | 26 ++++ src/pages/admin/AdminLayout.tsx | 11 +- src/pages/admin/EntityEdit.tsx | 104 ++++++++++++---- 5 files changed, 402 insertions(+), 67 deletions(-) create mode 100644 src/components/admin/SectionNav.tsx create mode 100644 src/lib/adminWidth.tsx diff --git a/src/components/admin/SectionNav.tsx b/src/components/admin/SectionNav.tsx new file mode 100644 index 0000000..9ef994a --- /dev/null +++ b/src/components/admin/SectionNav.tsx @@ -0,0 +1,141 @@ +/* ═══════════════════════════════════════════════════════════════ + EDITOR SECTION NAV + + The record editor's table of contents. On a wide screen it's a + sticky column left of the form; below lg it's a slim sticky bar + with a "Jump to" menu. Both list the same sections, which + EntityEdit derives from the manifest (field groups, then child + collections with their row counts), so every editor gets one + without declaring anything. + + The lit entry is the last section whose top has scrolled past + the line ACTIVE_LINE px below the viewport's top: the one you're + reading, not merely the one peeking in at the bottom. A section + with a save error carries a red dot, so a rejected save points + at where to look. + ═══════════════════════════════════════════════════════════════ */ + +import { useEffect, useState } from "react"; + +export type EditorSection = { + id: string; + label: string; + count?: number; + hasError?: boolean; +}; + +const ACTIVE_LINE = 140; + +function useActiveSection(sections: EditorSection[]) { + const [active, setActive] = useState<string | null>(sections[0]?.id ?? null); + const ids = sections.map((section) => section.id).join("|"); + + useEffect(() => { + let frame = 0; + const measure = () => { + frame = 0; + let current: string | null = null; + for (const id of ids.split("|")) { + const el = document.getElementById(id); + if (el && el.getBoundingClientRect().top <= ACTIVE_LINE) current = id; + } + // At the very bottom the last short section may never reach + // the line; it's the one being read. + if (window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 4) { + current = ids.split("|").pop() ?? current; + } + setActive(current ?? ids.split("|")[0] ?? null); + }; + const onScroll = () => { + if (!frame) frame = requestAnimationFrame(measure); + }; + measure(); + window.addEventListener("scroll", onScroll, { passive: true }); + window.addEventListener("resize", onScroll); + return () => { + window.removeEventListener("scroll", onScroll); + window.removeEventListener("resize", onScroll); + if (frame) cancelAnimationFrame(frame); + }; + }, [ids]); + + return active; +} + +function jump(id: string) { + document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" }); +} + +function Label({ section }: { section: EditorSection }) { + return ( + <> + <span className="truncate">{section.label}</span> + {section.count != null && ( + <span className="text-xs text-[#4a6b72]/70">({section.count})</span> + )} + {section.hasError && ( + <span aria-label="needs attention" className="h-1.5 w-1.5 shrink-0 rounded-full bg-[#b3261e]" /> + )} + </> + ); +} + +/* The desktop column. Place it in the grid's first track. */ +export function SectionNav({ sections }: { sections: EditorSection[] }) { + const active = useActiveSection(sections); + + return ( + <nav aria-label="Sections" className="sticky top-6 hidden max-h-[calc(100vh-8rem)] overflow-y-auto lg:block"> + <p className="mb-2 px-3 text-xs font-semibold uppercase tracking-wider text-[#4a6b72]/70"> + On this page + </p> + <ul className="space-y-0.5 border-l border-[#138ba0]/15"> + {sections.map((section) => { + const lit = section.id === active; + return ( + <li key={section.id}> + <button + type="button" + onClick={() => jump(section.id)} + aria-current={lit ? "location" : undefined} + className={`-ml-px flex w-full items-center gap-1.5 border-l-2 px-3 py-1.5 text-left text-sm transition-colors ${ + lit + ? "border-[#138ba0] font-semibold text-[#138ba0]" + : "border-transparent text-[#4a6b72] hover:border-[#138ba0]/40 hover:text-[#138ba0]" + }`} + > + <Label section={section} /> + </button> + </li> + ); + })} + </ul> + </nav> + ); +} + +/* The phone and tablet bar. Sits above the form, sticks to the top. */ +export function SectionJump({ sections }: { sections: EditorSection[] }) { + const active = useActiveSection(sections); + + return ( + <div className="sticky top-0 z-20 -mx-6 mb-2 border-b border-[#138ba0]/15 bg-[#f6fbfc]/95 px-6 py-2 backdrop-blur lg:hidden"> + <label className="flex items-center gap-3 text-sm text-[#4a6b72]"> + <span className="shrink-0">Jump to</span> + <select + value={active ?? ""} + onChange={(e) => jump(e.target.value)} + className="w-full rounded-lg border border-[#4a6b72]/25 bg-white px-3 py-1.5 text-sm text-[#26454c] outline-none focus:border-[#138ba0]" + > + {sections.map((section) => ( + <option key={section.id} value={section.id}> + {section.label} + {section.count != null ? ` (${section.count})` : ""} + {section.hasError ? ", needs attention" : ""} + </option> + ))} + </select> + </label> + </div> + ); +} diff --git a/src/components/admin/fields.tsx b/src/components/admin/fields.tsx index 8f395d7..f397f22 100644 --- a/src/components/admin/fields.tsx +++ b/src/components/admin/fields.tsx @@ -7,7 +7,15 @@ Ordering is array position (the server writes sort_order from the index), so moving a row is a splice, not a number to - hand-edit. Rows can be dragged by the handle or moved with the + hand-edit. + + Rows fold to their title line. They start folded, so a long + collection (the front page's slides and paths) reads as a list + rather than a wall of fields; a row just added starts open, and + one the server rejected opens itself so the error can't hide. + Which rows are open is a set of indices, remapped by every move, + insert and removal here, so it survives a save (which replaces + every row object but keeps their order). Rows can be dragged by the handle or moved with the arrow buttons; the arrows are the keyboard path and stay whether or not a pointer is in use. @@ -246,9 +254,42 @@ export function FieldGrid({ children }) { /* ── Repeater ────────────────────────────────────────────────── */ -export function Repeater({ spec, rows, options, errors, errorPrefix, onChange }) { +/* Where each old index ends up after a change to the list, or -1 + when that row is gone. Used to carry the open set across it. */ +function remapOpen(open: Set<number>, where: (index: number) => number) { + const next = new Set<number>(); + for (const index of open) { + const moved = where(index); + if (moved >= 0) next.add(moved); + } + return next; +} + +export function Repeater({ + spec, + rows, + options, + errors, + errorPrefix, + onChange, + className = "mt-8", +}: any) { const list = rows ?? []; + const [open, setOpen] = useState<Set<number>>(() => new Set()); + const hasError = (index) => + Object.keys(errors ?? {}).some( + (key) => errors[key] && key.startsWith(`${errorPrefix}${index}.`), + ); + const isOpen = (index) => open.has(index) || hasError(index); + const toggle = (index) => + setOpen((prev) => { + const next = new Set(prev); + if (next.has(index)) next.delete(index); + else next.add(index); + return next; + }); + // Which row is in flight, and which one it's currently over. // Both are per-Repeater, which is what keeps a drag inside a // nested collection from being accepted by the outer one. @@ -264,6 +305,9 @@ export function Repeater({ spec, rows, options, errors, errorPrefix, onChange }) if (target < 0 || target >= list.length) return; const next = [...list]; [next[index], next[target]] = [next[target], next[index]]; + setOpen((prev) => + remapOpen(prev, (i) => (i === index ? target : i === target ? index : i)), + ); onChange(next); }; @@ -272,22 +316,63 @@ export function Repeater({ spec, rows, options, errors, errorPrefix, onChange }) const next = [...list]; const [moved] = next.splice(from, 1); next.splice(to, 0, moved); + setOpen((prev) => + remapOpen(prev, (i) => { + if (i === from) return to; + if (from < to && i > from && i <= to) return i - 1; + if (from > to && i >= to && i < from) return i + 1; + return i; + }), + ); onChange(next); }; + const add = () => { + setOpen((prev) => new Set(prev).add(list.length)); + onChange([...list, { ...spec.blank }]); + }; + + const removeAt = (index) => { + setOpen((prev) => remapOpen(prev, (i) => (i === index ? -1 : i > index ? i - 1 : i))); + onChange(list.filter((_, i) => i !== index)); + }; + const endDrag = () => { setDragIndex(null); setOverIndex(null); }; return ( - <section className="mt-8"> - <div className="flex items-center justify-between"> - <h3 className="text-base font-semibold text-[#26454c]">{spec.label}</h3> + <section className={className}> + <div className="flex flex-wrap items-center gap-3"> + <h3 className="text-base font-semibold text-[#26454c]"> + {spec.label} + {list.length > 0 && ( + <span className="ml-2 text-sm font-normal text-[#4a6b72]/80">{list.length}</span> + )} + </h3> + {list.length > 1 && ( + <div className="flex gap-3 text-xs text-[#4a6b72]"> + <button + type="button" + onClick={() => setOpen(new Set(list.map((_, i) => i)))} + className="hover:text-[#138ba0] hover:underline" + > + Expand all + </button> + <button + type="button" + onClick={() => setOpen(new Set())} + className="hover:text-[#138ba0] hover:underline" + > + Collapse all + </button> + </div> + )} <button type="button" - onClick={() => onChange([...list, { ...spec.blank }])} - className="rounded-full border border-[#138ba0] px-3 py-1 text-sm font-medium text-[#138ba0] transition-colors hover:bg-[#eef9fb]" + onClick={add} + className="ml-auto rounded-full border border-[#138ba0] px-3 py-1 text-sm font-medium text-[#138ba0] transition-colors hover:bg-[#eef9fb]" > {spec.addLabel ?? "Add"} </button> @@ -301,6 +386,7 @@ export function Repeater({ spec, rows, options, errors, errorPrefix, onChange }) {list.map((row, index) => { const dragging = dragIndex === index; const over = overIndex === index && dragIndex !== null && !dragging; + const expanded = isOpen(index); return ( <div @@ -325,14 +411,14 @@ export function Repeater({ spec, rows, options, errors, errorPrefix, onChange }) endDrag(); }} className={ - "rounded-xl border bg-[#f6fbfc] p-4 transition-colors " + + `rounded-xl border bg-[#f6fbfc] ${expanded ? "p-4" : "px-4 py-2.5"} transition-colors ` + (over ? "border-[#138ba0] ring-2 ring-[#138ba0]/25 " : "border-[#4a6b72]/20 ") + (dragging ? "opacity-50" : "") } > - <div className="mb-3 flex items-center gap-2"> + <div className={`flex items-center gap-2 ${expanded ? "mb-3" : ""}`}> <span draggable onDragStart={(e) => { @@ -353,11 +439,29 @@ export function Repeater({ spec, rows, options, errors, errorPrefix, onChange }) ⠿ </span> - <span className="text-sm font-medium text-[#26454c]"> - {spec.title ? spec.title(row, options) : `#${index + 1}`} - </span> + <button + type="button" + onClick={() => toggle(index)} + aria-expanded={expanded} + className="flex min-w-0 flex-1 items-center gap-2 text-left text-sm font-medium text-[#26454c] hover:text-[#138ba0]" + > + <span + aria-hidden="true" + className={`inline-block text-xs text-[#4a6b72] transition-transform ${ + expanded ? "rotate-90" : "" + }`} + > + ▶ + </span> + <span className="truncate"> + {spec.title ? spec.title(row, options) : `#${index + 1}`} + </span> + {!expanded && hasError(index) && ( + <span className="text-xs text-[#b3261e]">needs attention</span> + )} + </button> - <div className="ml-auto flex gap-1"> + <div className="ml-auto flex shrink-0 gap-1"> <IconButton label="Move up" onClick={() => move(index, -1)} @@ -375,39 +479,44 @@ export function Repeater({ spec, rows, options, errors, errorPrefix, onChange }) <IconButton label="Remove" danger - onClick={() => onChange(list.filter((_, i) => i !== index))} + onClick={() => removeAt(index)} > ✕ </IconButton> </div> </div> - <FieldGrid> - {spec.fields.map((field) => ( - <Field - key={field.path} - field={field} - row={row} - value={row[field.path]} - options={options} - error={errors?.[`${errorPrefix}${index}.${field.path}`]} - onChange={(value) => update(index, { ...row, [field.path]: value })} - /> - ))} - </FieldGrid> + {expanded && ( + <> + <FieldGrid> + {spec.fields.map((field) => ( + <Field + key={field.path} + field={field} + row={row} + value={row[field.path]} + options={options} + error={errors?.[`${errorPrefix}${index}.${field.path}`]} + onChange={(value) => update(index, { ...row, [field.path]: value })} + /> + ))} + </FieldGrid> - {(spec.children ?? []).map((nested) => ( - <div key={nested.key} className="mt-4 border-t border-[#4a6b72]/15 pt-2"> - <Repeater - spec={nested} - rows={row[nested.key]} - options={options} - errors={errors} - errorPrefix={`${errorPrefix}${index}.${nested.key}.`} - onChange={(value) => update(index, { ...row, [nested.key]: value })} - /> - </div> - ))} + {(spec.children ?? []).map((nested) => ( + <div key={nested.key} className="mt-4 border-t border-[#4a6b72]/15 pt-4"> + <Repeater + spec={nested} + rows={row[nested.key]} + options={options} + errors={errors} + errorPrefix={`${errorPrefix}${index}.${nested.key}.`} + className="" + onChange={(value) => update(index, { ...row, [nested.key]: value })} + /> + </div> + ))} + </> + )} </div> ); })} diff --git a/src/lib/adminWidth.tsx b/src/lib/adminWidth.tsx new file mode 100644 index 0000000..3a3e2fe --- /dev/null +++ b/src/lib/adminWidth.tsx @@ -0,0 +1,26 @@ +/* ═══════════════════════════════════════════════════════════════ + ADMIN PAGE WIDTH + + 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. + Like the title (adminTitle.tsx), the page asks and the layout + decides, so AdminLayout stays the one place that sets <main>'s + width. + + Clears on unmount, so leaving the editor puts the list pages + back to their usual width. + ═══════════════════════════════════════════════════════════════ */ + +import { createContext, useContext, useEffect } from "react"; + +export const AdminWidthContext = createContext<((wide: boolean) => void) | null>(null); + +export function useWideAdminPage() { + const setWide = useContext(AdminWidthContext); + + useEffect(() => { + if (!setWide) return undefined; + setWide(true); + return () => setWide(false); + }, [setWide]); +} diff --git a/src/pages/admin/AdminLayout.tsx b/src/pages/admin/AdminLayout.tsx index 7bd1932..a3b5d2d 100644 --- a/src/pages/admin/AdminLayout.tsx +++ b/src/pages/admin/AdminLayout.tsx @@ -20,6 +20,7 @@ import { 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 { SITE_VERSION } from "../../lib/version.ts"; import { ROLE_LABELS, isSuper } from "../../lib/roles.ts"; import nguLogo from "../../assets/NGU_Logo.svg"; @@ -60,6 +61,10 @@ 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); + useEffect(() => { // Sections only exist in the CMS. Home and Panel already say // what they are in the area title; "Panel | NGU Admin Panel" @@ -159,9 +164,11 @@ export default function AdminLayout() { {/* flex-1 rather than a fixed height: the footer sits at the bottom of a short page and below the content of a long one, without ever floating over it. */} - <main className="mx-auto w-full max-w-5xl flex-1 px-6 py-10"> + <main className={`mx-auto w-full flex-1 px-6 py-10 ${wide ? "max-w-[82rem]" : "max-w-5xl"}`}> <AdminTitleContext.Provider value={titleContext}> - <Outlet /> + <AdminWidthContext.Provider value={setWide}> + <Outlet /> + </AdminWidthContext.Provider> </AdminTitleContext.Provider> </main> diff --git a/src/pages/admin/EntityEdit.tsx b/src/pages/admin/EntityEdit.tsx index 5511ce8..7cf4fc4 100644 --- a/src/pages/admin/EntityEdit.tsx +++ b/src/pages/admin/EntityEdit.tsx @@ -33,6 +33,12 @@ None of this is protection. The server refuses the request; this only decides whether to draw a button that would be refused. + The page is laid out as sections: the URL ID, each field group, + then each child collection in a card of its own. SectionNav lists + them (a sticky column on wide screens, a "Jump to" bar below lg), + derived here from the manifest, so no descriptor declares a nav. + The editor asks the layout for extra width to fit it. + slugFrom may name one field or several. Most ids are unique because the name is: two organizations aren't both called Northwest. Team ids are the exception: teams.id is a global @@ -46,9 +52,21 @@ import { useNavigate, useParams } from "react-router-dom"; import { get, post, patch, del, ApiError } from "../../lib/api.ts"; import { isUnauthorized, useAuth } from "../../lib/auth.tsx"; import { useAdminDetail } from "../../lib/adminTitle.tsx"; +import { useWideAdminPage } from "../../lib/adminWidth.tsx"; import { ADMIN_ENTITIES, slugify } from "../../lib/adminSchema.ts"; import { atLeast } from "../../lib/roles.ts"; import { Field, FieldGrid, Repeater, getPath, setPath } from "../../components/admin/fields.tsx"; +import { + SectionJump, + SectionNav, + type EditorSection, +} from "../../components/admin/SectionNav.tsx"; + +/* One card per section. scroll-mt clears the sticky "Jump to" bar + below lg, and leaves a little air above the card on desktop. */ +const CARD = "mt-6 scroll-mt-16 rounded-2xl border border-[#138ba0]/20 bg-white p-5 lg:scroll-mt-6"; + +const sectionId = (name) => `section-${slugify(name)}`; /* A foreign key refusing to budge is the most common way a save or delete fails here, and SQLite's own wording explains nothing to @@ -66,6 +84,8 @@ export default function EntityEdit() { const navigate = useNavigate(); const { user } = useAuth(); + useWideAdminPage(); + const isNew = id === "new"; const canWrite = atLeast(user, "editor"); const canDelete = atLeast(user, "admin"); @@ -302,6 +322,32 @@ export default function EntityEdit() { const visible = (when) => !when || getPath(form, when.path) === when.value; + const groups = manifest.groups.filter((group) => visible(group.when)); + const shownChildren = children.filter((child) => visible(child.when)); + const childHasError = (key) => + Object.keys(errors).some((path) => errors[path] && path.startsWith(`${key}.`)); + + // A singleton's only header box is "Last saved", and a new + // auto-id record has no box at all: neither is worth a nav entry. + const idSection = !singleton && (!autoId || !isNew); + + const sections: EditorSection[] = [ + ...(idSection + ? [{ id: "section-url-id", label: manifest.idLabel, hasError: Boolean(errors.id) }] + : []), + ...groups.map((group) => ({ + id: sectionId(group.legend), + label: group.legend, + hasError: group.fields.some((field) => errors[field.path]), + })), + ...shownChildren.map((child) => ({ + id: sectionId(`${child.key}-list`), + label: child.label, + count: (form[child.key] ?? []).length, + hasError: childHasError(child.key), + })), + ]; + return ( <div className="pb-24"> {!singleton && ( @@ -318,18 +364,29 @@ export default function EntityEdit() { {isNew ? `New ${manifest.singular}` : heading} </h1> + <div className="mt-4"> + <SectionJump sections={sections} /> + </div> + + <div className="lg:grid lg:grid-cols-[13rem_minmax(0,1fr)] lg:items-start lg:gap-10"> + <div className="lg:pt-6"> + <SectionNav sections={sections} /> + </div> + + <div className="min-w-0"> + {/* Slug. An auto-id entity has nothing to ask for on create, and nothing editable afterwards, so it gets a plain line rather than a disabled box pretending to be a field. */} {singleton ? ( updatedAt && ( - <div className="mt-6 rounded-2xl border border-[#138ba0]/20 bg-white p-5"> + <div className={CARD}> <p className="text-sm text-[#4a6b72]">Last saved {updatedAt}</p> </div> ) ) : autoId ? ( !isNew && ( - <div className="mt-6 rounded-2xl border border-[#138ba0]/20 bg-white p-5"> + <div id="section-url-id" className={CARD}> <p className="text-sm text-[#4a6b72]"> {manifest.idLabel} #{form.id} {form.updated_at && <> · last saved {form.updated_at}</>} @@ -337,7 +394,7 @@ export default function EntityEdit() { </div> ) ) : ( - <div className="mt-6 rounded-2xl border border-[#138ba0]/20 bg-white p-5"> + <div id="section-url-id" className={CARD}> <Field field={{ path: "id", @@ -368,11 +425,8 @@ export default function EntityEdit() { )} {/* Field groups */} - {manifest.groups.filter((group) => visible(group.when)).map((group) => ( - <section - key={group.legend} - className="mt-6 rounded-2xl border border-[#138ba0]/20 bg-white p-5" - > + {groups.map((group) => ( + <section key={group.legend} id={sectionId(group.legend)} className={CARD}> <h2 className="text-lg font-semibold text-[#26454c]">{group.legend}</h2> {group.note && <p className="mt-1 text-sm text-[#4a6b72]">{group.note}</p>} <div className="mt-4"> @@ -393,25 +447,23 @@ export default function EntityEdit() { </section> ))} - {/* Child collections. Awards own none, so the panel would be - an empty white box; skip it rather than render it. */} - {children.some((child) => visible(child.when)) && ( - <div className="mt-6 rounded-2xl border border-[#138ba0]/20 bg-white p-5"> - {children - .filter((child) => visible(child.when)) - .map((child) => ( - <Repeater - key={child.key} - spec={child} - rows={form[child.key]} - options={options} - errors={errors} - errorPrefix={`${child.key}.`} - onChange={(rows) => setForm((prev) => ({ ...prev, [child.key]: rows }))} - /> - ))} + {/* Child collections, a card each, so the front page's slides, + stats and paths read as separate things. */} + {shownChildren.map((child) => ( + <div key={child.key} id={sectionId(`${child.key}-list`)} className={CARD}> + <Repeater + spec={child} + rows={form[child.key]} + options={options} + errors={errors} + errorPrefix={`${child.key}.`} + className="" + onChange={(rows) => setForm((prev) => ({ ...prev, [child.key]: rows }))} + /> </div> - )} + ))} + </div> + </div> {/* Sticky action bar */} <div className="fixed inset-x-0 bottom-0 border-t border-[#138ba0]/20 bg-white/95 backdrop-blur"> From 960c85461104326e6c78e71d7fe128a8d2bef541 Mon Sep 17 00:00:00 2001 From: Zaldimmar <Zaldimmar@gmail.com> Date: Sun, 27 Sep 2026 15:36:02 -0500 Subject: [PATCH 14/22] Keep the editor's section nav in view while scrolling The nav was sticky inside a wrapper only as tall as itself, so it had nowhere to travel and scrolled away. The grid cell now sticks instead, and the mobile "Jump to" bar sits straight in the page for the same reason. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/components/admin/SectionNav.tsx | 7 ++++--- src/pages/admin/EntityEdit.tsx | 10 ++++++---- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/components/admin/SectionNav.tsx b/src/components/admin/SectionNav.tsx index 9ef994a..8a11e1e 100644 --- a/src/components/admin/SectionNav.tsx +++ b/src/components/admin/SectionNav.tsx @@ -80,12 +80,13 @@ function Label({ section }: { section: EditorSection }) { ); } -/* The desktop column. Place it in the grid's first track. */ +/* The desktop column. Place it in the grid's first track, in a cell + that is itself sticky (see EntityEdit). */ export function SectionNav({ sections }: { sections: EditorSection[] }) { const active = useActiveSection(sections); return ( - <nav aria-label="Sections" className="sticky top-6 hidden max-h-[calc(100vh-8rem)] overflow-y-auto lg:block"> + <nav aria-label="Sections" className="hidden max-h-[calc(100vh-8rem)] overflow-y-auto lg:block"> <p className="mb-2 px-3 text-xs font-semibold uppercase tracking-wider text-[#4a6b72]/70"> On this page </p> @@ -119,7 +120,7 @@ export function SectionJump({ sections }: { sections: EditorSection[] }) { const active = useActiveSection(sections); return ( - <div className="sticky top-0 z-20 -mx-6 mb-2 border-b border-[#138ba0]/15 bg-[#f6fbfc]/95 px-6 py-2 backdrop-blur lg:hidden"> + <div className="sticky top-0 z-20 -mx-6 mt-4 mb-2 border-b border-[#138ba0]/15 bg-[#f6fbfc]/95 px-6 py-2 backdrop-blur lg:hidden"> <label className="flex items-center gap-3 text-sm text-[#4a6b72]"> <span className="shrink-0">Jump to</span> <select diff --git a/src/pages/admin/EntityEdit.tsx b/src/pages/admin/EntityEdit.tsx index 7cf4fc4..aa2d85f 100644 --- a/src/pages/admin/EntityEdit.tsx +++ b/src/pages/admin/EntityEdit.tsx @@ -364,12 +364,14 @@ export default function EntityEdit() { {isNew ? `New ${manifest.singular}` : heading} </h1> - <div className="mt-4"> - <SectionJump sections={sections} /> - </div> + {/* Straight in the page, not wrapped: a sticky element only + travels within its parent, so its parent has to be tall. */} + <SectionJump sections={sections} /> <div className="lg:grid lg:grid-cols-[13rem_minmax(0,1fr)] lg:items-start lg:gap-10"> - <div className="lg:pt-6"> + {/* The grid cell is what sticks: it spans the grid, where the + nav inside it would only span itself and have nowhere to go. */} + <div className="lg:sticky lg:top-0 lg:pt-6"> <SectionNav sections={sections} /> </div> From d4f65d93b4f4a2b9f6b169e2cbb1805ac507a7ce Mon Sep 17 00:00:00 2001 From: Zaldimmar <Zaldimmar@gmail.com> Date: Sun, 27 Sep 2026 15:56:29 -0500 Subject: [PATCH 15/22] Add a Featured Content section to the front page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Front page → Featured cards (migration 030) holds cards of three kinds: a record on the site, whose title, picture and link fill in from the record; a link, with a Fetch preview button that reads the page's title, description and preview image into the media library; and a video, drawn as a thumbnail that loads the player when pressed. A 'featured' section draws them. The cards are shared: featured_cards is owned polymorphically and FeaturedCards.tsx draws them, ready for the Community blog. Deleting a record removes its cards; an unpublished record's card is hidden. The preview fetch only goes to public http(s) addresses on standard ports, pinned to the vetted IP, with each redirect checked again. Along the way: repeater fields can show by another field's value (a hidden one is cleared), a CHECK named as a sentence is shown as the error, and the timeline's record list is now record_refs for both. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/updating-data-in-code.md | 5 +- server/src/admin-crud.js | 9 +- server/src/admin-schema.js | 27 ++- server/src/linkPreview.js | 236 +++++++++++++++++++ server/src/migrations/030_featured_cards.sql | 167 +++++++++++++ server/src/routes/home.js | 8 +- server/src/routes/media.js | 99 ++++++-- server/src/shape.js | 110 +++++++++ src/components/FeaturedCards.tsx | 190 +++++++++++++++ src/components/admin/MediaLibrary.tsx | 89 ++++++- src/components/admin/fields.tsx | 73 ++++-- src/lib/adminSchema.ts | 75 +++++- src/lib/embeds.ts | 36 +++ src/lib/media.ts | 7 + src/lib/useFrontPage.ts | 16 ++ src/pages/Home.tsx | 11 +- src/pages/sections/home/FeaturedBand.tsx | 32 +++ 17 files changed, 1140 insertions(+), 50 deletions(-) create mode 100644 server/src/linkPreview.js create mode 100644 server/src/migrations/030_featured_cards.sql create mode 100644 src/components/FeaturedCards.tsx create mode 100644 src/pages/sections/home/FeaturedBand.tsx diff --git a/docs/updating-data-in-code.md b/docs/updating-data-in-code.md index b473c46..86b2c5f 100644 --- a/docs/updating-data-in-code.md +++ b/docs/updating-data-in-code.md @@ -181,8 +181,10 @@ also in `admin-schema.js` and a CHECK): | Front page → Countdown → Only this type | retreat, class, workshop, meeting, other | **yes** | `server/src/routes/home.js` (picks the countdown event). The same values as Events → Type, so adding a type widens both CHECKs. | | Front page → Background | brand, photos | **yes** | `HeroStage.tsx` | | Front page → Feature | none, livestream, video | **yes** | `HeroStage.tsx` | -| Front page → Sections → Section | countdown, retreats, calendar, stats, timeline, connect | **yes**, `FRONT_PAGE_SECTIONS` | `SECTIONS` in `src/pages/Home.tsx`; see [below](#front-page-section-names) | +| Front page → Sections → Section | countdown, retreats, calendar, stats, timeline, connect, featured | **yes**, `FRONT_PAGE_SECTIONS` | `SECTIONS` in `src/pages/Home.tsx`; see [below](#front-page-section-names) | | Front page → Stats → Number Source | manual, years_since, regions, … | **yes**, `STAT_SOURCES` | `STAT_QUERIES` in `server/src/routes/home.js`; see [below](#front-page-stat-sources) | +| Front page → Featured cards → Card type | record, link, video | **yes**, `FEATURED_KINDS` | `FeaturedCards.tsx` (how each kind draws), `loadFeaturedCards` in `server/src/shape.js` | +| Front page → Featured cards → Record type | event, organization, person, team, award | no | `FEATURED_REFS` in `server/src/shape.js` (what each fills the card with); the triggers in `030_featured_cards.sql` | | Every list → Published / Listed / Featured filter | 1, 0 | **yes** | n/a | "No, shows values" means the dropdown currently shows the raw value, @@ -197,6 +199,7 @@ code): | Event → Scope (+ list filter); Front page → Countdown → Only this scope | `event_scopes` | the `event_scopes` table (migration only) | | Event hosts → Organization; affiliations; team and award "Organization" / "Awarded by"; person → Home organization | `organizations` | organizations, labelled by name | | Event hosts / event people / team members / timeline people → Person | `people` | people | +| Timeline → Record; Featured cards → Record | `record_refs` | every event, organization, award, person and team, narrowed by the type picked beside it | | Affiliations → Team | `teams` | teams, filtered to the chosen organization | | Person awards → Award | `awards` | awards, labelled "Award (Organization)" | | Person awards → Presented at; Front page → Count down to | `events` | events | diff --git a/server/src/admin-crud.js b/server/src/admin-crud.js index 2dd977d..6fa3164 100644 --- a/server/src/admin-crud.js +++ b/server/src/admin-crud.js @@ -628,9 +628,14 @@ function wrapDbErrors(fn) { ); } - const check = /CHECK constraint failed: (\w+)/.exec(message); + // A CHECK named with a sentence (CONSTRAINT "A link or video + // card needs a URL." CHECK ...) is its own message. Anything else + // is named by the first word of its expression. + const check = /CHECK constraint failed: (.+)$/.exec(message); if (check) { - throw new HttpError(422, `A value was rejected by the "${check[1]}" rule.`); + const name = check[1].trim(); + if (/\s/.test(name) && /[.!?]$/.test(name)) throw new HttpError(422, name); + throw new HttpError(422, `A value was rejected by the "${name.split(/\W/)[0]}" rule.`); } // The polymorphic tables stand in for a foreign key with a diff --git a/server/src/admin-schema.js b/server/src/admin-schema.js index 95d227b..09ac3fd 100644 --- a/server/src/admin-schema.js +++ b/server/src/admin-schema.js @@ -122,6 +122,25 @@ const timelineExtension = (refKind) => ({ ], }); +/* Featured cards (030_featured_cards.sql): polymorphic like links, + so the Community blog can own a set too. */ +const featuredCardsChild = (ownerKind) => ({ + key: "featured_cards", + table: "featured_cards", + owner: { column: "owner_id", kindColumn: "owner_kind", kindValue: ownerKind }, + order: "sort_order", + columns: [ + enumeration("kind", ["record", "link", "video"], { required: true }), + enumeration("ref_kind", ["event", "organization", "person", "team", "award"]), + text("ref_id"), + text("url"), + text("eyebrow"), + text("title"), + text("blurb"), + text("image"), + ], +}); + /* The two polymorphic collections, parameterised by owner_kind. */ const linksChild = (ownerKind) => ({ key: "links", @@ -725,7 +744,7 @@ const frontPage = { columns: [ enumeration( "section", - ["countdown", "retreats", "calendar", "stats", "timeline", "connect"], + ["countdown", "retreats", "calendar", "stats", "timeline", "connect", "featured"], { required: true }, ), text("title"), @@ -756,6 +775,7 @@ const frontPage = { text("note"), ], }, + featuredCardsChild("front_page"), { key: "paths", table: "front_page_paths", @@ -806,10 +826,11 @@ export const OPTION_QUERIES = { "SELECT id, name AS label, org_id FROM teams ORDER BY org_id, sort_order, name", // One flat list the ref picker filters by ref_kind, rather than five - // dropdowns of which four are always wrong. `kind` is the discriminator + // dropdowns of which four are always wrong. The timeline and the + // featured cards both pick from it. `kind` is the discriminator // the client's filterBy matches on; org_kind disambiguates the label, // since a region and a chapter can share a name. - timeline_refs: ` + record_refs: ` SELECT 'event' AS kind, id, title AS label FROM events UNION ALL SELECT 'organization', id, name || ' (' || kind || ')' FROM organizations diff --git a/server/src/linkPreview.js b/server/src/linkPreview.js new file mode 100644 index 0000000..71a8187 --- /dev/null +++ b/server/src/linkPreview.js @@ -0,0 +1,236 @@ +/* ═══════════════════════════════════════════════════════════════ + LINK PREVIEW + + Reads a page's title, description and preview image (og:, then + twitter:, then <title>) for the featured card editor's "Fetch + preview" button. The image is downloaded and put through the + media library like any upload, so the card never hotlinks + someone else's server. + + This makes the server request a URL an editor typed, so it is + careful about where it goes: + + · http and https only, on ports 80 and 443 + · the host is resolved first, and refused if any address is + private, loopback, link-local, carrier-grade NAT, multicast + or unspecified (so no 127.0.0.1, no 10.x, no metadata + endpoint at 169.254.169.254) + · the connection goes to the address that was checked, not a + fresh lookup, so DNS can't change its answer in between + · redirects are followed by hand, at most MAX_REDIRECTS, and + every hop is checked again + · TIMEOUT_MS per request, and at most MAX_HTML_BYTES of page + or MAX_UPLOAD_BYTES of image is read + + Editors and up only (routes/media.js). + ═══════════════════════════════════════════════════════════════ */ + +import { lookup } from "node:dns/promises"; +import http from "node:http"; +import https from "node:https"; +import net from "node:net"; + +import { MAX_UPLOAD_BYTES, MediaError } from "./media.js"; + +const TIMEOUT_MS = 8000; +const MAX_REDIRECTS = 4; +const MAX_HTML_BYTES = 1024 * 1024; +const USER_AGENT = "NGU-LinkPreview/1.0 (+https://nextgenerationofunity.org)"; + +/* ── Address checks ────────────────────────────────────────── */ + +function ipv4Blocked(ip) { + const [a, b] = ip.split(".").map(Number); + return ( + a === 0 || + a === 10 || + a === 127 || + (a === 100 && b >= 64 && b <= 127) || + (a === 169 && b === 254) || + (a === 172 && b >= 16 && b <= 31) || + (a === 192 && b === 168) || + (a === 192 && b === 0) || + (a === 198 && (b === 18 || b === 19)) || + a >= 224 + ); +} + +function ipBlocked(ip) { + if (net.isIPv4(ip)) return ipv4Blocked(ip); + const lower = ip.toLowerCase(); + // An IPv4 address written as IPv6 is judged as the IPv4 it is. + const mapped = lower.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/); + if (mapped) return ipv4Blocked(mapped[1]); + return ( + lower === "::" || + lower === "::1" || + /^f[cd]/.test(lower) || // fc00::/7 unique local + /^fe[89ab]/.test(lower) || // fe80::/10 link-local + /^ff/.test(lower) // multicast + ); +} + +async function vet(raw) { + let url; + try { + url = new URL(raw); + } catch { + throw new MediaError(400, "That isn't a valid link."); + } + if (url.protocol !== "http:" && url.protocol !== "https:") { + throw new MediaError(400, "Only http and https links can be previewed."); + } + if (url.port && url.port !== "80" && url.port !== "443") { + throw new MediaError(400, "Only links on the standard ports can be previewed."); + } + if (url.username || url.password) { + throw new MediaError(400, "Links with a username or password can't be previewed."); + } + + const host = url.hostname.replace(/^\[|\]$/g, ""); + let addresses; + try { + addresses = net.isIP(host) ? [{ address: host, family: net.isIP(host) }] : await lookup(host, { all: true }); + } catch { + throw new MediaError(400, "That site couldn't be found."); + } + if (addresses.length === 0 || addresses.some(({ address }) => ipBlocked(address))) { + throw new MediaError(400, "That address can't be previewed."); + } + return { url, address: addresses[0] }; +} + +/* ── One request, pinned to the vetted address ─────────────── */ + +function requestOnce({ url, address }, { maxBytes, accept }) { + const client = url.protocol === "https:" ? https : http; + + return new Promise((resolve, reject) => { + const req = client.request( + url, + { + method: "GET", + headers: { "User-Agent": USER_AGENT, Accept: accept }, + timeout: TIMEOUT_MS, + // Hand back the address we already checked instead of + // resolving again. TLS still verifies against the hostname. + lookup: (_host, options, callback) => { + if (options?.all) callback(null, [address]); + else callback(null, address.address, address.family); + }, + }, + (res) => { + const status = res.statusCode ?? 0; + if (status >= 300 && status < 400 && res.headers.location) { + res.resume(); + resolve({ redirect: new URL(res.headers.location, url).toString() }); + return; + } + if (status < 200 || status >= 300) { + res.resume(); + reject(new MediaError(400, `The page answered ${status}.`)); + return; + } + + const chunks = []; + let size = 0; + res.on("data", (chunk) => { + size += chunk.length; + if (size > maxBytes) { + // A page's head is at the top; stop reading and use what + // arrived. An image that's too big is refused outright. + res.destroy(); + if (accept.startsWith("text/html")) { + resolve({ body: Buffer.concat(chunks), type: res.headers["content-type"] ?? "" }); + } else { + reject(new MediaError(413, "The preview image is too large.")); + } + return; + } + chunks.push(chunk); + }); + res.on("end", () => + resolve({ body: Buffer.concat(chunks), type: res.headers["content-type"] ?? "" }), + ); + res.on("error", reject); + }, + ); + req.on("timeout", () => req.destroy(new MediaError(504, "The site took too long to answer."))); + req.on("error", (err) => + reject(err instanceof MediaError ? err : new MediaError(400, "That site couldn't be reached.")), + ); + req.end(); + }); +} + +async function safeGet(raw, options) { + let next = raw; + for (let hop = 0; hop <= MAX_REDIRECTS; hop++) { + const target = await vet(next); + const result = await requestOnce(target, options); + if (!result.redirect) return { ...result, url: target.url }; + next = result.redirect; + } + throw new MediaError(400, "The link redirects too many times."); +} + +/* ── Reading the page ──────────────────────────────────────── */ + +const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " }; + +function decode(text) { + return text + .replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCodePoint(parseInt(hex, 16))) + .replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(Number(dec))) + .replace(/&([a-z]+);/gi, (whole, name) => ENTITIES[name.toLowerCase()] ?? whole) + .replace(/\s+/g, " ") + .trim(); +} + +function attr(tag, name) { + const match = tag.match(new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i")); + return match ? (match[1] ?? match[2] ?? match[3] ?? "") : null; +} + +function readMeta(html) { + const meta = {}; + for (const tag of html.match(/<meta\b[^>]*>/gi) ?? []) { + const key = (attr(tag, "property") ?? attr(tag, "name") ?? "").toLowerCase(); + const content = attr(tag, "content"); + if (key && content != null && !(key in meta)) meta[key] = decode(content); + } + const title = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1]; + return { + title: meta["og:title"] || meta["twitter:title"] || (title ? decode(title) : null) || null, + description: + meta["og:description"] || meta["twitter:description"] || meta.description || null, + image: meta["og:image:secure_url"] || meta["og:image"] || meta["twitter:image"] || null, + }; +} + +/* The page's title, description and image URL. */ +export async function previewLink(raw) { + const page = await safeGet(raw, { + maxBytes: MAX_HTML_BYTES, + accept: "text/html,application/xhtml+xml;q=0.9,*/*;q=0.1", + }); + if (!/html/i.test(page.type)) { + throw new MediaError(400, "That link isn't a web page."); + } + const meta = readMeta(page.body.toString("utf8")); + let image = null; + if (meta.image) { + try { + image = new URL(meta.image, page.url).toString(); + } catch { + image = null; + } + } + return { title: meta.title, description: meta.description, image }; +} + +/* The bytes of a preview image, for media.store(). */ +export async function fetchImage(raw) { + const result = await safeGet(raw, { maxBytes: MAX_UPLOAD_BYTES, accept: "image/*" }); + return result.body; +} diff --git a/server/src/migrations/030_featured_cards.sql b/server/src/migrations/030_featured_cards.sql new file mode 100644 index 0000000..9776cae --- /dev/null +++ b/server/src/migrations/030_featured_cards.sql @@ -0,0 +1,167 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 030 FEATURED CARDS +-- +-- A row of cards that point somewhere: the front page's new +-- 'featured' band first, and the Community page's blog posts next. +-- One table for both, owned polymorphically like links and +-- content_blocks, so the card's shape and the code that draws it +-- are written once. owner_kind only allows 'front_page' today; +-- adding an owner is a rebuild of this table, which nothing +-- references, so it's a cheap one. +-- +-- A card is one of three kinds: +-- +-- record points at an event, organization, person, team or +-- award. Title, image and link come from that record at +-- read time, so renaming the event renames the card. +-- Any of title, blurb and image filled in here overrides. +-- link any URL, on the site or off it. Title and image are +-- the card's own (the editor can fetch them from the +-- page's preview tags). +-- video a YouTube, Vimeo or Facebook link, or a video file. +-- Drawn as a thumbnail that swaps in the player when +-- pressed. image overrides the thumbnail. +-- +-- ref_kind + ref_id is checked by the triggers below, the same way +-- timeline_entries' is, and a deleted record takes its cards with +-- it. An unpublished record's card is left out when read. +-- +-- Also: 'featured' joins front_page_sections.section. A CHECK can't +-- be altered in place, so that table is rebuilt. No view or trigger +-- names it, and nothing references it. +-- +-- PRAGMA user_version; -- reads 29 before this file +-- ═══════════════════════════════════════════════════════════════ + +CREATE TABLE front_page_sections_new ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + page_id TEXT NOT NULL REFERENCES front_page (id) ON DELETE CASCADE, + sort_order INTEGER NOT NULL DEFAULT 0, + section TEXT NOT NULL + CHECK (section IN ('countdown', 'retreats', 'calendar', 'stats', + 'timeline', 'connect', 'featured')), + title TEXT, + blurb TEXT, + is_hidden INTEGER NOT NULL DEFAULT 0 CHECK (is_hidden IN (0, 1)), + UNIQUE (page_id, section) +) STRICT; + +INSERT INTO front_page_sections_new (id, page_id, sort_order, section, title, blurb, is_hidden) +SELECT id, page_id, sort_order, section, title, blurb, is_hidden + FROM front_page_sections; + +DROP TABLE front_page_sections; + +ALTER TABLE front_page_sections_new RENAME TO front_page_sections; + + +CREATE TABLE featured_cards ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + owner_kind TEXT NOT NULL CHECK (owner_kind IN ('front_page')), + owner_id TEXT NOT NULL, + sort_order INTEGER NOT NULL DEFAULT 0, + + kind TEXT NOT NULL DEFAULT 'link' + CHECK (kind IN ('record', 'link', 'video')), + + ref_kind TEXT CHECK (ref_kind IN ('event', 'organization', 'person', 'team', 'award')), + ref_id TEXT, + url TEXT, + + eyebrow TEXT, -- 'Article', 'Watch' + title TEXT, + blurb TEXT, + image TEXT, -- '/uploads/…', a filename, or a URL + + CHECK ((ref_kind IS NULL) = (ref_id IS NULL)), + -- A record card needs its record; the other two need somewhere to + -- go. Named as sentences: the admin shows a sentence-shaped + -- constraint name as the error (wrapDbErrors in admin-crud.js). + CONSTRAINT "A record card needs a record to point at." + CHECK (kind != 'record' OR ref_kind IS NOT NULL), + CONSTRAINT "A link or video card needs a URL." + CHECK (kind = 'record' OR url IS NOT NULL) +) STRICT; + +CREATE INDEX featured_cards_owner_idx ON featured_cards (owner_kind, owner_id, sort_order); + + +-- ── Triggers last (see CLAUDE.md, Migrations) ── + +CREATE TRIGGER featured_cards_ref_exists +BEFORE INSERT ON featured_cards +BEGIN + SELECT CASE + WHEN new.ref_kind = 'event' + AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id) + THEN RAISE(ABORT, 'featured_cards: no such event') + WHEN new.ref_kind = 'organization' + AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id) + THEN RAISE(ABORT, 'featured_cards: no such organization') + WHEN new.ref_kind = 'person' + AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id) + THEN RAISE(ABORT, 'featured_cards: no such person') + WHEN new.ref_kind = 'team' + AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id) + THEN RAISE(ABORT, 'featured_cards: no such team') + WHEN new.ref_kind = 'award' + AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id) + THEN RAISE(ABORT, 'featured_cards: no such award') + END; +END; + +CREATE TRIGGER featured_cards_ref_exists_update +BEFORE UPDATE OF ref_kind, ref_id ON featured_cards +BEGIN + SELECT CASE + WHEN new.ref_kind = 'event' + AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id) + THEN RAISE(ABORT, 'featured_cards: no such event') + WHEN new.ref_kind = 'organization' + AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id) + THEN RAISE(ABORT, 'featured_cards: no such organization') + WHEN new.ref_kind = 'person' + AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id) + THEN RAISE(ABORT, 'featured_cards: no such person') + WHEN new.ref_kind = 'team' + AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id) + THEN RAISE(ABORT, 'featured_cards: no such team') + WHEN new.ref_kind = 'award' + AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id) + THEN RAISE(ABORT, 'featured_cards: no such award') + END; +END; + +-- A deleted record takes the cards that point at it. Separate +-- triggers rather than additions to the existing *_cleanup ones, so +-- this file doesn't have to drop and restate those. + +CREATE TRIGGER events_featured_cleanup +AFTER DELETE ON events +BEGIN + DELETE FROM featured_cards WHERE ref_kind = 'event' AND ref_id = old.id; +END; + +CREATE TRIGGER organizations_featured_cleanup +AFTER DELETE ON organizations +BEGIN + DELETE FROM featured_cards WHERE ref_kind = 'organization' AND ref_id = old.id; +END; + +CREATE TRIGGER people_featured_cleanup +AFTER DELETE ON people +BEGIN + DELETE FROM featured_cards WHERE ref_kind = 'person' AND ref_id = old.id; +END; + +CREATE TRIGGER teams_featured_cleanup +AFTER DELETE ON teams +BEGIN + DELETE FROM featured_cards WHERE ref_kind = 'team' AND ref_id = old.id; +END; + +CREATE TRIGGER awards_featured_cleanup +AFTER DELETE ON awards +BEGIN + DELETE FROM featured_cards WHERE ref_kind = 'award' AND ref_id = old.id; +END; diff --git a/server/src/routes/home.js b/server/src/routes/home.js index 9173b54..d09a465 100644 --- a/server/src/routes/home.js +++ b/server/src/routes/home.js @@ -33,11 +33,16 @@ event" (National + Retreat skips a sooner regional class). Null means any. They don't apply to a pinned event: the admin chose that one by name. + + ── Featured ── + The featured band's cards, record cards filled in from their + records (loadFeaturedCards in shape.js, which the Community + blog will share). ═══════════════════════════════════════════════════════════════ */ import { Hono } from "hono"; -import { asBool, shapeSeries } from "../shape.js"; +import { asBool, loadFeaturedCards, shapeSeries } from "../shape.js"; const home = new Hono(); @@ -200,6 +205,7 @@ home.get("/front-page", (c) => { sections, stats, paths, + featured: loadFeaturedCards(db, "front_page", PAGE_ID), countdown: shapeCountdown(next), }, }); diff --git a/server/src/routes/media.js b/server/src/routes/media.js index a0df5fa..285ee8d 100644 --- a/server/src/routes/media.js +++ b/server/src/routes/media.js @@ -6,6 +6,9 @@ keep_original) GET /media/:id/uses which records name this file DELETE /media/:id remove the row and the file + POST /link-preview a page's title, description and + preview image, the image saved into + the library ({ url } in, JSON body) Reading needs a session, uploading needs editor, deleting needs admin: the same ladder the entity routes use, so an editor can @@ -21,6 +24,7 @@ import { bodyLimit } from "hono/body-limit"; import { requireAuth, requireRole } from "../auth.js"; import { MAX_UPLOAD_BYTES, MediaError, PUBLIC_PREFIX, remove, store } from "../media.js"; +import { fetchImage, previewLink } from "../linkPreview.js"; const media = new Hono(); @@ -52,6 +56,34 @@ const SELECT = `SELECT m.*, u.name AS uploaded_by_name, u.email AS uploaded_by_e FROM media m LEFT JOIN admin_users u ON u.id = m.uploaded_by`; +/* Writes the file, then its row; a failed insert takes the file + back out so nothing is left on disk that the library can't see. */ +async function addToLibrary(db, buf, { originalName, keepOriginal, userId }) { + const stored = await store(buf, { keepOriginal }); + try { + const { lastInsertRowid } = db + .prepare( + `INSERT INTO media + (filename, original_name, content_type, bytes, width, height, processed, uploaded_by) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + ) + .run( + stored.filename, + (originalName || "upload").slice(0, 200), + stored.content_type, + stored.bytes, + stored.width, + stored.height, + stored.processed, + userId, + ); + return db.prepare(`${SELECT} WHERE m.id = ?`).get(lastInsertRowid); + } catch (err) { + await remove(stored.filename); + throw err; + } +} + media.get("/media", (c) => { const q = (c.req.query("q") ?? "").trim().slice(0, 100); const rows = c @@ -88,39 +120,54 @@ media.post( const file = body.file; if (!(file instanceof File)) return c.json({ error: "No file was sent." }, 400); - const stored = await store(Buffer.from(await file.arrayBuffer()), { + const row = await addToLibrary(db, Buffer.from(await file.arrayBuffer()), { + originalName: file.name, keepOriginal: body.keep_original === "1", + userId: user.id, }); - let row; - try { - const { lastInsertRowid } = db - .prepare( - `INSERT INTO media - (filename, original_name, content_type, bytes, width, height, processed, uploaded_by) - VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, - ) - .run( - stored.filename, - (file.name || "upload").slice(0, 200), - stored.content_type, - stored.bytes, - stored.width, - stored.height, - stored.processed, - user.id, - ); - row = db.prepare(`${SELECT} WHERE m.id = ?`).get(lastInsertRowid); - } catch (err) { - await remove(stored.filename); - throw err; - } - - console.log(`media ${stored.filename} uploaded by ${user.email}`); + console.log(`media ${row.filename} uploaded by ${user.email}`); return c.json({ media: shape(row) }, 201, NO_STORE); }, ); +/* The page's text comes back whatever happens to the image: a site + whose preview image is missing or refused still has a title. */ +media.post("/link-preview", requireRole("editor"), async (c) => { + const user = c.get("user"); + let url; + try { + ({ url } = await c.req.json()); + } catch { + return c.json({ error: "Expected a JSON body." }, 400); + } + if (typeof url !== "string" || !url.trim()) return c.json({ error: "No link given." }, 400); + + const page = await previewLink(url.trim()); + + let image = null; + let imageError = null; + if (page.image) { + try { + const row = await addToLibrary(c.get("db"), await fetchImage(page.image), { + originalName: `preview ${new URL(page.image).hostname}`, + keepOriginal: false, + userId: user.id, + }); + image = shape(row); + } catch (err) { + imageError = err instanceof MediaError ? err.message : "The preview image couldn't be saved."; + } + } + + console.log(`link preview ${url.trim().slice(0, 200)} by ${user.email}`); + return c.json( + { preview: { title: page.title, description: page.description, image, image_error: imageError } }, + 200, + NO_STORE, + ); +}); + /* Every TEXT column of every content table, searched for the exact path. Read from the live schema rather than a list of image columns, so a new image field is covered the day it's added. */ diff --git a/server/src/shape.js b/server/src/shape.js index 246d014..b8dbde4 100644 --- a/server/src/shape.js +++ b/server/src/shape.js @@ -166,4 +166,114 @@ export function shapeSeries(row) { }; } +/* ── Featured cards ──────────────────────────────────────────── + One owner's cards (the front page's, today), in order, with + each record card filled in from its record. Shared so the + Community blog's cards will come out the same shape. + + A record card's own title, blurb and image override the + record's. One query per kind that is actually referenced, so a + row of six cards is at most six queries. + + `image` is { file, kind }, like the timeline's logo: the record + tables keep bare filenames in different public/ directories, + and logoForKind in media.ts knows which is which. The kinds are + the ref kinds, plus 'event-background' and 'featured' (the + card's own image). An unpublished + record's card is dropped; an unlisted one's stays, since + featuring it is attaching it by hand. + ───────────────────────────────────────────────────────────── */ + +const FEATURED_REFS = { + event: { + sql: (marks) => + `SELECT id, title, tagline AS blurb, date_label AS eyebrow, + card_image, event_logo + FROM events WHERE is_published = 1 AND id IN (${marks})`, + image: (row) => + row.card_image + ? { file: row.card_image, kind: "event-background" } + : row.event_logo + ? { file: row.event_logo, kind: "event" } + : null, + }, + organization: { + sql: (marks) => + `SELECT id, name AS title, tagline AS blurb, kind AS org_kind, logo + FROM organizations WHERE is_published = 1 AND id IN (${marks})`, + image: (row) => (row.logo ? { file: row.logo, kind: "organization" } : null), + }, + person: { + sql: (marks) => + `SELECT id, display_name AS title, tagline AS blurb, photo + FROM people WHERE is_published = 1 AND id IN (${marks})`, + image: (row) => (row.photo ? { file: row.photo, kind: "person" } : null), + }, + team: { + sql: (marks) => + `SELECT t.id, t.name AS title, t.tagline AS blurb, t.logo + FROM teams t + JOIN organizations o ON o.id = t.org_id AND o.is_published = 1 + WHERE t.is_published = 1 AND t.id IN (${marks})`, + image: (row) => (row.logo ? { file: row.logo, kind: "team" } : null), + }, + award: { + sql: (marks) => + `SELECT id, name AS title, description AS blurb, logo + FROM awards WHERE is_published = 1 AND id IN (${marks})`, + image: (row) => (row.logo ? { file: row.logo, kind: "award" } : null), + }, +}; + +export function loadFeaturedCards(db, ownerKind, ownerId) { + const rows = db + .prepare( + `SELECT * FROM featured_cards + WHERE owner_kind = ? AND owner_id = ? + ORDER BY sort_order, id`, + ) + .all(ownerKind, ownerId); + + // kind → id → record row + const records = new Map(); + for (const [kind, spec] of Object.entries(FEATURED_REFS)) { + const ids = [ + ...new Set(rows.filter((r) => r.kind === "record" && r.ref_kind === kind).map((r) => r.ref_id)), + ]; + if (ids.length === 0) continue; + const found = db.prepare(spec.sql(placeholders(ids.length))).all(...ids); + records.set(kind, new Map(found.map((r) => [r.id, r]))); + } + + const own = (row) => (row.image ? { file: row.image, kind: "featured" } : null); + + const cards = []; + for (const row of rows) { + if (row.kind === "record") { + const record = records.get(row.ref_kind)?.get(row.ref_id); + if (!record) continue; // unpublished, or its organization is + cards.push({ + kind: "record", + ref: { kind: row.ref_kind, id: row.ref_id, org_kind: record.org_kind ?? null }, + url: null, + eyebrow: row.eyebrow ?? record.eyebrow ?? null, + title: row.title ?? record.title, + blurb: row.blurb ?? record.blurb ?? null, + image: own(row) ?? FEATURED_REFS[row.ref_kind].image(record), + }); + } else { + cards.push({ + kind: row.kind, // 'link' | 'video' + ref: null, + url: row.url, + eyebrow: row.eyebrow, + title: row.title, + blurb: row.blurb, + image: own(row), + }); + } + } + return cards; +} + export { asBool }; diff --git a/src/components/FeaturedCards.tsx b/src/components/FeaturedCards.tsx new file mode 100644 index 0000000..f384137 --- /dev/null +++ b/src/components/FeaturedCards.tsx @@ -0,0 +1,190 @@ +/* ═══════════════════════════════════════════════════════════════ + FEATURED CARDS + + A grid of cards that point somewhere: the front page's featured + band now, the Community blog's posts next. The data comes from + loadFeaturedCards in server/src/shape.js, already resolved, so + this only draws. + + Three kinds of card: + + record links to the record's own page (hrefs.ts builds it) + link links to its URL, a new tab when it leaves the site + video a still with a play button; pressing it swaps in the + player, so the page loads no iframes until then. The + still is the card's image, else YouTube's thumbnail, + else a plain panel. + + A photo fills the picture area; a logo sits inside it on a soft + 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 { refHref } from '../lib/hrefs.ts' +import { logoForKind } from '../lib/media.ts' +import { playingSource, videoSource, videoThumbnail } from '../lib/embeds.ts' +import type { FeaturedCard } from '../lib/useFrontPage.ts' + +const ACCENT = '#138ba0' + +/* Image kinds that are photographs, drawn edge to edge. Anything + else is a logo, drawn whole. */ +const PHOTO_KINDS = new Set(['event-background', 'featured', 'person']) + +function hrefFor(card: FeaturedCard): string | null { + if (card.kind === 'record' && card.ref) { + return refHref(card.ref.kind, card.ref.id, card.ref.org_kind) + } + return card.kind === 'link' ? card.url : null +} + +function Picture({ card }: { card: FeaturedCard }) { + const [failed, setFailed] = useState(false) + const src = card.image ? logoForKind(card.image.kind, card.image.file) : null + const photo = card.image ? PHOTO_KINDS.has(card.image.kind) : false + + if (!src || failed) { + return <div className="aspect-video w-full bg-gradient-to-br from-[#eef9fb] to-[#d9f0f3]" /> + } + + return photo ? ( + <img + src={src} + alt="" + loading="lazy" + onError={() => setFailed(true)} + className="aspect-video w-full object-cover" + /> + ) : ( + <div className="flex aspect-video w-full items-center justify-center bg-[#eef9fb] p-8"> + <img + src={src} + alt="" + loading="lazy" + onError={() => setFailed(true)} + className="max-h-full max-w-full object-contain" + /> + </div> + ) +} + +function VideoPicture({ card }: { card: FeaturedCard }) { + const [playing, setPlaying] = useState(false) + const source = videoSource(card.url) + + if (playing && source) { + const live = playingSource(source) + return live.kind === 'file' ? ( + <video src={live.src} controls autoPlay playsInline className="aspect-video w-full bg-black" /> + ) : ( + <iframe + src={live.src} + title={card.title || 'Video'} + allow="autoplay; encrypted-media; picture-in-picture; fullscreen" + allowFullScreen + className="aspect-video w-full border-0 bg-black" + /> + ) + } + + const own = card.image ? logoForKind(card.image.kind, card.image.file) : null + const still = own ?? videoThumbnail(card.url) + + const face = ( + <> + {still ? ( + <img src={still} alt="" loading="lazy" className="aspect-video w-full object-cover" /> + ) : ( + <div className="aspect-video w-full bg-gradient-to-br from-[#073d4a] to-[#04262e]" /> + )} + <span + aria-hidden="true" + className="absolute inset-0 flex items-center justify-center bg-black/10 transition-colors group-hover:bg-black/25" + > + <span className="flex h-16 w-16 items-center justify-center rounded-full bg-white/90 shadow-lg transition-transform group-hover:scale-110"> + <svg viewBox="0 0 24 24" className="ml-1 h-7 w-7" fill={ACCENT}> + <path d="M8 5v14l11-7z" /> + </svg> + </span> + </span> + </> + ) + + // A link that can't be played here still goes somewhere. + if (!source) { + return card.url ? ( + <HomeLink url={card.url} className="group relative block"> + {face} + </HomeLink> + ) : ( + <div className="relative">{face}</div> + ) + } + + return ( + <button + type="button" + onClick={() => setPlaying(true)} + aria-label={`Play ${card.title || 'video'}`} + className="group relative block w-full" + > + {face} + </button> + ) +} + +function Card({ card }: { card: FeaturedCard }) { + const href = hrefFor(card) + + const text = ( + <div className="flex flex-1 flex-col p-6"> + {card.eyebrow && ( + <p className="text-xs font-bold uppercase tracking-[0.2em] text-[#138ba0]">{card.eyebrow}</p> + )} + {card.title && ( + <h3 className="mt-2 font-display text-xl font-extrabold leading-snug text-[#073d4a]"> + {href ? ( + // Stretched over the whole card, so the picture and the + // blurb are part of the click without nesting links. + <HomeLink + url={href} + className="after:absolute after:inset-0 after:rounded-2xl after:content-[''] hover:underline" + > + {card.title} + </HomeLink> + ) : ( + card.title + )} + </h3> + )} + {card.blurb && <p className="mt-2 leading-relaxed text-[#4a6b72]">{card.blurb}</p>} + </div> + ) + + return ( + <li className="relative flex flex-col overflow-hidden rounded-2xl border border-[#138ba0]/15 bg-white shadow-sm transition-shadow hover:shadow-lg"> + {card.kind === 'video' ? ( + // Above the stretched link, which a video card doesn't have + // anyway, so the play button always gets the click. + <div className="relative z-10"> + <VideoPicture card={card} /> + </div> + ) : ( + <Picture card={card} /> + )} + {text} + </li> + ) +} + +export default function FeaturedCards({ cards }: { cards: FeaturedCard[] }) { + return ( + <ul className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3"> + {cards.map((card, index) => ( + <Card key={`${card.kind}-${card.ref?.id ?? card.url}-${index}`} card={card} /> + ))} + </ul> + ) +} diff --git a/src/components/admin/MediaLibrary.tsx b/src/components/admin/MediaLibrary.tsx index 8bb3b55..3351b4d 100644 --- a/src/components/admin/MediaLibrary.tsx +++ b/src/components/admin/MediaLibrary.tsx @@ -11,6 +11,11 @@ (pages/admin/AdminMedia.tsx) draw. UploadButton a file input dressed as a button, with the "keep original" choice beside it. + LinkPreviewInput + the `widget: "linkPreview"` field: a URL box and a + "Fetch preview" button that reads the page's title, + description and preview image (the image lands in + the library) and fills the row's empty fields. An image field stores a path, not a media id: '/uploads/<file>' for an upload, or, as before, a bare filename in the field's @@ -26,7 +31,7 @@ import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from "react"; -import { ApiError, get, upload } from "../../lib/api.ts"; +import { ApiError, get, post, upload } from "../../lib/api.ts"; import { useAuth } from "../../lib/auth.tsx"; import { canWrite as roleCanWrite } from "../../lib/roles.ts"; @@ -405,3 +410,85 @@ export function ImageInput({ </div> ); } + +/* ── Link preview field ──────────────────────────────────────── */ + +/* Fills only what's empty: a title somebody already typed is theirs, + not the page's. Which fields it fills is the row's title, blurb and + image, the featured card's names. */ +export function LinkPreviewInput({ + id, + value, + row, + locked, + className, + showButton, + onChange, + onPatch, +}: { + id: string; + value: string | null | undefined; + row: Record<string, any>; + locked: boolean; + className: string; + showButton: boolean; + onChange: (value: string) => void; + onPatch?: (patch: Record<string, any>) => void; +}) { + const { user } = useAuth(); + const [busy, setBusy] = useState(false); + const [note, setNote] = useState<{ tone: "ok" | "error"; text: string } | null>(null); + + async function fetchPreview() { + if (!value || !onPatch) return; + setBusy(true); + setNote(null); + try { + const { preview } = await post("/admin/link-preview", { url: value }); + const patch: Record<string, any> = {}; + if (!row.title && preview.title) patch.title = preview.title; + if (!row.blurb && preview.description) patch.blurb = preview.description; + if (!row.image && preview.image) patch.image = preview.image.url; + onPatch(patch); + + const filled = Object.keys(patch).length; + setNote( + preview.image_error + ? { tone: "error", text: `Filled ${filled} field${filled === 1 ? "" : "s"}. ${preview.image_error}` } + : filled + ? { tone: "ok", text: `Filled ${filled} empty field${filled === 1 ? "" : "s"}.` } + : { tone: "ok", text: "Nothing to fill: those fields already have values, or the page has none." }, + ); + } catch (err) { + setNote({ tone: "error", text: err instanceof ApiError ? err.message : "Couldn't read that page." }); + } finally { + setBusy(false); + } + } + + return ( + <div className="space-y-2"> + <input + id={id} + type="text" + value={value ?? ""} + readOnly={locked} + onChange={(e) => onChange(e.target.value)} + placeholder="https://" + className={className} + /> + {showButton && !locked && roleCanWrite(user) && ( + <div className="flex flex-wrap items-center gap-3"> + <button type="button" className={button} disabled={busy || !value} onClick={fetchPreview}> + {busy ? "Fetching…" : "Fetch preview"} + </button> + {note && ( + <span className={`text-xs ${note.tone === "ok" ? "text-[#138ba0]" : "text-[#b3261e]"}`}> + {note.text} + </span> + )} + </div> + )} + </div> + ); +} diff --git a/src/components/admin/fields.tsx b/src/components/admin/fields.tsx index f397f22..232f1a6 100644 --- a/src/components/admin/fields.tsx +++ b/src/components/admin/fields.tsx @@ -26,6 +26,16 @@ that column in the server's admin-schema.js or the row will be saved as real input. + In a repeater row, `when: { path, value }` shows a field only + while another field of the row holds that value (or one of them, + given an array). A field that goes hidden is cleared, so a row + can't keep a value for a choice it no longer makes: a featured + card switched from "record" to "link" drops its record. + + `widget: "linkPreview"` is a URL box with a "Fetch preview" button + (LinkPreviewInput in MediaLibrary.tsx) that fills the row's empty + title, blurb and image through `onPatch`. + `widget: "image"` is a text box with a preview and upload and library buttons beside it (ImageInput in MediaLibrary.tsx). Its `resolve` option is the media.ts helper for the field's public/ @@ -47,7 +57,7 @@ import { useRef, useState } from "react"; -import { ImageInput } from "./MediaLibrary.tsx"; +import { ImageInput, LinkPreviewInput } from "./MediaLibrary.tsx"; const input = "w-full rounded-lg border border-[#4a6b72]/25 bg-white px-3 py-2 text-sm text-[#26454c] " + @@ -84,9 +94,30 @@ export function setPath(object, path, value) { return { ...object, [head]: setPath(object?.[head] ?? {}, rest.join("."), value) }; } +/* ── Conditional fields ──────────────────────────────────────── */ + +export function fieldShown(field, row) { + if (!field.when) return true; + const want = Array.isArray(field.when.value) ? field.when.value : [field.when.value]; + return want.includes(row?.[field.when.path]); +} + +/* A row after an edit, with any field the edit hid cleared. "" is + the engine's deliberate clear, so it saves as NULL. */ +function withHiddenCleared(fields, row) { + let next = row; + for (const field of fields) { + const value = next[field.path]; + if (!fieldShown(field, next) && value != null && value !== "") { + next = { ...next, [field.path]: "" }; + } + } + return next; +} + /* ── Field ───────────────────────────────────────────────────── */ -export function Field({ field, value, row, options, error, onChange }: any) { +export function Field({ field, value, row, options, error, onChange, onPatch }: any) { const id = `f-${field.path.replace(/\./g, "-")}`; const widget = field.widget ?? "text"; const locked = Boolean(field.readOnly); @@ -183,6 +214,17 @@ export function Field({ field, value, row, options, error, onChange }: any) { className={locked ? inputLocked : common.className} /> </div> + ) : widget === "linkPreview" ? ( + <LinkPreviewInput + id={id} + value={value} + row={row} + locked={locked} + className={locked ? inputLocked : common.className} + showButton={!field.previewWhen || fieldShown({ when: field.previewWhen }, row)} + onChange={onChange} + onPatch={onPatch} + /> ) : widget === "image" ? ( <ImageInput id={id} @@ -298,7 +340,7 @@ export function Repeater({ const rowRefs = useRef<any[]>([]); const update = (index, next) => - onChange(list.map((row, i) => (i === index ? next : row))); + onChange(list.map((row, i) => (i === index ? withHiddenCleared(spec.fields, next) : row))); const move = (index, delta) => { const target = index + delta; @@ -489,17 +531,20 @@ export function Repeater({ {expanded && ( <> <FieldGrid> - {spec.fields.map((field) => ( - <Field - key={field.path} - field={field} - row={row} - value={row[field.path]} - options={options} - error={errors?.[`${errorPrefix}${index}.${field.path}`]} - onChange={(value) => update(index, { ...row, [field.path]: value })} - /> - ))} + {spec.fields + .filter((field) => fieldShown(field, row)) + .map((field) => ( + <Field + key={field.path} + field={field} + row={row} + value={row[field.path]} + options={options} + error={errors?.[`${errorPrefix}${index}.${field.path}`]} + onChange={(value) => update(index, { ...row, [field.path]: value })} + onPatch={(patch) => update(index, { ...row, ...patch })} + /> + ))} </FieldGrid> {(spec.children ?? []).map((nested) => ( diff --git a/src/lib/adminSchema.ts b/src/lib/adminSchema.ts index 2be582b..dc85af7 100644 --- a/src/lib/adminSchema.ts +++ b/src/lib/adminSchema.ts @@ -22,6 +22,7 @@ import { blockMedia, eventBackground, eventLogo, + featuredImage, heroPhoto, orgLogo, personPhoto, @@ -148,6 +149,76 @@ const timelineDetailGroup = (noun) => ({ fields: timelineExtensionFields(noun), }); +/* Featured cards (030_featured_cards.sql), a front page collection + now and the Community blog's next, so it's written once. Fields + show by kind; switching kind clears the ones that stop applying + (see `when` in fields.tsx). */ +const FEATURED_KINDS = [ + ["record", "A page on this site (event, org, person…)"], + ["link", "A link (article, post, any URL)"], + ["video", "A video (YouTube, Vimeo, Facebook)"], +]; + +const featuredCardsChild = { + key: "featured_cards", + label: "Featured cards", + note: "Shown by the Featured Content section, in this order.", + addLabel: "Add card", + title: (row, options) => + row.title || + options?.record_refs?.find((o) => o.kind === row.ref_kind && o.id === row.ref_id)?.label || + row.url || + "New card", + blank: { kind: "", ref_kind: "", ref_id: "", url: "", title: "" }, + fields: [ + { + path: "kind", + label: "Card type", + widget: "select", + options: FEATURED_KINDS, + required: true, + }, + { + path: "ref_kind", + label: "Record type", + widget: "select", + options: ["event", "organization", "person", "team", "award"], + required: true, + when: { path: "kind", value: "record" }, + }, + { + path: "ref_id", + label: "Record", + widget: "select", + optionsFrom: "record_refs", + filterBy: (option, row) => option.kind === row.ref_kind, + required: true, + when: { path: "kind", value: "record" }, + help: "Its title, picture and link fill the card. Anything typed below overrides them.", + }, + { + path: "url", + label: "URL", + widget: "linkPreview", + previewWhen: { path: "kind", value: "link" }, + required: true, + full: true, + when: { path: "kind", value: ["link", "video"] }, + }, + { path: "eyebrow", label: "Label", help: "Small text above the title, eg. Article, Watch" }, + { path: "title", label: "Title" }, + { path: "blurb", label: "Blurb", widget: "textarea", full: true }, + { + path: "image", + label: "Image", + widget: "image", + resolve: featuredImage, + full: true, + help: "Default: the record's own picture, or for a YouTube video, its thumbnail.", + }, + ], +}; + /* The two collections every entity carries. */ const linksChild = { key: "links", @@ -915,7 +986,7 @@ const timeline = { path: "ref_id", label: "Record", widget: "select", - optionsFrom: "timeline_refs", + optionsFrom: "record_refs", blankLabel: "Default: none", // One flat list of every referenceable row, narrowed to the // kind chosen above. Five dropdowns of which four are always @@ -1015,6 +1086,7 @@ const FRONT_PAGE_SECTIONS = [ ["stats", "Stats"], ["timeline", "Featured Timeline"], ["connect", "Connect Nav"], + ["featured", "Featured Content"], ]; const STAT_SOURCES = [ @@ -1196,6 +1268,7 @@ const frontPage = { { path: "note", label: "Note", full: true }, ], }, + featuredCardsChild, { key: "paths", label: "Connect Nav", diff --git a/src/lib/embeds.ts b/src/lib/embeds.ts index cdcc86b..afc68c1 100644 --- a/src/lib/embeds.ts +++ b/src/lib/embeds.ts @@ -100,3 +100,39 @@ export function videoSource(raw?: string | null): VideoSource | null { const src = embedUrl(value, false) return src ? { kind: 'embed', src } : null } + +/* ── Click to play ───────────────────────────────────────────── + A featured card shows a still and swaps in the player when it's + pressed, so the page loads no iframes until someone asks for + one. The press is the user gesture browsers want before playing + with sound, so the player can start at once, unmuted. + ───────────────────────────────────────────────────────────── */ + +/** The same source, set to start playing as soon as it loads. */ +export function playingSource(source: VideoSource): VideoSource { + if (source.kind === 'file') return source + let url: URL + try { + url = new URL(source.src) + } catch { + return source + } + const host = url.hostname.replace(/^www\./, '') + if (host === 'youtube-nocookie.com' || host === 'player.vimeo.com' || host === 'vimeo.com' || host === 'facebook.com') { + url.searchParams.set('autoplay', '1') + } + return { kind: 'embed', src: url.toString() } +} + +/** A still for a video link: YouTube's own thumbnail. Other hosts + * need an API call to find theirs, so they return null and the + * card uses its uploaded image or a plain panel. */ +export function videoThumbnail(raw?: string | null): string | null { + if (!raw) return null + try { + const id = youtubeId(new URL(raw.trim())) + return id ? `https://i.ytimg.com/vi/${encodeURIComponent(id)}/hqdefault.jpg` : null + } catch { + return null + } +} diff --git a/src/lib/media.ts b/src/lib/media.ts index df238c8..0ccc163 100644 --- a/src/lib/media.ts +++ b/src/lib/media.ts @@ -48,6 +48,10 @@ export const heroVideo = inDir('/front-page') so it can't share a per-entity directory. */ export const blockMedia = inDir('/media') // ⚠ guess +/* featured_cards.image, a card's own picture. Normally an upload + ('/uploads/…'); a bare filename looks here. */ +export const featuredImage = inDir('/featured') + /* ── By record kind ──────────────────────────────────────────── The timeline sends `logo: { file, kind }` rather than a path, because v_timeline COALESCEs across five tables and only the @@ -64,6 +68,9 @@ const BY_KIND: Record<string, (file?: string | null) => string | null> = { team: teamLogo, award: awardLogo, person: personPhoto, + // Featured cards (loadFeaturedCards in shape.js) add two of their own. + 'event-background': eventBackground, + featured: featuredImage, } export function logoForKind( diff --git a/src/lib/useFrontPage.ts b/src/lib/useFrontPage.ts index e43c6e2..a1bba44 100644 --- a/src/lib/useFrontPage.ts +++ b/src/lib/useFrontPage.ts @@ -27,6 +27,7 @@ export type FrontPageSectionKey = | 'stats' | 'timeline' | 'connect' + | 'featured' export type HeroButton = { label: string; url: string } @@ -90,11 +91,26 @@ export type CountdownEvent = { series: EventSeries | null } +/** One featured card, as loadFeaturedCards in shape.js shapes it. + * A record card's title and image are already its record's unless + * the card overrides them; `ref` is what its link is built from. */ +export type FeaturedCard = { + kind: 'record' | 'link' | 'video' + ref: { kind: string; id: string; org_kind?: string | null } | null + url: string | null + eyebrow?: string | null + title?: string | null + blurb?: string | null + /** Resolve with logoForKind in media.ts. */ + image: { file: string; kind: string } | null +} + export type FrontPage = { hero: Hero sections: FrontPageSection[] stats: FrontPageStat[] paths: FrontPagePath[] + featured: FeaturedCard[] countdown: CountdownEvent | null } diff --git a/src/pages/Home.tsx b/src/pages/Home.tsx index 84ebc34..942b7d8 100644 --- a/src/pages/Home.tsx +++ b/src/pages/Home.tsx @@ -14,7 +14,8 @@ A band with nothing to show draws nothing: the countdown with no upcoming event, the numbers with no numbers, the timeline with - nothing featured, the pathfinder with no paths. + nothing featured, the pathfinder with no paths, the featured band + with no cards. If /front-page fails, the hero still draws (empty) and the error takes the place of the bands, with a retry. There's deliberately @@ -29,6 +30,7 @@ import NextEventCountdown from './sections/home/NextEventCountdown.tsx' import RetreatsBand from './sections/home/RetreatsBand.tsx' import CalendarBand from './sections/home/CalendarBand.tsx' 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 { @@ -90,6 +92,13 @@ const SECTIONS: Record< <Pathfinder id="connect" title={title} blurb={section.blurb} paths={page.paths} /> ), }, + featured: { + title: 'Featured', + render: ({ page, section, title }) => + page.featured.length > 0 && ( + <FeaturedBand id="featured" title={title} blurb={section.blurb} cards={page.featured} /> + ), + }, } export default function Home() { diff --git a/src/pages/sections/home/FeaturedBand.tsx b/src/pages/sections/home/FeaturedBand.tsx new file mode 100644 index 0000000..14453c0 --- /dev/null +++ b/src/pages/sections/home/FeaturedBand.tsx @@ -0,0 +1,32 @@ +/* ═══════════════════════════════════════════════════════════════ + FEATURED BAND + + The front page's featured content: the cards from the admin's + Front page editor (Featured cards), under the section's heading. + The cards themselves are FeaturedCards, which the Community + blog will share. No cards, no band. + ═══════════════════════════════════════════════════════════════ */ + +import FeaturedCards from '../../../components/FeaturedCards.tsx' +import type { FeaturedCard } from '../../../lib/useFrontPage.ts' + +type FeaturedBandProps = { + id: string + title: string + blurb?: string | null + cards: FeaturedCard[] +} + +export default function FeaturedBand({ id, title, blurb, cards }: FeaturedBandProps) { + return ( + <section id={id} className="py-24" style={{ background: '#f6fbfc' }}> + <div className="mx-auto max-w-6xl px-6"> + <h2 className="font-display text-4xl font-extrabold text-[#073d4a] md:text-5xl">{title}</h2> + {blurb && <p className="mt-4 max-w-2xl text-lg text-[#4a6b72]">{blurb}</p>} + <div className="mt-12"> + <FeaturedCards cards={cards} /> + </div> + </div> + </section> + ) +} From d374f9ac17f54ed740b17ffa15edfd1ff98d733a Mon Sep 17 00:00:00 2001 From: Zaldimmar <Zaldimmar@gmail.com> Date: Sun, 27 Sep 2026 16:27:00 -0500 Subject: [PATCH 16/22] Add a blog: posts at /blog/:id and a Community page section MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Admin → Blog → Posts (migration 031): our own posts with a content-block body, cover image, excerpt, date, tags, and authors shown as person tiles, either People records or a guest name and photo. A post is a draft until published; Listed works as it does elsewhere. Posts are on the QR page too. Admin → Blog → Community section: the first section of the Community page, with its heading and blurb from the admin, in two halves, each pinned first and then newest up to its slots. Our posts come from blog_posts; community posts are pinned link or video cards (reusing featured cards and Fetch preview), then the newest items from a list of RSS or Atom feeds. Feeds are read through the link preview's guarded fetch and cached for 30 minutes, and a failing feed keeps its last good items. content_blocks and featured_cards are rebuilt to accept the new owner kinds. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/updating-data-in-code.md | 4 +- server/src/admin-schema.js | 93 ++++++++++ server/src/feeds.js | 150 ++++++++++++++++ server/src/index.js | 2 + server/src/linkPreview.js | 17 +- server/src/migrations/031_blog.sql | 254 +++++++++++++++++++++++++++ server/src/routes/blog.js | 198 +++++++++++++++++++++ server/src/routes/directory.js | 7 + src/App.tsx | 2 + src/lib/adminSchema.ts | 178 +++++++++++++++++++ src/lib/hrefs.ts | 2 + src/lib/media.ts | 3 + src/lib/useBlog.ts | 71 ++++++++ src/lib/useContent.ts | 1 + src/navConfig.ts | 1 + src/pages/BlogPost.tsx | 114 ++++++++++++ src/pages/Community.tsx | 28 ++- src/pages/QrCodes.tsx | 2 +- src/pages/admin/adminNav.ts | 11 ++ src/pages/sections/CommunityBlog.tsx | 145 +++++++++++++++ src/pages/sections/QrCodeMaker.tsx | 7 +- 21 files changed, 1275 insertions(+), 15 deletions(-) create mode 100644 server/src/feeds.js create mode 100644 server/src/migrations/031_blog.sql create mode 100644 server/src/routes/blog.js create mode 100644 src/lib/useBlog.ts create mode 100644 src/pages/BlogPost.tsx create mode 100644 src/pages/sections/CommunityBlog.tsx diff --git a/docs/updating-data-in-code.md b/docs/updating-data-in-code.md index 86b2c5f..11b8d6c 100644 --- a/docs/updating-data-in-code.md +++ b/docs/updating-data-in-code.md @@ -29,6 +29,7 @@ what a dropdown in the admin editor says. | ------------------------------------------------------------ | ---------------- | ------------------------------------ | | A record: an event, organization, person, team, award, timeline entry | the database | editing it in the admin | | The front page's words, photos, bands, stats and paths | the database | Admin → Front page | +| Blog posts, and the Community page's blog section (headings, pins, feeds) | the database | Admin → Blog | | The **label** a dropdown shows in the admin | code | [one file](#renaming-what-a-dropdown-shows) | | The **list of allowed values** behind a fixed dropdown | database CHECK + code | [a migration and three files](#adding-removing-or-renaming-a-stored-value) | | Navigation, page section titles, colours, the site banner, history decades, the map grid | code | [the file named below](#other-content-that-lives-in-code) | @@ -183,7 +184,7 @@ also in `admin-schema.js` and a CHECK): | Front page → Feature | none, livestream, video | **yes** | `HeroStage.tsx` | | Front page → Sections → Section | countdown, retreats, calendar, stats, timeline, connect, featured | **yes**, `FRONT_PAGE_SECTIONS` | `SECTIONS` in `src/pages/Home.tsx`; see [below](#front-page-section-names) | | Front page → Stats → Number Source | manual, years_since, regions, … | **yes**, `STAT_SOURCES` | `STAT_QUERIES` in `server/src/routes/home.js`; see [below](#front-page-stat-sources) | -| Front page → Featured cards → Card type | record, link, video | **yes**, `FEATURED_KINDS` | `FeaturedCards.tsx` (how each kind draws), `loadFeaturedCards` in `server/src/shape.js` | +| Front page → Featured cards → Card type (Blog → Community section → Pinned community posts offers link and video only) | record, link, video | **yes**, `FEATURED_KINDS` | `FeaturedCards.tsx` (how each kind draws), `loadFeaturedCards` in `server/src/shape.js` | | Front page → Featured cards → Record type | event, organization, person, team, award | no | `FEATURED_REFS` in `server/src/shape.js` (what each fills the card with); the triggers in `030_featured_cards.sql` | | Every list → Published / Listed / Featured filter | 1, 0 | **yes** | n/a | @@ -199,6 +200,7 @@ code): | Event → Scope (+ list filter); Front page → Countdown → Only this scope | `event_scopes` | the `event_scopes` table (migration only) | | Event hosts → Organization; affiliations; team and award "Organization" / "Awarded by"; person → Home organization | `organizations` | organizations, labelled by name | | Event hosts / event people / team members / timeline people → Person | `people` | people | +| Blog → Community section → Pinned posts → Post | `blog_posts` | blog posts, newest first | | Timeline → Record; Featured cards → Record | `record_refs` | every event, organization, award, person and team, narrowed by the type picked beside it | | Affiliations → Team | `teams` | teams, filtered to the chosen organization | | Person awards → Award | `awards` | awards, labelled "Award (Organization)" | diff --git a/server/src/admin-schema.js b/server/src/admin-schema.js index 09ac3fd..a9c6828 100644 --- a/server/src/admin-schema.js +++ b/server/src/admin-schema.js @@ -799,6 +799,96 @@ const frontPage = { ], }; +/* ── Blog (031_blog.sql) ───────────────────────────────────────── + + Posts of our own, with a content-block body and people as + authors, and the Community page's blog section, a singleton like + the front page. The section's community posts are featured cards + owned by 'community_page'. ─────────────────────────────────── */ + +const blogPosts = { + key: "blog_posts", + table: "blog_posts", + idColumn: "id", + idKind: "slug", + concurrency: "updated_at", + + list: { + columns: ["id", "title", "published_on", "tags", "is_published", "is_listed", "updated_at"], + filters: ["is_published", "is_listed"], + search: ["title", "id", "tags"], + order: "published_on IS NULL, published_on DESC, title", + }, + + columns: [ + text("title", { required: true }), + text("excerpt"), + text("cover_image"), + date("published_on"), + text("tags"), + text("guest_author"), + text("guest_photo"), + bool("is_published"), + bool("is_listed"), + ], + + children: [ + { + key: "authors", + table: "blog_post_authors", + owner: { column: "post_id" }, + order: "sort_order", + columns: [text("person_id", { required: true })], + }, + blocksChild("blog_post"), + ], +}; + +const communityPage = { + key: "community_page", + table: "community_page", + idColumn: "id", + idKind: "slug", + singleton: "community", + concurrency: "updated_at", + + list: { + columns: ["id", "blog_title", "updated_at"], + filters: [], + search: [], + order: "id", + }, + + columns: [ + text("blog_title"), + text("blog_blurb"), + text("internal_title"), + int("internal_slots"), + text("external_title"), + int("external_slots"), + text("external_url"), + text("external_label"), + ], + + children: [ + { + key: "pinned_posts", + table: "community_page_pinned_posts", + owner: { column: "page_id" }, + order: "sort_order", + columns: [text("post_id", { required: true })], + }, + featuredCardsChild("community_page"), + { + key: "feeds", + table: "community_page_feeds", + owner: { column: "page_id" }, + order: "sort_order", + columns: [text("url", { required: true }), text("label")], + }, + ], +}; + export const ENTITIES = { organizations, events, @@ -807,6 +897,8 @@ export const ENTITIES = { awards, timeline, front_page: frontPage, + blog_posts: blogPosts, + community_page: communityPage, }; /* ── Options for the form's select inputs ────────────────────── */ @@ -819,6 +911,7 @@ export const OPTION_QUERIES = { event_scopes: "SELECT id, name AS label FROM event_scopes ORDER BY sort_order", events: "SELECT id, title AS label FROM events ORDER BY starts_on DESC, title", people: "SELECT id, display_name AS label FROM people ORDER BY sort_name, display_name", + blog_posts: "SELECT id, title AS label FROM blog_posts ORDER BY published_on DESC, title", // org_id rides along so the affiliation row can filter the list // down to teams of the organization it already names. diff --git a/server/src/feeds.js b/server/src/feeds.js new file mode 100644 index 0000000..d5b2fb5 --- /dev/null +++ b/server/src/feeds.js @@ -0,0 +1,150 @@ +/* ═══════════════════════════════════════════════════════════════ + FEEDS + + Reads the RSS and Atom feeds the Community page's blog section + lists (community_page_feeds), for its "newest community posts". + A Substack's feed is https://<name>.substack.com/feed. + + Each feed is fetched through linkPreview.js's safeGet, so it gets + the same public-address checks, timeout and size cap as a link + preview. Results are kept in memory for CACHE_MS. A feed that + fails keeps serving what it last returned, and one that has never + worked contributes nothing: the section shows the pinned posts + and whatever the other feeds have, rather than an error. + + Items come back as plain data: title, url, excerpt, image, + published (ISO), source. Only http(s) links and https images are + kept, so a feed can't put a javascript: link or a mixed-content + image on the page. + ═══════════════════════════════════════════════════════════════ */ + +import { decodeEntities, safeGet } from "./linkPreview.js"; + +const CACHE_MS = 30 * 60 * 1000; +const MAX_FEED_BYTES = 3 * 1024 * 1024; +const MAX_ITEMS_PER_FEED = 20; +const EXCERPT_CHARS = 300; + +const cache = new Map(); // url → { at, feed } + +/* ── Parsing ───────────────────────────────────────────────── */ + +function unwrap(text) { + return text.replace(/^\s*<!\[CDATA\[([\s\S]*?)\]\]>\s*$/, "$1"); +} + +/* The text inside the first <tag>…</tag>, CDATA unwrapped. Tag + names may carry a namespace prefix (content:encoded). */ +function inner(xml, tag) { + const match = xml.match(new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${tag}>`, "i")); + return match ? unwrap(match[1]) : null; +} + +function attrOf(xml, tag, name, where = () => true) { + for (const match of xml.matchAll(new RegExp(`<${tag}\\b[^>]*>`, "gi"))) { + const el = match[0]; + const value = el.match(new RegExp(`\\b${name}\\s*=\\s*("([^"]*)"|'([^']*)')`, "i")); + if (value && where(el)) return value[2] ?? value[3]; + } + return null; +} + +function plain(html) { + if (!html) return null; + const text = decodeEntities(html.replace(/<[^>]+>/g, " ")); + if (!text) return null; + return text.length > EXCERPT_CHARS ? `${text.slice(0, EXCERPT_CHARS).trimEnd()}…` : text; +} + +function safeUrl(raw, base, { httpsOnly = false } = {}) { + if (!raw) return null; + try { + const url = new URL(decodeEntities(raw), base); + if (url.protocol === "https:" || (!httpsOnly && url.protocol === "http:")) return url.toString(); + } catch { + /* not a URL */ + } + return null; +} + +function isoDate(raw) { + if (!raw) return null; + const date = new Date(raw.trim()); + return Number.isNaN(date.getTime()) ? null : date.toISOString(); +} + +function firstImage(html) { + return html?.match(/<img\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/i)?.[1] ?? null; +} + +function parseFeed(xml, feedUrl) { + const isAtom = /<feed\b[^>]*xmlns=["']http:\/\/www\.w3\.org\/2005\/Atom/i.test(xml) && !/<rss\b/i.test(xml); + const channelTitle = decodeEntities(inner(xml.replace(/<(item|entry)\b[\s\S]*$/i, ""), "title") ?? ""); + const blocks = xml.match(isAtom ? /<entry\b[\s\S]*?<\/entry>/gi : /<item\b[\s\S]*?<\/item>/gi) ?? []; + + const items = []; + for (const block of blocks.slice(0, MAX_ITEMS_PER_FEED)) { + const link = isAtom + ? attrOf(block, "link", "href", (el) => !/rel\s*=\s*["'](?!alternate)/i.test(el)) + : inner(block, "link"); + const url = safeUrl(link?.trim(), feedUrl); + const title = decodeEntities(inner(block, "title") ?? ""); + if (!url || !title) continue; + + const body = inner(block, "content:encoded") ?? inner(block, "content"); + const summary = inner(block, "description") ?? inner(block, "summary"); + + const image = + attrOf(block, "enclosure", "url", (el) => /type\s*=\s*["']image\//i.test(el)) ?? + attrOf(block, "media:content", "url") ?? + attrOf(block, "media:thumbnail", "url") ?? + firstImage(body) ?? + firstImage(summary); + + items.push({ + title, + url, + excerpt: plain(summary) ?? plain(body), + image: safeUrl(image, feedUrl, { httpsOnly: true }), + published: isoDate(inner(block, "pubDate") ?? inner(block, "published") ?? inner(block, "updated")), + }); + } + + return { title: channelTitle || null, items }; +} + +/* ── Fetching ──────────────────────────────────────────────── */ + +async function fetchFeed(url) { + const result = await safeGet(url, { + maxBytes: MAX_FEED_BYTES, + accept: "application/rss+xml, application/atom+xml, application/xml;q=0.9, text/xml;q=0.9, */*;q=0.1", + }); + return parseFeed(result.body.toString("utf8"), result.url.toString()); +} + +async function readFeed(url) { + const hit = cache.get(url); + if (hit && Date.now() - hit.at < CACHE_MS) return hit.feed; + try { + const feed = await fetchFeed(url); + cache.set(url, { at: Date.now(), feed }); + return feed; + } catch (err) { + console.warn(`feed ${url}: ${err.message}`); + // Serve the last good copy, and don't retry on every request. + const stale = hit?.feed ?? { title: null, items: [] }; + cache.set(url, { at: Date.now() - CACHE_MS + 5 * 60 * 1000, feed: stale }); + return stale; + } +} + +/* Every listed feed's items, newest first, each tagged with its + source: the row's label, else the feed's own title. */ +export async function readFeeds(rows) { + const feeds = await Promise.all(rows.map((row) => readFeed(row.url))); + const items = feeds.flatMap((feed, i) => + feed.items.map((item) => ({ ...item, source: rows[i].label || feed.title })), + ); + return items.sort((a, b) => (b.published ?? "").localeCompare(a.published ?? "")); +} diff --git a/server/src/index.js b/server/src/index.js index 1fde53f..aa8248f 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -22,6 +22,7 @@ import people from "./routes/people.js"; import history from "./routes/history.js"; import home from "./routes/home.js"; import directory from "./routes/directory.js"; +import blog from "./routes/blog.js"; import feedback from "./routes/feedback.js"; import auth from "./routes/auth.js"; import admin from "./routes/admin.js"; @@ -67,6 +68,7 @@ app.route("/api", people); app.route("/api", history); app.route("/api", home); app.route("/api", directory); +app.route("/api", blog); // Tighter limit on the write path than anything else gets. app.use("/api/feedback", rateLimit({ windowMs: 60_000, max: 5 })); diff --git a/server/src/linkPreview.js b/server/src/linkPreview.js index 71a8187..64e0f65 100644 --- a/server/src/linkPreview.js +++ b/server/src/linkPreview.js @@ -22,7 +22,8 @@ · TIMEOUT_MS per request, and at most MAX_HTML_BYTES of page or MAX_UPLOAD_BYTES of image is read - Editors and up only (routes/media.js). + Editors and up only (routes/media.js). feeds.js reads RSS + through the same safeGet. ═══════════════════════════════════════════════════════════════ */ import { lookup } from "node:dns/promises"; @@ -102,7 +103,7 @@ async function vet(raw) { /* ── One request, pinned to the vetted address ─────────────── */ -function requestOnce({ url, address }, { maxBytes, accept }) { +function requestOnce({ url, address }, { maxBytes, accept, truncate = false }) { const client = url.protocol === "https:" ? https : http; return new Promise((resolve, reject) => { @@ -140,7 +141,7 @@ function requestOnce({ url, address }, { maxBytes, accept }) { // A page's head is at the top; stop reading and use what // arrived. An image that's too big is refused outright. res.destroy(); - if (accept.startsWith("text/html")) { + if (truncate) { resolve({ body: Buffer.concat(chunks), type: res.headers["content-type"] ?? "" }); } else { reject(new MediaError(413, "The preview image is too large.")); @@ -163,7 +164,8 @@ function requestOnce({ url, address }, { maxBytes, accept }) { }); } -async function safeGet(raw, options) { +/* Also used by feeds.js, so feeds get the same address checks. */ +export async function safeGet(raw, options) { let next = raw; for (let hop = 0; hop <= MAX_REDIRECTS; hop++) { const target = await vet(next); @@ -178,7 +180,7 @@ async function safeGet(raw, options) { const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " }; -function decode(text) { +export function decodeEntities(text) { return text .replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCodePoint(parseInt(hex, 16))) .replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(Number(dec))) @@ -197,11 +199,11 @@ function readMeta(html) { for (const tag of html.match(/<meta\b[^>]*>/gi) ?? []) { const key = (attr(tag, "property") ?? attr(tag, "name") ?? "").toLowerCase(); const content = attr(tag, "content"); - if (key && content != null && !(key in meta)) meta[key] = decode(content); + if (key && content != null && !(key in meta)) meta[key] = decodeEntities(content); } const title = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1]; return { - title: meta["og:title"] || meta["twitter:title"] || (title ? decode(title) : null) || null, + title: meta["og:title"] || meta["twitter:title"] || (title ? decodeEntities(title) : null) || null, description: meta["og:description"] || meta["twitter:description"] || meta.description || null, image: meta["og:image:secure_url"] || meta["og:image"] || meta["twitter:image"] || null, @@ -212,6 +214,7 @@ function readMeta(html) { export async function previewLink(raw) { const page = await safeGet(raw, { maxBytes: MAX_HTML_BYTES, + truncate: true, accept: "text/html,application/xhtml+xml;q=0.9,*/*;q=0.1", }); if (!/html/i.test(page.type)) { diff --git a/server/src/migrations/031_blog.sql b/server/src/migrations/031_blog.sql new file mode 100644 index 0000000..a787dde --- /dev/null +++ b/server/src/migrations/031_blog.sql @@ -0,0 +1,254 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 031 BLOG +-- +-- Posts of our own, at /blog/<id>, and the Community page's blog +-- section, which shows two subsections: +-- +-- Our posts pinned blog_posts first, then the newest +-- published, listed ones, up to internal_slots +-- Community posts pinned featured_cards (owner 'community_page') +-- first, then the newest items from the RSS or +-- Atom feeds in community_page_feeds, up to +-- external_slots +-- +-- blog_posts +-- A draft until published (is_published defaults to 0, as for +-- people): a half-written post shouldn't go live by accident. +-- is_listed works as it does everywhere (027): unticked, the post +-- is left out of "newest" but its page works and it can be pinned. +-- The body is content_blocks with owner_kind 'blog_post', slot +-- 'body'. Authors are people (blog_post_authors), or a guest named +-- on the post itself, or both. tags is a comma-separated list, eg. +-- 'Reflection, Event recap'; it is only displayed, never joined on. +-- +-- content_blocks gains 'blog_post' as an owner. A CHECK can't be +-- altered in place, so the table is rebuilt; the *_cleanup triggers +-- on other tables name it, hence legacy_alter_table around the +-- rename. Its own index and owner trigger are recreated below. +-- +-- featured_cards gains 'community_page' as an owner, the same way. +-- Nothing names it but its own triggers, recreated below. +-- +-- community_page is a singleton like front_page: one row, made +-- here, which the admin edits and can't delete. +-- +-- PRAGMA user_version; -- reads 30 before this file +-- ═══════════════════════════════════════════════════════════════ + +CREATE TABLE blog_posts ( + id TEXT PRIMARY KEY, -- slug: 'finding-unity-at-camp' + title TEXT NOT NULL, + excerpt TEXT, -- the card's text; else the body's start + cover_image TEXT, -- '/uploads/…', a filename, or a URL + published_on TEXT, -- 'YYYY-MM-DD'; newest first + tags TEXT, -- 'Reflection, Event recap' + guest_author TEXT, -- someone with no people row + guest_photo TEXT, + is_published INTEGER NOT NULL DEFAULT 0 CHECK (is_published IN (0, 1)), + is_listed INTEGER NOT NULL DEFAULT 1 CHECK (is_listed IN (0, 1)), + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) +) STRICT; + +CREATE INDEX blog_posts_newest_idx ON blog_posts (is_published, is_listed, published_on DESC); + +CREATE TABLE blog_post_authors ( + post_id TEXT NOT NULL REFERENCES blog_posts (id) ON DELETE CASCADE, + person_id TEXT NOT NULL REFERENCES people (id) ON DELETE CASCADE, + sort_order INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY (post_id, person_id) +) STRICT; + +CREATE INDEX blog_post_authors_person_idx ON blog_post_authors (person_id); + + +CREATE TABLE community_page ( + id TEXT PRIMARY KEY CHECK (id = 'community'), + blog_title TEXT, -- null → 'Community Blog' + blog_blurb TEXT, + internal_title TEXT, -- null → 'From NGU' + internal_slots INTEGER NOT NULL DEFAULT 3 CHECK (internal_slots BETWEEN 0 AND 12), + external_title TEXT, -- null → 'From our community' + external_slots INTEGER NOT NULL DEFAULT 3 CHECK (external_slots BETWEEN 0 AND 12), + external_url TEXT, -- the Substack home, for its button + external_label TEXT, -- null → 'Read more on Substack' + updated_at TEXT NOT NULL DEFAULT (datetime('now')) +) STRICT; + +INSERT INTO community_page (id) VALUES ('community'); + +CREATE TABLE community_page_pinned_posts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + page_id TEXT NOT NULL REFERENCES community_page (id) ON DELETE CASCADE, + sort_order INTEGER NOT NULL DEFAULT 0, + post_id TEXT NOT NULL REFERENCES blog_posts (id) ON DELETE CASCADE, + UNIQUE (page_id, post_id) +) STRICT; + +CREATE TABLE community_page_feeds ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + page_id TEXT NOT NULL REFERENCES community_page (id) ON DELETE CASCADE, + sort_order INTEGER NOT NULL DEFAULT 0, + url TEXT NOT NULL, -- 'https://ngu.substack.com/feed' + label TEXT -- shown on its items; else the feed's own title +) STRICT; + + +-- ── content_blocks: add 'blog_post' ─────────────────────────── + +CREATE TABLE content_blocks_new ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + owner_kind TEXT NOT NULL + CHECK (owner_kind IN ('organization', 'event', 'person', 'team', 'blog_post')), + owner_id TEXT NOT NULL, + slot TEXT NOT NULL DEFAULT 'body' CHECK (slot IN ('card', 'body')), + sort_order INTEGER NOT NULL DEFAULT 0, + + type TEXT NOT NULL + CHECK (type IN ('heading', 'subheading', 'paragraph', + 'list', 'links', 'quote', 'image', 'divider')), + text TEXT, + media TEXT, + href TEXT +) STRICT; + +INSERT INTO content_blocks_new (id, owner_kind, owner_id, slot, sort_order, type, text, media, href) +SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href + FROM content_blocks; + +PRAGMA legacy_alter_table = ON; +DROP TABLE content_blocks; +ALTER TABLE content_blocks_new RENAME TO content_blocks; +PRAGMA legacy_alter_table = OFF; + +CREATE INDEX content_blocks_owner_idx + ON content_blocks (owner_kind, owner_id, slot, sort_order); + + +-- ── featured_cards: add 'community_page' ────────────────────── + +CREATE TABLE featured_cards_new ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + owner_kind TEXT NOT NULL CHECK (owner_kind IN ('front_page', 'community_page')), + owner_id TEXT NOT NULL, + sort_order INTEGER NOT NULL DEFAULT 0, + + kind TEXT NOT NULL DEFAULT 'link' + CHECK (kind IN ('record', 'link', 'video')), + + ref_kind TEXT CHECK (ref_kind IN ('event', 'organization', 'person', 'team', 'award')), + ref_id TEXT, + url TEXT, + + eyebrow TEXT, + title TEXT, + blurb TEXT, + image TEXT, + + CHECK ((ref_kind IS NULL) = (ref_id IS NULL)), + CONSTRAINT "A record card needs a record to point at." + CHECK (kind != 'record' OR ref_kind IS NOT NULL), + CONSTRAINT "A link or video card needs a URL." + CHECK (kind = 'record' OR url IS NOT NULL) +) STRICT; + +INSERT INTO featured_cards_new + (id, owner_kind, owner_id, sort_order, kind, ref_kind, ref_id, url, eyebrow, title, blurb, image) +SELECT id, owner_kind, owner_id, sort_order, kind, ref_kind, ref_id, url, eyebrow, title, blurb, image + FROM featured_cards; + +PRAGMA legacy_alter_table = ON; +DROP TABLE featured_cards; +ALTER TABLE featured_cards_new RENAME TO featured_cards; +PRAGMA legacy_alter_table = OFF; + +CREATE INDEX featured_cards_owner_idx ON featured_cards (owner_kind, owner_id, sort_order); + + +-- ── Triggers last (see CLAUDE.md, Migrations) ── + +CREATE TRIGGER content_blocks_owner_exists +BEFORE INSERT ON content_blocks +BEGIN + SELECT CASE + WHEN new.owner_kind = 'event' + AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.owner_id) + THEN RAISE(ABORT, 'content_blocks: no such event') + WHEN new.owner_kind = 'organization' + AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.owner_id) + THEN RAISE(ABORT, 'content_blocks: no such organization') + WHEN new.owner_kind = 'person' + AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.owner_id) + THEN RAISE(ABORT, 'content_blocks: no such person') + WHEN new.owner_kind = 'team' + AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.owner_id) + THEN RAISE(ABORT, 'content_blocks: no such team') + WHEN new.owner_kind = 'blog_post' + AND NOT EXISTS (SELECT 1 FROM blog_posts WHERE id = new.owner_id) + THEN RAISE(ABORT, 'content_blocks: no such blog post') + END; +END; + +CREATE TRIGGER featured_cards_ref_exists +BEFORE INSERT ON featured_cards +BEGIN + SELECT CASE + WHEN new.ref_kind = 'event' + AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id) + THEN RAISE(ABORT, 'featured_cards: no such event') + WHEN new.ref_kind = 'organization' + AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id) + THEN RAISE(ABORT, 'featured_cards: no such organization') + WHEN new.ref_kind = 'person' + AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id) + THEN RAISE(ABORT, 'featured_cards: no such person') + WHEN new.ref_kind = 'team' + AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id) + THEN RAISE(ABORT, 'featured_cards: no such team') + WHEN new.ref_kind = 'award' + AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id) + THEN RAISE(ABORT, 'featured_cards: no such award') + END; +END; + +CREATE TRIGGER featured_cards_ref_exists_update +BEFORE UPDATE OF ref_kind, ref_id ON featured_cards +BEGIN + SELECT CASE + WHEN new.ref_kind = 'event' + AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id) + THEN RAISE(ABORT, 'featured_cards: no such event') + WHEN new.ref_kind = 'organization' + AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id) + THEN RAISE(ABORT, 'featured_cards: no such organization') + WHEN new.ref_kind = 'person' + AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id) + THEN RAISE(ABORT, 'featured_cards: no such person') + WHEN new.ref_kind = 'team' + AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id) + THEN RAISE(ABORT, 'featured_cards: no such team') + WHEN new.ref_kind = 'award' + AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id) + THEN RAISE(ABORT, 'featured_cards: no such award') + END; +END; + +CREATE TRIGGER blog_posts_cleanup +AFTER DELETE ON blog_posts +BEGIN + DELETE FROM content_blocks WHERE owner_kind = 'blog_post' AND owner_id = old.id; +END; + +CREATE TRIGGER blog_posts_touch +AFTER UPDATE ON blog_posts +FOR EACH ROW WHEN new.updated_at = old.updated_at +BEGIN + UPDATE blog_posts SET updated_at = datetime('now') WHERE id = new.id; +END; + +CREATE TRIGGER community_page_touch +AFTER UPDATE ON community_page +FOR EACH ROW WHEN new.updated_at = old.updated_at +BEGIN + UPDATE community_page SET updated_at = datetime('now') WHERE id = new.id; +END; diff --git a/server/src/routes/blog.js b/server/src/routes/blog.js new file mode 100644 index 0000000..835de5f --- /dev/null +++ b/server/src/routes/blog.js @@ -0,0 +1,198 @@ +/* ═══════════════════════════════════════════════════════════════ + BLOG ROUTES: read-only, mounted under /api + + GET /blog/:id one published post, its body and authors + GET /community-blog the Community page's blog section + + A post is public once published. Unlisted (is_listed = 0) keeps + its page but leaves it out of the section's "newest", though it + can still be pinned there: pinning is attaching it by hand. + + The section has two halves, each pinned first and then newest, + up to its slot count (pinned posts always show, even past it): + + internal blog_posts + external featured cards owned by the community page, then + items from its RSS/Atom feeds (feeds.js), skipping + any URL a pinned card already shows. Shaped as + featured cards, so FeaturedCards.tsx draws both. + + Authors are published people, in order, and/or the post's guest + name. An author who is unpublished is left off rather than + named, the same as on every roster. + ═══════════════════════════════════════════════════════════════ */ + +import { Hono } from "hono"; + +import { asBool, loadBlocks, loadFeaturedCards, paragraphs } from "../shape.js"; +import { readFeeds } from "../feeds.js"; + +const blog = new Hono(); + +const CACHE = "public, max-age=60, stale-while-revalidate=300"; + +const json = (c, body) => c.json(body, 200, { "Cache-Control": CACHE }); + +const marks = (n) => Array(n).fill("?").join(","); + +const PAGE_ID = "community"; + +const splitTags = (tags) => + (tags ?? "") + .split(",") + .map((tag) => tag.trim()) + .filter(Boolean); + +/* Published authors for a batch of posts, keyed by post id. */ +function loadAuthors(db, ids) { + const byPost = new Map(); + if (ids.length === 0) return byPost; + const rows = db + .prepare( + `SELECT a.post_id, p.id, p.display_name, p.pronouns, p.tagline, p.photo + FROM blog_post_authors a + JOIN people p ON p.id = a.person_id AND p.is_published = 1 + WHERE a.post_id IN (${marks(ids.length)}) + ORDER BY a.post_id, a.sort_order`, + ) + .all(...ids); + for (const row of rows) { + const list = byPost.get(row.post_id) ?? []; + list.push({ + id: row.id, + name: row.display_name, + pronouns: row.pronouns, + tagline: row.tagline, + photo: row.photo, + }); + byPost.set(row.post_id, list); + } + return byPost; +} + +function shapeSummary(row, authors, body) { + return { + id: row.id, + title: row.title, + // The card's text: the excerpt, else the body's first paragraph. + excerpt: row.excerpt || paragraphs(body)[0] || null, + cover_image: row.cover_image, + published_on: row.published_on, + tags: splitTags(row.tags), + authors: [ + ...authors.map((a) => ({ id: a.id, name: a.name })), + ...(row.guest_author ? [{ id: null, name: row.guest_author }] : []), + ], + }; +} + +/* ── One post ──────────────────────────────────────────────── */ + +blog.get("/blog/:id", (c) => { + const db = c.get("db"); + const id = c.req.param("id"); + + const row = db.prepare(`SELECT * FROM blog_posts WHERE id = ? AND is_published = 1`).get(id); + if (!row) return c.json({ error: "No such post" }, 404); + + const authors = loadAuthors(db, [id]).get(id) ?? []; + const body = loadBlocks(db, "blog_post", [id], "body").get(id) ?? []; + + return json(c, { + post: { + id: row.id, + title: row.title, + excerpt: row.excerpt, + cover_image: row.cover_image, + published_on: row.published_on, + tags: splitTags(row.tags), + authors, + guest: row.guest_author ? { name: row.guest_author, photo: row.guest_photo } : null, + blocks: body, + is_listed: asBool(row.is_listed), + }, + }); +}); + +/* ── The Community page's section ──────────────────────────── */ + +blog.get("/community-blog", async (c) => { + const db = c.get("db"); + + const page = db.prepare(`SELECT * FROM community_page WHERE id = ?`).get(PAGE_ID); + if (!page) return c.json({ error: "The community page hasn't been set up." }, 500); + + // Ours: pinned, then newest. + const pinned = db + .prepare( + `SELECT b.* + FROM community_page_pinned_posts pp + JOIN blog_posts b ON b.id = pp.post_id AND b.is_published = 1 + WHERE pp.page_id = ? + ORDER BY pp.sort_order`, + ) + .all(PAGE_ID); + + const room = Math.max(0, page.internal_slots - pinned.length); + const pinnedIds = pinned.map((row) => row.id); + const newest = room + ? db + .prepare( + `SELECT * FROM blog_posts + WHERE is_published = 1 AND is_listed = 1 + ${pinnedIds.length ? `AND id NOT IN (${marks(pinnedIds.length)})` : ""} + ORDER BY published_on IS NULL, published_on DESC, created_at DESC + LIMIT ?`, + ) + .all(...pinnedIds, room) + : []; + + const posts = [...pinned, ...newest]; + const ids = posts.map((row) => row.id); + const authors = loadAuthors(db, ids); + const bodies = loadBlocks(db, "blog_post", ids, "body"); + + // Theirs: pinned cards, then the feeds' newest. + const cards = loadFeaturedCards(db, "community_page", PAGE_ID); + const feedRows = db + .prepare(`SELECT url, label FROM community_page_feeds WHERE page_id = ? ORDER BY sort_order`) + .all(PAGE_ID); + + const shown = new Set(cards.map((card) => card.url).filter(Boolean)); + const spare = Math.max(0, page.external_slots - cards.length); + const fromFeeds = spare && feedRows.length ? await readFeeds(feedRows) : []; + const latest = fromFeeds + .filter((item) => !shown.has(item.url)) + .slice(0, spare) + .map((item) => ({ + kind: "link", + ref: null, + url: item.url, + eyebrow: item.source, + title: item.title, + blurb: item.excerpt, + image: item.image ? { file: item.image, kind: "featured" } : null, + published: item.published, + })); + + return json(c, { + community_blog: { + title: page.blog_title, + blurb: page.blog_blurb, + internal: { + title: page.internal_title, + posts: posts.map((row) => + shapeSummary(row, authors.get(row.id) ?? [], bodies.get(row.id) ?? []), + ), + }, + external: { + title: page.external_title, + url: page.external_url, + label: page.external_label, + cards: [...cards, ...latest], + }, + }, + }); +}); + +export default blog; diff --git a/server/src/routes/directory.js b/server/src/routes/directory.js index 71b315f..538393b 100644 --- a/server/src/routes/directory.js +++ b/server/src/routes/directory.js @@ -18,6 +18,7 @@ teams published, and so is the organization awards published people published + blog_posts published and each leaves out unlisted records (is_listed = 0): the QR page is public, and listing them here would undo the point of them. @@ -70,6 +71,12 @@ directory.get("/directory", (c) => { WHERE is_published = 1 AND is_listed = 1 ORDER BY COALESCE(sort_name, display_name)`, ), + blog_posts: all( + `SELECT id, title AS name + FROM blog_posts + WHERE is_published = 1 AND is_listed = 1 + ORDER BY published_on IS NULL, published_on DESC, title`, + ), }, }, 200, diff --git a/src/App.tsx b/src/App.tsx index 8a8df02..7f54195 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -25,6 +25,7 @@ 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' /*Admin Pages*/ import AdminLayout from "./pages/admin/AdminLayout.tsx"; @@ -61,6 +62,7 @@ export default function App() { <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 />} /> diff --git a/src/lib/adminSchema.ts b/src/lib/adminSchema.ts index dc85af7..bb1b336 100644 --- a/src/lib/adminSchema.ts +++ b/src/lib/adminSchema.ts @@ -21,6 +21,7 @@ import { awardLogo, blockMedia, eventBackground, + blogImage, eventLogo, featuredImage, heroPhoto, @@ -1299,6 +1300,181 @@ const frontPage = { ], }; +/* ── Blog (031_blog.sql) ───────────────────────────────────────── + Posts at /blog/:id, and the Community page's blog section. The + section's community posts reuse the featured cards, limited to + links: a pinned Substack post is a link card, and Fetch preview + fills it from the post. */ + +/* A post's body is the content blocks without the card/body choice: + a post only has a body. */ +const blogBlocksChild = { + ...blocksChild, + label: "Post body", + note: "The post, top to bottom. The first paragraph doubles as the excerpt when that's left blank.", + fields: blocksChild.fields.filter((field) => field.path !== "slot"), +}; + +const blogPosts = { + key: "blog_posts", + label: "Blog posts", + singular: "blog post", + idLabel: "URL ID", + slugFrom: "title", + + list: { + columns: [ + { key: "title", label: "Title", primary: true }, + { key: "published_on", label: "Date" }, + { key: "tags", label: "Tags" }, + { key: "is_published", label: "Live", widget: "bool" }, + { key: "is_listed", label: "Listed", widget: "bool" }, + ], + filters: [ + { key: "is_published", label: "Published", options: [["1", "Live"], ["0", "Draft"]] }, + { key: "is_listed", label: "Listed", options: [["1", "Listed"], ["0", "Link only"]] }, + ], + }, + + groups: [ + { + legend: "Post", + fields: [ + { path: "title", label: "Title", required: true, full: true }, + { path: "published_on", label: "Date", widget: "date", help: "Newest first on the Community page" }, + { path: "tags", label: "Tags", help: "Comma separated, eg. Reflection, Event recap" }, + { + path: "excerpt", + label: "Excerpt", + widget: "textarea", + full: true, + help: "A sentence or two for the card. Default: the body's first paragraph.", + }, + { path: "cover_image", label: "Cover image", widget: "image", resolve: blogImage, full: true }, + ], + }, + { + legend: "Guest author", + note: "For a writer with no People record. People who wrote it go under Authors below; both can be set.", + fields: [ + { path: "guest_author", label: "Name" }, + { path: "guest_photo", label: "Photo", widget: "image", resolve: blogImage, full: true }, + ], + }, + { + legend: "Publishing", + note: "A new post is a draft until Published is ticked. Unlisted posts keep their page and can still be pinned.", + fields: [PUBLISHED_FIELD, LISTED_FIELD], + }, + ], + + children: [ + { + key: "authors", + label: "Authors", + note: "Shown as person tiles at the end of the post, in this order.", + addLabel: "Add author", + title: (row, options) => + options?.people?.find((p) => p.id === row.person_id)?.label ?? "New author", + blank: { person_id: "" }, + fields: [ + { + path: "person_id", + label: "Person", + widget: "select", + optionsFrom: "people", + required: true, + }, + ], + }, + blogBlocksChild, + ], +}; + +const communityPage = { + key: "community_page", + label: "Community blog section", + singular: "community blog section", + idLabel: "Page", + singleton: "community", + + list: { columns: [], filters: [] }, + + groups: [ + { + legend: "Section", + note: "The first section of the Community page.", + fields: [ + { path: "blog_title", label: "Heading", help: "Default: Community Blog" }, + { path: "blog_blurb", label: "Blurb", widget: "textarea", full: true }, + ], + }, + { + legend: "Our posts", + note: "Pinned posts first, then the newest published, listed posts, up to the number of slots.", + fields: [ + { path: "internal_title", label: "Heading", help: "Default: From NGU" }, + { path: "internal_slots", label: "Slots", widget: "number", help: "0 to 12. Default: 3" }, + ], + }, + { + legend: "Community posts", + note: "Pinned cards first, then the newest items from the feeds below, up to the number of slots.", + fields: [ + { path: "external_title", label: "Heading", help: "Default: From our community" }, + { path: "external_slots", label: "Slots", widget: "number", help: "0 to 12. Default: 3" }, + { path: "external_url", label: "Button link", help: "eg. https://ngu.substack.com", full: true }, + { path: "external_label", label: "Button text", help: "Default: Read more on Substack" }, + ], + }, + ], + + children: [ + { + key: "pinned_posts", + label: "Pinned posts (ours)", + note: "Always shown, before the newest.", + addLabel: "Pin a post", + title: (row, options) => + options?.blog_posts?.find((p) => p.id === row.post_id)?.label ?? "New pin", + blank: { post_id: "" }, + fields: [ + { + path: "post_id", + label: "Post", + widget: "select", + optionsFrom: "blog_posts", + required: true, + }, + ], + }, + { + ...featuredCardsChild, + label: "Pinned community posts", + note: "Always shown, before the feeds' newest. Paste a post's link and press Fetch preview.", + addLabel: "Pin a post", + blank: { kind: "", url: "", title: "" }, + fields: featuredCardsChild.fields.map((field) => + field.path === "kind" + ? { ...field, options: FEATURED_KINDS.filter(([kind]) => kind !== "record") } + : field, + ), + }, + { + key: "feeds", + label: "Feeds", + note: "RSS or Atom feeds whose newest posts fill the community slots. Read about every 30 minutes.", + addLabel: "Add feed", + title: (row) => row.label || row.url || "New feed", + blank: { url: "", label: "" }, + fields: [ + { path: "url", label: "Feed URL", required: true, full: true, help: "eg. https://ngu.substack.com/feed" }, + { path: "label", label: "Source name", help: "Shown on its cards. Default: the feed's own title" }, + ], + }, + ], +}; + export const ADMIN_ENTITIES: Record<string, any> = { organizations, events, @@ -1307,6 +1483,8 @@ export const ADMIN_ENTITIES: Record<string, any> = { awards, timeline, front_page: frontPage, + blog_posts: blogPosts, + community_page: communityPage, }; export function slugify(value) { diff --git a/src/lib/hrefs.ts b/src/lib/hrefs.ts index 78b77c2..36bdcfe 100644 --- a/src/lib/hrefs.ts +++ b/src/lib/hrefs.ts @@ -116,6 +116,8 @@ export const awardHref = (id?: string | null) => `/awards/${checkId(id, 'awardHr export const personHref = (id?: string | null) => `/people/${checkId(id, 'personHref')}` +export const blogHref = (id?: string | null) => `/blog/${checkId(id, 'blogHref')}` + export function orgHref(id?: string | null, kind?: string | null): string { return `${ORG_BASE[kind ?? ''] ?? '/organizations'}/${checkId(id, 'orgHref')}` } diff --git a/src/lib/media.ts b/src/lib/media.ts index 0ccc163..35b35f0 100644 --- a/src/lib/media.ts +++ b/src/lib/media.ts @@ -52,6 +52,9 @@ export const blockMedia = inDir('/media') // ⚠ guess ('/uploads/…'); a bare filename looks here. */ export const featuredImage = inDir('/featured') +/* blog_posts.cover_image and guest_photo. Normally uploads. */ +export const blogImage = inDir('/blog') + /* ── By record kind ──────────────────────────────────────────── The timeline sends `logo: { file, kind }` rather than a path, because v_timeline COALESCEs across five tables and only the diff --git a/src/lib/useBlog.ts b/src/lib/useBlog.ts new file mode 100644 index 0000000..0a5ab41 --- /dev/null +++ b/src/lib/useBlog.ts @@ -0,0 +1,71 @@ +/* ═══════════════════════════════════════════════════════════════ + BLOG DATA + + GET /blog/:id and GET /community-blog, as routes/blog.js shapes + them. The section's community posts arrive as featured cards, so + FeaturedCards.tsx draws them unchanged. + ═══════════════════════════════════════════════════════════════ */ + +import { detailPath } from './hrefs.ts' +import { useRecord, type Resource } from './useRecord.ts' +import type { ContentBlock } from './useContent.ts' +import type { FeaturedCard } from './useFrontPage.ts' + +export type BlogAuthor = { + id: string + name: string + pronouns?: string | null + tagline?: string | null + photo?: string | null +} + +export type BlogPostRecord = { + id: string + title: string + excerpt?: string | null + cover_image?: string | null + published_on?: string | null + tags: string[] + authors: BlogAuthor[] + guest: { name: string; photo?: string | null } | null + blocks: ContentBlock[] + is_listed: boolean +} + +/** A post on the Community page's section. `id` is null on a guest. */ +export type BlogPostSummary = { + id: string + title: string + excerpt?: string | null + cover_image?: string | null + published_on?: string | null + tags: string[] + authors: Array<{ id: string | null; name: string }> +} + +export type CommunityBlog = { + title?: string | null + blurb?: string | null + internal: { title?: string | null; posts: BlogPostSummary[] } + external: { + title?: string | null + url?: string | null + label?: string | null + cards: FeaturedCard[] + } +} + +export const useBlogPost = (id?: string | null): Resource<BlogPostRecord> => + useRecord<BlogPostRecord>(detailPath('/blog', id), 'post') + +export const useCommunityBlog = (): Resource<CommunityBlog> => + useRecord<CommunityBlog>('/community-blog', 'community_blog') + +/** '2026-09-01' → 'September 1, 2026'. Parsed as a local date, so + * it can't slip a day in a timezone west of UTC. */ +export function postDate(value?: string | null): string | null { + const match = value?.match(/^(\d{4})-(\d{2})-(\d{2})/) + if (!match) return null + const date = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3])) + return date.toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' }) +} diff --git a/src/lib/useContent.ts b/src/lib/useContent.ts index 7a6972d..6c7efb0 100644 --- a/src/lib/useContent.ts +++ b/src/lib/useContent.ts @@ -351,6 +351,7 @@ export type Directory = { teams: Array<DirectoryEntry & { org_name: string }> awards: DirectoryEntry[] people: DirectoryEntry[] + blog_posts: DirectoryEntry[] } export const useDirectory = (): Resource<Directory> => diff --git a/src/navConfig.ts b/src/navConfig.ts index 539b5bf..9a43f86 100644 --- a/src/navConfig.ts +++ b/src/navConfig.ts @@ -26,6 +26,7 @@ export const PAGE_SECTIONS = { { label: "Partner Events", hash: "#partner"}, ], "/community": [ + { label: "Community Blog", hash: "#blog" }, { label: "Local Chapters", hash: "#local" }, { label: "Virtual Community", hash: "#virtual" }, { label: "Partner Organizations", hash: "#partners" }, diff --git a/src/pages/BlogPost.tsx b/src/pages/BlogPost.tsx new file mode 100644 index 0000000..fdeaeb9 --- /dev/null +++ b/src/pages/BlogPost.tsx @@ -0,0 +1,114 @@ +/* ═══════════════════════════════════════════════════════════════ + BLOG POST: /blog/:id + + One of our own posts: cover, date and tags, the content-block + body, then its authors as person tiles. Authors are published + people (linked to their pages) and, when the post names one, a + guest with no people record (a tile that links nowhere). + + There's no /blog index on purpose: the Community page's blog + section is where posts are listed, so "back" goes there. + ═══════════════════════════════════════════════════════════════ */ + +import { Link, useParams } from 'react-router-dom' + +import PageShell, { type ShellSection } from '../components/PageShell.tsx' +import PageState from '../components/PageState.tsx' +import ContentBlocks from '../components/ContentBlocks.tsx' +import PeopleTiles from '../components/PeopleTiles.tsx' +import { blogImage, personPhoto } from '../lib/media.ts' +import { postDate, useBlogPost } from '../lib/useBlog.ts' + +const ACCENT = '#138ba0' +const BODY = '#4a6b72' + +/* Where "back" goes: the section on the Community page. */ +const BACK = { to: '/community#blog', label: 'Community Blog' } + +export default function BlogPost() { + const { id } = useParams() + const { data: post, loading, error, notFound, reload } = useBlogPost(id) + + if (!post) { + return ( + <PageState + loading={loading} + error={error} + notFound={notFound} + onRetry={reload} + noun="post" + backTo={BACK.to} + backLabel={BACK.label} + /> + ) + } + + const date = postDate(post.published_on) + const cover = blogImage(post.cover_image) + const byline = [ + ...post.authors.map((author) => author.name), + ...(post.guest ? [post.guest.name] : []), + ].join(', ') + + const authors = [ + ...post.authors.map((author) => ({ + id: author.id, + name: author.name, + tagline: author.tagline, + pronouns: author.pronouns, + photo: personPhoto(author.photo), + })), + ...(post.guest ? [{ name: post.guest.name, title: 'Guest author', photo: blogImage(post.guest.photo) }] : []), + ] + + const sections: ShellSection[] = [ + { + id: 'post', + title: 'Post', + accent: ACCENT, + background: '#ffffff', + content: ( + <article className="mx-auto max-w-3xl space-y-8 px-6"> + <div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-sm" style={{ color: BODY }}> + {date && <time dateTime={post.published_on ?? undefined}>{date}</time>} + {byline && <span>By {byline}</span>} + {post.tags.map((tag) => ( + <span + key={tag} + className="rounded-full px-3 py-0.5 text-xs font-semibold" + style={{ background: '#eef9fb', color: ACCENT }} + > + {tag} + </span> + ))} + <Link to={BACK.to} className="ml-auto hover:underline" style={{ color: ACCENT }}> + {BACK.label} + </Link> + </div> + + {cover && ( + <img src={cover} alt="" className="aspect-video w-full rounded-2xl object-cover" /> + )} + + <ContentBlocks blocks={post.blocks} accent={ACCENT} /> + </article> + ), + }, + ] + + if (authors.length > 0) { + sections.push({ + id: 'authors', + title: authors.length === 1 ? 'About the author' : 'About the authors', + accent: ACCENT, + background: '#eef9fb', + content: ( + <div className="mx-auto max-w-6xl px-6"> + <PeopleTiles size="md" accent={ACCENT} people={authors} /> + </div> + ), + }) + } + + return <PageShell title={post.title} intro={post.excerpt ?? undefined} sections={sections} /> +} diff --git a/src/pages/Community.tsx b/src/pages/Community.tsx index 3a7dc6f..fd0e449 100644 --- a/src/pages/Community.tsx +++ b/src/pages/Community.tsx @@ -3,15 +3,23 @@ import { useSectionManifest } from "../lib/sections.tsx"; import OrgListMap, { OrgMapToggle } from "./sections/OrgList-Map.tsx"; import OrgListVertical from "./sections/OrgList-Vertical.tsx"; import OrgListCards from "./sections/OrgList-Card.tsx"; +import CommunityBlog from "./sections/CommunityBlog.tsx"; +import { useCommunityBlog } from "../lib/useBlog.ts"; /* ═══════════════════════════════════════════════════════════════ COMMUNITY PAGE - Two views of the organizations table. The map is filtered to - chapters; the vertical list is filtered to regions. Same rows, - same endpoint, different shape on the page. + The blog first, then two views of the organizations table. The + map is filtered to chapters; the vertical list is filtered to + regions. Same rows, same endpoint, different shape on the page. + + The blog's heading and blurb are the admin's (Blog → Community + section), so that one entry is built here from the same cached + request CommunityBlog makes for its posts. ═══════════════════════════════════════════════════════════════ */ +const BLOG_DEFAULT_TITLE = "Community Blog"; + const SECTIONS = [ { id: "chapters", @@ -58,7 +66,19 @@ const SECTIONS = [ ]; export default function CommunityPage() { - const sections = useSectionManifest(SECTIONS); + const { data: blog } = useCommunityBlog(); + + const sections = useSectionManifest([ + { + id: "blog", + title: blog?.title || BLOG_DEFAULT_TITLE, + blurb: blog?.blurb ?? undefined, + accent: "#138ba0", + background: "#ffffff", + Component: CommunityBlog, + }, + ...SECTIONS, + ]); return ( <PageShell diff --git a/src/pages/QrCodes.tsx b/src/pages/QrCodes.tsx index a0173d7..ce011d6 100644 --- a/src/pages/QrCodes.tsx +++ b/src/pages/QrCodes.tsx @@ -15,7 +15,7 @@ const SECTIONS = [ id: 'make', title: 'Make a QR code', blurb: - 'Pick a page from the main navigation, or any event, organization, team, award or person on the site. The code always points at the live site.', + 'Pick a page from the main navigation, or any event, organization, team, award, person or blog post on the site. The code always points at the live site.', accent: '#138ba0', background: '#eef9fb', content: ( diff --git a/src/pages/admin/adminNav.ts b/src/pages/admin/adminNav.ts index b907f54..d300267 100644 --- a/src/pages/admin/adminNav.ts +++ b/src/pages/admin/adminNav.ts @@ -70,6 +70,17 @@ export const CMS_NAV = [ label: "Front page", blurb: "The hero, its photos or livestream, and which bands the home page draws.", }, + // Posts, and the Community page section that lists them. Two + // entities, one tab, like Organizations with Teams and Awards. + { + to: "/admin/blog_posts", + label: "Blog", + blurb: "Posts of our own, and the Community page's blog section.", + children: [ + { to: "/admin/blog_posts", label: "Posts" }, + { to: "/admin/community_page", label: "Community section" }, + ], + }, // Not an entity: the uploaded-image library every image field // picks from. Its own page, AdminMedia.tsx. { diff --git a/src/pages/sections/CommunityBlog.tsx b/src/pages/sections/CommunityBlog.tsx new file mode 100644 index 0000000..bb0916c --- /dev/null +++ b/src/pages/sections/CommunityBlog.tsx @@ -0,0 +1,145 @@ +/* ═══════════════════════════════════════════════════════════════ + COMMUNITY BLOG + + The Community page's blog section (Admin → Blog → Community + section). Two halves, each pinned first and then newest, as + routes/blog.js decides: + + our posts cards for our own /blog/:id pages + community posts featured cards (pinned by hand, or the + newest from the listed feeds), drawn by + FeaturedCards, with a button to the Substack + + The section's heading and blurb come from the same record; the + page reads them through the same cached request (Community.tsx). + A half with nothing in it isn't drawn. + ═══════════════════════════════════════════════════════════════ */ + +import { Link } from 'react-router-dom' + +import FeaturedCards from '../../components/FeaturedCards.tsx' +import PlatformIcon from '../../components/PlatformIcon.tsx' +import { blogHref } from '../../lib/hrefs.ts' +import { blogImage } from '../../lib/media.ts' +import { preview } from '../../lib/text.ts' +import { postDate, useCommunityBlog, type BlogPostSummary } from '../../lib/useBlog.ts' +import HomeLink from './home/HomeLink.tsx' + +/* Headings for a half the admin didn't title. */ +const DEFAULTS = { + internal: 'From NGU', + external: 'From our community', + externalLabel: 'Read more on Substack', +} + +const EXCERPT_CHARS = 180 + +function PostCard({ post, accent }: { post: BlogPostSummary; accent: string }) { + const cover = blogImage(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-[#138ba0]/15 bg-white shadow-sm transition-shadow hover:shadow-lg"> + {cover ? ( + <img src={cover} alt="" loading="lazy" className="aspect-video w-full object-cover" /> + ) : ( + <div className="aspect-video w-full bg-gradient-to-br from-[#eef9fb] to-[#d9f0f3]" /> + )} + <div className="flex flex-1 flex-col p-6"> + {(date || post.tags.length > 0) && ( + <p className="text-xs font-bold uppercase tracking-[0.2em]" style={{ color: accent }}> + {[date, ...post.tags].filter(Boolean).join(' · ')} + </p> + )} + <h4 className="mt-2 font-display text-xl font-extrabold leading-snug text-[#073d4a]"> + <Link + to={blogHref(post.id)} + className="after:absolute after:inset-0 after:rounded-2xl after:content-[''] hover:underline" + > + {post.title} + </Link> + </h4> + {post.excerpt && ( + <p className="mt-2 leading-relaxed text-[#4a6b72]">{preview(post.excerpt, EXCERPT_CHARS)}</p> + )} + {authors && <p className="mt-auto pt-4 text-sm font-medium text-[#26454c]">By {authors}</p>} + </div> + </li> + ) +} + +function Subheading({ children, accent }: { children: string; accent: string }) { + return ( + <h3 className="text-2xl font-800" style={{ color: accent }}> + {children} + </h3> + ) +} + +export default function CommunityBlog({ accent = '#138ba0' }: { accent?: string }) { + const { data: blog, loading, error, reload } = useCommunityBlog() + + if (!blog) { + return ( + <div className="mx-auto max-w-6xl px-6 text-[#4a6b72]"> + {loading ? ( + 'Loading…' + ) : ( + <> + Couldn’t load the blog. {error}{' '} + <button type="button" onClick={reload} className="underline" style={{ color: accent }}> + Try again + </button> + </> + )} + </div> + ) + } + + const { internal, external } = blog + const hasInternal = internal.posts.length > 0 + const hasExternal = external.cards.length > 0 || Boolean(external.url) + + if (!hasInternal && !hasExternal) { + return <p className="mx-auto max-w-6xl px-6 text-center text-[#4a6b72]">· Posts coming soon ·</p> + } + + return ( + <div className="mx-auto max-w-6xl space-y-16 px-6"> + {hasInternal && ( + <div> + <Subheading accent={accent}>{internal.title || DEFAULTS.internal}</Subheading> + <ul className="mt-6 grid gap-6 sm:grid-cols-2 lg:grid-cols-3"> + {internal.posts.map((post) => ( + <PostCard key={post.id} post={post} accent={accent} /> + ))} + </ul> + </div> + )} + + {hasExternal && ( + <div> + <div className="flex flex-wrap items-end gap-4"> + <Subheading accent={accent}>{external.title || DEFAULTS.external}</Subheading> + {external.url && ( + <HomeLink + url={external.url} + className="ml-auto inline-flex items-center gap-2 rounded-full px-5 py-2 text-sm font-semibold text-white transition-transform hover:scale-105" + style={{ background: accent }} + > + <PlatformIcon platform={/substack\.com/i.test(external.url) ? 'substack' : null} /> + {external.label || DEFAULTS.externalLabel} + </HomeLink> + )} + </div> + {external.cards.length > 0 && ( + <div className="mt-6"> + <FeaturedCards cards={external.cards} /> + </div> + )} + </div> + )} + </div> + ) +} diff --git a/src/pages/sections/QrCodeMaker.tsx b/src/pages/sections/QrCodeMaker.tsx index 8495f37..4db3dcb 100644 --- a/src/pages/sections/QrCodeMaker.tsx +++ b/src/pages/sections/QrCodeMaker.tsx @@ -24,7 +24,7 @@ import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react' import QrCode from '../../components/QrCode.tsx' import { NAV_ACTIONS, PAGE_LINKS, PAGE_SECTIONS } from '../../navConfig.ts' -import { awardHref, eventHref, orgHref, personHref, teamHref } from '../../lib/hrefs.ts' +import { awardHref, blogHref, eventHref, orgHref, personHref, teamHref } from '../../lib/hrefs.ts' import { siteUrl } from '../../lib/site.ts' import { useDirectory, type Directory } from '../../lib/useContent.ts' @@ -35,7 +35,7 @@ const MUTED = '#4a6b72' anything bigger should use the SVG. */ const PNG_SIZE = 1024 -type Kind = 'pages' | 'events' | 'organizations' | 'teams' | 'awards' | 'people' +type Kind = 'pages' | 'events' | 'organizations' | 'teams' | 'awards' | 'people' | 'blog_posts' const KINDS: Array<[Kind, string]> = [ ['pages', 'Main navigation'], @@ -44,6 +44,7 @@ const KINDS: Array<[Kind, string]> = [ ['teams', 'Teams'], ['awards', 'Awards'], ['people', 'People'], + ['blog_posts', 'Blog posts'], ] /* Organizations are grouped by kind in the dropdown, in this order. */ @@ -106,6 +107,8 @@ function groupsFor(kind: Kind, directory: Directory | null): Group[] { return [{ choices: directory.awards.map((a) => ({ path: awardHref(a.id), label: a.name })) }] case 'people': return [{ choices: directory.people.map((p) => ({ path: personHref(p.id), label: p.name })) }] + case 'blog_posts': + return [{ choices: directory.blog_posts.map((b) => ({ path: blogHref(b.id), label: b.name })) }] } } From c62dc84adde4ba6f08ff013e68c572f445d07f92 Mon Sep 17 00:00:00 2001 From: Zaldimmar <Zaldimmar@gmail.com> Date: Sun, 27 Sep 2026 16:28:26 -0500 Subject: [PATCH 17/22] Point Community page links at the sections that exist The nav and the org pages' "All regions" and "All chapters" links used #local and #virtual, but the Community page's sections are #chapters and #regions, so those links didn't jump anywhere. The nav labels now match the section headings too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/lib/hrefs.ts | 4 ++-- src/navConfig.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/lib/hrefs.ts b/src/lib/hrefs.ts index 36bdcfe..a793416 100644 --- a/src/lib/hrefs.ts +++ b/src/lib/hrefs.ts @@ -165,9 +165,9 @@ export const ORG_KIND_LABEL: Record<string, string> = { export function orgListHref(kind?: string | null): { to: string; label: string } { switch (kind) { case 'region': - return { to: '/community#local', label: 'All regions' } + return { to: '/community#regions', label: 'All regions' } case 'chapter': - return { to: '/community#local', label: 'All chapters' } + return { to: '/community#chapters', label: 'All chapters' } case 'partner': return { to: '/community#partners', label: 'All partner organizations' } default: diff --git a/src/navConfig.ts b/src/navConfig.ts index 9a43f86..967ee3b 100644 --- a/src/navConfig.ts +++ b/src/navConfig.ts @@ -27,8 +27,8 @@ export const PAGE_SECTIONS = { ], "/community": [ { label: "Community Blog", hash: "#blog" }, - { label: "Local Chapters", hash: "#local" }, - { label: "Virtual Community", hash: "#virtual" }, + { label: "Local Chapters", hash: "#chapters" }, + { label: "Unity Regions", hash: "#regions" }, { label: "Partner Organizations", hash: "#partners" }, ], "/leadership": [ From c5f12c769f0e11e1e8d568fcbfe6eeca39acd143 Mon Sep 17 00:00:00 2001 From: Zaldimmar <Zaldimmar@gmail.com> Date: Sun, 27 Sep 2026 16:50:21 -0500 Subject: [PATCH 18/22] Improve content blocks: new types, formatting, and a better editor Blocks (migration 032): video (click to play, sharing the featured cards' player), button and callout types; quotes get an attribution and images alt text separate from the caption. Paragraphs, callouts, quotes and list items take **bold**, *italic*, [text](url), line breaks and blank-line paragraphs, parsed into elements (never HTML) with only safe link schemes. A list item's detail no longer uses an em-dash. Editor: each block type shows only its fields, with a named type and a description, and every open block previews itself with the site's renderer. Any repeater row can now be duplicated or have a new row inserted below it; nested collections take `when`, and help text can depend on the row. src/seed-showcase.js writes a local test post using every block type and option. It refuses the production database. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- CLAUDE.md | 1 + docs/updating-data-in-code.md | 4 +- server/src/admin-schema.js | 5 + .../migrations/032_content_block_types.sql | 80 +++++++++ server/src/seed-showcase.js | 109 +++++++++++++ server/src/shape.js | 4 +- src/components/ContentBlocks.tsx | 154 +++++++++++------- src/components/FeaturedCards.tsx | 73 +-------- src/components/InlineText.tsx | 137 ++++++++++++++++ src/components/VideoPlayer.tsx | 93 +++++++++++ src/components/admin/fields.tsx | 108 ++++++++++-- src/lib/adminSchema.ts | 117 +++++++++++-- src/lib/useContent.ts | 7 + 13 files changed, 723 insertions(+), 169 deletions(-) create mode 100644 server/src/migrations/032_content_block_types.sql create mode 100644 server/src/seed-showcase.js create mode 100644 src/components/InlineText.tsx create mode 100644 src/components/VideoPlayer.tsx diff --git a/CLAUDE.md b/CLAUDE.md index 977fbfb..7b23b88 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -22,6 +22,7 @@ Backend (`server/`, Node >= 22). The server reads `HOST` (default `127.0.0.1`), - `DB_PATH=./dev.db pnpm dev`: run with `node --watch` - `DB_PATH=./dev.db pnpm migrate`: apply migrations without starting the server - `DB_PATH=./dev.db node src/admin-cli.js add|list|passwd|role|disable|enable ...`: the only way accounts are created +- `DB_PATH=./dev.db node src/seed-showcase.js`: writes /blog/content-block-showcase, every content block type in one page, for checking `ContentBlocks.tsx`. Local only; refuses /var/lib/ngu. In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API must listen on that port. diff --git a/docs/updating-data-in-code.md b/docs/updating-data-in-code.md index 11b8d6c..8c09e41 100644 --- a/docs/updating-data-in-code.md +++ b/docs/updating-data-in-code.md @@ -174,8 +174,8 @@ also in `admin-schema.js` and a CHECK): | People → Affiliations → Role; Teams → Members → Role | lead, board, staff, volunteer, member | no | `ROLE_LABEL` in `src/pages/PersonDetail.tsx` | | Links → Kind (on organizations, events, people, teams) | action, social, website, email | no | `splitLinks` in `server/src/shape.js` | | Links → Platform | instagram, facebook, discord, youtube, tiktok, x, substack, spotify, linkedin | **yes**, `PLATFORMS` | `PlatformIcon.tsx` draws the icon on the button. **No CHECK and no `enumeration`**: the column is plain text, so adding one is an entry in `PLATFORMS` (`src/lib/platforms.ts`) and its icon in `src/components/PlatformIcon.tsx`, no migration. | -| Content blocks → Slot | card, body | no | `ContentBlocks.tsx` | -| Content blocks → Type | heading, subheading, paragraph, list, links, quote, image, divider | no | `ContentBlocks.tsx` (one renderer per type) | +| Content blocks → Shown in (slot) | card, body | **yes** | `paragraphs()` in `server/src/shape.js` (card), `ContentBlocks.tsx` (body) | +| Content blocks → Type | heading, subheading, paragraph, list, links, quote, image, divider, video, button, callout | **yes**, `BLOCK_TYPES` (with each type's description) | `ContentBlocks.tsx` (one renderer per type). Which fields each type shows is `when` on the fields in `blocksChild` (`src/lib/adminSchema.ts`). | | Timeline → Kind (+ list filter) | milestone, event, organization, award, people | no | `KIND_NAMES` in `src/pages/sections/history/TimelineEntry.tsx` | | Timeline → Points at (+ list filter) | event, organization, award, person, team | no | `refHref` in `src/lib/hrefs.ts` | | Timeline → Precision (and on events/orgs) | year, month, day | no | the history page's grouping | diff --git a/server/src/admin-schema.js b/server/src/admin-schema.js index a9c6828..fafa531 100644 --- a/server/src/admin-schema.js +++ b/server/src/admin-schema.js @@ -176,12 +176,17 @@ const blocksChild = (ownerKind) => ({ "quote", "image", "divider", + "video", + "button", + "callout", ], { required: true }, ), text("text"), text("media"), text("href"), + text("alt"), + text("cite"), ], children: [ { diff --git a/server/src/migrations/032_content_block_types.sql b/server/src/migrations/032_content_block_types.sql new file mode 100644 index 0000000..ccb59d5 --- /dev/null +++ b/server/src/migrations/032_content_block_types.sql @@ -0,0 +1,80 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 032 CONTENT BLOCKS: VIDEO, BUTTON, CALLOUT, ALT TEXT, ATTRIBUTION +-- +-- Three new block types, and two columns for types that had to +-- borrow one: +-- +-- video href is the link (YouTube, Vimeo, Facebook) or a +-- video file; text is the caption; media an optional +-- still. Drawn click-to-play, like a featured card. +-- button text is the label, href where it goes. +-- callout text in a tinted box, for a note or announcement. +-- +-- alt an image's alt text. text stays its caption: a +-- caption describes the moment, alt describes the +-- picture to someone who can't see it. +-- cite who a quote is by. +-- +-- The type list is a CHECK, so the table is rebuilt, the same way +-- 031 did (see its header): legacy_alter_table around the rename, +-- because the *_cleanup triggers on other tables name it, then the +-- index and the owner trigger again. +-- +-- PRAGMA user_version; -- reads 31 before this file +-- ═══════════════════════════════════════════════════════════════ + +CREATE TABLE content_blocks_new ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + owner_kind TEXT NOT NULL + CHECK (owner_kind IN ('organization', 'event', 'person', 'team', 'blog_post')), + owner_id TEXT NOT NULL, + slot TEXT NOT NULL DEFAULT 'body' CHECK (slot IN ('card', 'body')), + sort_order INTEGER NOT NULL DEFAULT 0, + + type TEXT NOT NULL + CHECK (type IN ('heading', 'subheading', 'paragraph', + 'list', 'links', 'quote', 'image', 'divider', + 'video', 'button', 'callout')), + text TEXT, + media TEXT, + href TEXT, + alt TEXT, + cite TEXT +) STRICT; + +INSERT INTO content_blocks_new (id, owner_kind, owner_id, slot, sort_order, type, text, media, href) +SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href + FROM content_blocks; + +PRAGMA legacy_alter_table = ON; +DROP TABLE content_blocks; +ALTER TABLE content_blocks_new RENAME TO content_blocks; +PRAGMA legacy_alter_table = OFF; + +CREATE INDEX content_blocks_owner_idx + ON content_blocks (owner_kind, owner_id, slot, sort_order); + + +-- ── Triggers last (see CLAUDE.md, Migrations) ── + +CREATE TRIGGER content_blocks_owner_exists +BEFORE INSERT ON content_blocks +BEGIN + SELECT CASE + WHEN new.owner_kind = 'event' + AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.owner_id) + THEN RAISE(ABORT, 'content_blocks: no such event') + WHEN new.owner_kind = 'organization' + AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.owner_id) + THEN RAISE(ABORT, 'content_blocks: no such organization') + WHEN new.owner_kind = 'person' + AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.owner_id) + THEN RAISE(ABORT, 'content_blocks: no such person') + WHEN new.owner_kind = 'team' + AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.owner_id) + THEN RAISE(ABORT, 'content_blocks: no such team') + WHEN new.owner_kind = 'blog_post' + AND NOT EXISTS (SELECT 1 FROM blog_posts WHERE id = new.owner_id) + THEN RAISE(ABORT, 'content_blocks: no such blog post') + END; +END; diff --git a/server/src/seed-showcase.js b/server/src/seed-showcase.js new file mode 100644 index 0000000..36c3e28 --- /dev/null +++ b/server/src/seed-showcase.js @@ -0,0 +1,109 @@ +/* ═══════════════════════════════════════════════════════════════ + CONTENT BLOCK SHOWCASE: a local test page + + DB_PATH=./dev.db node src/seed-showcase.js + + Writes one blog post, /blog/content-block-showcase, that uses + every content block type and every option each one has, so a + change to ContentBlocks.tsx can be checked against all of them + in one place. Run it again to put the post back as written here; + it replaces the post and its blocks, and nothing else. + + The post is published but unlisted: its page works, and it stays + out of the Community page's "newest". It is test content, so this + refuses the production database (anything under /var/lib/ngu). + + Image blocks point at /uploads/showcase.jpg. Upload any photo in + Admin → Media and paste its path into those blocks, or leave them + to check how a missing image degrades. + ═══════════════════════════════════════════════════════════════ */ + +import { openDatabase, migrate, tx } from "./db.js"; + +const DB_PATH = process.env.DB_PATH ?? "./ngu.db"; + +// Matched anywhere in the path, not only at its start, so a shell +// that rewrites /var/lib/... into its own form (Git Bash) is caught too. +if (/(^|\/)var\/lib\/ngu(\/|$)/.test(DB_PATH.replace(/\\/g, "/"))) { + console.error("✗ This is test content. It won't write to the production database."); + process.exit(1); +} + +const POST_ID = "content-block-showcase"; +const IMAGE = "/uploads/showcase.jpg"; + +/* [type, fields, items?] in page order. */ +const BLOCKS = [ + ["paragraph", { text: "Every content block type, top to bottom, with each of its options. Use it to check the page after changing how blocks draw." }], + ["heading", { text: "Heading" }], + ["subheading", { text: "Subheading" }], + ["paragraph", { text: "A paragraph with **bold**, *italic*, a [link to the history page](/history) and an [outside link](https://example.org).\nThis line follows a single line break.\n\nA blank line starts a second paragraph in the same block." }], + ["paragraph", { text: "A whole paragraph that is a link, set with the block's Link field.", href: "/community" }], + ["callout", { text: "**A callout.** For a note or an announcement. It takes the same formatting as a paragraph, including [links](/give)." }], + ["quote", { text: "Unity is not a feeling we wait for. It is a practice we keep.", cite: "A retreat speaker" }], + ["quote", { text: "A quote with no attribution." }], + ["divider", {}], + ["subheading", { text: "Lists" }], + ["list", {}, [ + { text: "A plain item" }, + { text: "An item with a detail", detail: "the detail" }, + { text: "A linked item", url: "/retreats" }, + { text: "A linked item with a detail", url: "https://example.org", detail: "opens in a new tab" }, + ]], + ["links", {}, [ + { text: "Retreats", url: "/retreats" }, + { text: "Community", url: "/community" }, + { text: "An outside site", url: "https://example.org" }, + ]], + ["button", { text: "A button", href: "/give" }], + ["divider", {}], + ["subheading", { text: "Images" }], + ["image", { media: IMAGE, alt: "Describe the picture here", text: "An image with a caption and alt text" }], + ["image", { media: IMAGE, alt: "The same picture, linked", href: "/history" }], + ["subheading", { text: "Video" }], + ["video", { href: "https://www.youtube.com/watch?v=dQw4w9WgXcQ", text: "A YouTube video, with its own thumbnail" }], + ["video", { href: "https://vimeo.com/76979871", media: IMAGE, text: "A Vimeo video with an uploaded still" }], +]; + +const db = await openDatabase(DB_PATH); +migrate(db, { log: () => {} }); + +tx(db, () => { + db.prepare(`DELETE FROM blog_posts WHERE id = ?`).run(POST_ID); // takes its blocks (blog_posts_cleanup) + + db.prepare( + `INSERT INTO blog_posts (id, title, excerpt, published_on, tags, guest_author, is_published, is_listed) + VALUES (?, ?, ?, date('now'), ?, ?, 1, 0)`, + ).run( + POST_ID, + "Content block showcase", + "Every block type in one place, for checking the page.", + "Test, Showcase", + "The showcase script", + ); + + const block = db.prepare( + `INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite) + VALUES ('blog_post', ?, 'body', ?, ?, ?, ?, ?, ?, ?)`, + ); + const item = db.prepare( + `INSERT INTO content_block_items (block_id, sort_order, text, detail, url) VALUES (?, ?, ?, ?, ?)`, + ); + + BLOCKS.forEach(([type, f, items = []], order) => { + const { lastInsertRowid } = block.run( + POST_ID, + order, + type, + f.text ?? null, + f.media ?? null, + f.href ?? null, + f.alt ?? null, + f.cite ?? null, + ); + items.forEach((it, i) => item.run(lastInsertRowid, i, it.text, it.detail ?? null, it.url ?? null)); + }); +}); + +db.close(); +console.log(`✓ ${BLOCKS.length} blocks written. Open /blog/${POST_ID}`); diff --git a/server/src/shape.js b/server/src/shape.js index b8dbde4..5973156 100644 --- a/server/src/shape.js +++ b/server/src/shape.js @@ -66,7 +66,7 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") { const blockRows = db .prepare( - `SELECT id, owner_id, type, text, media, href + `SELECT id, owner_id, type, text, media, href, alt, cite FROM content_blocks WHERE owner_kind = ? AND slot = ? AND owner_id IN (${placeholders(ids.length)}) ORDER BY owner_id, sort_order`, @@ -83,6 +83,8 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") { text: row.text, media: row.media, href: row.href, + alt: row.alt, + cite: row.cite, items: [], }; byId.set(row.id, block); diff --git a/src/components/ContentBlocks.tsx b/src/components/ContentBlocks.tsx index fab186c..d94e4b9 100644 --- a/src/components/ContentBlocks.tsx +++ b/src/components/ContentBlocks.tsx @@ -1,55 +1,41 @@ /* ═══════════════════════════════════════════════════════════════ CONTENT BLOCKS - Renders the `body` slot of content_blocks. Events, organizations - and teams all own blocks and all render them the same way, so - this is written once and tinted by the caller's accent. + Renders the `body` slot of content_blocks. Events, organizations, + teams, people and blog posts all own blocks and all render them + the same way, so this is written once and tinted by the caller's + accent. The admin's block editor previews each block through this + same component. - ⚠ Assumes shape.js's loadBlocks returns rows carrying `type`, - `text`, `media`, `href` and an `items` array. If the field names - differ, this is the only file to fix — nothing else reads a - block. + What each type reads (see 032_content_block_types.sql): + + heading, subheading text + paragraph text (formatted), href makes it all a link + callout text (formatted), in a tinted box + quote text (formatted), cite is who said it + list items: text, detail, url + links items with a url, as outlined buttons + button text is the label, href where it goes + image media, alt, text is the caption, href + video href is the video, media a still, text + the caption; click to play + divider nothing + + "Formatted" is InlineText.tsx: **bold**, *italic*, [text](url), + line breaks, and a blank line for a new paragraph. An unknown `type` renders its text as a paragraph rather than disappearing. A block somebody typed into the admin should be visible even if the renderer hasn't caught up with it. ═══════════════════════════════════════════════════════════════ */ -import { Link } from 'react-router-dom' import { blockMedia } from '../lib/media.ts' import type { ContentBlock } from '../lib/useContent.ts' +import { Anchor, Inline, Paragraphs } from './InlineText.tsx' +import VideoPlayer from './VideoPlayer.tsx' const BODY = '#4a6b72' -/** External if it has a scheme or starts with //; otherwise it's - * one of our own routes and should go through the router. */ -const isExternal = (url: string) => /^([a-z][a-z0-9+.-]*:|\/\/)/i.test(url) - -function Anchor({ - href, - children, - className, - style, -}: { - href: string - children: React.ReactNode - className?: string - style?: React.CSSProperties -}) { - if (isExternal(href)) { - return ( - <a href={href} target="_blank" rel="noreferrer" className={className} style={style}> - {children} - </a> - ) - } - return ( - <Link to={href} className={className} style={style}> - {children} - </Link> - ) -} - export default function ContentBlocks({ blocks, accent = '#138ba0', @@ -70,6 +56,15 @@ export default function ContentBlocks({ ) } +function Caption({ text }: { text?: string | null }) { + if (!text) return null + return ( + <figcaption className="mt-2 text-sm opacity-70" style={{ color: BODY }}> + {text} + </figcaption> + ) +} + function Block({ block, accent }: { block: ContentBlock; accent: string }) { const text = block.text ?? '' @@ -102,11 +97,9 @@ function Block({ block, accent }: { block: ContentBlock; accent: string }) { {item.text} </Anchor> ) : ( - item.text - )} - {item.detail && ( - <span className="opacity-70"> — {item.detail}</span> + <Inline text={item.text} accent={accent} /> )} + {item.detail && <span className="opacity-70">: {item.detail}</span>} </span> </li> ))} @@ -131,14 +124,43 @@ function Block({ block, accent }: { block: ContentBlock; accent: string }) { </div> ) + case 'button': + if (!text || !block.href) return null + return ( + <div> + <Anchor + href={block.href} + className="inline-block rounded-full px-6 py-2.5 font-semibold text-white transition-transform hover:scale-105" + style={{ background: accent }} + > + {text} + </Anchor> + </div> + ) + case 'quote': return ( - <blockquote - className="border-l-2 pl-5 text-lg italic" - style={{ borderColor: accent, color: BODY }} + <figure className="border-l-2 pl-5" style={{ borderColor: accent }}> + <blockquote className="text-lg italic" style={{ color: BODY }}> + <Inline text={text} accent={accent} /> + </blockquote> + {block.cite && ( + <figcaption className="mt-2 text-sm font-semibold not-italic" style={{ color: accent }}> + {block.cite} + </figcaption> + )} + </figure> + ) + + case 'callout': + if (!text) return null + return ( + <aside + className="space-y-3 rounded-2xl border-l-4 px-6 py-5 leading-relaxed" + style={{ borderColor: accent, background: `color-mix(in srgb, ${accent} 8%, white)`, color: '#26454c' }} > - {text} - </blockquote> + <Paragraphs text={text} accent={accent} /> + </aside> ) case 'image': { @@ -147,10 +169,9 @@ function Block({ block, accent }: { block: ContentBlock; accent: string }) { const img = ( <img src={src} - // A caption is a caption, not alt text — but an image with - // neither is decorative, and alt="" is the correct answer - // for that rather than a filename read aloud. - alt={text} + // Alt describes the picture; the caption describes the + // moment. No alt means decorative, which alt="" says. + alt={block.alt ?? ''} loading="lazy" decoding="async" className="w-full rounded-lg" @@ -159,31 +180,38 @@ function Block({ block, accent }: { block: ContentBlock; accent: string }) { return ( <figure> {block.href ? <Anchor href={block.href}>{img}</Anchor> : img} - {text && ( - <figcaption className="mt-2 text-sm opacity-70" style={{ color: BODY }}> - {text} - </figcaption> - )} + <Caption text={text} /> </figure> ) } + case 'video': + if (!block.href) return null + return ( + <figure> + <div className="overflow-hidden rounded-lg"> + <VideoPlayer url={block.href} still={blockMedia(block.media)} title={text || null} /> + </div> + <Caption text={text} /> + </figure> + ) + case 'divider': return <hr className="border-0 h-px" style={{ background: accent, opacity: 0.3 }} /> case 'paragraph': default: if (!text) return null - return ( + return block.href ? ( <p className="leading-relaxed" style={{ color: BODY }}> - {block.href ? ( - <Anchor href={block.href} className="underline" style={{ color: accent }}> - {text} - </Anchor> - ) : ( - text - )} + <Anchor href={block.href} className="underline" style={{ color: accent }}> + {text} + </Anchor> </p> + ) : ( + <div className="space-y-4"> + <Paragraphs text={text} accent={accent} className="leading-relaxed" style={{ color: BODY }} /> + </div> ) } } diff --git a/src/components/FeaturedCards.tsx b/src/components/FeaturedCards.tsx index f384137..f6ddac3 100644 --- a/src/components/FeaturedCards.tsx +++ b/src/components/FeaturedCards.tsx @@ -10,10 +10,9 @@ record links to the record's own page (hrefs.ts builds it) link links to its URL, a new tab when it leaves the site - video a still with a play button; pressing it swaps in the - player, so the page loads no iframes until then. The - still is the card's image, else YouTube's thumbnail, - else a plain panel. + video VideoPlayer: a still with a play button that swaps in + the player when pressed. The still is the card's + image, else YouTube's thumbnail, else a plain panel. A photo fills the picture area; a logo sits inside it on a soft panel instead, since cropping a logo to 16:9 cuts it off. @@ -22,13 +21,11 @@ import { useState } from 'react' import HomeLink from '../pages/sections/home/HomeLink.tsx' +import VideoPlayer from './VideoPlayer.tsx' import { refHref } from '../lib/hrefs.ts' import { logoForKind } from '../lib/media.ts' -import { playingSource, videoSource, videoThumbnail } from '../lib/embeds.ts' import type { FeaturedCard } from '../lib/useFrontPage.ts' -const ACCENT = '#138ba0' - /* Image kinds that are photographs, drawn edge to edge. Anything else is a logo, drawn whole. */ const PHOTO_KINDS = new Set(['event-background', 'featured', 'person']) @@ -71,68 +68,8 @@ function Picture({ card }: { card: FeaturedCard }) { } function VideoPicture({ card }: { card: FeaturedCard }) { - const [playing, setPlaying] = useState(false) - const source = videoSource(card.url) - - if (playing && source) { - const live = playingSource(source) - return live.kind === 'file' ? ( - <video src={live.src} controls autoPlay playsInline className="aspect-video w-full bg-black" /> - ) : ( - <iframe - src={live.src} - title={card.title || 'Video'} - allow="autoplay; encrypted-media; picture-in-picture; fullscreen" - allowFullScreen - className="aspect-video w-full border-0 bg-black" - /> - ) - } - const own = card.image ? logoForKind(card.image.kind, card.image.file) : null - const still = own ?? videoThumbnail(card.url) - - const face = ( - <> - {still ? ( - <img src={still} alt="" loading="lazy" className="aspect-video w-full object-cover" /> - ) : ( - <div className="aspect-video w-full bg-gradient-to-br from-[#073d4a] to-[#04262e]" /> - )} - <span - aria-hidden="true" - className="absolute inset-0 flex items-center justify-center bg-black/10 transition-colors group-hover:bg-black/25" - > - <span className="flex h-16 w-16 items-center justify-center rounded-full bg-white/90 shadow-lg transition-transform group-hover:scale-110"> - <svg viewBox="0 0 24 24" className="ml-1 h-7 w-7" fill={ACCENT}> - <path d="M8 5v14l11-7z" /> - </svg> - </span> - </span> - </> - ) - - // A link that can't be played here still goes somewhere. - if (!source) { - return card.url ? ( - <HomeLink url={card.url} className="group relative block"> - {face} - </HomeLink> - ) : ( - <div className="relative">{face}</div> - ) - } - - return ( - <button - type="button" - onClick={() => setPlaying(true)} - aria-label={`Play ${card.title || 'video'}`} - className="group relative block w-full" - > - {face} - </button> - ) + return <VideoPlayer url={card.url} still={own} title={card.title} /> } function Card({ card }: { card: FeaturedCard }) { diff --git a/src/components/InlineText.tsx b/src/components/InlineText.tsx new file mode 100644 index 0000000..37338c0 --- /dev/null +++ b/src/components/InlineText.tsx @@ -0,0 +1,137 @@ +/* ═══════════════════════════════════════════════════════════════ + INLINE TEXT + + The little formatting a content block's text may carry, typed in + the admin as plain characters: + + **bold** *italic* [link text](url) + a line break keeps its place + a blank line starts a new paragraph + + Parsed into React elements, never HTML, so nothing typed can + inject markup. A link only becomes one when its URL is a site + path (/history, #section), https/http, mailto: or tel:; anything + else (javascript:, data:) shows as the plain text it was. + + `Paragraphs` is for block-level text (paragraph, callout): one + <p> per blank-line-separated part. `Inline` is for text that sits + inside something else (a quote, a list item). + ═══════════════════════════════════════════════════════════════ */ + +import { Fragment, type CSSProperties, type ReactNode } from 'react' +import { Link } from 'react-router-dom' + +const TOKEN = /\*\*(.+?)\*\*|\*(.+?)\*|\[([^\]]+)\]\(([^)\s]+)\)/g +const SAFE_URL = /^(\/(?!\/)|#|https?:\/\/|mailto:|tel:)/i + +/** External if it has a scheme or starts with //; otherwise it's + * one of our own routes and goes through the router. */ +export const isExternalUrl = (url: string) => /^([a-z][a-z0-9+.-]*:|\/\/)/i.test(url) + +export function Anchor({ + href, + children, + className, + style, +}: { + href: string + children: ReactNode + className?: string + style?: CSSProperties +}) { + if (isExternalUrl(href)) { + const app = /^(mailto|tel):/i.test(href) + return ( + <a + href={href} + className={className} + style={style} + {...(app ? {} : { target: '_blank', rel: 'noreferrer' })} + > + {children} + </a> + ) + } + if (href.startsWith('#')) { + return ( + <a href={href} className={className} style={style}> + {children} + </a> + ) + } + return ( + <Link to={href} className={className} style={style}> + {children} + </Link> + ) +} + +function line(text: string, accent: string, key: string): ReactNode[] { + const out: ReactNode[] = [] + let last = 0 + let n = 0 + for (const match of text.matchAll(TOKEN)) { + const at = match.index ?? 0 + if (at > last) out.push(text.slice(last, at)) + const [whole, bold, italic, label, url] = match + const k = `${key}-${n++}` + if (bold != null) out.push(<strong key={k} className="font-semibold">{bold}</strong>) + else if (italic != null) out.push(<em key={k}>{italic}</em>) + else if (label != null && SAFE_URL.test(url)) { + out.push( + <Anchor key={k} href={url} className="underline underline-offset-2" style={{ color: accent }}> + {label} + </Anchor>, + ) + } else out.push(whole) + last = at + whole.length + } + if (last < text.length) out.push(text.slice(last)) + return out +} + +/** Text inside another element: formatting and line breaks. */ +export function Inline({ text, accent }: { text?: string | null; accent: string }) { + const lines = (text ?? '').split('\n') + return ( + <> + {lines.map((part, i) => ( + <Fragment key={i}> + {i > 0 && <br />} + {line(part, accent, `l${i}`)} + </Fragment> + ))} + </> + ) +} + +/** Block text: one <p> per part separated by a blank line. */ +export function Paragraphs({ + text, + accent, + className, + style, +}: { + text?: string | null + accent: string + className?: string + style?: CSSProperties +}) { + const parts = (text ?? '') + .split(/\n\s*\n/) + .map((part) => part.trim()) + .filter(Boolean) + return ( + <> + {parts.map((part, i) => ( + <p key={i} className={className} style={style}> + <Inline text={part} accent={accent} /> + </p> + ))} + </> + ) +} + +/** For the editor's help text under a formatted box. */ +export const FORMATTING_HELP = + '**bold**, *italic*, [link text](https://…). A blank line starts a new paragraph.' diff --git a/src/components/VideoPlayer.tsx b/src/components/VideoPlayer.tsx new file mode 100644 index 0000000..8fb842c --- /dev/null +++ b/src/components/VideoPlayer.tsx @@ -0,0 +1,93 @@ +/* ═══════════════════════════════════════════════════════════════ + VIDEO PLAYER: click to play + + A still with a play button; pressing it swaps in the player, so a + page loads no iframes until someone asks for one. Used by the + featured cards and the video content block. + + The still is the caller's image, else YouTube's own thumbnail, + else a plain dark panel. A link that embeds.ts can't turn into a + player (not https, or not a host it knows how to frame) still + goes somewhere: the still becomes a link to it. + ═══════════════════════════════════════════════════════════════ */ + +import { useState } from 'react' + +import HomeLink from '../pages/sections/home/HomeLink.tsx' +import { playingSource, videoSource, videoThumbnail } from '../lib/embeds.ts' + +const ACCENT = '#138ba0' + +export default function VideoPlayer({ + url, + still, + title, + className = '', +}: { + url?: string | null + /** An image URL to show before it plays. */ + still?: string | null + title?: string | null + className?: string +}) { + const [playing, setPlaying] = useState(false) + const source = videoSource(url) + + if (playing && source) { + const live = playingSource(source) + return live.kind === 'file' ? ( + <video src={live.src} controls autoPlay playsInline className={`aspect-video w-full bg-black ${className}`} /> + ) : ( + <iframe + src={live.src} + title={title || 'Video'} + allow="autoplay; encrypted-media; picture-in-picture; fullscreen" + allowFullScreen + className={`aspect-video w-full border-0 bg-black ${className}`} + /> + ) + } + + const image = still ?? videoThumbnail(url) + + const face = ( + <> + {image ? ( + <img src={image} alt="" loading="lazy" className={`aspect-video w-full object-cover ${className}`} /> + ) : ( + <div className={`aspect-video w-full bg-gradient-to-br from-[#073d4a] to-[#04262e] ${className}`} /> + )} + <span + aria-hidden="true" + className="absolute inset-0 flex items-center justify-center bg-black/10 transition-colors group-hover:bg-black/25" + > + <span className="flex h-16 w-16 items-center justify-center rounded-full bg-white/90 shadow-lg transition-transform group-hover:scale-110"> + <svg viewBox="0 0 24 24" className="ml-1 h-7 w-7" fill={ACCENT}> + <path d="M8 5v14l11-7z" /> + </svg> + </span> + </span> + </> + ) + + if (!source) { + return url ? ( + <HomeLink url={url} className="group relative block"> + {face} + </HomeLink> + ) : ( + <div className="relative">{face}</div> + ) + } + + return ( + <button + type="button" + onClick={() => setPlaying(true)} + aria-label={`Play ${title || 'video'}`} + className="group relative block w-full" + > + {face} + </button> + ) +} diff --git a/src/components/admin/fields.tsx b/src/components/admin/fields.tsx index 232f1a6..0ab717d 100644 --- a/src/components/admin/fields.tsx +++ b/src/components/admin/fields.tsx @@ -32,6 +32,21 @@ can't keep a value for a choice it no longer makes: a featured card switched from "record" to "link" drops its record. + A nested collection takes `when` the same way, and one that goes + hidden is emptied: a list block turned into a paragraph drops its + items. + + `help` may be a function of the row, for help that depends on + another field (a content block's type says what its text is). + + `preview` on a collection names an entry in PREVIEWS below; each + open row then shows how it will look on the site, drawn by the + site's own component. + + Every row can be duplicated (a copy lands below it, ids stripped + so it saves as new) or have a blank row inserted below it, as + well as appended at the end. + `widget: "linkPreview"` is a URL box with a "Fetch preview" button (LinkPreviewInput in MediaLibrary.tsx) that fills the row's empty title, blurb and image through `onPatch`. @@ -57,8 +72,15 @@ import { useRef, useState } from "react"; +import ContentBlocks from "../ContentBlocks.tsx"; import { ImageInput, LinkPreviewInput } from "./MediaLibrary.tsx"; +/* Live previews a collection can name with `preview`. Each gets the + row as the form holds it, which is the API's shape. */ +const PREVIEWS = { + contentBlock: (row) => <ContentBlocks blocks={[row]} />, +}; + const input = "w-full rounded-lg border border-[#4a6b72]/25 bg-white px-3 py-2 text-sm text-[#26454c] " + "outline-none transition-colors focus:border-[#138ba0] focus:ring-2 focus:ring-[#138ba0]/25"; @@ -104,17 +126,37 @@ export function fieldShown(field, row) { /* A row after an edit, with any field the edit hid cleared. "" is the engine's deliberate clear, so it saves as NULL. */ -function withHiddenCleared(fields, row) { +function withHiddenCleared(spec, row) { let next = row; - for (const field of fields) { + for (const field of spec.fields) { const value = next[field.path]; if (!fieldShown(field, next) && value != null && value !== "") { next = { ...next, [field.path]: "" }; } } + for (const nested of spec.children ?? []) { + if (!fieldShown(nested, next) && next[nested.key]?.length) { + next = { ...next, [nested.key]: [] }; + } + } return next; } +/* A copy of a row with every id removed, nested rows included, so + the server inserts it as new rather than colliding with the row + it was copied from. */ +function withoutIds(value) { + if (Array.isArray(value)) return value.map(withoutIds); + if (!value || typeof value !== "object") return value; + const copy = {}; + for (const [key, inner] of Object.entries(value)) { + if (key !== "id") copy[key] = withoutIds(inner); + } + return copy; +} + +const helpText = (field, row) => (typeof field.help === "function" ? field.help(row) : field.help); + /* ── Field ───────────────────────────────────────────────────── */ export function Field({ field, value, row, options, error, onChange, onPatch }: any) { @@ -170,7 +212,7 @@ export function Field({ field, value, row, options, error, onChange, onPatch }: onChange={(e) => onChange(e.target.checked ? 1 : 0)} className="h-4 w-4 rounded border-[#4a6b72]/40 text-[#138ba0] focus:ring-[#138ba0]/40 disabled:opacity-50" /> - {field.help ?? "Yes"} + {helpText(field, row) ?? "Yes"} </label> ) : widget === "textarea" ? ( <textarea @@ -281,9 +323,9 @@ export function Field({ field, value, row, options, error, onChange, onPatch }: This points at something that has been deleted. Pick a replacement before saving. </p> ) : ( - field.help && + helpText(field, row) && widget !== "checkbox" && ( - <p className="mt-1 text-xs text-[#4a6b72]">{field.help}</p> + <p className="mt-1 text-xs text-[#4a6b72]">{helpText(field, row)}</p> ) )} </div> @@ -340,7 +382,7 @@ export function Repeater({ const rowRefs = useRef<any[]>([]); const update = (index, next) => - onChange(list.map((row, i) => (i === index ? withHiddenCleared(spec.fields, next) : row))); + onChange(list.map((row, i) => (i === index ? withHiddenCleared(spec, next) : row))); const move = (index, delta) => { const target = index + delta; @@ -374,6 +416,13 @@ export function Repeater({ onChange([...list, { ...spec.blank }]); }; + /* A row placed at `at`, pushing everything from there down one, + and opened so it can be filled in straight away. */ + const insertAt = (at, row) => { + setOpen((prev) => remapOpen(prev, (i) => (i >= at ? i + 1 : i)).add(at)); + onChange([...list.slice(0, at), row, ...list.slice(at)]); + }; + const removeAt = (index) => { setOpen((prev) => remapOpen(prev, (i) => (i === index ? -1 : i > index ? i - 1 : i))); onChange(list.filter((_, i) => i !== index)); @@ -518,6 +567,18 @@ export function Repeater({ > ↓ </IconButton> + <IconButton + label="Insert a new one below" + onClick={() => insertAt(index + 1, { ...spec.blank })} + > + + + </IconButton> + <IconButton + label="Duplicate" + onClick={() => insertAt(index + 1, withoutIds(row))} + > + ⧉ + </IconButton> <IconButton label="Remove" danger @@ -547,19 +608,30 @@ export function Repeater({ ))} </FieldGrid> - {(spec.children ?? []).map((nested) => ( - <div key={nested.key} className="mt-4 border-t border-[#4a6b72]/15 pt-4"> - <Repeater - spec={nested} - rows={row[nested.key]} - options={options} - errors={errors} - errorPrefix={`${errorPrefix}${index}.${nested.key}.`} - className="" - onChange={(value) => update(index, { ...row, [nested.key]: value })} - /> + {(spec.children ?? []) + .filter((nested) => fieldShown(nested, row)) + .map((nested) => ( + <div key={nested.key} className="mt-4 border-t border-[#4a6b72]/15 pt-4"> + <Repeater + spec={nested} + rows={row[nested.key]} + options={options} + errors={errors} + errorPrefix={`${errorPrefix}${index}.${nested.key}.`} + className="" + onChange={(value) => update(index, { ...row, [nested.key]: value })} + /> + </div> + ))} + + {spec.preview && PREVIEWS[spec.preview] && ( + <div className="mt-4 rounded-lg border border-dashed border-[#138ba0]/30 bg-white p-4"> + <p className="mb-3 text-xs font-semibold uppercase tracking-wider text-[#4a6b72]/70"> + Preview + </p> + {PREVIEWS[spec.preview](row)} </div> - ))} + )} </> )} </div> diff --git a/src/lib/adminSchema.ts b/src/lib/adminSchema.ts index bb1b336..f035adf 100644 --- a/src/lib/adminSchema.ts +++ b/src/lib/adminSchema.ts @@ -17,6 +17,7 @@ import { preview } from "./text.ts"; import { PLATFORMS } from "./platforms.ts"; +import { FORMATTING_HELP } from "../components/InlineText.tsx"; import { awardLogo, blockMedia, @@ -286,44 +287,126 @@ const hostsChild = { ], }; +/* Content blocks. The type decides which fields appear (`when`), + what the text box is for (`help` as a function), and whether the + block has items; the preview under each open block is the site's + own renderer. Types and what they read: ContentBlocks.tsx. */ +const BLOCK_TYPES = [ + ["paragraph", "Paragraph", "Body text. Formatting: " + FORMATTING_HELP], + ["heading", "Heading", "A section heading."], + ["subheading", "Subheading", "A smaller heading under a heading."], + ["callout", "Callout", "A note or announcement in a tinted box. Formatting: " + FORMATTING_HELP], + ["quote", "Quote", "A quotation, with who said it. Formatting: " + FORMATTING_HELP], + ["list", "List", "Bulleted items, each optionally linked, with an optional detail."], + ["links", "Link buttons", "A row of outlined buttons, one per item."], + ["button", "Button", "One filled call-to-action button, eg. Register, Donate."], + ["image", "Image", "A picture, with alt text and an optional caption and link."], + ["video", "Video", "A YouTube, Vimeo or Facebook video, or a video file, played in place."], + ["divider", "Divider", "A thin line between parts."], +]; + +const blockTypeLabel = (type) => BLOCK_TYPES.find(([value]) => value === type)?.[1] ?? type; + +const TEXT_TYPES = ["paragraph", "heading", "subheading", "callout", "quote", "button", "image", "video"]; + +const TEXT_HELP = { + paragraph: FORMATTING_HELP, + callout: FORMATTING_HELP, + quote: FORMATTING_HELP, + button: "The button's label, eg. Register now", + image: "Caption shown under the image. Optional.", + video: "Caption shown under the video. Optional.", +}; + +const TEXT_LABEL = { button: "Label", image: "Caption", video: "Caption" }; + +const HREF_HELP = { + paragraph: "Optional. Makes the whole paragraph one link. For a link inside the text, use [text](url).", + button: "Where the button goes, eg. /give or https://…", + image: "Optional. Makes the image a link.", + video: "The video's page, eg. https://www.youtube.com/watch?v=…, or a video file", +}; + const blocksChild = { key: "content_blocks", label: "Content blocks", addLabel: "Add block", - title: (row) => `${row.type ?? "block"}: ${preview(row.text, 40) || "empty"}`, + preview: "contentBlock", + title: (row) => { + const label = blockTypeLabel(row.type) || "Block"; + const text = preview(row.text || row.href || row.media || "", 40); + return text ? `${label}: ${text}` : label; + }, blank: { slot: "body", type: "paragraph", text: "" }, fields: [ - { path: "slot", label: "Slot", widget: "select", options: ["card", "body"] }, + { + path: "slot", + label: "Shown in", + widget: "select", + options: [ + ["body", "The page"], + ["card", "The card (paragraphs only)"], + ], + }, { path: "type", label: "Type", widget: "select", - options: [ - "heading", - "subheading", - "paragraph", - "list", - "links", - "quote", - "image", - "divider", - ], + options: BLOCK_TYPES.map(([value, label]) => [value, label]), + help: (row) => BLOCK_TYPES.find(([value]) => value === row?.type)?.[2], + }, + { + path: "text", + label: "Text", + widget: "textarea", + full: true, + when: { path: "type", value: TEXT_TYPES }, + help: (row) => TEXT_HELP[row?.type], + }, + { + path: "cite", + label: "Attribution", + help: "Who said it, eg. Jane Doe, Retreat 2024", + full: true, + when: { path: "type", value: "quote" }, + }, + { + path: "href", + label: "Link", + full: true, + when: { path: "type", value: ["paragraph", "button", "image", "video"] }, + help: (row) => HREF_HELP[row?.type], + }, + { + path: "media", + label: "Image", + widget: "image", + resolve: blockMedia, + full: true, + when: { path: "type", value: ["image", "video"] }, + help: (row) => + row?.type === "video" ? "Still shown before it plays. Default: YouTube's own thumbnail." : undefined, + }, + { + path: "alt", + label: "Alt text", + full: true, + when: { path: "type", value: "image" }, + help: "Describes the picture for someone who can't see it, eg. Campers around a fire at dusk", }, - { path: "text", label: "Text", widget: "textarea", full: true }, - { path: "media", label: "Media", widget: "image", resolve: blockMedia, full: true }, - { path: "href", label: "Link" }, ], children: [ { key: "items", label: "Items", addLabel: "Add item", + when: { path: "type", value: ["list", "links"] }, title: (row) => row.text || "New item", blank: { text: "" }, fields: [ { path: "text", label: "Text", required: true }, - { path: "detail", label: "Detail" }, - { path: "url", label: "URL", help: "Blank for a plain list item" }, + { path: "detail", label: "Detail", help: "Lists only: shown after the text" }, + { path: "url", label: "URL", help: "Blank for a plain list item. Link buttons need one." }, ], }, ], diff --git a/src/lib/useContent.ts b/src/lib/useContent.ts index 6c7efb0..f3ce42c 100644 --- a/src/lib/useContent.ts +++ b/src/lib/useContent.ts @@ -31,9 +31,16 @@ export type ContentBlock = { | 'quote' | 'image' | 'divider' + | 'video' + | 'button' + | 'callout' text?: string | null media?: string | null href?: string | null + /** An image's alt text. */ + alt?: string | null + /** Who a quote is by. */ + cite?: string | null items?: Array<{ text: string; detail?: string | null; url?: string | null }> } From 422e521394918cbcbf77aace6f2d361a5a6826d2 Mon Sep 17 00:00:00 2001 From: Zaldimmar <Zaldimmar@gmail.com> Date: Sun, 27 Sep 2026 16:58:49 -0500 Subject: [PATCH 19/22] Extend the showcase seed to every record kind seed-showcase.js now writes a fully filled region (with map areas), chapter, team with a lead and members, award with recipients, person (bio, private details, links, current and past roles), an upcoming retreat with hosts, billed people, links and a card background, a weekly series, a past event where the award was given, and the content block showcase post with a real author and a guest. All test data with showcase- ids. Published but unlisted by default; --listed also puts it in the site's lists, map, counts and the History page. It still refuses the production database. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- CLAUDE.md | 2 +- server/src/seed-showcase.js | 445 ++++++++++++++++++++++++++++++++---- 2 files changed, 398 insertions(+), 49 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 7b23b88..0ac0f25 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -22,7 +22,7 @@ Backend (`server/`, Node >= 22). The server reads `HOST` (default `127.0.0.1`), - `DB_PATH=./dev.db pnpm dev`: run with `node --watch` - `DB_PATH=./dev.db pnpm migrate`: apply migrations without starting the server - `DB_PATH=./dev.db node src/admin-cli.js add|list|passwd|role|disable|enable ...`: the only way accounts are created -- `DB_PATH=./dev.db node src/seed-showcase.js`: writes /blog/content-block-showcase, every content block type in one page, for checking `ContentBlocks.tsx`. Local only; refuses /var/lib/ngu. +- `DB_PATH=./dev.db node src/seed-showcase.js [--listed]`: writes fully filled test records (a region, chapter, team, award, person, three events and a blog post with every content block type), ids starting `showcase-`, for checking pages. Unlisted unless `--listed`. Local only; refuses /var/lib/ngu. In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API must listen on that port. diff --git a/server/src/seed-showcase.js b/server/src/seed-showcase.js index 36c3e28..e93e3fb 100644 --- a/server/src/seed-showcase.js +++ b/server/src/seed-showcase.js @@ -1,26 +1,51 @@ /* ═══════════════════════════════════════════════════════════════ - CONTENT BLOCK SHOWCASE: a local test page + SHOWCASE: local test records with every field filled in DB_PATH=./dev.db node src/seed-showcase.js + DB_PATH=./dev.db node src/seed-showcase.js --listed - Writes one blog post, /blog/content-block-showcase, that uses - every content block type and every option each one has, so a - change to ContentBlocks.tsx can be checked against all of them - in one place. Run it again to put the post back as written here; - it replaces the post and its blocks, and nothing else. + Writes one of each record kind with every field and option used, + so a change to any page can be checked against a record that + exercises all of it: - The post is published but unlisted: its page works, and it stays - out of the Community page's "newest". It is test content, so this - refuses the production database (anything under /var/lib/ngu). + /regions/showcase-region region: areas, map note, links, blocks + /chapters/showcase-chapter chapter: meets, started, region + /teams/showcase-team team: a lead and members + /awards/showcase-award award: recipients, one at an event + /people/showcase-person person: bio, links, roles past and + current, events, awards, private data + /events/showcase-event upcoming retreat: hosts, billed + people, links, blocks, background + /events/showcase-series weekly series with times + /events/showcase-past-event past event where the award was given + /blog/content-block-showcase every content block type - Image blocks point at /uploads/showcase.jpg. Upload any photo in - Admin → Media and paste its path into those blocks, or leave them - to check how a missing image degrades. + Everything is test data: ids start with showcase- (the blog post + is content-block-showcase), names say Showcase, and contact + details use example.org and 555 numbers. Run it again to put it + all back as written here; it replaces these records and nothing + else. + + Published but unlisted by default: every page above works, and + none of it shows in the site's lists, counts, map or QR page. + One consequence: a region's page lists only listed chapters, + teams, awards and events, so the showcase region's are empty. + --listed lists everything instead, and + adds timeline entries, so the Community map, Retreats bands, + calendar, History page and front page counts can be checked too. + Run without it again to take them back out. + + Images point at /uploads/showcase.jpg. Upload any photo in + Admin → Media and copy it to that name in the uploads directory, + or leave it missing to check how each page copes without one. + + It refuses the production database (anything under /var/lib/ngu). ═══════════════════════════════════════════════════════════════ */ import { openDatabase, migrate, tx } from "./db.js"; const DB_PATH = process.env.DB_PATH ?? "./ngu.db"; +const LISTED = process.argv.includes("--listed") ? 1 : 0; // Matched anywhere in the path, not only at its start, so a shell // that rewrites /var/lib/... into its own form (Git Bash) is caught too. @@ -29,11 +54,23 @@ if (/(^|\/)var\/lib\/ngu(\/|$)/.test(DB_PATH.replace(/\\/g, "/"))) { process.exit(1); } -const POST_ID = "content-block-showcase"; const IMAGE = "/uploads/showcase.jpg"; +const POST_ID = "content-block-showcase"; -/* [type, fields, items?] in page order. */ -const BLOCKS = [ +const REGION = "showcase-region"; +const CHAPTER = "showcase-chapter"; +const TEAM = "showcase-team"; +const AWARD = "showcase-award"; +const PERSON = "showcase-person"; +const MEMBERS = ["showcase-member-1", "showcase-member-2", "showcase-member-3"]; +const EVENT = "showcase-event"; +const SERIES = "showcase-series"; +const PAST = "showcase-past-event"; + +/* ── Content ───────────────────────────────────────────────── */ + +/* Every block type, for the blog showcase. [type, fields, items?] */ +const ALL_BLOCKS = [ ["paragraph", { text: "Every content block type, top to bottom, with each of its options. Use it to check the page after changing how blocks draw." }], ["heading", { text: "Heading" }], ["subheading", { text: "Subheading" }], @@ -65,45 +102,357 @@ const BLOCKS = [ ["video", { href: "https://vimeo.com/76979871", media: IMAGE, text: "A Vimeo video with an uploaded still" }], ]; +/* A record page's body: a handful of types, so it reads like a + real page rather than a catalogue. */ +const pageBody = (what) => [ + ["heading", { text: `About this ${what}` }], + ["paragraph", { text: `This is **showcase data** for a ${what} page. Every field on the record is filled in, so anything left blank on the page is something the page doesn't draw.\n\nSee the [content block showcase](/blog/${POST_ID}) for every block type.` }], + ["callout", { text: `**Test content:** made by seed-showcase.js, not a real ${what}.` }], + ["list", {}, [ + { text: "What we do", detail: "gather, learn, serve" }, + { text: "Where to start", url: "/community" }, + ]], + ["quote", { text: "A line someone said about this place.", cite: "Showcase Person" }], + ["image", { media: IMAGE, alt: "A group photo", text: "A caption for the photo" }], + ["button", { text: "Get involved", href: "/feedback" }], +]; + +/* The card slot: paragraphs only, shown on cards and list rows. */ +const cardText = (what) => [ + ["paragraph", { text: `Showcase ${what}: the short description that appears on its card.` }], + ["paragraph", { text: "A second card paragraph, to check how two read." }], +]; + +const standardLinks = (name) => [ + { kind: "action", label: "Register", url: "https://example.org/register", is_primary: 1 }, + { kind: "action", platform: "discord", label: "Join the Discord", url: "https://discord.com/invite/example" }, + { kind: "social", platform: "instagram", label: "@showcase", url: "https://instagram.com/showcase" }, + { kind: "social", platform: "facebook", label: `${name} on Facebook`, url: "https://facebook.com/showcase" }, + { kind: "social", platform: "youtube", label: "YouTube", url: "https://youtube.com/@showcase" }, + { kind: "website", label: "Website", url: "https://example.org" }, + { kind: "email", label: "showcase@example.org", url: "mailto:showcase@example.org" }, +]; + +/* ── Writing ───────────────────────────────────────────────── */ + const db = await openDatabase(DB_PATH); migrate(db, { log: () => {} }); -tx(db, () => { - db.prepare(`DELETE FROM blog_posts WHERE id = ?`).run(POST_ID); // takes its blocks (blog_posts_cleanup) +function insert(table, row) { + const keys = Object.keys(row); + return db + .prepare(`INSERT INTO ${table} (${keys.join(", ")}) VALUES (${keys.map(() => "?").join(", ")})`) + .run(...keys.map((k) => row[k] ?? null)); +} - db.prepare( - `INSERT INTO blog_posts (id, title, excerpt, published_on, tags, guest_author, is_published, is_listed) - VALUES (?, ?, ?, date('now'), ?, ?, 1, 0)`, - ).run( - POST_ID, - "Content block showcase", - "Every block type in one place, for checking the page.", - "Test, Showcase", - "The showcase script", - ); - - const block = db.prepare( - `INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite) - VALUES ('blog_post', ?, 'body', ?, ?, ?, ?, ?, ?, ?)`, - ); - const item = db.prepare( - `INSERT INTO content_block_items (block_id, sort_order, text, detail, url) VALUES (?, ?, ?, ?, ?)`, - ); - - BLOCKS.forEach(([type, f, items = []], order) => { - const { lastInsertRowid } = block.run( - POST_ID, - order, +function blocks(ownerKind, ownerId, slot, list) { + list.forEach(([type, f, items = []], order) => { + const { lastInsertRowid } = insert("content_blocks", { + owner_kind: ownerKind, + owner_id: ownerId, + slot, + sort_order: order, type, - f.text ?? null, - f.media ?? null, - f.href ?? null, - f.alt ?? null, - f.cite ?? null, - ); - items.forEach((it, i) => item.run(lastInsertRowid, i, it.text, it.detail ?? null, it.url ?? null)); + ...f, + }); + items.forEach((item, i) => insert("content_block_items", { block_id: lastInsertRowid, sort_order: i, ...item })); }); +} + +function links(ownerKind, ownerId, list) { + list.forEach((link, order) => insert("links", { owner_kind: ownerKind, owner_id: ownerId, sort_order: order, ...link })); +} + +const place = { + venue: "Showcase Retreat Center", + address: "123 Example Road", + locality: "Exampletown", + state_code: "PA", + country: "US", + location_label: "Exampletown, PA", + latitude: 40.2732, + longitude: -76.8867, +}; + +tx(db, () => { + /* ── Clear the last run ── cleanup triggers take blocks, links, + timeline entries and featured cards; foreign keys the rest. */ + db.prepare(`DELETE FROM blog_posts WHERE id = ?`).run(POST_ID); + db.prepare(`DELETE FROM timeline_entries WHERE title LIKE 'Showcase%' OR ref_id LIKE 'showcase-%'`).run(); + db.prepare(`DELETE FROM events WHERE id LIKE 'showcase-%'`).run(); + db.prepare(`DELETE FROM person_awards WHERE award_id LIKE 'showcase-%' OR person_id LIKE 'showcase-%'`).run(); + db.prepare(`DELETE FROM awards WHERE id LIKE 'showcase-%'`).run(); + db.prepare(`DELETE FROM affiliations WHERE person_id LIKE 'showcase-%' OR org_id LIKE 'showcase-%'`).run(); + db.prepare(`DELETE FROM teams WHERE id LIKE 'showcase-%'`).run(); + db.prepare(`DELETE FROM people WHERE id LIKE 'showcase-%'`).run(); + db.prepare(`DELETE FROM organizations WHERE id = ?`).run(CHAPTER); + db.prepare(`DELETE FROM organizations WHERE id LIKE 'showcase-%'`).run(); + + /* ── Organizations ── */ + insert("organizations", { + id: REGION, + kind: "region", + name: "Showcase Region", + short_name: "Showcase", + tagline: "A region with every field filled in", + color: "#7a5ea8", + logo: IMAGE, + ...place, + is_online: 0, + is_published: 1, + is_listed: LISTED, + sort_order: 99, + in_timeline: LISTED, + }); + insert("regions", { id: REGION, scope: "domestic", map_note: "Showcase map note: shares Pennsylvania" }); + insert("region_areas", { region_id: REGION, area_code: "PA", share: 0.5, edge: "top", note: "western half" }); + insert("region_areas", { region_id: REGION, area_code: "OH", share: 1 }); + links("organization", REGION, standardLinks("Showcase Region")); + blocks("organization", REGION, "card", cardText("region")); + blocks("organization", REGION, "body", pageBody("region")); + + insert("organizations", { + id: CHAPTER, + kind: "chapter", + name: "Showcase Chapter", + short_name: "Showcase Ch.", + tagline: "A chapter with every field filled in", + color: "#138ba0", + logo: IMAGE, + ...place, + venue: "Showcase Community Hall", + is_online: 1, + is_published: 1, + is_listed: LISTED, + sort_order: 99, + }); + insert("chapters", { id: CHAPTER, region_id: REGION, meets: "2nd Sundays, 6:00pm", started: "Since 2021" }); + links("organization", CHAPTER, standardLinks("Showcase Chapter")); + blocks("organization", CHAPTER, "card", cardText("chapter")); + blocks("organization", CHAPTER, "body", pageBody("chapter")); + + /* ── People ── */ + insert("people", { + id: PERSON, + display_name: "Showcase Person", + sort_name: "Person, Showcase", + pronouns: "they/them", + tagline: "A person with every field filled in", + photo: IMAGE, + public_email: "showcase.person@example.org", + public_phone: "555-0100", + locality: "Exampletown", + state_code: "PA", + country: "US", + location_label: "Exampletown, PA", + bio: "Showcase Person is test data. This bio has two paragraphs so the page's spacing can be checked.\n\nThe second paragraph. Everything about this person is made up by seed-showcase.js.", + primary_org_id: CHAPTER, + is_published: 1, + is_listed: LISTED, + }); + insert("person_private", { + person_id: PERSON, + birth_date: "2000-01-01", + private_email: "private@example.org", + private_phone: "555-0199", + address: "1 Private Lane, Exampletown, PA", + notes: "Private notes: only the admin shows these.", + }); + links("person", PERSON, [ + { kind: "social", platform: "instagram", label: "@showcase.person", url: "https://instagram.com/showcase.person" }, + { kind: "social", platform: "linkedin", label: "LinkedIn", url: "https://linkedin.com/in/showcase" }, + { kind: "website", label: "Website", url: "https://example.org/person" }, + { kind: "action", label: "Book a call", url: "https://example.org/call" }, + ]); + blocks("person", PERSON, "card", cardText("person")); + blocks("person", PERSON, "body", pageBody("person")); + + MEMBERS.forEach((id, i) => + insert("people", { + id, + display_name: `Showcase Member ${i + 1}`, + sort_name: `Member ${i + 1}, Showcase`, + pronouns: ["she/her", "he/him", "they/them"][i], + tagline: "A supporting person for rosters", + photo: i === 2 ? null : IMAGE, // one without a photo, for the initials fallback + location_label: "Exampletown, PA", + primary_org_id: REGION, + is_published: 1, + is_listed: LISTED, + }), + ); + + /* ── Team, and everyone's roles ── */ + insert("teams", { + id: TEAM, + org_id: REGION, + name: "Showcase Team", + tagline: "A team with a lead and members", + color: "#88b668", + logo: IMAGE, + is_published: 1, + is_listed: LISTED, + sort_order: 99, + }); + links("team", TEAM, [{ kind: "action", label: "Join the team", url: "https://example.org/join" }]); + blocks("team", TEAM, "card", cardText("team")); + blocks("team", TEAM, "body", pageBody("team")); + + insert("affiliations", { person_id: PERSON, org_id: REGION, team_id: TEAM, title: "Showcase Team Lead", role: "lead", is_owner: 1, started_on: "2023-01-01", is_public: 1, sort_order: 0 }); + insert("affiliations", { person_id: PERSON, org_id: CHAPTER, title: "Former Chapter Coordinator", role: "volunteer", started_on: "2021-01-01", ended_on: "2022-12-31", is_public: 1, sort_order: 1 }); + MEMBERS.forEach((id, i) => + insert("affiliations", { person_id: id, org_id: REGION, team_id: TEAM, title: ["Treasurer", "Secretary", null][i], role: i === 2 ? "member" : "board", is_public: 1, sort_order: i + 1 }), + ); + + /* ── Events ── */ + insert("events", { + id: EVENT, + scope_id: "regional", + event_type: "retreat", + title: "Showcase Retreat", + theme: "Every Field Filled", + tagline: "An upcoming event with everything set", + starts_on: db.prepare(`SELECT date('now', '+45 days') AS d`).get().d, + ends_on: db.prepare(`SELECT date('now', '+47 days') AS d`).get().d, + date_label: "Three days, six weeks from now", + ...place, + is_online: 0, + org_logo: IMAGE, + event_logo: IMAGE, + color: "#d62976", + gradient: "linear-gradient(160deg, rgba(214,41,118,0.10), rgba(19,139,160,0.10))", + card_image: IMAGE, + is_published: 1, + is_listed: LISTED, + in_timeline: LISTED, + }); + insert("event_hosts", { event_id: EVENT, org_id: REGION, sort_order: 0 }); + insert("event_hosts", { event_id: EVENT, person_id: PERSON, sort_order: 1 }); + [ + [PERSON, "speaker", "Keynote"], + [MEMBERS[0], "leader", "Worship leader"], + [MEMBERS[1], "facilitator", "Workshop facilitator"], + [MEMBERS[2], "musician", null], + ].forEach(([person_id, role, title], i) => + insert("event_people", { event_id: EVENT, person_id, role, title, is_public: 1, sort_order: i }), + ); + links("event", EVENT, [ + { kind: "action", label: "Register", url: "https://example.org/register", is_primary: 1 }, + { kind: "action", platform: "discord", label: "Event Discord", url: "https://discord.com/invite/example" }, + { kind: "social", platform: "instagram", label: "@showcaseretreat", url: "https://instagram.com/showcaseretreat" }, + ]); + blocks("event", EVENT, "card", cardText("event")); + blocks("event", EVENT, "body", pageBody("event")); + + insert("events", { + id: SERIES, + scope_id: "local", + event_type: "class", + title: "Showcase Weekly Class", + tagline: "A repeating series", + starts_on: db.prepare(`SELECT date('now', '-14 days') AS d`).get().d, + ends_on: db.prepare(`SELECT date('now', '+90 days') AS d`).get().d, + location_label: "Online", + is_online: 1, + color: "#138ba0", + is_series: 1, + series_frequency: "weekly", + series_interval: 1, + series_tue: 1, + series_thu: 1, + series_start_time: "19:00", + series_end_time: "20:30", + series_count: 24, + is_published: 1, + is_listed: LISTED, + }); + insert("event_hosts", { event_id: SERIES, org_id: CHAPTER, sort_order: 0 }); + links("event", SERIES, [{ kind: "action", label: "Join on Zoom", url: "https://example.org/zoom" }]); + blocks("event", SERIES, "card", cardText("series")); + + insert("events", { + id: PAST, + scope_id: "regional", + event_type: "workshop", + title: "Showcase Past Workshop", + starts_on: "2025-06-14", + ends_on: "2025-06-14", + date_label: "June 14, 2025", + location_label: "Exampletown, PA", + color: "#4a6b72", + is_published: 1, + is_listed: LISTED, + }); + insert("event_hosts", { event_id: PAST, org_id: REGION, sort_order: 0 }); + insert("event_people", { event_id: PAST, person_id: PERSON, role: "host", is_public: 1, sort_order: 0 }); + blocks("event", PAST, "card", cardText("past event")); + + /* ── Award ── */ + insert("awards", { + id: AWARD, + org_id: REGION, + name: "Showcase Award", + description: "An award with recipients. One was presented at an event, one wasn't.", + logo: IMAGE, + is_published: 1, + is_listed: LISTED, + sort_order: 99, + }); + insert("person_awards", { person_id: PERSON, award_id: AWARD, event_id: PAST, awarded_on: "2025-06-14", citation: "For filling in every field.", is_public: 1 }); + insert("person_awards", { person_id: MEMBERS[0], award_id: AWARD, awarded_on: "2024-05-01", citation: "For showing up.", is_public: 1 }); + + /* ── Timeline, only when listed: the history page shows every + published entry, so an unlisted showcase would still appear + there. ── */ + if (LISTED) { + insert("timeline_entries", { kind: "event", ref_kind: "event", ref_id: EVENT, precision: "day", is_featured: 1, is_published: 1 }); + insert("timeline_entries", { kind: "organization", ref_kind: "organization", ref_id: REGION, occurred_on: "2020-09-01", precision: "month", is_published: 1 }); + insert("timeline_entries", { kind: "award", ref_kind: "award", ref_id: AWARD, occurred_on: "2025-06-14", precision: "day", is_published: 1 }); + const { lastInsertRowid } = insert("timeline_entries", { + kind: "people", + ref_kind: "team", + ref_id: TEAM, + occurred_on: "2023-01-01", + precision: "year", + title: "Showcase Team formed", + blurb: "A team entry drawn as a roster.", + meta: "Showcase", + is_published: 1, + }); + insert("timeline_entry_people", { entry_id: lastInsertRowid, person_id: PERSON, note: "Founding lead", sort_order: 0 }); + insert("timeline_entries", { kind: "milestone", occurred_on: "2019", precision: "year", title: "Showcase milestone", blurb: "A hand-written entry with no record behind it.", link_url: "/history", is_published: 1 }); + } + + /* ── Blog post ── */ + insert("blog_posts", { + id: POST_ID, + title: "Content block showcase", + excerpt: "Every block type in one place, for checking the page.", + cover_image: IMAGE, + published_on: db.prepare(`SELECT date('now') AS d`).get().d, + tags: "Test, Showcase", + guest_author: "A Guest Author", + guest_photo: IMAGE, + is_published: 1, + is_listed: LISTED, + }); + insert("blog_post_authors", { post_id: POST_ID, person_id: PERSON, sort_order: 0 }); + blocks("blog_post", POST_ID, "body", ALL_BLOCKS); }); db.close(); -console.log(`✓ ${BLOCKS.length} blocks written. Open /blog/${POST_ID}`); + +console.log(`✓ Showcase written (${LISTED ? "listed" : "unlisted: pages only"}):`); +for (const path of [ + `/regions/${REGION}`, + `/chapters/${CHAPTER}`, + `/teams/${TEAM}`, + `/awards/${AWARD}`, + `/people/${PERSON}`, + `/events/${EVENT}`, + `/events/${SERIES}`, + `/events/${PAST}`, + `/blog/${POST_ID}`, +]) { + console.log(` ${path}`); +} From 9b6d9b9aff836b94f2b909faef1a2c7ba992b584 Mon Sep 17 00:00:00 2001 From: Zaldimmar <Zaldimmar@gmail.com> Date: Sun, 27 Sep 2026 17:05:22 -0500 Subject: [PATCH 20/22] Let the showcase seed write a deployed database with --production A database under /var/lib/ngu is still refused by default; adding --production allows it, for a server that exists to be tested, and the script says which database it is writing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- CLAUDE.md | 2 +- server/src/seed-showcase.js | 20 ++++++++++++++++---- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 0ac0f25..04b725c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -22,7 +22,7 @@ Backend (`server/`, Node >= 22). The server reads `HOST` (default `127.0.0.1`), - `DB_PATH=./dev.db pnpm dev`: run with `node --watch` - `DB_PATH=./dev.db pnpm migrate`: apply migrations without starting the server - `DB_PATH=./dev.db node src/admin-cli.js add|list|passwd|role|disable|enable ...`: the only way accounts are created -- `DB_PATH=./dev.db node src/seed-showcase.js [--listed]`: writes fully filled test records (a region, chapter, team, award, person, three events and a blog post with every content block type), ids starting `showcase-`, for checking pages. Unlisted unless `--listed`. Local only; refuses /var/lib/ngu. +- `DB_PATH=./dev.db node src/seed-showcase.js [--listed]`: writes fully filled test records (a region, chapter, team, award, person, three events and a blog post with every content block type), ids starting `showcase-`, for checking pages. Unlisted unless `--listed`. Refuses a database under /var/lib/ngu unless `--production` is also given. In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API must listen on that port. diff --git a/server/src/seed-showcase.js b/server/src/seed-showcase.js index e93e3fb..616fc47 100644 --- a/server/src/seed-showcase.js +++ b/server/src/seed-showcase.js @@ -1,8 +1,9 @@ /* ═══════════════════════════════════════════════════════════════ - SHOWCASE: local test records with every field filled in + SHOWCASE: test records with every field filled in DB_PATH=./dev.db node src/seed-showcase.js DB_PATH=./dev.db node src/seed-showcase.js --listed + DB_PATH=/var/lib/ngu/ngu.db node src/seed-showcase.js --production Writes one of each record kind with every field and option used, so a change to any page can be checked against a record that @@ -39,20 +40,31 @@ Admin → Media and copy it to that name in the uploads directory, or leave it missing to check how each page copes without one. - It refuses the production database (anything under /var/lib/ngu). + A database under /var/lib/ngu (where the deployed service keeps + its data) is refused unless --production is given too. That's for + a server that exists to be tested; on the live site, back up the + database first and leave --listed off, so the showcase is only + reachable by its links. ═══════════════════════════════════════════════════════════════ */ import { openDatabase, migrate, tx } from "./db.js"; const DB_PATH = process.env.DB_PATH ?? "./ngu.db"; const LISTED = process.argv.includes("--listed") ? 1 : 0; +const PRODUCTION = process.argv.includes("--production"); // Matched anywhere in the path, not only at its start, so a shell // that rewrites /var/lib/... into its own form (Git Bash) is caught too. -if (/(^|\/)var\/lib\/ngu(\/|$)/.test(DB_PATH.replace(/\\/g, "/"))) { - console.error("✗ This is test content. It won't write to the production database."); +const deployed = /(^|\/)var\/lib\/ngu(\/|$)/.test(DB_PATH.replace(/\\/g, "/")); + +if (deployed && !PRODUCTION) { + console.error( + `✗ ${DB_PATH} is a deployed database. This writes test content;\n` + + " add --production if that's what you mean.", + ); process.exit(1); } +if (deployed) console.warn(`! Writing showcase records to the deployed database ${DB_PATH}.`); const IMAGE = "/uploads/showcase.jpg"; const POST_ID = "content-block-showcase"; From be07bc18106de91a0e41578d3b5aaf53ff5723a4 Mon Sep 17 00:00:00 2001 From: Zaldimmar <Zaldimmar@gmail.com> Date: Sun, 27 Sep 2026 17:31:10 -0500 Subject: [PATCH 21/22] Commit the server lockfile Pins the server's dependencies, sharp included, so the VPS installs the same versions that were tested. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- server/pnpm-lock.yaml | 375 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 375 insertions(+) create mode 100644 server/pnpm-lock.yaml diff --git a/server/pnpm-lock.yaml b/server/pnpm-lock.yaml new file mode 100644 index 0000000..142f8b5 --- /dev/null +++ b/server/pnpm-lock.yaml @@ -0,0 +1,375 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + '@hono/node-server': + specifier: ^1.0.0 + version: 1.19.17(hono@4.13.9) + hono: + specifier: ^4.0.0 + version: 4.13.9 + sharp: + specifier: ^0.35.4 + version: 0.35.4 + +packages: + + '@emnapi/runtime@1.11.3': + resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==} + + '@hono/node-server@1.19.17': + resolution: {integrity: sha512-dSneS5qhiauZWGDCeK4o695Xd9nUNjviSZCMQrj10eetr8Uln1ucn6bbphOM6UynAMMtNIzZNSpL9vnASJwrPQ==} + engines: {node: '>=18.14.1'} + peerDependencies: + hono: ^4 + + '@img/colour@1.1.0': + resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} + engines: {node: '>=18'} + + '@img/sharp-darwin-arm64@0.35.4': + resolution: {integrity: sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [darwin] + + '@img/sharp-darwin-x64@0.35.4': + resolution: {integrity: sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [darwin] + + '@img/sharp-freebsd-wasm32@0.35.4': + resolution: {integrity: sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA==} + engines: {node: '>=20.9.0'} + os: [freebsd] + + '@img/sharp-libvips-darwin-arm64@1.3.3': + resolution: {integrity: sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg==} + cpu: [arm64] + os: [darwin] + + '@img/sharp-libvips-darwin-x64@1.3.3': + resolution: {integrity: sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw==} + cpu: [x64] + os: [darwin] + + '@img/sharp-libvips-linux-arm64@1.3.3': + resolution: {integrity: sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-arm@1.3.3': + resolution: {integrity: sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA==} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-ppc64@1.3.3': + resolution: {integrity: sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-riscv64@1.3.3': + resolution: {integrity: sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-s390x@1.3.3': + resolution: {integrity: sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-x64@1.3.3': + resolution: {integrity: sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linuxmusl-arm64@1.3.3': + resolution: {integrity: sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@img/sharp-libvips-linuxmusl-x64@1.3.3': + resolution: {integrity: sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@img/sharp-linux-arm64@0.35.4': + resolution: {integrity: sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-arm@0.35.4': + resolution: {integrity: sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A==} + engines: {node: '>=20.9.0'} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-ppc64@0.35.4': + resolution: {integrity: sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ==} + engines: {node: '>=20.9.0'} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-riscv64@0.35.4': + resolution: {integrity: sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA==} + engines: {node: '>=20.9.0'} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-s390x@0.35.4': + resolution: {integrity: sha512-RY0JFY8Fd6RonCBtHz+DvadaPkXDSI1AUn6yWL9TipqkZ1vY8w8evqdgyDFnkm4/K1ve1TvZiaePP5oSd4+WVQ==} + engines: {node: '>=20.9.0'} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-x64@0.35.4': + resolution: {integrity: sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@img/sharp-linuxmusl-arm64@0.35.4': + resolution: {integrity: sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@img/sharp-linuxmusl-x64@0.35.4': + resolution: {integrity: sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@img/sharp-wasm32@0.35.4': + resolution: {integrity: sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA==} + engines: {node: '>=20.9.0'} + + '@img/sharp-webcontainers-wasm32@0.35.4': + resolution: {integrity: sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA==} + engines: {node: '>=20.9.0'} + cpu: [wasm32] + + '@img/sharp-win32-arm64@0.35.4': + resolution: {integrity: sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [win32] + + '@img/sharp-win32-ia32@0.35.4': + resolution: {integrity: sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw==} + engines: {node: ^20.9.0} + cpu: [ia32] + os: [win32] + + '@img/sharp-win32-x64@0.35.4': + resolution: {integrity: sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [win32] + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + hono@4.13.9: + resolution: {integrity: sha512-7dMkQmZoC4E6F7AtaQSPhlWAdnBti+j7rreMZl8QB4jFiEhP9TWbGWUMi8WYzBCgmgulxuvLQupKqo+Co6Omyg==} + engines: {node: '>=16.9.0'} + + semver@7.8.5: + resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} + engines: {node: '>=10'} + hasBin: true + + sharp@0.35.4: + resolution: {integrity: sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA==} + engines: {node: '>=20.9.0'} + peerDependencies: + '@types/node': '*' + peerDependenciesMeta: + '@types/node': + optional: true + + tslib@2.8.1: + resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + +snapshots: + + '@emnapi/runtime@1.11.3': + dependencies: + tslib: 2.8.1 + optional: true + + '@hono/node-server@1.19.17(hono@4.13.9)': + dependencies: + hono: 4.13.9 + + '@img/colour@1.1.0': {} + + '@img/sharp-darwin-arm64@0.35.4': + optionalDependencies: + '@img/sharp-libvips-darwin-arm64': 1.3.3 + optional: true + + '@img/sharp-darwin-x64@0.35.4': + optionalDependencies: + '@img/sharp-libvips-darwin-x64': 1.3.3 + optional: true + + '@img/sharp-freebsd-wasm32@0.35.4': + dependencies: + '@img/sharp-wasm32': 0.35.4 + optional: true + + '@img/sharp-libvips-darwin-arm64@1.3.3': + optional: true + + '@img/sharp-libvips-darwin-x64@1.3.3': + optional: true + + '@img/sharp-libvips-linux-arm64@1.3.3': + optional: true + + '@img/sharp-libvips-linux-arm@1.3.3': + optional: true + + '@img/sharp-libvips-linux-ppc64@1.3.3': + optional: true + + '@img/sharp-libvips-linux-riscv64@1.3.3': + optional: true + + '@img/sharp-libvips-linux-s390x@1.3.3': + optional: true + + '@img/sharp-libvips-linux-x64@1.3.3': + optional: true + + '@img/sharp-libvips-linuxmusl-arm64@1.3.3': + optional: true + + '@img/sharp-libvips-linuxmusl-x64@1.3.3': + optional: true + + '@img/sharp-linux-arm64@0.35.4': + optionalDependencies: + '@img/sharp-libvips-linux-arm64': 1.3.3 + optional: true + + '@img/sharp-linux-arm@0.35.4': + optionalDependencies: + '@img/sharp-libvips-linux-arm': 1.3.3 + optional: true + + '@img/sharp-linux-ppc64@0.35.4': + optionalDependencies: + '@img/sharp-libvips-linux-ppc64': 1.3.3 + optional: true + + '@img/sharp-linux-riscv64@0.35.4': + optionalDependencies: + '@img/sharp-libvips-linux-riscv64': 1.3.3 + optional: true + + '@img/sharp-linux-s390x@0.35.4': + optionalDependencies: + '@img/sharp-libvips-linux-s390x': 1.3.3 + optional: true + + '@img/sharp-linux-x64@0.35.4': + optionalDependencies: + '@img/sharp-libvips-linux-x64': 1.3.3 + optional: true + + '@img/sharp-linuxmusl-arm64@0.35.4': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-arm64': 1.3.3 + optional: true + + '@img/sharp-linuxmusl-x64@0.35.4': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-x64': 1.3.3 + optional: true + + '@img/sharp-wasm32@0.35.4': + dependencies: + '@emnapi/runtime': 1.11.3 + optional: true + + '@img/sharp-webcontainers-wasm32@0.35.4': + dependencies: + '@img/sharp-wasm32': 0.35.4 + optional: true + + '@img/sharp-win32-arm64@0.35.4': + optional: true + + '@img/sharp-win32-ia32@0.35.4': + optional: true + + '@img/sharp-win32-x64@0.35.4': + optional: true + + detect-libc@2.1.2: {} + + hono@4.13.9: {} + + semver@7.8.5: {} + + sharp@0.35.4: + dependencies: + '@img/colour': 1.1.0 + detect-libc: 2.1.2 + semver: 7.8.5 + optionalDependencies: + '@img/sharp-darwin-arm64': 0.35.4 + '@img/sharp-darwin-x64': 0.35.4 + '@img/sharp-freebsd-wasm32': 0.35.4 + '@img/sharp-libvips-darwin-arm64': 1.3.3 + '@img/sharp-libvips-darwin-x64': 1.3.3 + '@img/sharp-libvips-linux-arm': 1.3.3 + '@img/sharp-libvips-linux-arm64': 1.3.3 + '@img/sharp-libvips-linux-ppc64': 1.3.3 + '@img/sharp-libvips-linux-riscv64': 1.3.3 + '@img/sharp-libvips-linux-s390x': 1.3.3 + '@img/sharp-libvips-linux-x64': 1.3.3 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.3 + '@img/sharp-libvips-linuxmusl-x64': 1.3.3 + '@img/sharp-linux-arm': 0.35.4 + '@img/sharp-linux-arm64': 0.35.4 + '@img/sharp-linux-ppc64': 0.35.4 + '@img/sharp-linux-riscv64': 0.35.4 + '@img/sharp-linux-s390x': 0.35.4 + '@img/sharp-linux-x64': 0.35.4 + '@img/sharp-linuxmusl-arm64': 0.35.4 + '@img/sharp-linuxmusl-x64': 0.35.4 + '@img/sharp-webcontainers-wasm32': 0.35.4 + '@img/sharp-win32-arm64': 0.35.4 + '@img/sharp-win32-ia32': 0.35.4 + '@img/sharp-win32-x64': 0.35.4 + + tslib@2.8.1: + optional: true From eaa9b7589bb7c3c3de945acf5fdd9b673271cdb0 Mon Sep 17 00:00:00 2001 From: Zaldimmar <Zaldimmar@gmail.com> Date: Sun, 27 Sep 2026 17:31:11 -0500 Subject: [PATCH 22/22] Bump SITE_VERSION to v1.7.4-feature-updates It still read v1.5-history, behind every v1.7 tag. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/lib/version.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/version.ts b/src/lib/version.ts index e7adbb4..0b35772 100644 --- a/src/lib/version.ts +++ b/src/lib/version.ts @@ -7,4 +7,4 @@ box or a build banner can read the same value later. ═══════════════════════════════════════════════════════════════ */ -export const SITE_VERSION = "NGU-Web.v1.5-history"; +export const SITE_VERSION = "NGU-Web.v1.7.4-feature-updates";