Compare commits

..

No commits in common. "422e521394918cbcbf77aace6f2d361a5a6826d2" and "c62dc84adde4ba6f08ff013e68c572f445d07f92" have entirely different histories.

13 changed files with 169 additions and 1072 deletions

View file

@ -22,7 +22,6 @@ Backend (`server/`, Node >= 22). The server reads `HOST` (default `127.0.0.1`),
- `DB_PATH=./dev.db pnpm dev`: run with `node --watch`
- `DB_PATH=./dev.db pnpm migrate`: apply migrations without starting the server
- `DB_PATH=./dev.db node src/admin-cli.js add|list|passwd|role|disable|enable ...`: the only way accounts are created
- `DB_PATH=./dev.db node src/seed-showcase.js [--listed]`: writes fully filled test records (a region, chapter, team, award, person, three events and a blog post with every content block type), ids starting `showcase-`, for checking pages. Unlisted unless `--listed`. Local only; refuses /var/lib/ngu.
In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API must listen on that port.

View file

@ -174,8 +174,8 @@ also in `admin-schema.js` and a CHECK):
| People → Affiliations → Role; Teams → Members → Role | lead, board, staff, volunteer, member | no | `ROLE_LABEL` in `src/pages/PersonDetail.tsx` |
| Links → Kind (on organizations, events, people, teams) | action, social, website, email | no | `splitLinks` in `server/src/shape.js` |
| Links → Platform | instagram, facebook, discord, youtube, tiktok, x, substack, spotify, linkedin | **yes**, `PLATFORMS` | `PlatformIcon.tsx` draws the icon on the button. **No CHECK and no `enumeration`**: the column is plain text, so adding one is an entry in `PLATFORMS` (`src/lib/platforms.ts`) and its icon in `src/components/PlatformIcon.tsx`, no migration. |
| Content blocks → Shown in (slot) | card, body | **yes** | `paragraphs()` in `server/src/shape.js` (card), `ContentBlocks.tsx` (body) |
| Content blocks → Type | heading, subheading, paragraph, list, links, quote, image, divider, video, button, callout | **yes**, `BLOCK_TYPES` (with each type's description) | `ContentBlocks.tsx` (one renderer per type). Which fields each type shows is `when` on the fields in `blocksChild` (`src/lib/adminSchema.ts`). |
| Content blocks → Slot | card, body | no | `ContentBlocks.tsx` |
| Content blocks → Type | heading, subheading, paragraph, list, links, quote, image, divider | no | `ContentBlocks.tsx` (one renderer per type) |
| Timeline → Kind (+ list filter) | milestone, event, organization, award, people | no | `KIND_NAMES` in `src/pages/sections/history/TimelineEntry.tsx` |
| Timeline → Points at (+ list filter) | event, organization, award, person, team | no | `refHref` in `src/lib/hrefs.ts` |
| Timeline → Precision (and on events/orgs) | year, month, day | no | the history page's grouping |

View file

@ -176,17 +176,12 @@ const blocksChild = (ownerKind) => ({
"quote",
"image",
"divider",
"video",
"button",
"callout",
],
{ required: true },
),
text("text"),
text("media"),
text("href"),
text("alt"),
text("cite"),
],
children: [
{

View file

@ -1,80 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 032 CONTENT BLOCKS: VIDEO, BUTTON, CALLOUT, ALT TEXT, ATTRIBUTION
--
-- Three new block types, and two columns for types that had to
-- borrow one:
--
-- video href is the link (YouTube, Vimeo, Facebook) or a
-- video file; text is the caption; media an optional
-- still. Drawn click-to-play, like a featured card.
-- button text is the label, href where it goes.
-- callout text in a tinted box, for a note or announcement.
--
-- alt an image's alt text. text stays its caption: a
-- caption describes the moment, alt describes the
-- picture to someone who can't see it.
-- cite who a quote is by.
--
-- The type list is a CHECK, so the table is rebuilt, the same way
-- 031 did (see its header): legacy_alter_table around the rename,
-- because the *_cleanup triggers on other tables name it, then the
-- index and the owner trigger again.
--
-- PRAGMA user_version; -- reads 31 before this file
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE content_blocks_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_kind TEXT NOT NULL
CHECK (owner_kind IN ('organization', 'event', 'person', 'team', 'blog_post')),
owner_id TEXT NOT NULL,
slot TEXT NOT NULL DEFAULT 'body' CHECK (slot IN ('card', 'body')),
sort_order INTEGER NOT NULL DEFAULT 0,
type TEXT NOT NULL
CHECK (type IN ('heading', 'subheading', 'paragraph',
'list', 'links', 'quote', 'image', 'divider',
'video', 'button', 'callout')),
text TEXT,
media TEXT,
href TEXT,
alt TEXT,
cite TEXT
) STRICT;
INSERT INTO content_blocks_new (id, owner_kind, owner_id, slot, sort_order, type, text, media, href)
SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href
FROM content_blocks;
PRAGMA legacy_alter_table = ON;
DROP TABLE content_blocks;
ALTER TABLE content_blocks_new RENAME TO content_blocks;
PRAGMA legacy_alter_table = OFF;
CREATE INDEX content_blocks_owner_idx
ON content_blocks (owner_kind, owner_id, slot, sort_order);
-- ── Triggers last (see CLAUDE.md, Migrations) ──
CREATE TRIGGER content_blocks_owner_exists
BEFORE INSERT ON content_blocks
BEGIN
SELECT CASE
WHEN new.owner_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such event')
WHEN new.owner_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such organization')
WHEN new.owner_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such person')
WHEN new.owner_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such team')
WHEN new.owner_kind = 'blog_post'
AND NOT EXISTS (SELECT 1 FROM blog_posts WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such blog post')
END;
END;

View file

@ -1,458 +0,0 @@
/* ═══════════════════════════════════════════════════════════════
SHOWCASE: local test records with every field filled in
DB_PATH=./dev.db node src/seed-showcase.js
DB_PATH=./dev.db node src/seed-showcase.js --listed
Writes one of each record kind with every field and option used,
so a change to any page can be checked against a record that
exercises all of it:
/regions/showcase-region region: areas, map note, links, blocks
/chapters/showcase-chapter chapter: meets, started, region
/teams/showcase-team team: a lead and members
/awards/showcase-award award: recipients, one at an event
/people/showcase-person person: bio, links, roles past and
current, events, awards, private data
/events/showcase-event upcoming retreat: hosts, billed
people, links, blocks, background
/events/showcase-series weekly series with times
/events/showcase-past-event past event where the award was given
/blog/content-block-showcase every content block type
Everything is test data: ids start with showcase- (the blog post
is content-block-showcase), names say Showcase, and contact
details use example.org and 555 numbers. Run it again to put it
all back as written here; it replaces these records and nothing
else.
Published but unlisted by default: every page above works, and
none of it shows in the site's lists, counts, map or QR page.
One consequence: a region's page lists only listed chapters,
teams, awards and events, so the showcase region's are empty.
--listed lists everything instead, and
adds timeline entries, so the Community map, Retreats bands,
calendar, History page and front page counts can be checked too.
Run without it again to take them back out.
Images point at /uploads/showcase.jpg. Upload any photo in
Admin → Media and copy it to that name in the uploads directory,
or leave it missing to check how each page copes without one.
It refuses the production database (anything under /var/lib/ngu).
═══════════════════════════════════════════════════════════════ */
import { openDatabase, migrate, tx } from "./db.js";
const DB_PATH = process.env.DB_PATH ?? "./ngu.db";
const LISTED = process.argv.includes("--listed") ? 1 : 0;
// Matched anywhere in the path, not only at its start, so a shell
// that rewrites /var/lib/... into its own form (Git Bash) is caught too.
if (/(^|\/)var\/lib\/ngu(\/|$)/.test(DB_PATH.replace(/\\/g, "/"))) {
console.error("✗ This is test content. It won't write to the production database.");
process.exit(1);
}
const IMAGE = "/uploads/showcase.jpg";
const POST_ID = "content-block-showcase";
const REGION = "showcase-region";
const CHAPTER = "showcase-chapter";
const TEAM = "showcase-team";
const AWARD = "showcase-award";
const PERSON = "showcase-person";
const MEMBERS = ["showcase-member-1", "showcase-member-2", "showcase-member-3"];
const EVENT = "showcase-event";
const SERIES = "showcase-series";
const PAST = "showcase-past-event";
/* ── Content ───────────────────────────────────────────────── */
/* Every block type, for the blog showcase. [type, fields, items?] */
const ALL_BLOCKS = [
["paragraph", { text: "Every content block type, top to bottom, with each of its options. Use it to check the page after changing how blocks draw." }],
["heading", { text: "Heading" }],
["subheading", { text: "Subheading" }],
["paragraph", { text: "A paragraph with **bold**, *italic*, a [link to the history page](/history) and an [outside link](https://example.org).\nThis line follows a single line break.\n\nA blank line starts a second paragraph in the same block." }],
["paragraph", { text: "A whole paragraph that is a link, set with the block's Link field.", href: "/community" }],
["callout", { text: "**A callout.** For a note or an announcement. It takes the same formatting as a paragraph, including [links](/give)." }],
["quote", { text: "Unity is not a feeling we wait for. It is a practice we keep.", cite: "A retreat speaker" }],
["quote", { text: "A quote with no attribution." }],
["divider", {}],
["subheading", { text: "Lists" }],
["list", {}, [
{ text: "A plain item" },
{ text: "An item with a detail", detail: "the detail" },
{ text: "A linked item", url: "/retreats" },
{ text: "A linked item with a detail", url: "https://example.org", detail: "opens in a new tab" },
]],
["links", {}, [
{ text: "Retreats", url: "/retreats" },
{ text: "Community", url: "/community" },
{ text: "An outside site", url: "https://example.org" },
]],
["button", { text: "A button", href: "/give" }],
["divider", {}],
["subheading", { text: "Images" }],
["image", { media: IMAGE, alt: "Describe the picture here", text: "An image with a caption and alt text" }],
["image", { media: IMAGE, alt: "The same picture, linked", href: "/history" }],
["subheading", { text: "Video" }],
["video", { href: "https://www.youtube.com/watch?v=dQw4w9WgXcQ", text: "A YouTube video, with its own thumbnail" }],
["video", { href: "https://vimeo.com/76979871", media: IMAGE, text: "A Vimeo video with an uploaded still" }],
];
/* A record page's body: a handful of types, so it reads like a
real page rather than a catalogue. */
const pageBody = (what) => [
["heading", { text: `About this ${what}` }],
["paragraph", { text: `This is **showcase data** for a ${what} page. Every field on the record is filled in, so anything left blank on the page is something the page doesn't draw.\n\nSee the [content block showcase](/blog/${POST_ID}) for every block type.` }],
["callout", { text: `**Test content:** made by seed-showcase.js, not a real ${what}.` }],
["list", {}, [
{ text: "What we do", detail: "gather, learn, serve" },
{ text: "Where to start", url: "/community" },
]],
["quote", { text: "A line someone said about this place.", cite: "Showcase Person" }],
["image", { media: IMAGE, alt: "A group photo", text: "A caption for the photo" }],
["button", { text: "Get involved", href: "/feedback" }],
];
/* The card slot: paragraphs only, shown on cards and list rows. */
const cardText = (what) => [
["paragraph", { text: `Showcase ${what}: the short description that appears on its card.` }],
["paragraph", { text: "A second card paragraph, to check how two read." }],
];
const standardLinks = (name) => [
{ kind: "action", label: "Register", url: "https://example.org/register", is_primary: 1 },
{ kind: "action", platform: "discord", label: "Join the Discord", url: "https://discord.com/invite/example" },
{ kind: "social", platform: "instagram", label: "@showcase", url: "https://instagram.com/showcase" },
{ kind: "social", platform: "facebook", label: `${name} on Facebook`, url: "https://facebook.com/showcase" },
{ kind: "social", platform: "youtube", label: "YouTube", url: "https://youtube.com/@showcase" },
{ kind: "website", label: "Website", url: "https://example.org" },
{ kind: "email", label: "showcase@example.org", url: "mailto:showcase@example.org" },
];
/* ── Writing ───────────────────────────────────────────────── */
const db = await openDatabase(DB_PATH);
migrate(db, { log: () => {} });
function insert(table, row) {
const keys = Object.keys(row);
return db
.prepare(`INSERT INTO ${table} (${keys.join(", ")}) VALUES (${keys.map(() => "?").join(", ")})`)
.run(...keys.map((k) => row[k] ?? null));
}
function blocks(ownerKind, ownerId, slot, list) {
list.forEach(([type, f, items = []], order) => {
const { lastInsertRowid } = insert("content_blocks", {
owner_kind: ownerKind,
owner_id: ownerId,
slot,
sort_order: order,
type,
...f,
});
items.forEach((item, i) => insert("content_block_items", { block_id: lastInsertRowid, sort_order: i, ...item }));
});
}
function links(ownerKind, ownerId, list) {
list.forEach((link, order) => insert("links", { owner_kind: ownerKind, owner_id: ownerId, sort_order: order, ...link }));
}
const place = {
venue: "Showcase Retreat Center",
address: "123 Example Road",
locality: "Exampletown",
state_code: "PA",
country: "US",
location_label: "Exampletown, PA",
latitude: 40.2732,
longitude: -76.8867,
};
tx(db, () => {
/* ── Clear the last run ── cleanup triggers take blocks, links,
timeline entries and featured cards; foreign keys the rest. */
db.prepare(`DELETE FROM blog_posts WHERE id = ?`).run(POST_ID);
db.prepare(`DELETE FROM timeline_entries WHERE title LIKE 'Showcase%' OR ref_id LIKE 'showcase-%'`).run();
db.prepare(`DELETE FROM events WHERE id LIKE 'showcase-%'`).run();
db.prepare(`DELETE FROM person_awards WHERE award_id LIKE 'showcase-%' OR person_id LIKE 'showcase-%'`).run();
db.prepare(`DELETE FROM awards WHERE id LIKE 'showcase-%'`).run();
db.prepare(`DELETE FROM affiliations WHERE person_id LIKE 'showcase-%' OR org_id LIKE 'showcase-%'`).run();
db.prepare(`DELETE FROM teams WHERE id LIKE 'showcase-%'`).run();
db.prepare(`DELETE FROM people WHERE id LIKE 'showcase-%'`).run();
db.prepare(`DELETE FROM organizations WHERE id = ?`).run(CHAPTER);
db.prepare(`DELETE FROM organizations WHERE id LIKE 'showcase-%'`).run();
/* ── Organizations ── */
insert("organizations", {
id: REGION,
kind: "region",
name: "Showcase Region",
short_name: "Showcase",
tagline: "A region with every field filled in",
color: "#7a5ea8",
logo: IMAGE,
...place,
is_online: 0,
is_published: 1,
is_listed: LISTED,
sort_order: 99,
in_timeline: LISTED,
});
insert("regions", { id: REGION, scope: "domestic", map_note: "Showcase map note: shares Pennsylvania" });
insert("region_areas", { region_id: REGION, area_code: "PA", share: 0.5, edge: "top", note: "western half" });
insert("region_areas", { region_id: REGION, area_code: "OH", share: 1 });
links("organization", REGION, standardLinks("Showcase Region"));
blocks("organization", REGION, "card", cardText("region"));
blocks("organization", REGION, "body", pageBody("region"));
insert("organizations", {
id: CHAPTER,
kind: "chapter",
name: "Showcase Chapter",
short_name: "Showcase Ch.",
tagline: "A chapter with every field filled in",
color: "#138ba0",
logo: IMAGE,
...place,
venue: "Showcase Community Hall",
is_online: 1,
is_published: 1,
is_listed: LISTED,
sort_order: 99,
});
insert("chapters", { id: CHAPTER, region_id: REGION, meets: "2nd Sundays, 6:00pm", started: "Since 2021" });
links("organization", CHAPTER, standardLinks("Showcase Chapter"));
blocks("organization", CHAPTER, "card", cardText("chapter"));
blocks("organization", CHAPTER, "body", pageBody("chapter"));
/* ── People ── */
insert("people", {
id: PERSON,
display_name: "Showcase Person",
sort_name: "Person, Showcase",
pronouns: "they/them",
tagline: "A person with every field filled in",
photo: IMAGE,
public_email: "showcase.person@example.org",
public_phone: "555-0100",
locality: "Exampletown",
state_code: "PA",
country: "US",
location_label: "Exampletown, PA",
bio: "Showcase Person is test data. This bio has two paragraphs so the page's spacing can be checked.\n\nThe second paragraph. Everything about this person is made up by seed-showcase.js.",
primary_org_id: CHAPTER,
is_published: 1,
is_listed: LISTED,
});
insert("person_private", {
person_id: PERSON,
birth_date: "2000-01-01",
private_email: "private@example.org",
private_phone: "555-0199",
address: "1 Private Lane, Exampletown, PA",
notes: "Private notes: only the admin shows these.",
});
links("person", PERSON, [
{ kind: "social", platform: "instagram", label: "@showcase.person", url: "https://instagram.com/showcase.person" },
{ kind: "social", platform: "linkedin", label: "LinkedIn", url: "https://linkedin.com/in/showcase" },
{ kind: "website", label: "Website", url: "https://example.org/person" },
{ kind: "action", label: "Book a call", url: "https://example.org/call" },
]);
blocks("person", PERSON, "card", cardText("person"));
blocks("person", PERSON, "body", pageBody("person"));
MEMBERS.forEach((id, i) =>
insert("people", {
id,
display_name: `Showcase Member ${i + 1}`,
sort_name: `Member ${i + 1}, Showcase`,
pronouns: ["she/her", "he/him", "they/them"][i],
tagline: "A supporting person for rosters",
photo: i === 2 ? null : IMAGE, // one without a photo, for the initials fallback
location_label: "Exampletown, PA",
primary_org_id: REGION,
is_published: 1,
is_listed: LISTED,
}),
);
/* ── Team, and everyone's roles ── */
insert("teams", {
id: TEAM,
org_id: REGION,
name: "Showcase Team",
tagline: "A team with a lead and members",
color: "#88b668",
logo: IMAGE,
is_published: 1,
is_listed: LISTED,
sort_order: 99,
});
links("team", TEAM, [{ kind: "action", label: "Join the team", url: "https://example.org/join" }]);
blocks("team", TEAM, "card", cardText("team"));
blocks("team", TEAM, "body", pageBody("team"));
insert("affiliations", { person_id: PERSON, org_id: REGION, team_id: TEAM, title: "Showcase Team Lead", role: "lead", is_owner: 1, started_on: "2023-01-01", is_public: 1, sort_order: 0 });
insert("affiliations", { person_id: PERSON, org_id: CHAPTER, title: "Former Chapter Coordinator", role: "volunteer", started_on: "2021-01-01", ended_on: "2022-12-31", is_public: 1, sort_order: 1 });
MEMBERS.forEach((id, i) =>
insert("affiliations", { person_id: id, org_id: REGION, team_id: TEAM, title: ["Treasurer", "Secretary", null][i], role: i === 2 ? "member" : "board", is_public: 1, sort_order: i + 1 }),
);
/* ── Events ── */
insert("events", {
id: EVENT,
scope_id: "regional",
event_type: "retreat",
title: "Showcase Retreat",
theme: "Every Field Filled",
tagline: "An upcoming event with everything set",
starts_on: db.prepare(`SELECT date('now', '+45 days') AS d`).get().d,
ends_on: db.prepare(`SELECT date('now', '+47 days') AS d`).get().d,
date_label: "Three days, six weeks from now",
...place,
is_online: 0,
org_logo: IMAGE,
event_logo: IMAGE,
color: "#d62976",
gradient: "linear-gradient(160deg, rgba(214,41,118,0.10), rgba(19,139,160,0.10))",
card_image: IMAGE,
is_published: 1,
is_listed: LISTED,
in_timeline: LISTED,
});
insert("event_hosts", { event_id: EVENT, org_id: REGION, sort_order: 0 });
insert("event_hosts", { event_id: EVENT, person_id: PERSON, sort_order: 1 });
[
[PERSON, "speaker", "Keynote"],
[MEMBERS[0], "leader", "Worship leader"],
[MEMBERS[1], "facilitator", "Workshop facilitator"],
[MEMBERS[2], "musician", null],
].forEach(([person_id, role, title], i) =>
insert("event_people", { event_id: EVENT, person_id, role, title, is_public: 1, sort_order: i }),
);
links("event", EVENT, [
{ kind: "action", label: "Register", url: "https://example.org/register", is_primary: 1 },
{ kind: "action", platform: "discord", label: "Event Discord", url: "https://discord.com/invite/example" },
{ kind: "social", platform: "instagram", label: "@showcaseretreat", url: "https://instagram.com/showcaseretreat" },
]);
blocks("event", EVENT, "card", cardText("event"));
blocks("event", EVENT, "body", pageBody("event"));
insert("events", {
id: SERIES,
scope_id: "local",
event_type: "class",
title: "Showcase Weekly Class",
tagline: "A repeating series",
starts_on: db.prepare(`SELECT date('now', '-14 days') AS d`).get().d,
ends_on: db.prepare(`SELECT date('now', '+90 days') AS d`).get().d,
location_label: "Online",
is_online: 1,
color: "#138ba0",
is_series: 1,
series_frequency: "weekly",
series_interval: 1,
series_tue: 1,
series_thu: 1,
series_start_time: "19:00",
series_end_time: "20:30",
series_count: 24,
is_published: 1,
is_listed: LISTED,
});
insert("event_hosts", { event_id: SERIES, org_id: CHAPTER, sort_order: 0 });
links("event", SERIES, [{ kind: "action", label: "Join on Zoom", url: "https://example.org/zoom" }]);
blocks("event", SERIES, "card", cardText("series"));
insert("events", {
id: PAST,
scope_id: "regional",
event_type: "workshop",
title: "Showcase Past Workshop",
starts_on: "2025-06-14",
ends_on: "2025-06-14",
date_label: "June 14, 2025",
location_label: "Exampletown, PA",
color: "#4a6b72",
is_published: 1,
is_listed: LISTED,
});
insert("event_hosts", { event_id: PAST, org_id: REGION, sort_order: 0 });
insert("event_people", { event_id: PAST, person_id: PERSON, role: "host", is_public: 1, sort_order: 0 });
blocks("event", PAST, "card", cardText("past event"));
/* ── Award ── */
insert("awards", {
id: AWARD,
org_id: REGION,
name: "Showcase Award",
description: "An award with recipients. One was presented at an event, one wasn't.",
logo: IMAGE,
is_published: 1,
is_listed: LISTED,
sort_order: 99,
});
insert("person_awards", { person_id: PERSON, award_id: AWARD, event_id: PAST, awarded_on: "2025-06-14", citation: "For filling in every field.", is_public: 1 });
insert("person_awards", { person_id: MEMBERS[0], award_id: AWARD, awarded_on: "2024-05-01", citation: "For showing up.", is_public: 1 });
/* ── Timeline, only when listed: the history page shows every
published entry, so an unlisted showcase would still appear
there. ── */
if (LISTED) {
insert("timeline_entries", { kind: "event", ref_kind: "event", ref_id: EVENT, precision: "day", is_featured: 1, is_published: 1 });
insert("timeline_entries", { kind: "organization", ref_kind: "organization", ref_id: REGION, occurred_on: "2020-09-01", precision: "month", is_published: 1 });
insert("timeline_entries", { kind: "award", ref_kind: "award", ref_id: AWARD, occurred_on: "2025-06-14", precision: "day", is_published: 1 });
const { lastInsertRowid } = insert("timeline_entries", {
kind: "people",
ref_kind: "team",
ref_id: TEAM,
occurred_on: "2023-01-01",
precision: "year",
title: "Showcase Team formed",
blurb: "A team entry drawn as a roster.",
meta: "Showcase",
is_published: 1,
});
insert("timeline_entry_people", { entry_id: lastInsertRowid, person_id: PERSON, note: "Founding lead", sort_order: 0 });
insert("timeline_entries", { kind: "milestone", occurred_on: "2019", precision: "year", title: "Showcase milestone", blurb: "A hand-written entry with no record behind it.", link_url: "/history", is_published: 1 });
}
/* ── Blog post ── */
insert("blog_posts", {
id: POST_ID,
title: "Content block showcase",
excerpt: "Every block type in one place, for checking the page.",
cover_image: IMAGE,
published_on: db.prepare(`SELECT date('now') AS d`).get().d,
tags: "Test, Showcase",
guest_author: "A Guest Author",
guest_photo: IMAGE,
is_published: 1,
is_listed: LISTED,
});
insert("blog_post_authors", { post_id: POST_ID, person_id: PERSON, sort_order: 0 });
blocks("blog_post", POST_ID, "body", ALL_BLOCKS);
});
db.close();
console.log(`✓ Showcase written (${LISTED ? "listed" : "unlisted: pages only"}):`);
for (const path of [
`/regions/${REGION}`,
`/chapters/${CHAPTER}`,
`/teams/${TEAM}`,
`/awards/${AWARD}`,
`/people/${PERSON}`,
`/events/${EVENT}`,
`/events/${SERIES}`,
`/events/${PAST}`,
`/blog/${POST_ID}`,
]) {
console.log(` ${path}`);
}

View file

@ -66,7 +66,7 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") {
const blockRows = db
.prepare(
`SELECT id, owner_id, type, text, media, href, alt, cite
`SELECT id, owner_id, type, text, media, href
FROM content_blocks
WHERE owner_kind = ? AND slot = ? AND owner_id IN (${placeholders(ids.length)})
ORDER BY owner_id, sort_order`,
@ -83,8 +83,6 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") {
text: row.text,
media: row.media,
href: row.href,
alt: row.alt,
cite: row.cite,
items: [],
};
byId.set(row.id, block);

View file

@ -1,41 +1,55 @@
/* ═══════════════════════════════════════════════════════════════
CONTENT BLOCKS
Renders the `body` slot of content_blocks. Events, organizations,
teams, people and blog posts all own blocks and all render them
the same way, so this is written once and tinted by the caller's
accent. The admin's block editor previews each block through this
same component.
Renders the `body` slot of content_blocks. Events, organizations
and teams all own blocks and all render them the same way, so
this is written once and tinted by the caller's accent.
What each type reads (see 032_content_block_types.sql):
heading, subheading text
paragraph text (formatted), href makes it all a link
callout text (formatted), in a tinted box
quote text (formatted), cite is who said it
list items: text, detail, url
links items with a url, as outlined buttons
button text is the label, href where it goes
image media, alt, text is the caption, href
video href is the video, media a still, text
the caption; click to play
divider nothing
"Formatted" is InlineText.tsx: **bold**, *italic*, [text](url),
line breaks, and a blank line for a new paragraph.
⚠ Assumes shape.js's loadBlocks returns rows carrying `type`,
`text`, `media`, `href` and an `items` array. If the field names
differ, this is the only file to fix — nothing else reads a
block.
An unknown `type` renders its text as a paragraph rather than
disappearing. A block somebody typed into the admin should be
visible even if the renderer hasn't caught up with it.
═══════════════════════════════════════════════════════════════ */
import { Link } from 'react-router-dom'
import { blockMedia } from '../lib/media.ts'
import type { ContentBlock } from '../lib/useContent.ts'
import { Anchor, Inline, Paragraphs } from './InlineText.tsx'
import VideoPlayer from './VideoPlayer.tsx'
const BODY = '#4a6b72'
/** External if it has a scheme or starts with //; otherwise it's
* one of our own routes and should go through the router. */
const isExternal = (url: string) => /^([a-z][a-z0-9+.-]*:|\/\/)/i.test(url)
function Anchor({
href,
children,
className,
style,
}: {
href: string
children: React.ReactNode
className?: string
style?: React.CSSProperties
}) {
if (isExternal(href)) {
return (
<a href={href} target="_blank" rel="noreferrer" className={className} style={style}>
{children}
</a>
)
}
return (
<Link to={href} className={className} style={style}>
{children}
</Link>
)
}
export default function ContentBlocks({
blocks,
accent = '#138ba0',
@ -56,15 +70,6 @@ export default function ContentBlocks({
)
}
function Caption({ text }: { text?: string | null }) {
if (!text) return null
return (
<figcaption className="mt-2 text-sm opacity-70" style={{ color: BODY }}>
{text}
</figcaption>
)
}
function Block({ block, accent }: { block: ContentBlock; accent: string }) {
const text = block.text ?? ''
@ -97,9 +102,11 @@ function Block({ block, accent }: { block: ContentBlock; accent: string }) {
{item.text}
</Anchor>
) : (
<Inline text={item.text} accent={accent} />
item.text
)}
{item.detail && (
<span className="opacity-70"> — {item.detail}</span>
)}
{item.detail && <span className="opacity-70">: {item.detail}</span>}
</span>
</li>
))}
@ -124,43 +131,14 @@ function Block({ block, accent }: { block: ContentBlock; accent: string }) {
</div>
)
case 'button':
if (!text || !block.href) return null
return (
<div>
<Anchor
href={block.href}
className="inline-block rounded-full px-6 py-2.5 font-semibold text-white transition-transform hover:scale-105"
style={{ background: accent }}
>
{text}
</Anchor>
</div>
)
case 'quote':
return (
<figure className="border-l-2 pl-5" style={{ borderColor: accent }}>
<blockquote className="text-lg italic" style={{ color: BODY }}>
<Inline text={text} accent={accent} />
</blockquote>
{block.cite && (
<figcaption className="mt-2 text-sm font-semibold not-italic" style={{ color: accent }}>
{block.cite}
</figcaption>
)}
</figure>
)
case 'callout':
if (!text) return null
return (
<aside
className="space-y-3 rounded-2xl border-l-4 px-6 py-5 leading-relaxed"
style={{ borderColor: accent, background: `color-mix(in srgb, ${accent} 8%, white)`, color: '#26454c' }}
<blockquote
className="border-l-2 pl-5 text-lg italic"
style={{ borderColor: accent, color: BODY }}
>
<Paragraphs text={text} accent={accent} />
</aside>
{text}
</blockquote>
)
case 'image': {
@ -169,9 +147,10 @@ function Block({ block, accent }: { block: ContentBlock; accent: string }) {
const img = (
<img
src={src}
// Alt describes the picture; the caption describes the
// moment. No alt means decorative, which alt="" says.
alt={block.alt ?? ''}
// A caption is a caption, not alt text — but an image with
// neither is decorative, and alt="" is the correct answer
// for that rather than a filename read aloud.
alt={text}
loading="lazy"
decoding="async"
className="w-full rounded-lg"
@ -180,38 +159,31 @@ function Block({ block, accent }: { block: ContentBlock; accent: string }) {
return (
<figure>
{block.href ? <Anchor href={block.href}>{img}</Anchor> : img}
<Caption text={text} />
{text && (
<figcaption className="mt-2 text-sm opacity-70" style={{ color: BODY }}>
{text}
</figcaption>
)}
</figure>
)
}
case 'video':
if (!block.href) return null
return (
<figure>
<div className="overflow-hidden rounded-lg">
<VideoPlayer url={block.href} still={blockMedia(block.media)} title={text || null} />
</div>
<Caption text={text} />
</figure>
)
case 'divider':
return <hr className="border-0 h-px" style={{ background: accent, opacity: 0.3 }} />
case 'paragraph':
default:
if (!text) return null
return block.href ? (
return (
<p className="leading-relaxed" style={{ color: BODY }}>
<Anchor href={block.href} className="underline" style={{ color: accent }}>
{text}
</Anchor>
{block.href ? (
<Anchor href={block.href} className="underline" style={{ color: accent }}>
{text}
</Anchor>
) : (
text
)}
</p>
) : (
<div className="space-y-4">
<Paragraphs text={text} accent={accent} className="leading-relaxed" style={{ color: BODY }} />
</div>
)
}
}

View file

@ -10,9 +10,10 @@
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 VideoPlayer: a still with a play button that swaps in
the player when pressed. The still is the card's
image, else YouTube's thumbnail, else a plain panel.
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.
@ -21,11 +22,13 @@
import { useState } from 'react'
import HomeLink from '../pages/sections/home/HomeLink.tsx'
import VideoPlayer from './VideoPlayer.tsx'
import { refHref } from '../lib/hrefs.ts'
import { logoForKind } from '../lib/media.ts'
import { playingSource, videoSource, videoThumbnail } from '../lib/embeds.ts'
import type { FeaturedCard } from '../lib/useFrontPage.ts'
const ACCENT = '#138ba0'
/* Image kinds that are photographs, drawn edge to edge. Anything
else is a logo, drawn whole. */
const PHOTO_KINDS = new Set(['event-background', 'featured', 'person'])
@ -68,8 +71,68 @@ function Picture({ card }: { card: FeaturedCard }) {
}
function VideoPicture({ card }: { card: FeaturedCard }) {
const [playing, setPlaying] = useState(false)
const source = videoSource(card.url)
if (playing && source) {
const live = playingSource(source)
return live.kind === 'file' ? (
<video src={live.src} controls autoPlay playsInline className="aspect-video w-full bg-black" />
) : (
<iframe
src={live.src}
title={card.title || 'Video'}
allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
allowFullScreen
className="aspect-video w-full border-0 bg-black"
/>
)
}
const own = card.image ? logoForKind(card.image.kind, card.image.file) : null
return <VideoPlayer url={card.url} still={own} title={card.title} />
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 }) {

View file

@ -1,137 +0,0 @@
/* ═══════════════════════════════════════════════════════════════
INLINE TEXT
The little formatting a content block's text may carry, typed in
the admin as plain characters:
**bold** *italic* [link text](url)
a line break keeps its place
a blank line starts a new paragraph
Parsed into React elements, never HTML, so nothing typed can
inject markup. A link only becomes one when its URL is a site
path (/history, #section), https/http, mailto: or tel:; anything
else (javascript:, data:) shows as the plain text it was.
`Paragraphs` is for block-level text (paragraph, callout): one
<p> per blank-line-separated part. `Inline` is for text that sits
inside something else (a quote, a list item).
═══════════════════════════════════════════════════════════════ */
import { Fragment, type CSSProperties, type ReactNode } from 'react'
import { Link } from 'react-router-dom'
const TOKEN = /\*\*(.+?)\*\*|\*(.+?)\*|\[([^\]]+)\]\(([^)\s]+)\)/g
const SAFE_URL = /^(\/(?!\/)|#|https?:\/\/|mailto:|tel:)/i
/** External if it has a scheme or starts with //; otherwise it's
* one of our own routes and goes through the router. */
export const isExternalUrl = (url: string) => /^([a-z][a-z0-9+.-]*:|\/\/)/i.test(url)
export function Anchor({
href,
children,
className,
style,
}: {
href: string
children: ReactNode
className?: string
style?: CSSProperties
}) {
if (isExternalUrl(href)) {
const app = /^(mailto|tel):/i.test(href)
return (
<a
href={href}
className={className}
style={style}
{...(app ? {} : { target: '_blank', rel: 'noreferrer' })}
>
{children}
</a>
)
}
if (href.startsWith('#')) {
return (
<a href={href} className={className} style={style}>
{children}
</a>
)
}
return (
<Link to={href} className={className} style={style}>
{children}
</Link>
)
}
function line(text: string, accent: string, key: string): ReactNode[] {
const out: ReactNode[] = []
let last = 0
let n = 0
for (const match of text.matchAll(TOKEN)) {
const at = match.index ?? 0
if (at > last) out.push(text.slice(last, at))
const [whole, bold, italic, label, url] = match
const k = `${key}-${n++}`
if (bold != null) out.push(<strong key={k} className="font-semibold">{bold}</strong>)
else if (italic != null) out.push(<em key={k}>{italic}</em>)
else if (label != null && SAFE_URL.test(url)) {
out.push(
<Anchor key={k} href={url} className="underline underline-offset-2" style={{ color: accent }}>
{label}
</Anchor>,
)
} else out.push(whole)
last = at + whole.length
}
if (last < text.length) out.push(text.slice(last))
return out
}
/** Text inside another element: formatting and line breaks. */
export function Inline({ text, accent }: { text?: string | null; accent: string }) {
const lines = (text ?? '').split('\n')
return (
<>
{lines.map((part, i) => (
<Fragment key={i}>
{i > 0 && <br />}
{line(part, accent, `l${i}`)}
</Fragment>
))}
</>
)
}
/** Block text: one <p> per part separated by a blank line. */
export function Paragraphs({
text,
accent,
className,
style,
}: {
text?: string | null
accent: string
className?: string
style?: CSSProperties
}) {
const parts = (text ?? '')
.split(/\n\s*\n/)
.map((part) => part.trim())
.filter(Boolean)
return (
<>
{parts.map((part, i) => (
<p key={i} className={className} style={style}>
<Inline text={part} accent={accent} />
</p>
))}
</>
)
}
/** For the editor's help text under a formatted box. */
export const FORMATTING_HELP =
'**bold**, *italic*, [link text](https://…). A blank line starts a new paragraph.'

View file

@ -1,93 +0,0 @@
/* ═══════════════════════════════════════════════════════════════
VIDEO PLAYER: click to play
A still with a play button; pressing it swaps in the player, so a
page loads no iframes until someone asks for one. Used by the
featured cards and the video content block.
The still is the caller's image, else YouTube's own thumbnail,
else a plain dark panel. A link that embeds.ts can't turn into a
player (not https, or not a host it knows how to frame) still
goes somewhere: the still becomes a link to it.
═══════════════════════════════════════════════════════════════ */
import { useState } from 'react'
import HomeLink from '../pages/sections/home/HomeLink.tsx'
import { playingSource, videoSource, videoThumbnail } from '../lib/embeds.ts'
const ACCENT = '#138ba0'
export default function VideoPlayer({
url,
still,
title,
className = '',
}: {
url?: string | null
/** An image URL to show before it plays. */
still?: string | null
title?: string | null
className?: string
}) {
const [playing, setPlaying] = useState(false)
const source = videoSource(url)
if (playing && source) {
const live = playingSource(source)
return live.kind === 'file' ? (
<video src={live.src} controls autoPlay playsInline className={`aspect-video w-full bg-black ${className}`} />
) : (
<iframe
src={live.src}
title={title || 'Video'}
allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
allowFullScreen
className={`aspect-video w-full border-0 bg-black ${className}`}
/>
)
}
const image = still ?? videoThumbnail(url)
const face = (
<>
{image ? (
<img src={image} alt="" loading="lazy" className={`aspect-video w-full object-cover ${className}`} />
) : (
<div className={`aspect-video w-full bg-gradient-to-br from-[#073d4a] to-[#04262e] ${className}`} />
)}
<span
aria-hidden="true"
className="absolute inset-0 flex items-center justify-center bg-black/10 transition-colors group-hover:bg-black/25"
>
<span className="flex h-16 w-16 items-center justify-center rounded-full bg-white/90 shadow-lg transition-transform group-hover:scale-110">
<svg viewBox="0 0 24 24" className="ml-1 h-7 w-7" fill={ACCENT}>
<path d="M8 5v14l11-7z" />
</svg>
</span>
</span>
</>
)
if (!source) {
return url ? (
<HomeLink url={url} className="group relative block">
{face}
</HomeLink>
) : (
<div className="relative">{face}</div>
)
}
return (
<button
type="button"
onClick={() => setPlaying(true)}
aria-label={`Play ${title || 'video'}`}
className="group relative block w-full"
>
{face}
</button>
)
}

View file

@ -32,21 +32,6 @@
can't keep a value for a choice it no longer makes: a featured
card switched from "record" to "link" drops its record.
A nested collection takes `when` the same way, and one that goes
hidden is emptied: a list block turned into a paragraph drops its
items.
`help` may be a function of the row, for help that depends on
another field (a content block's type says what its text is).
`preview` on a collection names an entry in PREVIEWS below; each
open row then shows how it will look on the site, drawn by the
site's own component.
Every row can be duplicated (a copy lands below it, ids stripped
so it saves as new) or have a blank row inserted below it, as
well as appended at the end.
`widget: "linkPreview"` is a URL box with a "Fetch preview" button
(LinkPreviewInput in MediaLibrary.tsx) that fills the row's empty
title, blurb and image through `onPatch`.
@ -72,15 +57,8 @@
import { useRef, useState } from "react";
import ContentBlocks from "../ContentBlocks.tsx";
import { ImageInput, LinkPreviewInput } from "./MediaLibrary.tsx";
/* Live previews a collection can name with `preview`. Each gets the
row as the form holds it, which is the API's shape. */
const PREVIEWS = {
contentBlock: (row) => <ContentBlocks blocks={[row]} />,
};
const input =
"w-full rounded-lg border border-[#4a6b72]/25 bg-white px-3 py-2 text-sm text-[#26454c] " +
"outline-none transition-colors focus:border-[#138ba0] focus:ring-2 focus:ring-[#138ba0]/25";
@ -126,37 +104,17 @@ export function fieldShown(field, row) {
/* A row after an edit, with any field the edit hid cleared. "" is
the engine's deliberate clear, so it saves as NULL. */
function withHiddenCleared(spec, row) {
function withHiddenCleared(fields, row) {
let next = row;
for (const field of spec.fields) {
for (const field of fields) {
const value = next[field.path];
if (!fieldShown(field, next) && value != null && value !== "") {
next = { ...next, [field.path]: "" };
}
}
for (const nested of spec.children ?? []) {
if (!fieldShown(nested, next) && next[nested.key]?.length) {
next = { ...next, [nested.key]: [] };
}
}
return next;
}
/* A copy of a row with every id removed, nested rows included, so
the server inserts it as new rather than colliding with the row
it was copied from. */
function withoutIds(value) {
if (Array.isArray(value)) return value.map(withoutIds);
if (!value || typeof value !== "object") return value;
const copy = {};
for (const [key, inner] of Object.entries(value)) {
if (key !== "id") copy[key] = withoutIds(inner);
}
return copy;
}
const helpText = (field, row) => (typeof field.help === "function" ? field.help(row) : field.help);
/* ── Field ───────────────────────────────────────────────────── */
export function Field({ field, value, row, options, error, onChange, onPatch }: any) {
@ -212,7 +170,7 @@ export function Field({ field, value, row, options, error, onChange, onPatch }:
onChange={(e) => onChange(e.target.checked ? 1 : 0)}
className="h-4 w-4 rounded border-[#4a6b72]/40 text-[#138ba0] focus:ring-[#138ba0]/40 disabled:opacity-50"
/>
{helpText(field, row) ?? "Yes"}
{field.help ?? "Yes"}
</label>
) : widget === "textarea" ? (
<textarea
@ -323,9 +281,9 @@ export function Field({ field, value, row, options, error, onChange, onPatch }:
This points at something that has been deleted. Pick a replacement before saving.
</p>
) : (
helpText(field, row) &&
field.help &&
widget !== "checkbox" && (
<p className="mt-1 text-xs text-[#4a6b72]">{helpText(field, row)}</p>
<p className="mt-1 text-xs text-[#4a6b72]">{field.help}</p>
)
)}
</div>
@ -382,7 +340,7 @@ export function Repeater({
const rowRefs = useRef<any[]>([]);
const update = (index, next) =>
onChange(list.map((row, i) => (i === index ? withHiddenCleared(spec, next) : row)));
onChange(list.map((row, i) => (i === index ? withHiddenCleared(spec.fields, next) : row)));
const move = (index, delta) => {
const target = index + delta;
@ -416,13 +374,6 @@ export function Repeater({
onChange([...list, { ...spec.blank }]);
};
/* A row placed at `at`, pushing everything from there down one,
and opened so it can be filled in straight away. */
const insertAt = (at, row) => {
setOpen((prev) => remapOpen(prev, (i) => (i >= at ? i + 1 : i)).add(at));
onChange([...list.slice(0, at), row, ...list.slice(at)]);
};
const removeAt = (index) => {
setOpen((prev) => remapOpen(prev, (i) => (i === index ? -1 : i > index ? i - 1 : i)));
onChange(list.filter((_, i) => i !== index));
@ -567,18 +518,6 @@ export function Repeater({
>
↓
</IconButton>
<IconButton
label="Insert a new one below"
onClick={() => insertAt(index + 1, { ...spec.blank })}
>
+
</IconButton>
<IconButton
label="Duplicate"
onClick={() => insertAt(index + 1, withoutIds(row))}
>
⧉
</IconButton>
<IconButton
label="Remove"
danger
@ -608,30 +547,19 @@ export function Repeater({
))}
</FieldGrid>
{(spec.children ?? [])
.filter((nested) => fieldShown(nested, row))
.map((nested) => (
<div key={nested.key} className="mt-4 border-t border-[#4a6b72]/15 pt-4">
<Repeater
spec={nested}
rows={row[nested.key]}
options={options}
errors={errors}
errorPrefix={`${errorPrefix}${index}.${nested.key}.`}
className=""
onChange={(value) => update(index, { ...row, [nested.key]: value })}
/>
</div>
))}
{spec.preview && PREVIEWS[spec.preview] && (
<div className="mt-4 rounded-lg border border-dashed border-[#138ba0]/30 bg-white p-4">
<p className="mb-3 text-xs font-semibold uppercase tracking-wider text-[#4a6b72]/70">
Preview
</p>
{PREVIEWS[spec.preview](row)}
{(spec.children ?? []).map((nested) => (
<div key={nested.key} className="mt-4 border-t border-[#4a6b72]/15 pt-4">
<Repeater
spec={nested}
rows={row[nested.key]}
options={options}
errors={errors}
errorPrefix={`${errorPrefix}${index}.${nested.key}.`}
className=""
onChange={(value) => update(index, { ...row, [nested.key]: value })}
/>
</div>
)}
))}
</>
)}
</div>

View file

@ -17,7 +17,6 @@
import { preview } from "./text.ts";
import { PLATFORMS } from "./platforms.ts";
import { FORMATTING_HELP } from "../components/InlineText.tsx";
import {
awardLogo,
blockMedia,
@ -287,126 +286,44 @@ const hostsChild = {
],
};
/* Content blocks. The type decides which fields appear (`when`),
what the text box is for (`help` as a function), and whether the
block has items; the preview under each open block is the site's
own renderer. Types and what they read: ContentBlocks.tsx. */
const BLOCK_TYPES = [
["paragraph", "Paragraph", "Body text. Formatting: " + FORMATTING_HELP],
["heading", "Heading", "A section heading."],
["subheading", "Subheading", "A smaller heading under a heading."],
["callout", "Callout", "A note or announcement in a tinted box. Formatting: " + FORMATTING_HELP],
["quote", "Quote", "A quotation, with who said it. Formatting: " + FORMATTING_HELP],
["list", "List", "Bulleted items, each optionally linked, with an optional detail."],
["links", "Link buttons", "A row of outlined buttons, one per item."],
["button", "Button", "One filled call-to-action button, eg. Register, Donate."],
["image", "Image", "A picture, with alt text and an optional caption and link."],
["video", "Video", "A YouTube, Vimeo or Facebook video, or a video file, played in place."],
["divider", "Divider", "A thin line between parts."],
];
const blockTypeLabel = (type) => BLOCK_TYPES.find(([value]) => value === type)?.[1] ?? type;
const TEXT_TYPES = ["paragraph", "heading", "subheading", "callout", "quote", "button", "image", "video"];
const TEXT_HELP = {
paragraph: FORMATTING_HELP,
callout: FORMATTING_HELP,
quote: FORMATTING_HELP,
button: "The button's label, eg. Register now",
image: "Caption shown under the image. Optional.",
video: "Caption shown under the video. Optional.",
};
const TEXT_LABEL = { button: "Label", image: "Caption", video: "Caption" };
const HREF_HELP = {
paragraph: "Optional. Makes the whole paragraph one link. For a link inside the text, use [text](url).",
button: "Where the button goes, eg. /give or https://…",
image: "Optional. Makes the image a link.",
video: "The video's page, eg. https://www.youtube.com/watch?v=…, or a video file",
};
const blocksChild = {
key: "content_blocks",
label: "Content blocks",
addLabel: "Add block",
preview: "contentBlock",
title: (row) => {
const label = blockTypeLabel(row.type) || "Block";
const text = preview(row.text || row.href || row.media || "", 40);
return text ? `${label}: ${text}` : label;
},
title: (row) => `${row.type ?? "block"}: ${preview(row.text, 40) || "empty"}`,
blank: { slot: "body", type: "paragraph", text: "" },
fields: [
{
path: "slot",
label: "Shown in",
widget: "select",
options: [
["body", "The page"],
["card", "The card (paragraphs only)"],
],
},
{ path: "slot", label: "Slot", widget: "select", options: ["card", "body"] },
{
path: "type",
label: "Type",
widget: "select",
options: BLOCK_TYPES.map(([value, label]) => [value, label]),
help: (row) => BLOCK_TYPES.find(([value]) => value === row?.type)?.[2],
},
{
path: "text",
label: "Text",
widget: "textarea",
full: true,
when: { path: "type", value: TEXT_TYPES },
help: (row) => TEXT_HELP[row?.type],
},
{
path: "cite",
label: "Attribution",
help: "Who said it, eg. Jane Doe, Retreat 2024",
full: true,
when: { path: "type", value: "quote" },
},
{
path: "href",
label: "Link",
full: true,
when: { path: "type", value: ["paragraph", "button", "image", "video"] },
help: (row) => HREF_HELP[row?.type],
},
{
path: "media",
label: "Image",
widget: "image",
resolve: blockMedia,
full: true,
when: { path: "type", value: ["image", "video"] },
help: (row) =>
row?.type === "video" ? "Still shown before it plays. Default: YouTube's own thumbnail." : undefined,
},
{
path: "alt",
label: "Alt text",
full: true,
when: { path: "type", value: "image" },
help: "Describes the picture for someone who can't see it, eg. Campers around a fire at dusk",
options: [
"heading",
"subheading",
"paragraph",
"list",
"links",
"quote",
"image",
"divider",
],
},
{ path: "text", label: "Text", widget: "textarea", full: true },
{ path: "media", label: "Media", widget: "image", resolve: blockMedia, full: true },
{ path: "href", label: "Link" },
],
children: [
{
key: "items",
label: "Items",
addLabel: "Add item",
when: { path: "type", value: ["list", "links"] },
title: (row) => row.text || "New item",
blank: { text: "" },
fields: [
{ path: "text", label: "Text", required: true },
{ path: "detail", label: "Detail", help: "Lists only: shown after the text" },
{ path: "url", label: "URL", help: "Blank for a plain list item. Link buttons need one." },
{ path: "detail", label: "Detail" },
{ path: "url", label: "URL", help: "Blank for a plain list item" },
],
},
],

View file

@ -31,16 +31,9 @@ export type ContentBlock = {
| 'quote'
| 'image'
| 'divider'
| 'video'
| 'button'
| 'callout'
text?: string | null
media?: string | null
href?: string | null
/** An image's alt text. */
alt?: string | null
/** Who a quote is by. */
cite?: string | null
items?: Array<{ text: string; detail?: string | null; url?: string | null }>
}