Merge pull request 'Region featured cards, featured grid, video stills, media naming (v1.13.2-region-cards)' (#30) from region-featured-cards into main
Reviewed-on: #30
This commit is contained in:
commit
2e6c8b45e6
35 changed files with 1065 additions and 125 deletions
|
|
@ -27,6 +27,18 @@ in the `media` table (`server/src/migrations/028_media.sql`).
|
|||
(`.vtt`, kept as they are, always in `captions/`). The type is read
|
||||
from the file's contents, not its name: a captions file has to start
|
||||
with `WEBVTT`.
|
||||
- Every upload and save asks for a **Name** (prefilled: the file's own
|
||||
name, "Video frame at 1:23", a clip's title and span). It's the
|
||||
library's name and the readable part of the file's, plus a short
|
||||
random ending: `images/spring-retreat-group-3f9c1a.webp`
|
||||
(`slugify` and `storedNameFor` in `server/src/media.js`). Fetch preview
|
||||
names its picture after the page's title.
|
||||
- **Rename** (Media page, editors and up) changes both. The file and its
|
||||
small copy move to a new name, and every record that names the file is
|
||||
pointed at it in the same step (the same search the delete check
|
||||
uses). Anything outside the site still holding the old address (a
|
||||
sent newsletter, a shared link) stops working. A rename that only
|
||||
changes capitals or punctuation keeps the file where it is.
|
||||
- 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.
|
||||
|
|
@ -106,7 +118,9 @@ which git ignores). The API serves `/uploads/` itself, and Vite proxies
|
|||
}
|
||||
```
|
||||
|
||||
Filenames are random and never reused, so `immutable` is safe.
|
||||
Every stored name ends in a random part and a new one is never an
|
||||
existing file's, so `immutable` is safe; a rename makes a new name
|
||||
rather than changing a file in place.
|
||||
|
||||
4. `sharp` is a server dependency now: run `pnpm install` in
|
||||
`/srv/ngu-api` after the deploy. It ships prebuilt Linux binaries,
|
||||
|
|
|
|||
|
|
@ -189,6 +189,8 @@ also in `server/src/admin-schema/` and a CHECK):
|
|||
| 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 (Community → Community blog: 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 Content → Columns (073) | 2, 3, 4 | **yes**, inline in `src/lib/adminSchema/frontPage.ts` | `GRID_COLUMNS` in `FeaturedCards.tsx`; the CHECK on `front_page.featured_columns` |
|
||||
| Front page → Featured cards → Size (073; front page only, regions and the Community blog stay automatic) | normal, wide, tall, large | **yes**, inline in `src/lib/adminSchema/frontPage.ts` | `SPANS` and `sizeOf` in `FeaturedCards.tsx`; the CHECK on `featured_cards.size` |
|
||||
| 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` |
|
||||
| Pages → Sections → Preset | community_blog, group_map, region_list, partner_list, events, timeline, people_directory | **yes**, `PRESETS` in `src/lib/adminSchema/sitePages.ts` (which pages offer which, the list passed to each `sitePage`) | `PRESETS` in `src/pages/SitePage.tsx`. A People directory shows its tag's first `DIRECTORY_PREVIEW` people (`src/pages/sections/PeopleDirectory.tsx`), linking to `/directory/<tag>`. |
|
||||
| Pages → Sections → Cards: list (organization cards preset, 067) | partner, ministry, partner,ministry | **yes**, inline in `src/lib/adminSchema/sitePages.ts` | `partner_list` in `PRESETS` in `src/pages/SitePage.tsx` passes it as the kind to `OrgListCards`; a section's hand-picked Cards: organizations (`page_section_orgs`) replace it |
|
||||
|
|
|
|||
|
|
@ -14,11 +14,18 @@ it: **Save to library** and **Save to Drive** on the download itself.
|
|||
It stays on the server to cut clips from either way (until the day's
|
||||
sweep).
|
||||
|
||||
The same tools take stills: a video featured card's Image field has
|
||||
**Frame at** (editors and up), which saves the frame at a typed time to
|
||||
`/uploads/thumbnails/` (`grabFrame` in `server/src/clips.js`). It
|
||||
downloads only that frame, outside the queue. A link's own `t=` (eg.
|
||||
`?t=83`) fills in the time.
|
||||
The same tools take stills (editors and up), each saving the frame at
|
||||
a typed time to `/uploads/thumbnails/` (`grabFrame` in
|
||||
`server/src/clips.js`, `POST /api/admin/video-frame`). It downloads only
|
||||
that frame, outside the queue. A link's own `t=` (eg. `?t=83`) fills in
|
||||
the time. **Frame at** is on:
|
||||
|
||||
- a video featured card's Image field (the front page, a region)
|
||||
- a video content block's Image field (its still)
|
||||
- the front page's Video still (the hero's featured video, migration 074)
|
||||
|
||||
and **Tools → Video thumbnails** (`AdminVideoFrames.tsx`) takes one from
|
||||
any link, to download or copy its path into a field.
|
||||
|
||||
Clips queue and run one at a time. A finished clip is deleted from the
|
||||
server once it's downloaded, unless **Save to library** is pressed first,
|
||||
|
|
|
|||
|
|
@ -105,6 +105,8 @@ export const featuredCardsChild = (ownerKind) => ({
|
|||
text("title"),
|
||||
text("blurb"),
|
||||
text("image"),
|
||||
// Its shape in the grid (073); only the Front page editor sets it.
|
||||
enumeration("size", ["normal", "wide", "tall", "large"]),
|
||||
],
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -48,6 +48,8 @@ export const frontPage = {
|
|||
text("countdown_event_id"),
|
||||
text("countdown_scope_id"),
|
||||
enumeration("countdown_event_type", ["retreat", "class", "workshop", "meeting", "other"]),
|
||||
int("featured_columns"),
|
||||
text("video_still"),
|
||||
],
|
||||
|
||||
children: [
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { text, int, real, bool, enumeration, placeColumns, timelineExtension, linksChild, blocksChild } from "./columns.js";
|
||||
import { text, int, real, bool, enumeration, placeColumns, timelineExtension, linksChild, blocksChild, featuredCardsChild } from "./columns.js";
|
||||
import { tagsChild } from "./tags.js";
|
||||
|
||||
/* ── Organizations ───────────────────────────────────────────── */
|
||||
|
|
@ -86,6 +86,9 @@ export const organizations = {
|
|||
text("phone"),
|
||||
],
|
||||
},
|
||||
// A region's own featured cards (072), in its row of the region
|
||||
// list and on its page.
|
||||
{ ...featuredCardsChild("organization"), when: { column: "kind", value: "region" } },
|
||||
{
|
||||
key: "region_areas",
|
||||
table: "region_areas",
|
||||
|
|
|
|||
|
|
@ -52,7 +52,7 @@ import { randomBytes } from "node:crypto";
|
|||
import { access, constants, copyFile, mkdir, readFile, readdir, rm, stat } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
import { UPLOADS_DIR, PUBLIC_PREFIX } from "./media.js";
|
||||
import { UPLOADS_DIR, publicPath, storedNameFor } from "./media.js";
|
||||
|
||||
export const CLIPS_DIR = path.resolve(process.env.CLIPS_DIR ?? "./clips");
|
||||
const YTDLP = process.env.YTDLP_PATH ?? "yt-dlp";
|
||||
|
|
@ -548,17 +548,24 @@ export function kick(db = dbRef) {
|
|||
export const fileOf = (job) => (job?.file ? filePath(job.file) : null);
|
||||
|
||||
/* A finished clip, or a whole downloaded video, into the media
|
||||
library: copied into the uploads directory under a random name and
|
||||
library: copied into the uploads directory, named for `name` (the
|
||||
Save to library box; blank: its title and span), and
|
||||
given a media row. A clip's working file is deleted; a video's is
|
||||
kept for cutting. Returns the media row's id. */
|
||||
export async function saveToLibrary(db, job, userId) {
|
||||
export async function saveToLibrary(db, job, userId, name = null) {
|
||||
const from = fileOf(job);
|
||||
if (!from) throw new ClipError(410, "That clip's file is gone. Make it again.");
|
||||
|
||||
const audio = job.file.endsWith(".mp3");
|
||||
const ext = audio ? ".mp3" : ".mp4";
|
||||
const filename = `${randomBytes(12).toString("hex")}${ext}`;
|
||||
const to = path.join(UPLOADS_DIR, filename);
|
||||
const params = JSON.parse(job.params ?? "{}");
|
||||
const stamp = (s) => `${Math.floor(s / 60)}m${String(Math.floor(s % 60)).padStart(2, "0")}s`;
|
||||
// A whole download is named for itself; a clip for its span.
|
||||
const label =
|
||||
name ??
|
||||
(job.kind === "source"
|
||||
? `${job.title ?? "Video"}${ext}`
|
||||
: `${job.title ?? "Clip"} (${stamp(params.start ?? 0)} to ${stamp(params.end ?? 0)})${ext}`);
|
||||
|
||||
// Each step says what it was doing if it fails, so the page can
|
||||
// tell an admin (this tool is admin-only) what to fix: usually the
|
||||
|
|
@ -576,6 +583,8 @@ export async function saveToLibrary(db, job, userId) {
|
|||
};
|
||||
|
||||
await step(`making the uploads folder ${UPLOADS_DIR}`, () => mkdir(UPLOADS_DIR, { recursive: true }));
|
||||
const filename = await step("choosing its file name", () => storedNameFor(label, ext));
|
||||
const to = path.join(UPLOADS_DIR, filename);
|
||||
await step(`copying the clip into ${UPLOADS_DIR}`, () => copyFile(from, to));
|
||||
|
||||
let id;
|
||||
|
|
@ -584,13 +593,6 @@ export async function saveToLibrary(db, job, userId) {
|
|||
? { width: null, height: null }
|
||||
: await step("reading the clip's size", () => probe(from));
|
||||
const { size } = await stat(from);
|
||||
const params = JSON.parse(job.params ?? "{}");
|
||||
const stamp = (s) => `${Math.floor(s / 60)}m${String(Math.floor(s % 60)).padStart(2, "0")}s`;
|
||||
// A whole download is named for itself; a clip for its span.
|
||||
const label =
|
||||
job.kind === "source"
|
||||
? `${job.title ?? "Video"}${ext}`
|
||||
: `${job.title ?? "Clip"} (${stamp(params.start ?? 0)} to ${stamp(params.end ?? 0)})${ext}`;
|
||||
|
||||
id = await step("adding it to the media table", () =>
|
||||
Number(
|
||||
|
|
@ -616,7 +618,7 @@ export async function saveToLibrary(db, job, userId) {
|
|||
await rm(from, { force: true });
|
||||
update(db, job.id, { saved_media_id: id, file: null });
|
||||
}
|
||||
return { id, url: `${PUBLIC_PREFIX}${filename}` };
|
||||
return { id, url: publicPath(filename) };
|
||||
}
|
||||
|
||||
/* After a clip has gone out in full: its file isn't needed. */
|
||||
|
|
|
|||
|
|
@ -28,8 +28,12 @@
|
|||
is: it's already small, and rasterizing it would lose the point
|
||||
of it. So is a WebVTT file, always into captions/.
|
||||
|
||||
Names are random, so two uploads of "logo.png" can't collide
|
||||
and a filename says nothing about what's in it.
|
||||
A stored name is made from the name it's given (the Name box on
|
||||
every upload and save), plus a short random ending, so two
|
||||
uploads called "Logo" can't collide: 'images/logo-3f9c1a.webp'.
|
||||
The ending also means no name can end in -640, the small copies'
|
||||
mark. Renaming (renameStored) makes a new stored name and moves
|
||||
the file, its small copy and every record naming it to it.
|
||||
|
||||
── Folders ──
|
||||
Each upload goes in a folder by what it's for (FOLDERS): logos/
|
||||
|
|
@ -80,6 +84,37 @@ export function isStoredName(name) {
|
|||
return parts.length === 1 || (parts.length === 2 && FOLDERS.includes(parts[0]));
|
||||
}
|
||||
|
||||
/* A name as the readable part of a stored name: lowercase letters,
|
||||
digits and hyphens, accents dropped, at most 60 characters.
|
||||
Nothing usable (eg. only emoji) gives `fallback`. */
|
||||
export function slugify(name, fallback = "file") {
|
||||
const slug = String(name ?? "")
|
||||
.normalize("NFKD")
|
||||
.replace(/[̀-ͯ]/g, "")
|
||||
.toLowerCase()
|
||||
.replace(/\.[a-z0-9]{2,4}$/, "") // a typed "photo.jpg" keeps its own ending off
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.slice(0, 60)
|
||||
.replace(/^-+|-+$/g, "");
|
||||
return slug || fallback;
|
||||
}
|
||||
|
||||
/* A new stored name in `dir` ('' for the root) for something called
|
||||
`name`, ending in `ext` ('.webp'), that no file has yet: writing
|
||||
over one would lose it, and a failed save would then delete it. */
|
||||
export async function storedNameFor(name, ext, dir = "") {
|
||||
for (let tries = 0; tries < 8; tries++) {
|
||||
const filename = `${dir ? `${dir}/` : ""}${slugify(name)}-${randomBytes(3).toString("hex")}${ext}`;
|
||||
try {
|
||||
await stat(path.join(UPLOADS_DIR, filename));
|
||||
} catch (err) {
|
||||
if (err.code === "ENOENT") return filename;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
throw new MediaError(500, "Couldn't find a free file name. Try again.");
|
||||
}
|
||||
|
||||
/* The public path of a stored name, each part escaped. */
|
||||
export const publicPath = (filename) =>
|
||||
`${PUBLIC_PREFIX}${String(filename).split("/").map(encodeURIComponent).join("/")}`;
|
||||
|
|
@ -167,7 +202,7 @@ function sniff(buf) {
|
|||
and leave nothing behind.
|
||||
───────────────────────────────────────────────────────────── */
|
||||
|
||||
export async function store(buf, { keepOriginal = false, folder } = {}) {
|
||||
export async function store(buf, { keepOriginal = false, folder, name } = {}) {
|
||||
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.`);
|
||||
|
|
@ -216,10 +251,9 @@ export async function store(buf, { keepOriginal = false, folder } = {}) {
|
|||
}
|
||||
|
||||
const dir = kind === "vtt" ? "captions" : folderOf(folder);
|
||||
const base = `${randomBytes(12).toString("hex")}${type.ext}`;
|
||||
const filename = `${dir}/${base}`;
|
||||
|
||||
await mkdir(path.join(UPLOADS_DIR, dir), { recursive: true });
|
||||
const filename = await storedNameFor(name, type.ext, dir);
|
||||
const base = path.basename(filename);
|
||||
// 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, dir, `.${base}.tmp`);
|
||||
|
|
@ -300,6 +334,46 @@ export async function remove(filename) {
|
|||
}
|
||||
}
|
||||
|
||||
/* ── Renaming ──────────────────────────────────────────────────
|
||||
Moves a stored file (and its small copy) to a new name made
|
||||
from `name`, keeping its folder and ending, and returns the new
|
||||
stored name. `commit(newName)` writes the database's side (the
|
||||
media row and every record naming the file) and must be
|
||||
synchronous, so it runs in one transaction; if it throws, the
|
||||
files go back where they were.
|
||||
───────────────────────────────────────────────────────────── */
|
||||
|
||||
export async function renameStored(filename, name, commit) {
|
||||
if (!isStoredName(filename)) throw new MediaError(400, "That file can't be renamed.");
|
||||
const dir = filename.includes("/") ? filename.split("/")[0] : "";
|
||||
const ext = path.extname(filename).toLowerCase();
|
||||
const next = await storedNameFor(name, ext, dir);
|
||||
|
||||
const moves = [[filename, next]];
|
||||
const thumb = thumbName(filename);
|
||||
if (!THUMB.test(filename) && (await stat(path.join(UPLOADS_DIR, thumb)).catch(() => null))) {
|
||||
moves.push([thumb, thumbName(next)]);
|
||||
}
|
||||
|
||||
const done = [];
|
||||
try {
|
||||
for (const [from, to] of moves) {
|
||||
await rename(path.join(UPLOADS_DIR, from), path.join(UPLOADS_DIR, to));
|
||||
done.push([from, to]);
|
||||
}
|
||||
commit(next);
|
||||
return next;
|
||||
} catch (err) {
|
||||
for (const [from, to] of done.reverse()) {
|
||||
await rename(path.join(UPLOADS_DIR, to), path.join(UPLOADS_DIR, from)).catch((undo) =>
|
||||
console.error(`media: couldn't move ${to} back to ${from}: ${undo.message}`),
|
||||
);
|
||||
}
|
||||
if (err.code === "ENOENT") throw new MediaError(404, "The file is missing from the uploads folder.");
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Files copied in by hand ─────────────────────────────────── */
|
||||
|
||||
/* What a file already on disk is: the fields a media row needs, or
|
||||
|
|
|
|||
111
server/src/migrations/072_region_featured_cards.sql
Normal file
111
server/src/migrations/072_region_featured_cards.sql
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
-- ═══════════════════════════════════════════════════════════════
|
||||
-- 072 REGION FEATURED CARDS
|
||||
--
|
||||
-- A region gets featured cards of its own, the same cards the front
|
||||
-- page and the Community blog own, shown in its row of the region
|
||||
-- list and on its page. featured_cards takes a third owner kind,
|
||||
-- 'organization'. The CHECK can't change in place, so the table is
|
||||
-- rebuilt, then its index and triggers are made again.
|
||||
--
|
||||
-- An organization's own cards go when it does
|
||||
-- (organizations_owned_featured_cleanup), and an insert has to name
|
||||
-- an organization that exists (featured_cards_owner_exists).
|
||||
-- ═══════════════════════════════════════════════════════════════
|
||||
|
||||
CREATE TABLE featured_cards_new (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
owner_kind TEXT NOT NULL CHECK (owner_kind IN ('front_page', 'community_page', 'organization')),
|
||||
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;
|
||||
|
||||
-- The cleanup triggers on events, people, teams, awards and
|
||||
-- organizations name featured_cards; legacy mode leaves them alone
|
||||
-- through the rename.
|
||||
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);
|
||||
|
||||
CREATE TRIGGER organizations_owned_featured_cleanup
|
||||
AFTER DELETE ON organizations
|
||||
BEGIN
|
||||
DELETE FROM featured_cards WHERE owner_kind = 'organization' AND owner_id = old.id;
|
||||
END;
|
||||
|
||||
CREATE TRIGGER featured_cards_owner_exists
|
||||
BEFORE INSERT ON featured_cards
|
||||
WHEN new.owner_kind = 'organization'
|
||||
BEGIN
|
||||
SELECT RAISE(ABORT, 'featured_cards: no such organization')
|
||||
WHERE NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.owner_id);
|
||||
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;
|
||||
21
server/src/migrations/073_featured_grid.sql
Normal file
21
server/src/migrations/073_featured_grid.sql
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
-- ═══════════════════════════════════════════════════════════════
|
||||
-- 073 FEATURED GRID
|
||||
--
|
||||
-- The front page's featured cards get a hand-set shape:
|
||||
--
|
||||
-- front_page.featured_columns 2, 3 or 4 across on a wide screen;
|
||||
-- null is 3, as before
|
||||
-- featured_cards.size normal, wide (2 columns), tall
|
||||
-- (2 rows) or large (both); null is
|
||||
-- automatic, as before: the first of
|
||||
-- three or more cards is large
|
||||
--
|
||||
-- Only the Front page editor offers them. A region's or the
|
||||
-- Community blog's cards keep a null size, so they lay out as before.
|
||||
-- ═══════════════════════════════════════════════════════════════
|
||||
|
||||
ALTER TABLE front_page ADD COLUMN featured_columns INTEGER
|
||||
CHECK (featured_columns IN (2, 3, 4));
|
||||
|
||||
ALTER TABLE featured_cards ADD COLUMN size TEXT
|
||||
CHECK (size IN ('normal', 'wide', 'tall', 'large'));
|
||||
11
server/src/migrations/074_front_page_video_still.sql
Normal file
11
server/src/migrations/074_front_page_video_still.sql
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
-- ═══════════════════════════════════════════════════════════════
|
||||
-- 074 FRONT PAGE VIDEO STILL
|
||||
--
|
||||
-- The hero's featured video gets a still of its own: the picture
|
||||
-- shown before it plays (a /uploads/ path, a bare filename or a
|
||||
-- URL, like every image field). Null keeps YouTube's thumbnail, or
|
||||
-- for a video file, its first frame. The editor's Frame at fills it
|
||||
-- from the video at a typed time.
|
||||
-- ═══════════════════════════════════════════════════════════════
|
||||
|
||||
ALTER TABLE front_page ADD COLUMN video_still TEXT;
|
||||
|
|
@ -11,9 +11,9 @@
|
|||
GET /clips/:id/download a finished clip, as an attachment;
|
||||
its file is deleted once it has
|
||||
gone out in full, unless saved
|
||||
POST /clips/:id/save a finished clip, or a whole
|
||||
downloaded video, into the media
|
||||
library
|
||||
POST /clips/:id/save { name }: a finished clip, or a
|
||||
whole downloaded video, into the
|
||||
media library under that name
|
||||
POST /clips/:id/drive { folder }: a finished clip (or a
|
||||
whole downloaded video) into a
|
||||
folder under Media in Drive, as a
|
||||
|
|
@ -47,6 +47,7 @@ import {
|
|||
} from "../clips.js";
|
||||
import { NO_STORE } from "../shape.js";
|
||||
import { UPLOADS_DIR } from "../media.js";
|
||||
import { nameFrom } from "./media.js";
|
||||
import { driveDelete, driveReady, driveShareWithAnyone, driveUploadFile } from "../googleService.js";
|
||||
import { cleanFolder, inDrive, recordDriveUpload } from "./files.js";
|
||||
|
||||
|
|
@ -219,7 +220,8 @@ clips.post("/clips/:id/save", async (c) => {
|
|||
if (job.status !== "done") throw new ClipError(400, "Only a finished download or clip can be saved.");
|
||||
if (job.saved_media_id) throw new ClipError(409, "It's already in the media library.");
|
||||
if (!job.file) throw new ClipError(410, "Its file is gone from the server.");
|
||||
const media = await saveToLibrary(db, job, c.get("user").id);
|
||||
const body = (await c.req.json().catch(() => null)) ?? {};
|
||||
const media = await saveToLibrary(db, job, c.get("user").id, nameFrom(body.name));
|
||||
console.log(`clips: clip ${job.id} saved to the library by ${c.get("user").email}`);
|
||||
return c.json({ media, job: shape(db.prepare(`${SELECT} WHERE j.id = ?`).get(job.id)) }, 200, NO_STORE);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -56,6 +56,7 @@ import {
|
|||
asBool,
|
||||
json,
|
||||
loadBlocks,
|
||||
loadFeaturedCardsFor,
|
||||
loadLinks,
|
||||
loadOwned,
|
||||
marks,
|
||||
|
|
@ -286,6 +287,9 @@ function attachRegionDetails(db, orgs) {
|
|||
)
|
||||
.all(...ids);
|
||||
|
||||
// Its own featured cards (072), for its row and its page.
|
||||
const featuredBy = loadFeaturedCardsFor(db, "organization", ids);
|
||||
|
||||
const byId = Object.fromEntries(rows.map((r) => [r.id, r]));
|
||||
const areasBy = new Map();
|
||||
const childrenBy = new Map();
|
||||
|
|
@ -321,6 +325,7 @@ function attachRegionDetails(db, orgs) {
|
|||
map_note: byId[org.id]?.map_note ?? null,
|
||||
areas: areasBy.get(org.id) ?? [],
|
||||
groups: childrenBy.get(org.id) ?? [],
|
||||
featured: featuredBy.get(org.id) ?? [],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -225,7 +225,7 @@ home.get("/front-page", (c) => {
|
|||
? { url: page.livestream_url, title: page.livestream_title }
|
||||
: null,
|
||||
video: page.video_url
|
||||
? { url: page.video_url, title: page.video_title, captions: page.video_captions }
|
||||
? { url: page.video_url, title: page.video_title, captions: page.video_captions, still: page.video_still }
|
||||
: null,
|
||||
event: shapeHeroEvent(db, heroEvent),
|
||||
},
|
||||
|
|
@ -233,6 +233,8 @@ home.get("/front-page", (c) => {
|
|||
stats,
|
||||
paths,
|
||||
featured: loadFeaturedCards(db, "front_page", PAGE_ID),
|
||||
// 2, 3 or 4 across (073); null is the grid's own default.
|
||||
featured_columns: page.featured_columns,
|
||||
countdown: shapeCountdown(next),
|
||||
},
|
||||
});
|
||||
|
|
|
|||
|
|
@ -9,9 +9,11 @@
|
|||
(registerLooseFiles, at most every
|
||||
SCAN_EVERY_MS)
|
||||
POST /media upload one image or .vtt (multipart: file,
|
||||
keep_original, folder: FOLDERS in
|
||||
media.js, default images)
|
||||
name, keep_original, folder: FOLDERS
|
||||
in media.js, default images)
|
||||
GET /media/:id/uses which records name this file
|
||||
PATCH /media/:id rename it ({ name }): the file too,
|
||||
and every record naming it
|
||||
DELETE /media/:id remove the row and the file
|
||||
POST /link-preview a page's title, description and
|
||||
preview image, the image saved into
|
||||
|
|
@ -26,18 +28,24 @@
|
|||
claim /media and answer "Unknown entity."
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import path from "node:path";
|
||||
|
||||
import { Hono } from "hono";
|
||||
import { bodyLimit } from "hono/body-limit";
|
||||
|
||||
import { requireAuth, requireRole } from "../auth.js";
|
||||
import { tx } from "../db.js";
|
||||
import {
|
||||
FOLDERS,
|
||||
MAX_UPLOAD_BYTES,
|
||||
MediaError,
|
||||
PUBLIC_PREFIX,
|
||||
publicPath,
|
||||
isStoredName,
|
||||
registerLooseFiles,
|
||||
remove,
|
||||
renameStored,
|
||||
slugify,
|
||||
store,
|
||||
} from "../media.js";
|
||||
import { fetchImage, previewLink } from "../linkPreview.js";
|
||||
|
|
@ -77,6 +85,13 @@ export function shape(row) {
|
|||
};
|
||||
}
|
||||
|
||||
/* A name typed in a Name box: trimmed, at most 200 characters, null
|
||||
when blank (the caller's default then applies). */
|
||||
export function nameFrom(value) {
|
||||
const name = typeof value === "string" ? value.trim().slice(0, 200) : "";
|
||||
return name || null;
|
||||
}
|
||||
|
||||
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`;
|
||||
|
|
@ -84,7 +99,8 @@ const SELECT = `SELECT m.*, u.name AS uploaded_by_name, u.email AS uploaded_by_e
|
|||
/* 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. */
|
||||
export async function addToLibrary(db, buf, { originalName, keepOriginal, userId, folder }) {
|
||||
const stored = await store(buf, { keepOriginal, folder });
|
||||
// The stored file is named for it too (slugify in media.js).
|
||||
const stored = await store(buf, { keepOriginal, folder, name: originalName });
|
||||
try {
|
||||
const { lastInsertRowid } = db
|
||||
.prepare(
|
||||
|
|
@ -156,7 +172,7 @@ media.post(
|
|||
if (!(file instanceof File)) return c.json({ error: "No file was sent." }, 400);
|
||||
|
||||
const row = await addToLibrary(db, Buffer.from(await file.arrayBuffer()), {
|
||||
originalName: file.name,
|
||||
originalName: nameFrom(body.name) ?? file.name,
|
||||
keepOriginal: body.keep_original === "1",
|
||||
folder: body.folder,
|
||||
userId: user.id,
|
||||
|
|
@ -186,7 +202,8 @@ media.post("/link-preview", requireRole("editor"), async (c) => {
|
|||
if (page.image) {
|
||||
try {
|
||||
const row = await addToLibrary(c.get("db"), await fetchImage(page.image), {
|
||||
originalName: `preview ${new URL(page.image).hostname}`,
|
||||
// Named for the page it previews; renamed in the library if wanted.
|
||||
originalName: page.title?.trim() || `preview ${new URL(page.image).hostname}`,
|
||||
folder: "thumbnails",
|
||||
keepOriginal: false,
|
||||
userId: user.id,
|
||||
|
|
@ -216,7 +233,7 @@ media.post("/video-frame", requireRole("editor"), async (c) => {
|
|||
return c.json({ error: "Expected a JSON body." }, 400);
|
||||
}
|
||||
const row = await addToLibrary(c.get("db"), await grabFrame(body.url, Number(body.seconds)), {
|
||||
originalName: `video frame ${Math.floor(Number(body.seconds))}s`,
|
||||
originalName: nameFrom(body.name) ?? `video frame ${Math.floor(Number(body.seconds))}s`,
|
||||
folder: "thumbnails",
|
||||
keepOriginal: false,
|
||||
userId: user.id,
|
||||
|
|
@ -231,13 +248,36 @@ media.post("/video-frame", requireRole("editor"), async (c) => {
|
|||
typed into a field) its bare name, which media.ts resolves to the
|
||||
same place. 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, filename) {
|
||||
return recordsNaming(db, [
|
||||
const namesFor = (filename) => [
|
||||
...new Set([
|
||||
`${PUBLIC_PREFIX}${filename}`,
|
||||
`${PUBLIC_PREFIX}${encodeURIComponent(filename)}`,
|
||||
publicPath(filename),
|
||||
filename,
|
||||
]);
|
||||
]),
|
||||
];
|
||||
|
||||
function usesOf(db, filename) {
|
||||
return recordsNaming(db, namesFor(filename));
|
||||
}
|
||||
|
||||
/* Every content table's TEXT columns: [{ table, columns }]. Names
|
||||
come from the schema, not a request; they're quoted anyway. */
|
||||
function contentColumns(db) {
|
||||
return 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))
|
||||
.map((table) => ({
|
||||
table,
|
||||
columns: db
|
||||
.prepare(`SELECT name, type FROM pragma_table_info(?)`)
|
||||
.all(table)
|
||||
.filter((col) => col.type.toUpperCase() === "TEXT")
|
||||
.map((col) => col.name),
|
||||
}))
|
||||
.filter(({ columns }) => columns.length > 0);
|
||||
}
|
||||
|
||||
/* Which content tables have a TEXT column holding exactly one of
|
||||
|
|
@ -245,23 +285,9 @@ function usesOf(db, filename) {
|
|||
what links to a file (routes/files.js). */
|
||||
export function recordsNaming(db, values) {
|
||||
values = [...new Set(values)];
|
||||
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 marks = values.map(() => "?").join(", ");
|
||||
const uses = [];
|
||||
for (const { table, columns } of contentColumns(db)) {
|
||||
const where = columns.map((col) => `"${col}" IN (${marks})`).join(" OR ");
|
||||
const { n } = db
|
||||
.prepare(`SELECT COUNT(*) AS n FROM "${table}" WHERE ${where}`)
|
||||
|
|
@ -271,6 +297,25 @@ export function recordsNaming(db, values) {
|
|||
return uses;
|
||||
}
|
||||
|
||||
/* Points every record naming `from` at `to` instead: the same exact
|
||||
values usesOf finds, each swapped for its new form (a bare name
|
||||
for a bare name, the public path for any path). Returns how many
|
||||
values were rewritten. The touch triggers move each record's
|
||||
updated_at, so an editor still open on one is told it changed
|
||||
rather than saving the old path back. */
|
||||
function rewriteRecords(db, from, to) {
|
||||
const swaps = namesFor(from).map((old) => [old, old === from ? to : publicPath(to)]);
|
||||
let changed = 0;
|
||||
for (const { table, columns } of contentColumns(db)) {
|
||||
for (const col of columns) {
|
||||
for (const [old, next] of swaps) {
|
||||
changed += Number(db.prepare(`UPDATE "${table}" SET "${col}" = ? WHERE "${col}" = ?`).run(next, old).changes);
|
||||
}
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
function findOr404(c) {
|
||||
const id = Number(c.req.param("id"));
|
||||
const row = Number.isInteger(id)
|
||||
|
|
@ -285,6 +330,33 @@ media.get("/media/:id/uses", (c) => {
|
|||
return c.json({ uses: usesOf(c.get("db"), row.filename) }, 200, NO_STORE);
|
||||
});
|
||||
|
||||
/* A new name ({ name }): the library's name and the file's own, with
|
||||
every record that names the file pointed at the new one, in one
|
||||
transaction (renameStored in media.js moves the files back if it
|
||||
fails). A name whose readable part is unchanged (eg. only its
|
||||
capitals) keeps the file where it is. */
|
||||
media.patch("/media/:id", requireRole("editor"), async (c) => {
|
||||
const db = c.get("db");
|
||||
const row = findOr404(c);
|
||||
const body = (await c.req.json().catch(() => null)) ?? {};
|
||||
const name = nameFrom(body.name);
|
||||
if (!name) throw new MediaError(400, "Give it a name.");
|
||||
|
||||
const sameFile = path.basename(row.filename).startsWith(`${slugify(name)}-`) || !isStoredName(row.filename);
|
||||
let records = 0;
|
||||
const filename = sameFile
|
||||
? (db.prepare(`UPDATE media SET original_name = ? WHERE id = ?`).run(name, row.id), row.filename)
|
||||
: await renameStored(row.filename, name, (next) =>
|
||||
tx(db, () => {
|
||||
db.prepare(`UPDATE media SET filename = ?, original_name = ? WHERE id = ?`).run(next, name, row.id);
|
||||
records = rewriteRecords(db, row.filename, next);
|
||||
}),
|
||||
);
|
||||
|
||||
console.log(`media ${row.filename} renamed to ${filename} ("${name}"), ${records} references updated, by ${c.get("user").email}`);
|
||||
return c.json({ media: shape(db.prepare(`${SELECT} WHERE m.id = ?`).get(row.id)), updated: records }, 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);
|
||||
|
|
|
|||
|
|
@ -226,7 +226,7 @@ export function shapeSeries(row) {
|
|||
}
|
||||
|
||||
/* ── Featured cards ────────────────────────────────────────────
|
||||
One owner's cards (the front page's, today), in order, with
|
||||
One owner's cards (the front page's, a region's), in order, with
|
||||
each record card filled in from its record. Shared so the
|
||||
Community blog's cards will come out the same shape.
|
||||
|
||||
|
|
@ -238,7 +238,8 @@ export function shapeSeries(row) {
|
|||
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-photo' and 'featured' (the
|
||||
card's own image). An unpublished
|
||||
card's own image). `size` is its shape in the grid (073), null
|
||||
for automatic. An unpublished
|
||||
record's card is dropped; an unlisted one's stays, since
|
||||
featuring it is attaching it by hand.
|
||||
───────────────────────────────────────────────────────────── */
|
||||
|
|
@ -285,13 +286,22 @@ const FEATURED_REFS = {
|
|||
};
|
||||
|
||||
export function loadFeaturedCards(db, ownerKind, ownerId) {
|
||||
return loadFeaturedCardsFor(db, ownerKind, [ownerId]).get(ownerId) ?? [];
|
||||
}
|
||||
|
||||
/* Several owners' cards at once (every region in the region list),
|
||||
as owner id → cards, in the same number of queries as one owner. */
|
||||
export function loadFeaturedCardsFor(db, ownerKind, ownerIds) {
|
||||
const byOwner = new Map();
|
||||
if (ownerIds.length === 0) return byOwner;
|
||||
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT * FROM featured_cards
|
||||
WHERE owner_kind = ? AND owner_id = ?
|
||||
ORDER BY sort_order, id`,
|
||||
WHERE owner_kind = ? AND owner_id IN (${placeholders(ownerIds.length)})
|
||||
ORDER BY owner_id, sort_order, id`,
|
||||
)
|
||||
.all(ownerKind, ownerId);
|
||||
.all(ownerKind, ...ownerIds);
|
||||
|
||||
// kind → id → record row
|
||||
const records = new Map();
|
||||
|
|
@ -306,8 +316,9 @@ export function loadFeaturedCards(db, ownerKind, ownerId) {
|
|||
|
||||
const own = (row) => (row.image ? { file: row.image, kind: "featured" } : null);
|
||||
|
||||
const cards = [];
|
||||
for (const row of rows) {
|
||||
let cards = byOwner.get(row.owner_id);
|
||||
if (!cards) byOwner.set(row.owner_id, (cards = []));
|
||||
if (row.kind === "record") {
|
||||
const record = records.get(row.ref_kind)?.get(row.ref_id);
|
||||
if (!record) continue; // unpublished, or its organization is
|
||||
|
|
@ -319,6 +330,7 @@ export function loadFeaturedCards(db, ownerKind, ownerId) {
|
|||
title: row.title ?? record.title,
|
||||
blurb: row.blurb ?? record.blurb ?? null,
|
||||
image: own(row) ?? FEATURED_REFS[row.ref_kind].image(record),
|
||||
size: row.size,
|
||||
});
|
||||
} else {
|
||||
cards.push({
|
||||
|
|
@ -329,10 +341,11 @@ export function loadFeaturedCards(db, ownerKind, ownerId) {
|
|||
title: row.title,
|
||||
blurb: row.blurb,
|
||||
image: own(row),
|
||||
size: row.size,
|
||||
});
|
||||
}
|
||||
}
|
||||
return cards;
|
||||
return byOwner;
|
||||
}
|
||||
|
||||
export { asBool };
|
||||
|
|
|
|||
|
|
@ -80,6 +80,7 @@ const AdminHome = lazyPage(() => import("./pages/admin/AdminHome.tsx"))
|
|||
const AdminFeedback = lazyPage(() => import("./pages/admin/AdminFeedback.tsx"))
|
||||
const AdminMedia = lazyPage(() => import("./pages/admin/AdminMedia.tsx"))
|
||||
const AdminClips = lazyPage(() => import("./pages/admin/AdminClips.tsx"))
|
||||
const AdminVideoFrames = lazyPage(() => import("./pages/admin/AdminVideoFrames.tsx"))
|
||||
const AdminNewsletter = lazyPage(() => import("./pages/admin/AdminNewsletter.tsx"))
|
||||
const EntityList = lazyPage(() => import("./pages/admin/EntityList.tsx"))
|
||||
const EntityEdit = lazyPage(() => import("./pages/admin/EntityEdit.tsx"))
|
||||
|
|
@ -145,6 +146,9 @@ export default function App() {
|
|||
<Route path="requests" element={<AdminFeedback kind="content" />} />
|
||||
<Route path="media" element={<AdminMedia />} />
|
||||
<Route path="newsletter" element={<AdminNewsletter />} />
|
||||
<Route element={<RequireRole role="editor" />}>
|
||||
<Route path="thumbnails" element={<AdminVideoFrames />} />
|
||||
</Route>
|
||||
<Route element={<RequireRole role="admin" />}>
|
||||
<Route path="clips" element={<AdminClips />} />
|
||||
</Route>
|
||||
|
|
|
|||
|
|
@ -2,7 +2,8 @@
|
|||
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
|
||||
band, the Community blog's posts, a region's own cards (in the
|
||||
region list and on its page). The data comes from
|
||||
loadFeaturedCards in server/src/shape.js, already resolved, so
|
||||
this only draws.
|
||||
|
||||
|
|
@ -24,6 +25,13 @@
|
|||
one, two rows tall, and the next two stack beside it, so it no
|
||||
longer stretches its neighbor.
|
||||
|
||||
The front page sets the shape by hand (073): `columns` is how many
|
||||
across on a wide screen (2, 3 or 4; default 3), and a card's
|
||||
`size` makes it wide (2 columns), tall (2 rows), large (both) or
|
||||
normal. A card with no size is automatic, the rule above, so
|
||||
cards nobody has sized lay out as they always have. Cards stay in
|
||||
their list order; a shape that leaves a hole leaves it.
|
||||
|
||||
Reading mode (readingMode.ts) gets each card as a linked heading
|
||||
and its words, a video card linking to its video. `level` is that
|
||||
heading's level, one under the heading above the cards.
|
||||
|
|
@ -34,7 +42,7 @@ import HomeLink from '../pages/sections/home/HomeLink.tsx'
|
|||
import VideoPlayer from './VideoPlayer.tsx'
|
||||
import { refHref } from '../lib/hrefs.ts'
|
||||
import { mediaUrl } from '../lib/media.ts'
|
||||
import type { FeaturedCard } from '../lib/useFrontPage.ts'
|
||||
import type { FeaturedCard, FeaturedColumns, FeaturedSize } from '../lib/useFrontPage.ts'
|
||||
import { useReadingMode } from '../lib/readingMode.ts'
|
||||
import { useSmallImage } from '../lib/useSmallImage.ts'
|
||||
|
||||
|
|
@ -85,9 +93,32 @@ function VideoPicture({ card }: { card: FeaturedCard }) {
|
|||
|
||||
const RULE = 'border-brand'
|
||||
|
||||
function Card({ card, large, level }: { card: FeaturedCard; large: boolean; level: 3 | 4 }) {
|
||||
/* Columns across, by setting. Two columns start at sm; three and
|
||||
four take over at lg. Written out whole so Tailwind sees them. */
|
||||
const GRID_COLUMNS: Record<FeaturedColumns, string> = {
|
||||
2: 'sm:grid-cols-2',
|
||||
3: 'sm:grid-cols-2 lg:grid-cols-3',
|
||||
4: 'sm:grid-cols-2 lg:grid-cols-4',
|
||||
}
|
||||
|
||||
/* A card's spans, from the breakpoint its grid reaches its full
|
||||
width: sm for a two column grid, lg otherwise. Below that every
|
||||
card is one cell, so a wide card can't overflow a narrow grid. */
|
||||
const SPANS: Record<'sm' | 'lg', Record<FeaturedSize, string>> = {
|
||||
sm: { normal: '', wide: 'sm:col-span-2', tall: 'sm:row-span-2', large: 'sm:col-span-2 sm:row-span-2' },
|
||||
lg: { normal: '', wide: 'lg:col-span-2', tall: 'lg:row-span-2', large: 'lg:col-span-2 lg:row-span-2' },
|
||||
}
|
||||
|
||||
/* A card's size, or for one with none, the automatic rule: the first
|
||||
of three or more is large. */
|
||||
function sizeOf(card: FeaturedCard, index: number, count: number): FeaturedSize {
|
||||
return card.size ?? (index === 0 && count >= 3 ? 'large' : 'normal')
|
||||
}
|
||||
|
||||
function Card({ card, size, spans, level }: { card: FeaturedCard; size: FeaturedSize; spans: string; level: 3 | 4 | 5 }) {
|
||||
const large = size === 'large'
|
||||
const href = hrefFor(card)
|
||||
const Title = level === 4 ? 'h4' : 'h3'
|
||||
const Title = `h${level}` as const
|
||||
|
||||
const text = (
|
||||
<div className={`flex flex-1 flex-col ${large ? 'p-8 md:p-10' : 'p-7'}`}>
|
||||
|
|
@ -118,9 +149,7 @@ function Card({ card, large, level }: { card: FeaturedCard; large: boolean; leve
|
|||
|
||||
return (
|
||||
<li
|
||||
className={`relative flex flex-col overflow-hidden border-r-4 border-b-4 ${RULE} bg-raised transition-colors hover:bg-tint-soft ${
|
||||
large ? 'lg:col-span-2 lg:row-span-2' : ''
|
||||
}`}
|
||||
className={`relative flex flex-col overflow-hidden border-r-4 border-b-4 ${RULE} bg-raised transition-colors hover:bg-tint-soft ${spans}`}
|
||||
>
|
||||
{card.kind === 'video' ? (
|
||||
// Above the stretched link, which a video card doesn't have
|
||||
|
|
@ -137,10 +166,10 @@ function Card({ card, large, level }: { card: FeaturedCard; large: boolean; leve
|
|||
)
|
||||
}
|
||||
|
||||
type FeaturedCardsProps = { cards: FeaturedCard[]; level?: 3 | 4 }
|
||||
type FeaturedCardsProps = { cards: FeaturedCard[]; level?: 3 | 4 | 5; columns?: FeaturedColumns }
|
||||
|
||||
function ReadingCards({ cards, level = 3 }: FeaturedCardsProps) {
|
||||
const Title = level === 4 ? 'h4' : 'h3'
|
||||
const Title = `h${level}` as const
|
||||
return (
|
||||
<>
|
||||
{cards.map((card, index) => {
|
||||
|
|
@ -157,21 +186,25 @@ function ReadingCards({ cards, level = 3 }: FeaturedCardsProps) {
|
|||
)
|
||||
}
|
||||
|
||||
export default function FeaturedCards({ cards, level = 3 }: FeaturedCardsProps) {
|
||||
export default function FeaturedCards({ cards, level = 3, columns = 3 }: FeaturedCardsProps) {
|
||||
const reading = useReadingMode()
|
||||
if (reading) return <ReadingCards cards={cards} level={level} />
|
||||
const leadLarge = cards.length >= 3
|
||||
const spans = SPANS[columns === 2 ? 'sm' : 'lg']
|
||||
return (
|
||||
<div className="overflow-hidden shadow-md">
|
||||
<ul className="-mr-[4px] -mb-[4px] grid sm:grid-cols-2 lg:grid-cols-3">
|
||||
{cards.map((card, index) => (
|
||||
<ul className={`-mr-[4px] -mb-[4px] grid ${GRID_COLUMNS[columns]}`}>
|
||||
{cards.map((card, index) => {
|
||||
const size = sizeOf(card, index, cards.length)
|
||||
return (
|
||||
<Card
|
||||
key={`${card.kind}-${card.ref?.id ?? card.url}-${index}`}
|
||||
card={card}
|
||||
large={leadLarge && index === 0}
|
||||
size={size}
|
||||
spans={spans[size]}
|
||||
level={level}
|
||||
/>
|
||||
))}
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -134,14 +134,54 @@ export function mediaSize(item: MediaItem) {
|
|||
|
||||
/* ── Data ────────────────────────────────────────────────────── */
|
||||
|
||||
export function uploadImage(file: File, keepOriginal: boolean, folder?: string): Promise<MediaItem> {
|
||||
/* `name` is the library's name for it and the readable part of its
|
||||
file name (server/src/media.js); blank: the file's own name. */
|
||||
export function uploadImage(file: File, keepOriginal: boolean, folder?: string, name?: string): Promise<MediaItem> {
|
||||
const form = new FormData();
|
||||
form.append("file", file);
|
||||
if (name?.trim()) form.append("name", name.trim());
|
||||
if (keepOriginal) form.append("keep_original", "1");
|
||||
if (folder) form.append("folder", folder);
|
||||
return upload("/admin/media", form).then((data) => data.media);
|
||||
}
|
||||
|
||||
/* What a Name box starts with for a chosen file: its name without the
|
||||
ending, separators read as spaces ("spring_retreat-1.jpg" →
|
||||
"spring retreat 1"). */
|
||||
export function nameOfFile(file: File): string {
|
||||
return file.name.replace(/\.[^.]+$/, "").replace(/[_-]+/g, " ").trim();
|
||||
}
|
||||
|
||||
/* A Name box, labeled, for anything about to be saved to the library. */
|
||||
export function NameBox({
|
||||
value,
|
||||
onChange,
|
||||
className = "",
|
||||
label = "Name",
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
className?: string;
|
||||
label?: string;
|
||||
}) {
|
||||
const id = useId();
|
||||
return (
|
||||
<div className={`flex min-w-0 items-center gap-2 ${className}`}>
|
||||
<label htmlFor={id} className="shrink-0 text-sm text-muted">
|
||||
{label}
|
||||
</label>
|
||||
<input
|
||||
id={id}
|
||||
type="text"
|
||||
value={value}
|
||||
maxLength={200}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className="min-w-0 flex-1 border border-muted/25 bg-surface px-2 py-1 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* How long a search waits after the last keystroke. */
|
||||
export const SEARCH_PAUSE_MS = 250;
|
||||
/* The most the library route sends (MAX_LIST, server/src/routes/media.js). */
|
||||
|
|
@ -204,36 +244,58 @@ export function UploadButton({
|
|||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [framing, setFraming] = useState<File | null>(null);
|
||||
// Chosen (and framed) but not sent yet: each waits with a Name box,
|
||||
// prefilled from its own name, until Upload is pressed.
|
||||
const [pending, setPending] = useState<Array<{ file: File; name: string }>>([]);
|
||||
// Captions are kept as they are, so there's no original to keep.
|
||||
const captions = folder === "captions";
|
||||
|
||||
const clearInput = () => {
|
||||
if (inputRef.current) inputRef.current.value = "";
|
||||
};
|
||||
|
||||
// A single photo for a field with a shape is framed first; SVGs and
|
||||
// GIFs (which would lose their animation) go as they are.
|
||||
// GIFs (which would lose their animation) go as they are. Either
|
||||
// way the names come next.
|
||||
function choose(files: FileList | null) {
|
||||
const one = files?.length === 1 ? files[0] : null;
|
||||
if (crop && one && /^image\/(jpeg|png|webp)$/.test(one.type)) setFraming(one);
|
||||
else send(files ? Array.from(files) : []);
|
||||
else name(files ? Array.from(files) : []);
|
||||
}
|
||||
|
||||
async function send(files: File[]) {
|
||||
function name(files: File[]) {
|
||||
setError(null);
|
||||
setPending(files.map((file) => ({ file, name: nameOfFile(file) })));
|
||||
clearInput();
|
||||
}
|
||||
|
||||
function cancel() {
|
||||
setPending([]);
|
||||
clearInput();
|
||||
}
|
||||
|
||||
async function send() {
|
||||
const files = pending;
|
||||
if (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 files) {
|
||||
// name the file it happened to. What went stays gone from the
|
||||
// list; what didn't stays, to try again.
|
||||
for (const [index, { file, name }] of files.entries()) {
|
||||
try {
|
||||
onUploaded(await uploadImage(file, keepOriginal, folder));
|
||||
onUploaded(await uploadImage(file, keepOriginal, folder, name));
|
||||
} catch (err) {
|
||||
const why = err instanceof ApiError ? err.message : "Upload failed.";
|
||||
setError(files.length > 1 ? `${file.name}: ${why}` : why);
|
||||
break;
|
||||
setError(files.length > 1 ? `${name || file.name}: ${why}` : why);
|
||||
setPending(files.slice(index));
|
||||
return;
|
||||
}
|
||||
}
|
||||
setPending([]);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
if (inputRef.current) inputRef.current.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -243,10 +305,10 @@ export function UploadButton({
|
|||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
disabled={busy || pending.length > 0}
|
||||
onClick={() => inputRef.current?.click()}
|
||||
>
|
||||
{busy ? "Uploading…" : label}
|
||||
{label}
|
||||
</button>
|
||||
<input
|
||||
ref={inputRef}
|
||||
|
|
@ -269,6 +331,29 @@ export function UploadButton({
|
|||
</label>
|
||||
)}
|
||||
</div>
|
||||
{pending.length > 0 && (
|
||||
<div className="mt-2 space-y-2 border border-muted/20 bg-surface p-3">
|
||||
{pending.map((item, index) => (
|
||||
<NameBox
|
||||
key={`${item.file.name}-${index}`}
|
||||
label={pending.length > 1 ? `Name ${index + 1}` : "Name"}
|
||||
value={item.name}
|
||||
onChange={(value) =>
|
||||
setPending((list) => list.map((entry, i) => (i === index ? { ...entry, name: value } : entry)))
|
||||
}
|
||||
/>
|
||||
))}
|
||||
<p className="text-xs text-muted">Also its file name, eg. spring-retreat-group-3f9c1a.webp.</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button type="button" className={button} disabled={busy} onClick={send}>
|
||||
{busy ? "Uploading…" : pending.length > 1 ? `Upload ${pending.length}` : "Upload"}
|
||||
</button>
|
||||
<button type="button" className="px-2 py-1 text-sm text-muted hover:text-danger" disabled={busy} onClick={cancel}>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{error && <p className="mt-1 text-xs text-danger">{error}</p>}
|
||||
{framing && crop && (
|
||||
<CropDialog
|
||||
|
|
@ -276,8 +361,8 @@ export function UploadButton({
|
|||
crop={crop}
|
||||
onDone={(file) => {
|
||||
setFraming(null);
|
||||
if (file) send([file]);
|
||||
else if (inputRef.current) inputRef.current.value = "";
|
||||
if (file) name([file]);
|
||||
else clearInput();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
|
@ -647,8 +732,9 @@ export function ImageInput({
|
|||
/* ── Frame from a video ──────────────────────────────────────── */
|
||||
|
||||
/* A link's own start time (YouTube's t=83 or t=83s), so a link
|
||||
copied at the moment wanted starts the picker there. */
|
||||
function startOf(url: string): number {
|
||||
copied at the moment wanted starts the picker there. Tools →
|
||||
Video thumbnails (AdminVideoFrames.tsx) reads it too. */
|
||||
export function startOf(url: string): number {
|
||||
try {
|
||||
const t = new URL(url).searchParams.get("t") ?? "";
|
||||
return /^\d+s?$/.test(t) ? parseInt(t, 10) : 0;
|
||||
|
|
@ -657,18 +743,24 @@ function startOf(url: string): number {
|
|||
}
|
||||
}
|
||||
|
||||
/* What a frame's Name box says until somebody types in it. */
|
||||
export const frameName = (text: string) => `Video frame at ${text.trim() || "0:00"}`;
|
||||
|
||||
function FrameFromVideo({ url, className, onSaved }: { url: string; className: string; onSaved: (value: string) => void }) {
|
||||
const [text, setText] = useState(() => clock(startOf(url)));
|
||||
// null: follow the time ("Video frame at 1:23"); typed, it's kept.
|
||||
const [typedName, setTypedName] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const timeId = useId();
|
||||
const seconds = parseClock(text);
|
||||
const name = typedName ?? frameName(text);
|
||||
|
||||
async function take() {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const { media } = await post("/admin/video-frame", { url, seconds });
|
||||
const { media } = await post("/admin/video-frame", { url, seconds, name });
|
||||
onSaved(media.url);
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : "Couldn't take that frame.");
|
||||
|
|
@ -685,6 +777,7 @@ function FrameFromVideo({ url, className, onSaved }: { url: string; className: s
|
|||
<div className="w-24">
|
||||
<input id={timeId} type="text" value={text} onChange={(e) => setText(e.target.value)} placeholder="eg. 1:23" className={className} />
|
||||
</div>
|
||||
<NameBox value={name} onChange={setTypedName} className="w-64" />
|
||||
<button type="button" className={button} disabled={busy || seconds == null} onClick={take}>
|
||||
{busy ? "Taking…" : "Use this frame"}
|
||||
</button>
|
||||
|
|
|
|||
|
|
@ -630,6 +630,16 @@ iframe[src*="churchcenter"] {
|
|||
transition: transform 200ms ease;
|
||||
}
|
||||
|
||||
/* A closed region row's featured cards: the top of them, fading out
|
||||
into whatever is behind (a mask, not a painted gradient, so it
|
||||
works over the page backdrop in both modes). */
|
||||
.ol-peek {
|
||||
max-height: 9rem;
|
||||
overflow: hidden;
|
||||
opacity: 0.85;
|
||||
mask-image: linear-gradient(to bottom, black 20%, transparent);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.ol-panel,
|
||||
.ol-chevron {
|
||||
|
|
|
|||
|
|
@ -107,6 +107,16 @@ export const frontPage = {
|
|||
"A YouTube, Vimeo or Facebook link, or a video file: a filename in " +
|
||||
"the uploads folder, or a link ending in .mp4 or .webm",
|
||||
},
|
||||
{
|
||||
path: "video_still",
|
||||
label: "Video still",
|
||||
widget: "image",
|
||||
crop: 16 / 9,
|
||||
resolve: mediaUrl,
|
||||
full: true,
|
||||
frameFrom: "video_url",
|
||||
help: "Shown before it plays. Default: YouTube's own thumbnail, or a video file's first frame. Frame at takes a still from a YouTube or Facebook video.",
|
||||
},
|
||||
{
|
||||
path: "video_captions",
|
||||
label: "Video captions",
|
||||
|
|
@ -163,6 +173,24 @@ export const frontPage = {
|
|||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
legend: "Featured Content",
|
||||
note: "The cards themselves are under Featured cards below, each with its own Size.",
|
||||
fields: [
|
||||
{
|
||||
path: "featured_columns",
|
||||
label: "Columns",
|
||||
widget: "select",
|
||||
options: [
|
||||
["2", "2 across"],
|
||||
["3", "3 across"],
|
||||
["4", "4 across"],
|
||||
],
|
||||
blankLabel: "Default: 3 across",
|
||||
help: "On a wide screen. Tablets show 2, phones 1",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
children: [
|
||||
|
|
@ -222,7 +250,25 @@ export const frontPage = {
|
|||
{ path: "note", label: "Note", full: true },
|
||||
],
|
||||
},
|
||||
featuredCardsChild,
|
||||
{
|
||||
...featuredCardsChild,
|
||||
fields: [
|
||||
...featuredCardsChild.fields,
|
||||
{
|
||||
path: "size",
|
||||
label: "Size",
|
||||
widget: "select",
|
||||
options: [
|
||||
["normal", "Normal: one cell"],
|
||||
["wide", "Wide: two columns"],
|
||||
["tall", "Tall: two rows"],
|
||||
["large", "Large: two columns, two rows"],
|
||||
],
|
||||
blankLabel: "Default: automatic (the first of three or more is large)",
|
||||
help: "On a wide screen. Phones show one card per row",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "paths",
|
||||
label: "Connect Nav",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { mediaUrl } from "../media.ts";
|
||||
import { PLACE_FIELDS, PUBLISH_FIELDS, timelineGroup, timelineDetailGroup, linksChild, blocksChild, tagsChild } from "./shared.ts";
|
||||
import { PLACE_FIELDS, PUBLISH_FIELDS, timelineGroup, timelineDetailGroup, linksChild, blocksChild, tagsChild, featuredCardsChild } from "./shared.ts";
|
||||
|
||||
/* ── Organizations ───────────────────────────────────────────── */
|
||||
|
||||
|
|
@ -90,6 +90,11 @@ export const organizations = {
|
|||
|
||||
children: [
|
||||
tagsChild,
|
||||
{
|
||||
...featuredCardsChild,
|
||||
when: { path: "kind", value: "region" },
|
||||
note: "Shown in this region's row of the region list (when it's opened) and on its page, in this order.",
|
||||
},
|
||||
{
|
||||
key: "region_areas",
|
||||
label: "Map areas",
|
||||
|
|
|
|||
|
|
@ -408,8 +408,12 @@ export const blocksChild = {
|
|||
resolve: mediaUrl,
|
||||
full: true,
|
||||
when: { path: "type", value: ["image", "video"] },
|
||||
frameFrom: "href",
|
||||
frameWhen: { path: "type", value: "video" },
|
||||
help: (row) =>
|
||||
row?.type === "video" ? "Still shown before it plays. Default: YouTube's own thumbnail." : undefined,
|
||||
row?.type === "video"
|
||||
? "Still shown before it plays. Default: YouTube's own thumbnail. Frame at takes a still from a YouTube or Facebook video."
|
||||
: undefined,
|
||||
},
|
||||
{
|
||||
path: "captions",
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@
|
|||
*/
|
||||
|
||||
import type { BlogPostSummary } from './useBlog.ts'
|
||||
import type { FeaturedCard } from './useFrontPage.ts'
|
||||
import { detailPath } from './hrefs.ts'
|
||||
import { useRecord, type Resource } from './useRecord.ts'
|
||||
import type { EventType } from './eventTypes.ts'
|
||||
|
|
@ -257,6 +258,8 @@ export type OrganizationRecord = {
|
|||
map_note?: string | null
|
||||
areas?: RegionArea[]
|
||||
groups?: Array<{ id: string; name: string; location_label?: string | null; logo?: string | null }>
|
||||
/** A region's own featured cards, in order. */
|
||||
featured?: FeaturedCard[]
|
||||
region_id?: string | null
|
||||
region_name?: string | null
|
||||
region_color?: string | null
|
||||
|
|
|
|||
|
|
@ -51,7 +51,8 @@ export type Hero = {
|
|||
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; captions?: string | null } | null
|
||||
/** `still` is shown before it plays; resolve it with mediaUrl. */
|
||||
video: { url: string; title?: string | null; captions?: string | null; still?: string | null } | null
|
||||
/** With the 'event' feature: the pinned event, else the countdown's. */
|
||||
event: HeroEvent | null
|
||||
}
|
||||
|
|
@ -106,8 +107,13 @@ export type FeaturedCard = {
|
|||
blurb?: string | null
|
||||
/** Resolve the file with mediaUrl in media.ts. */
|
||||
image: { file: string; kind: string } | null
|
||||
/** Its shape in the grid; null is automatic (FeaturedCards). */
|
||||
size?: FeaturedSize | null
|
||||
}
|
||||
|
||||
export type FeaturedSize = 'normal' | 'wide' | 'tall' | 'large'
|
||||
export type FeaturedColumns = 2 | 3 | 4
|
||||
|
||||
/** The countdown's event plus what the hero's event card draws. */
|
||||
export type HeroEvent = CountdownEvent & {
|
||||
tagline?: string | null
|
||||
|
|
@ -123,6 +129,8 @@ export type FrontPage = {
|
|||
stats: FrontPageStat[]
|
||||
paths: FrontPagePath[]
|
||||
featured: FeaturedCard[]
|
||||
/** Columns across on a wide screen; null is the grid's default. */
|
||||
featured_columns: FeaturedColumns | null
|
||||
countdown: CountdownEvent | null
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -7,4 +7,4 @@
|
|||
box or a build banner can read the same value later.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
export const SITE_VERSION = "NGU-Web.v1.13.1-data";
|
||||
export const SITE_VERSION = "NGU-Web.v1.13.2-region-cards";
|
||||
|
|
|
|||
|
|
@ -70,7 +70,7 @@ const BANDS: Record<FrontPageSectionKey, (props: BandProps) => ReactNode> = {
|
|||
<Pathfinder id={id('connect')!} title={title} blurb={section.blurb} paths={page.paths} />
|
||||
),
|
||||
featured: ({ page, section, title }) => (
|
||||
<FeaturedBand id={id('featured')!} title={title} blurb={section.blurb} cards={page.featured} />
|
||||
<FeaturedBand id={id('featured')!} title={title} blurb={section.blurb} cards={page.featured} columns={page.featured_columns} />
|
||||
),
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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 ContentBlocks from '../components/ContentBlocks.tsx'
|
||||
import FeaturedCards from '../components/FeaturedCards.tsx'
|
||||
import OrgTeams, { hasTeams } from '../components/OrgTeams.tsx'
|
||||
import OrgContact from '../components/OrgContact.tsx'
|
||||
import Tags from '../components/Tags.tsx'
|
||||
|
|
@ -94,6 +95,21 @@ export default function OrganizationDetail() {
|
|||
},
|
||||
]
|
||||
|
||||
// A region's own featured cards, the same ones its row in the
|
||||
// region list shows.
|
||||
if (org.kind === 'region' && (org.details.featured?.length ?? 0) > 0) {
|
||||
sections.push({
|
||||
id: 'featured',
|
||||
title: 'Featured',
|
||||
accent,
|
||||
content: (
|
||||
<div className="max-w-6xl mx-auto px-6">
|
||||
<FeaturedCards cards={org.details.featured ?? []} />
|
||||
</div>
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
if (hasTeams(org)) {
|
||||
sections.push({
|
||||
id: 'leadership',
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ import { Link } from "react-router-dom";
|
|||
import { ApiError, del, get, post } from "../../lib/api.ts";
|
||||
import { clock, parseClock } from "../../lib/clock.ts";
|
||||
import { accentText, BRAND } from '../../lib/color.ts'
|
||||
import { NameBox } from "../../components/admin/MediaLibrary.tsx";
|
||||
|
||||
const MUTED = "var(--color-muted)";
|
||||
const POLL_MS = 2000;
|
||||
|
|
@ -71,6 +72,52 @@ const primary =
|
|||
const input =
|
||||
"border border-muted/25 bg-surface px-3 py-2 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25";
|
||||
|
||||
/* Save to library: a Name box first, prefilled with the video's title
|
||||
(and a clip's span), which also names the file. `act` is the
|
||||
page's, so a failure shows on the row like any other action. */
|
||||
function SaveToLibrary({
|
||||
id,
|
||||
defaultName,
|
||||
act,
|
||||
}: {
|
||||
id: number;
|
||||
defaultName: string;
|
||||
act: (fn: () => Promise<unknown>) => Promise<void>;
|
||||
}) {
|
||||
const [name, setName] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
if (name === null) {
|
||||
return (
|
||||
<button type="button" className={button} onClick={() => setName(defaultName)}>
|
||||
Save to library
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-wrap items-center gap-2">
|
||||
<NameBox value={name} onChange={setName} className="min-w-64 flex-1" />
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy || !name.trim()}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
await act(() => post(`/admin/clips/${id}/save`, { name }));
|
||||
setBusy(false);
|
||||
setName(null);
|
||||
}}
|
||||
>
|
||||
{busy ? "Saving…" : "Save"}
|
||||
</button>
|
||||
<button type="button" className="text-sm text-muted hover:underline" disabled={busy} onClick={() => setName(null)}>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* Save to Drive: a folder under Media (Tools → Media → Files), then
|
||||
the clip goes there as a Files entry. Opens on a folder named for
|
||||
the clip's kind (Videos, Audio) when there is one. */
|
||||
|
|
@ -477,9 +524,7 @@ export default function AdminClips() {
|
|||
{/* The whole video, before (or without) cutting: it
|
||||
stays here to cut from either way. */}
|
||||
{s.status === "done" && s.has_file && !s.saved_url && (
|
||||
<button type="button" className={button} onClick={() => act(() => post(`/admin/clips/${s.id}/save`, {}))}>
|
||||
Save to library
|
||||
</button>
|
||||
<SaveToLibrary id={s.id} defaultName={s.title ?? "Video"} act={act} />
|
||||
)}
|
||||
{s.saved_url && (
|
||||
<Link to="/admin/media" className="text-sm underline" style={{ color: accentText(BRAND) }}>
|
||||
|
|
@ -553,9 +598,13 @@ export default function AdminClips() {
|
|||
>
|
||||
Download
|
||||
</a>
|
||||
<button type="button" className={button} onClick={() => act(() => post(`/admin/clips/${clip.id}/save`, {}))}>
|
||||
Save to library
|
||||
</button>
|
||||
<SaveToLibrary
|
||||
id={clip.id}
|
||||
defaultName={`${sourceTitle(clip.source_id)}${
|
||||
clip.params ? ` (${clock(clip.params.start)} to ${clock(clip.params.end)})` : ""
|
||||
}`}
|
||||
act={act}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{clip.saved_url && (
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@
|
|||
a page (an image field stores the path, not a foreign key).
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
|
||||
import { ApiError, del, get, patch, post } from "../../lib/api.ts";
|
||||
|
|
@ -38,6 +38,7 @@ import {
|
|||
FolderTabs,
|
||||
formatBytes,
|
||||
MediaGrid,
|
||||
NameBox,
|
||||
UPLOAD_HELP,
|
||||
UploadButton,
|
||||
useMediaLibrary,
|
||||
|
|
@ -131,6 +132,73 @@ function DeleteControl({
|
|||
);
|
||||
}
|
||||
|
||||
/* Rename: the library's name and the file's own. Opening it asks what
|
||||
uses the file first, since the server repoints those records at the
|
||||
new address and anything outside the site (a sent newsletter, a
|
||||
shared link) keeps the old one, which stops working. */
|
||||
function RenameControl({ item, onRenamed }: { item: MediaItem; onRenamed: (item: MediaItem) => void }) {
|
||||
const [name, setName] = useState<string | null>(null);
|
||||
const [uses, setUses] = useState<Use[] | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function open() {
|
||||
setName(item.original_name);
|
||||
setError(null);
|
||||
setUses(null);
|
||||
try {
|
||||
setUses((await get(`/admin/media/${item.id}/uses`, { ttl: 0 })).uses);
|
||||
} catch {
|
||||
setUses([]);
|
||||
}
|
||||
}
|
||||
|
||||
async function save(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!name?.trim()) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const { media } = await patch(`/admin/media/${item.id}`, { name });
|
||||
onRenamed(media);
|
||||
setName(null);
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : "Couldn't rename that.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (name === null) {
|
||||
return (
|
||||
<button type="button" onClick={open} className="text-xs text-link hover:underline">
|
||||
Rename
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
const count = uses?.reduce((sum, use) => sum + use.count, 0) ?? 0;
|
||||
return (
|
||||
<form onSubmit={save} className="w-full space-y-2 bg-tint p-2 text-xs text-body">
|
||||
<NameBox value={name} onChange={setName} />
|
||||
<p className="text-muted">
|
||||
{uses === null
|
||||
? "Checking what uses it…"
|
||||
: `Also renames the file${count > 0 ? `, and updates the ${count} record${count === 1 ? "" : "s"} using it` : ""}. Links to the old address outside the site (eg. a sent newsletter) will stop working.`}
|
||||
</p>
|
||||
<div className="flex gap-3">
|
||||
<button type="submit" disabled={busy || !name.trim()} className="font-medium text-link hover:underline disabled:opacity-50">
|
||||
{busy ? "Renaming…" : "Save name"}
|
||||
</button>
|
||||
<button type="button" onClick={() => setName(null)} className="text-muted hover:underline">
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
{error && <p className="text-danger">{error}</p>}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function CopyPath({ url, label = "Copy path" }: { url: string; label?: string }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
return (
|
||||
|
|
@ -573,6 +641,14 @@ export default function AdminMedia() {
|
|||
>
|
||||
Open
|
||||
</a>
|
||||
{roleCanWrite(user) && (
|
||||
<RenameControl
|
||||
item={item}
|
||||
onRenamed={(renamed) =>
|
||||
setItems((current) => (current ?? []).map((m) => (m.id === renamed.id ? renamed : m)))
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{canDelete(user) && (
|
||||
<div className="w-full">
|
||||
<DeleteControl
|
||||
|
|
|
|||
191
src/pages/admin/AdminVideoFrames.tsx
Normal file
191
src/pages/admin/AdminVideoFrames.tsx
Normal file
|
|
@ -0,0 +1,191 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
ADMIN: VIDEO THUMBNAILS (Tools → Video thumbnails, editors and up)
|
||||
|
||||
Paste a YouTube or Facebook link and a time, and the server takes
|
||||
that one frame (grabFrame in server/src/clips.js, the same as an
|
||||
image field's Frame at) and saves it to the media library's
|
||||
Previews folder (thumbnails/). A link's own t= fills in the time.
|
||||
|
||||
Frames taken here are listed until the page is left, each with a
|
||||
full-size link, a download and its path to copy into a field.
|
||||
They stay in the library (Tools → Media) after that.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { useId, useState, type FormEvent } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
|
||||
import { ApiError, post } from "../../lib/api.ts";
|
||||
import { clock, parseClock } from "../../lib/clock.ts";
|
||||
import { frameName, startOf, type MediaItem } from "../../components/admin/MediaLibrary.tsx";
|
||||
|
||||
const MUTED = "var(--color-muted)";
|
||||
|
||||
const button =
|
||||
"btn border border-brand px-4 py-2 text-sm text-link transition-colors hover:bg-tint disabled:cursor-default disabled:opacity-50";
|
||||
const primary =
|
||||
"btn bg-action px-5 py-2.5 text-white transition-colors hover:bg-action-hover disabled:bg-muted/25";
|
||||
const input =
|
||||
"border border-muted/25 bg-surface px-3 py-2 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25";
|
||||
|
||||
type Taken = { media: MediaItem; url: string; seconds: number };
|
||||
|
||||
function Frame({ frame }: { frame: Taken }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
async function copy() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(frame.media.url);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 1500);
|
||||
} catch {
|
||||
setCopied(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<li className="bg-raised shadow-md">
|
||||
<a href={frame.media.url} target="_blank" rel="noopener noreferrer">
|
||||
<img src={frame.media.url} alt="" className="aspect-video w-full bg-tint object-cover" />
|
||||
</a>
|
||||
<div className="space-y-3 p-4">
|
||||
<div>
|
||||
<p className="font-medium text-body">{frame.media.original_name}</p>
|
||||
<p className="text-xs" style={{ color: MUTED }}>
|
||||
At {clock(frame.seconds)}
|
||||
</p>
|
||||
<p className="truncate text-xs" style={{ color: MUTED }} title={frame.url}>
|
||||
{frame.url}
|
||||
</p>
|
||||
{frame.media.width && frame.media.height && (
|
||||
<p className="text-xs" style={{ color: MUTED }}>
|
||||
{frame.media.width} × {frame.media.height}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<a href={frame.media.url} download className={button}>
|
||||
Download
|
||||
</a>
|
||||
<button type="button" className={button} onClick={copy}>
|
||||
{copied ? "Copied" : "Copy path"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AdminVideoFrames() {
|
||||
const [url, setUrl] = useState("");
|
||||
const [time, setTime] = useState("0:00");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [frames, setFrames] = useState<Taken[]>([]);
|
||||
// null: follow the time ("Video frame at 1:23"); typed, it's kept.
|
||||
const [typedName, setTypedName] = useState<string | null>(null);
|
||||
const urlId = useId();
|
||||
const timeId = useId();
|
||||
const nameId = useId();
|
||||
|
||||
const seconds = parseClock(time);
|
||||
const name = typedName ?? frameName(time);
|
||||
|
||||
// A pasted link that carries its own time (t=83) sets the box.
|
||||
function changeUrl(next: string) {
|
||||
setUrl(next);
|
||||
const start = startOf(next.trim());
|
||||
if (start > 0) setTime(clock(start));
|
||||
}
|
||||
|
||||
async function take(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
if (seconds == null) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const link = url.trim();
|
||||
const { media } = await post("/admin/video-frame", { url: link, seconds, name });
|
||||
setFrames((list) => [{ media, url: link, seconds }, ...list]);
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : "Couldn't take that frame.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex flex-wrap items-baseline gap-3">
|
||||
<h1 className="text-2xl font-bold text-link">Video thumbnails</h1>
|
||||
<p className="text-sm" style={{ color: MUTED }}>
|
||||
Take a still from one of our YouTube or Facebook videos at any moment.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<section className="mt-6 bg-raised p-5 shadow-md">
|
||||
<form onSubmit={take} className="flex flex-wrap items-end gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<label htmlFor={urlId} className="block text-sm font-medium text-body">
|
||||
Video link
|
||||
</label>
|
||||
<input
|
||||
id={urlId}
|
||||
type="url"
|
||||
value={url}
|
||||
onChange={(e) => changeUrl(e.target.value)}
|
||||
placeholder="eg. https://www.youtube.com/watch?v=…"
|
||||
className={`mt-1 w-full ${input}`}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-28">
|
||||
<label htmlFor={timeId} className="block text-sm font-medium text-body">
|
||||
Time
|
||||
</label>
|
||||
<input
|
||||
id={timeId}
|
||||
type="text"
|
||||
value={time}
|
||||
onChange={(e) => setTime(e.target.value)}
|
||||
placeholder="eg. 1:23"
|
||||
className={`mt-1 w-full ${input}`}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-64">
|
||||
<label htmlFor={nameId} className="block text-sm font-medium text-body">
|
||||
Name
|
||||
</label>
|
||||
<input
|
||||
id={nameId}
|
||||
type="text"
|
||||
value={name}
|
||||
maxLength={200}
|
||||
onChange={(e) => setTypedName(e.target.value)}
|
||||
className={`mt-1 w-full ${input}`}
|
||||
/>
|
||||
</div>
|
||||
<button type="submit" className={primary} disabled={busy || !url.trim() || seconds == null}>
|
||||
{busy ? "Taking…" : "Take frame"}
|
||||
</button>
|
||||
</form>
|
||||
<p className="mt-2 text-xs" style={{ color: MUTED }}>
|
||||
YouTube and Facebook links only, and only videos NGU owns or has permission to use. A link copied with
|
||||
its time (eg. Share → Start at) fills in the time. Frames are saved to{" "}
|
||||
<Link to="/admin/media" className="text-link underline">
|
||||
Media
|
||||
</Link>{" "}
|
||||
→ Previews.
|
||||
</p>
|
||||
{seconds == null && <p className="mt-2 text-sm text-danger">Write the time as seconds or m:ss, eg. 83 or 1:23.</p>}
|
||||
{error && <p className="mt-2 text-sm text-danger">{error}</p>}
|
||||
</section>
|
||||
|
||||
{frames.length > 0 && (
|
||||
<ul className="mt-6 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{frames.map((frame) => (
|
||||
<Frame key={frame.media.id} frame={frame} />
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -190,6 +190,12 @@ export const TOOLS_NAV = {
|
|||
blurb: "Cut clips from our YouTube and Facebook videos: trimmed, reshaped for Reels, or audio only.",
|
||||
minRole: "admin",
|
||||
},
|
||||
{
|
||||
to: "/admin/thumbnails",
|
||||
label: "Video thumbnails",
|
||||
blurb: "A still from one of our YouTube or Facebook videos at any moment, saved to the media library.",
|
||||
minRole: "editor",
|
||||
},
|
||||
{
|
||||
to: "/admin/newsletter",
|
||||
label: "Newsletter",
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import { ArrowUpRight, CaretRight } from '@phosphor-icons/react';
|
||||
import { useId, useState } from "react";
|
||||
import { ArrowUpRight, CaretDown, CaretRight } from '@phosphor-icons/react';
|
||||
import { useId, useRef, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import ArrowLink from "../../components/ArrowLink.tsx";
|
||||
import FeaturedCards from "../../components/FeaturedCards.tsx";
|
||||
import { mediaUrl } from "../../lib/media.ts";
|
||||
import Logo from "../../components/Logo.tsx";
|
||||
import PlatformIcon from "../../components/PlatformIcon.tsx";
|
||||
|
|
@ -38,9 +39,9 @@ import { useReadingMode } from '../../lib/readingMode.ts'
|
|||
groupBy={org => org.details?.scope}
|
||||
/>
|
||||
|
||||
Kind-specific extras (the areas a region covers, its map note)
|
||||
come from `details` and render only when present, so a partner
|
||||
row simply doesn't have them.
|
||||
Kind-specific extras (the areas a region covers, its map note,
|
||||
its featured cards) come from `details` and render only when
|
||||
present, so a partner row simply doesn't have them.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
const MUTED = "var(--color-muted)";
|
||||
|
|
@ -83,6 +84,7 @@ function OrgMark({ org, color }) {
|
|||
function OrgRow({ org, pageLabel, siteLabel, titled }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const panelId = useId();
|
||||
const toggleRef = useRef<HTMLButtonElement>(null);
|
||||
const reading = useReadingMode();
|
||||
// Under a block title the names are a level below it.
|
||||
const Name = titled ? "h4" : "h3";
|
||||
|
|
@ -100,9 +102,12 @@ function OrgRow({ org, pageLabel, siteLabel, titled }) {
|
|||
exactly once rather than in both places. */
|
||||
const summary = org.tagline;
|
||||
|
||||
// A region's own featured cards, last in the panel.
|
||||
const featured = org.details?.featured ?? [];
|
||||
|
||||
// Something has to be behind the chevron or opening it does nothing.
|
||||
const hasPanel =
|
||||
org.description?.length > 0 || areas || note || org.links?.length > 0;
|
||||
org.description?.length > 0 || areas || note || org.links?.length > 0 || featured.length > 0;
|
||||
|
||||
return (
|
||||
<div className="py-3" style={{ borderTop: `1px solid ${RULE}` }}>
|
||||
|
|
@ -116,6 +121,7 @@ function OrgRow({ org, pageLabel, siteLabel, titled }) {
|
|||
</div>
|
||||
) : (
|
||||
<button
|
||||
ref={toggleRef}
|
||||
onClick={() => setOpen(v => !v)}
|
||||
aria-expanded={open}
|
||||
aria-controls={panelId}
|
||||
|
|
@ -163,6 +169,35 @@ function OrgRow({ org, pageLabel, siteLabel, titled }) {
|
|||
</div>
|
||||
</div>
|
||||
|
||||
{/* Closed, a region with featured cards shows their top half
|
||||
fading out, and a button that opens the row to them. The
|
||||
peek is a picture of the cards, not a second set of links:
|
||||
inert, so it takes no clicks or tab stops, and hidden from
|
||||
screen readers, which get the button. */}
|
||||
{featured.length > 0 && !open && !reading && (
|
||||
<div className="pl-10 pr-2 pt-2">
|
||||
<div className="ol-peek" inert aria-hidden="true">
|
||||
<FeaturedCards cards={featured} level={titled ? 5 : 4} />
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
// The button goes as the row opens, so focus moves to the
|
||||
// row's own toggle rather than falling back to the page.
|
||||
onClick={() => {
|
||||
setOpen(true);
|
||||
toggleRef.current?.focus();
|
||||
}}
|
||||
aria-controls={panelId}
|
||||
aria-expanded={false}
|
||||
className="btn -mt-4 relative inline-flex items-center gap-2 py-2 px-4 text-sm"
|
||||
style={{ border: `1px solid ${color}`, color: accentText(color) }}
|
||||
>
|
||||
Show featured ({featured.length})
|
||||
<CaretDown size="1em" weight="bold" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 0fr → 1fr animates to the panel's real height, so nobody
|
||||
has to guess a max-height that's wrong the moment a
|
||||
description grows. */}
|
||||
|
|
@ -214,6 +249,12 @@ function OrgRow({ org, pageLabel, siteLabel, titled }) {
|
|||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{featured.length > 0 && (
|
||||
<div className="pt-2">
|
||||
<FeaturedCards cards={featured} level={titled ? 5 : 4} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -8,23 +8,24 @@
|
|||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import FeaturedCards from '../../../components/FeaturedCards.tsx'
|
||||
import type { FeaturedCard } from '../../../lib/useFrontPage.ts'
|
||||
import type { FeaturedCard, FeaturedColumns } from '../../../lib/useFrontPage.ts'
|
||||
|
||||
type FeaturedBandProps = {
|
||||
id: string
|
||||
title: string
|
||||
blurb?: string | null
|
||||
cards: FeaturedCard[]
|
||||
columns?: FeaturedColumns | null
|
||||
}
|
||||
|
||||
export default function FeaturedBand({ id, title, blurb, cards }: FeaturedBandProps) {
|
||||
export default function FeaturedBand({ id, title, blurb, cards, columns }: FeaturedBandProps) {
|
||||
return (
|
||||
<section id={id} className="py-24">
|
||||
<div className="mx-auto max-w-6xl px-6">
|
||||
<h2 className="font-display text-4xl font-bold text-ink md:text-5xl">{title}</h2>
|
||||
{blurb && <p className="mt-4 max-w-2xl text-lg text-muted">{blurb}</p>}
|
||||
<div className="mt-12">
|
||||
<FeaturedCards cards={cards} />
|
||||
<FeaturedCards cards={cards} columns={columns ?? undefined} />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
|
|
|||
|
|
@ -113,7 +113,13 @@ export default function HeroStage({ hero }: { hero: Hero | null }) {
|
|||
|
||||
{feature === 'video' && hero?.video && (
|
||||
<div className="lg:col-span-7">
|
||||
<VideoFrame source={video} url={hero.video.url} title={hero.video.title} captions={mediaUrl(hero.video.captions)} />
|
||||
<VideoFrame
|
||||
source={video}
|
||||
url={hero.video.url}
|
||||
title={hero.video.title}
|
||||
captions={mediaUrl(hero.video.captions)}
|
||||
still={mediaUrl(hero.video.still)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
|
@ -493,18 +499,22 @@ function LiveFrame({ src, url, title }: { src: string | null; url: string; title
|
|||
"metadata" fetches enough for the first frame and the length,
|
||||
not the whole file. An embed is a VideoPlayer: a still until
|
||||
pressed, so the video's host sets nothing before then. A link
|
||||
that is neither still gets a button out to it. */
|
||||
that is neither still gets a button out to it. `still` is the
|
||||
editor's chosen picture (074): the embed's still, or the file's
|
||||
poster; without one, YouTube's thumbnail or the first frame. */
|
||||
function VideoFrame({
|
||||
source,
|
||||
url,
|
||||
title,
|
||||
captions,
|
||||
still,
|
||||
}: {
|
||||
source: VideoSource | null
|
||||
url: string
|
||||
title?: string | null
|
||||
/** A WebVTT file's URL; only a file plays it, an embed has its own. */
|
||||
captions?: string | null
|
||||
still?: string | null
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
|
|
@ -520,11 +530,12 @@ function VideoFrame({
|
|||
controls
|
||||
playsInline
|
||||
preload="metadata"
|
||||
poster={still ?? undefined}
|
||||
>
|
||||
{captions && <track kind="captions" src={captions} srcLang="en" label="Captions" default />}
|
||||
</video>
|
||||
) : source?.kind === 'embed' ? (
|
||||
<VideoPlayer url={url} title={title || 'Featured video'} className="h-full" />
|
||||
<VideoPlayer url={url} still={still} title={title || 'Featured video'} className="h-full" />
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
<HomeLink
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue