From d4f65d93b4f4a2b9f6b169e2cbb1805ac507a7ce Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Sun, 27 Sep 2026 15:56:29 -0500 Subject: [PATCH] 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 --- 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 ) 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> + ) +}