Page management, step 3: section types with their own settings; the front page as sections

Migration 083 gives the section types that need more than blocks their
own tables (hero, slides, countdown, stats, paths, featured cards, the
Community blog's slots, pinned posts and feeds) and turns the front page
into Home's sections: the hero, then its bands in order. Any section can
be hidden. The Front page editor, its tables and the Community page's
are gone; /api/front-page and /api/community-blog fold into the page's
sections (sectionData.js). The admin engine reads and writes a child
collection's own side tables and gated nested collections.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Aidan Dona 2026-10-17 00:34:56 -05:00
parent f33c0008fe
commit f1a0b06ac2
46 changed files with 1525 additions and 1339 deletions

View file

@ -139,7 +139,9 @@ function coerceRow(columns, data, { prefix = "" } = {}) {
return { values, errors };
}
const applies = (gate, row) => !gate || row[gate.column] === gate.value;
/* A gate on a column's value: one value, or any of a list. */
const applies = (gate, row) =>
!gate || (Array.isArray(gate.value) ? gate.value.includes(row[gate.column]) : row[gate.column] === gate.value);
/* ── Read ────────────────────────────────────────────────────── */
@ -242,6 +244,12 @@ function readChildren(db, child, ownerId) {
)
.all(...params);
// A row's own 1:1 side tables (a section's settings for its type:
// its hero's words, its blog's slots).
for (const ext of child.extensions ?? []) {
for (const row of rows) row[ext.key] = readExtension(db, ext, row.id);
}
// Nested collections, to any depth: a page's sections, each
// section's blocks, each block's items. The id goes as text: a JS
// number binds as REAL, which a TEXT owner column (a section's
@ -423,7 +431,7 @@ export function deleteRow(db, entity, rawId) {
/* ── Write helpers ───────────────────────────────────────────── */
function writeExtensions(db, entity, id, payload, parentValues) {
function writeExtensions(db, entity, id, payload, parentValues, prefix = "") {
for (const ext of entity.extensions ?? []) {
if (!applies(ext.when, parentValues)) {
// The gate closed (the kind changed away from this side
@ -435,7 +443,7 @@ function writeExtensions(db, entity, id, payload, parentValues) {
}
const { values, errors } = coerceRow(ext.columns, payload[ext.key] ?? {}, {
prefix: `${ext.key}.`,
prefix: `${prefix}${ext.key}.`,
});
if (Object.keys(errors).length) {
throw new HttpError(422, "Validation failed", errors);
@ -588,8 +596,13 @@ function writeRows(db, child, ownerId, incomingRaw, prefix, parentValues) {
.run(...params),
);
const rowId = Number(result.lastInsertRowid);
// Its own side tables, gated on its values (a section's preset),
// then its collections, gated the same way.
if (child.extensions) writeExtensions(db, child, rowId, raw, values, rowPrefix);
for (const child2 of child.children ?? []) {
writeRows(db, child2, String(result.lastInsertRowid), raw[child2.key], `${rowPrefix}${child2.key}.`, values);
if (!applies(child2.when, values)) continue;
writeRows(db, child2, String(rowId), raw[child2.key], `${rowPrefix}${child2.key}.`, values);
}
});
}

View file

@ -85,6 +85,13 @@ function collectGroups(entity) {
...Object.keys(child.owner.inherit ?? {}),
].filter(Boolean),
});
for (const ext of child.extensions ?? []) {
groups.push({
table: ext.table,
columns: ext.columns ?? [],
engineSupplied: [ext.idColumn, ext.owner?.column, ext.owner?.kindColumn].filter(Boolean),
});
}
for (const nested of child.children ?? []) walk(nested);
};

View file

@ -18,9 +18,12 @@
regions or groups row should exist)
children ordered collections, replaced wholesale on save;
`readRole` on one hides it from lesser roles, as
on an extension (an organization's contacts)
on an extension (an organization's contacts). A
child may have `extensions` of its own (a page
section's settings for its type), and its nested
collections a `when` on its values
singleton the one id this entity ever has; the engine
refuses create and delete (see front_page)
refuses create and delete (see navigation)
undeletable ids the engine refuses to delete (the pages the
site draws in code)
check (db, id) => void, run after a save has written
@ -52,7 +55,6 @@ import { people } from "./admin-schema/people.js";
import { teams } from "./admin-schema/teams.js";
import { awards } from "./admin-schema/awards.js";
import { timeline } from "./admin-schema/timeline.js";
import { frontPage } from "./admin-schema/frontPage.js";
import { blogPosts } from "./admin-schema/blog.js";
import { siteSettings } from "./admin-schema/siteSettings.js";
import { siteNav } from "./admin-schema/siteNav.js";
@ -74,7 +76,6 @@ export const ENTITIES = {
teams,
awards,
timeline,
front_page: frontPage,
blog_posts: blogPosts,
pages,
navigation: siteNav,

View file

@ -1,129 +0,0 @@
import { text, url, int, bool, enumeration, featuredCardsChild } from "./columns.js";
/* ── Front page ──────────────────────────────────────────────────
A singleton: one row, id 'home', seeded by the schema and never
created by the admin. `singleton` tells the engine to refuse create
and delete, and the CHECK on front_page.id is what makes a second
row impossible even without it.
Every collection here is owned by page_id and replaced wholesale.
That is safe for the same reason it is for links and blocks
(nothing has a foreign key into these tables), and paths carry
their actions as a nested collection, the shape content blocks
and their items already use. */
export const frontPage = {
key: "front_page",
table: "front_page",
idColumn: "id",
idKind: "slug",
singleton: "home",
concurrency: "updated_at",
list: {
columns: ["id", "headline", "hero_backdrop", "hero_feature", "updated_at"],
filters: [],
search: [],
order: "id",
},
columns: [
enumeration("hero_backdrop", ["brand", "photos"]),
enumeration("hero_feature", ["none", "livestream", "video", "event"]),
text("hero_event_id"),
text("eyebrow"),
text("headline"),
text("subhead"),
text("primary_label"),
url("primary_url"),
text("secondary_label"),
url("secondary_url"),
int("slide_seconds"),
url("livestream_url"),
text("livestream_title"),
url("video_url"),
text("video_title"),
text("video_captions"),
text("countdown_event_id"),
text("countdown_scope_id"),
enumeration("countdown_event_type", ["retreat", "class", "workshop", "meeting", "other"]),
int("featured_columns"),
text("video_still"),
],
children: [
{
key: "slides",
table: "front_page_slides",
owner: { column: "page_id" },
order: "sort_order",
columns: [
text("media", { required: true }),
text("alt"),
text("caption"),
url("link_url"),
],
},
{
key: "sections",
table: "front_page_sections",
owner: { column: "page_id" },
order: "sort_order",
columns: [
enumeration(
"section",
["countdown", "retreats", "calendar", "stats", "timeline", "connect", "featured"],
{ required: true },
),
text("title"),
text("blurb"),
bool("is_hidden"),
],
},
{
key: "stats",
table: "front_page_stats",
owner: { column: "page_id" },
order: "sort_order",
columns: [
text("label", { required: true }),
enumeration("source", [
"manual",
"years_since",
"regions",
"groups",
"partners",
"events_held",
"retreats_held",
"people",
"awards_given",
]),
text("value"),
text("suffix"),
text("note"),
],
},
featuredCardsChild("front_page"),
{
key: "paths",
table: "front_page_paths",
owner: { column: "page_id" },
order: "sort_order",
columns: [text("label", { required: true }), text("icon"), text("blurb")],
children: [
{
key: "actions",
table: "front_page_path_actions",
owner: { column: "path_id" },
order: "sort_order",
columns: [
text("label", { required: true }),
text("description"),
url("url", { required: true }),
],
},
],
},
],
};

View file

@ -10,10 +10,16 @@ import { text, url, int, bool, enumeration, featuredCardsChild, blocksChild } fr
either its blocks or a preset, a prebuilt part of the site
(SitePage.tsx draws both). New pages are made here.
Community also carries the blog section's settings: the
community_page row (same id) as an extension, and its pinned
posts, cards and feeds, all owned by that id; only for the page
whose id is community. */
A section type that needs more than its blocks keeps its settings
in tables of its own (083_section_settings.sql), the section's
extensions and collections here, each gated on its preset: a
hero's words and slides, a countdown's event, a stats band's
numbers, a pathfinder's paths, featured cards, a Community blog's
slots, pinned posts and feeds. The front page is a page of
sections like the rest. */
/* Gates on the section's preset. */
const is = (preset) => ({ column: "preset", value: preset });
const sectionsChild = {
key: "sections",
@ -39,12 +45,75 @@ const sectionsChild = {
"data_request_form",
"giving",
"qr_maker",
// The front page's bands, on any page (083).
"hero",
"countdown",
"calendar",
"stats",
"featured_cards",
"connect",
]),
text("scope_id"),
enumeration("event_type", ["retreat", "class", "workshop", "meeting", "other"]),
enumeration("view", ["carousel", "grid", "map"]),
// Organization cards (067): the kinds listed by themselves.
enumeration("org_kinds", ["partner", "ministry", "partner,ministry"]),
bool("is_hidden"),
],
extensions: [
{
key: "hero",
table: "section_hero",
idColumn: "section_id",
when: is("hero"),
columns: [
text("eyebrow"),
text("headline"),
text("subhead"),
text("primary_label"),
url("primary_url"),
text("secondary_label"),
url("secondary_url"),
enumeration("backdrop", ["brand", "photos"]),
int("slide_seconds"),
enumeration("feature", ["none", "livestream", "video", "event"]),
url("livestream_url"),
text("livestream_title"),
url("video_url"),
text("video_title"),
text("video_captions"),
text("video_still"),
text("event_id"),
],
},
{
key: "countdown",
table: "section_countdown",
idColumn: "section_id",
when: is("countdown"),
columns: [text("event_id"), text("scope_id"), enumeration("event_type", ["retreat", "class", "workshop", "meeting", "other"])],
},
{
key: "featured",
table: "section_featured",
idColumn: "section_id",
when: is("featured_cards"),
columns: [int("columns")],
},
{
key: "blog",
table: "section_blog",
idColumn: "section_id",
when: is("community_blog"),
columns: [
text("internal_title"),
int("internal_slots"),
text("external_title"),
int("external_slots"),
url("external_url"),
text("external_label"),
],
},
],
children: [
blocksChild("page_section"),
@ -64,6 +133,73 @@ const sectionsChild = {
order: "sort_order",
columns: [text("org_id", { required: true })],
},
{
key: "slides",
table: "section_slides",
owner: { column: "section_id" },
order: "sort_order",
when: is("hero"),
columns: [text("media", { required: true }), text("alt"), text("caption"), url("link_url")],
},
{
key: "stats",
table: "section_stats",
owner: { column: "section_id" },
order: "sort_order",
when: is("stats"),
columns: [
text("label", { required: true }),
enumeration("source", [
"manual",
"years_since",
"regions",
"groups",
"partners",
"events_held",
"retreats_held",
"people",
"awards_given",
]),
text("value"),
text("suffix"),
text("note"),
],
},
{
key: "paths",
table: "section_paths",
owner: { column: "section_id" },
order: "sort_order",
when: is("connect"),
columns: [text("label", { required: true }), text("icon"), text("blurb")],
children: [
{
key: "actions",
table: "section_path_actions",
owner: { column: "path_id" },
order: "sort_order",
columns: [text("label", { required: true }), text("description"), url("url", { required: true })],
},
],
},
// Featured cards, and a Community blog's pinned community posts.
{ ...featuredCardsChild("page_section"), when: { column: "preset", value: ["featured_cards", "community_blog"] } },
{
key: "blog_posts",
table: "section_blog_posts",
owner: { column: "section_id" },
order: "sort_order",
when: is("community_blog"),
columns: [text("post_id", { required: true })],
},
{
key: "feeds",
table: "section_feeds",
owner: { column: "section_id" },
order: "sort_order",
when: is("community_blog"),
columns: [url("url", { required: true }), text("label")],
},
],
};
@ -94,8 +230,6 @@ function checkPage(db, id) {
if (id !== "home" && page.path === "/") throw new HttpError(422, "Validation failed", { path: "/ is the front page." });
}
const isCommunity = { column: "id", value: "community" };
export const pages = {
key: "pages",
table: "site_pages",
@ -120,43 +254,7 @@ export const pages = {
int("sort_order"),
],
extensions: [
{
key: "blog",
table: "community_page",
idColumn: "id",
when: isCommunity,
columns: [
text("internal_title"),
int("internal_slots"),
text("external_title"),
int("external_slots"),
url("external_url"),
text("external_label"),
],
},
],
children: [
sectionsChild,
{
key: "pinned_posts",
table: "community_page_pinned_posts",
owner: { column: "page_id" },
order: "sort_order",
when: isCommunity,
columns: [text("post_id", { required: true })],
},
{ ...featuredCardsChild("community_page"), when: isCommunity },
{
key: "feeds",
table: "community_page_feeds",
owner: { column: "page_id" },
order: "sort_order",
when: isCommunity,
columns: [url("url", { required: true }), text("label")],
},
],
children: [sectionsChild],
check: checkPage,
};

View file

@ -2,7 +2,7 @@
FEEDS
Reads the RSS and Atom feeds the Community page's blog section
lists (community_page_feeds), for its "newest community posts".
lists (section_feeds, 083), for its "newest community posts".
A Substack's feed is https://<name>.substack.com/feed.
Each feed is fetched through linkPreview.js's safeGet, so it gets

View file

@ -24,7 +24,6 @@ import { rateLimit } from "./rateLimit.js";
import content from "./routes/content.js";
import people from "./routes/people.js";
import history from "./routes/history.js";
import home from "./routes/home.js";
import directory from "./routes/directory.js";
import blog from "./routes/blog.js";
import sitePages from "./routes/sitePages.js";
@ -192,7 +191,6 @@ app.get("/api/health", (c) =>
app.route("/api", content);
app.route("/api", people);
app.route("/api", history);
app.route("/api", home);
app.route("/api", directory);
app.route("/api", blog);
app.route("/api", sitePages);

View file

@ -0,0 +1,435 @@
-- ═══════════════════════════════════════════════════════════════
-- 083 SECTION SETTINGS, AND THE FRONT PAGE AS SECTIONS
--
-- A section type that needs more than its blocks keeps its settings
-- in a table of its own, one row per section (and its lists in
-- tables under the section), so it can go on any page with content
-- of its own. The admin engine reads and writes them as the section's
-- own side tables (admin-crud.js, a child's extensions):
--
-- section_hero a hero: words, buttons, backdrop, feature
-- section_slides its photos
-- section_countdown a countdown: the pinned event, or the next
-- one of a scope and type
-- section_stats a stats band's numbers
-- section_paths a pathfinder's paths
-- section_path_actions each path's links
-- section_featured featured cards' columns (the cards are
-- featured_cards owned by 'page_section')
-- section_blog a Community blog's headings and slots
-- section_blog_posts its pinned posts of ours
-- section_feeds the feeds its community posts come from
-- (its pinned community posts are
-- featured_cards owned by 'page_section')
--
-- page_sections gets is_hidden (any section can be left out without
-- deleting it, as the front page's bands could), and a title of up
-- to 60 characters on the front page, which has no side nav; 30
-- elsewhere. The table is rebuilt for that.
--
-- Then what was the front page's own (front_page and its lists, 012
-- to 074) becomes the home page's sections: the hero first, then
-- each band in its order, hidden ones kept hidden; and the Community
-- page's blog settings (community_page) move into its blog section.
-- Those tables go. A timeline section whose view is 'carousel' is
-- the rail of featured moments the front page showed; the full
-- timeline otherwise.
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE page_sections_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id TEXT NOT NULL REFERENCES site_pages (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
anchor TEXT NOT NULL
CONSTRAINT "A section's URL ID can use only lowercase letters, numbers and hyphens, eg. leadership."
CHECK (anchor <> '' AND anchor NOT GLOB '*[^a-z0-9-]*'),
title TEXT NOT NULL
CONSTRAINT "A section title can be 30 characters at most (it's listed in the page's side nav), 60 on the front page."
CHECK (length(title) <= CASE WHEN page_id = 'home' THEN 60 ELSE 30 END),
blurb TEXT,
accent TEXT CHECK (accent IN ('teal', 'deep', 'green', 'amber')),
preset TEXT CHECK (preset IN ('community_blog', 'group_map', 'region_list', 'partner_list',
'events', 'timeline', 'people_directory',
'feedback_form', 'request_form', 'data_request_form', 'giving', 'qr_maker',
'hero', 'countdown', 'calendar', 'stats', 'featured_cards', 'connect')),
-- An events preset's filter and first view.
scope_id TEXT REFERENCES event_scopes (id) ON DELETE SET NULL,
event_type TEXT CHECK (event_type IN ('retreat', 'class', 'workshop', 'meeting', 'other')),
view TEXT CHECK (view IN ('carousel', 'grid', 'map')),
-- Organization cards (067): the kinds listed by themselves.
org_kinds TEXT CHECK (org_kinds IN ('partner', 'ministry', 'partner,ministry')),
is_hidden INTEGER NOT NULL DEFAULT 0 CHECK (is_hidden IN (0, 1)),
UNIQUE (page_id, anchor)
) STRICT;
INSERT INTO page_sections_new
(id, page_id, sort_order, anchor, title, blurb, accent, preset, scope_id, event_type, view, org_kinds)
SELECT id, page_id, sort_order, anchor, title, blurb, accent, preset, scope_id, event_type, view, org_kinds
FROM page_sections;
PRAGMA legacy_alter_table = ON;
DROP TABLE page_sections;
ALTER TABLE page_sections_new RENAME TO page_sections;
PRAGMA legacy_alter_table = OFF;
CREATE INDEX page_sections_page_idx ON page_sections (page_id, sort_order);
-- ── The settings tables ──────────────────────────────────────────
CREATE TABLE section_hero (
section_id INTEGER PRIMARY KEY REFERENCES page_sections (id) ON DELETE CASCADE,
eyebrow TEXT,
headline TEXT,
subhead TEXT,
primary_label TEXT,
primary_url TEXT,
secondary_label TEXT,
secondary_url TEXT,
backdrop TEXT NOT NULL DEFAULT 'brand' CHECK (backdrop IN ('brand', 'photos')),
slide_seconds INTEGER NOT NULL DEFAULT 7 CHECK (slide_seconds BETWEEN 3 AND 60),
feature TEXT NOT NULL DEFAULT 'none' CHECK (feature IN ('none', 'livestream', 'video', 'event')),
livestream_url TEXT,
livestream_title TEXT,
video_url TEXT,
video_title TEXT,
video_captions TEXT,
video_still TEXT,
event_id TEXT REFERENCES events (id) ON DELETE SET NULL
) STRICT;
CREATE TABLE section_slides (
id INTEGER PRIMARY KEY AUTOINCREMENT,
section_id INTEGER NOT NULL REFERENCES page_sections (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
media TEXT NOT NULL,
alt TEXT,
caption TEXT,
link_url TEXT
) STRICT;
CREATE INDEX section_slides_section_idx ON section_slides (section_id, sort_order);
CREATE TABLE section_countdown (
section_id INTEGER PRIMARY KEY REFERENCES page_sections (id) ON DELETE CASCADE,
event_id TEXT REFERENCES events (id) ON DELETE SET NULL,
scope_id TEXT REFERENCES event_scopes (id) ON DELETE SET NULL,
event_type TEXT CHECK (event_type IN ('retreat', 'class', 'workshop', 'meeting', 'other'))
) STRICT;
CREATE TABLE section_stats (
id INTEGER PRIMARY KEY AUTOINCREMENT,
section_id INTEGER NOT NULL REFERENCES page_sections (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
label TEXT NOT NULL,
source TEXT NOT NULL DEFAULT 'manual'
CHECK (source IN ('manual', 'years_since', 'regions', 'groups',
'partners', 'events_held', 'retreats_held',
'people', 'awards_given')),
value TEXT,
suffix TEXT,
note TEXT
) STRICT;
CREATE INDEX section_stats_section_idx ON section_stats (section_id, sort_order);
CREATE TABLE section_paths (
id INTEGER PRIMARY KEY AUTOINCREMENT,
section_id INTEGER NOT NULL REFERENCES page_sections (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
label TEXT NOT NULL,
icon TEXT,
blurb TEXT
) STRICT;
CREATE INDEX section_paths_section_idx ON section_paths (section_id, sort_order);
CREATE TABLE section_path_actions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
path_id INTEGER NOT NULL REFERENCES section_paths (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
label TEXT NOT NULL,
description TEXT,
url TEXT NOT NULL
) STRICT;
CREATE INDEX section_path_actions_path_idx ON section_path_actions (path_id, sort_order);
CREATE TABLE section_featured (
section_id INTEGER PRIMARY KEY REFERENCES page_sections (id) ON DELETE CASCADE,
columns INTEGER CHECK (columns IN (2, 3, 4))
) STRICT;
CREATE TABLE section_blog (
section_id INTEGER PRIMARY KEY REFERENCES page_sections (id) ON DELETE CASCADE,
internal_title TEXT,
internal_slots INTEGER NOT NULL DEFAULT 3 CHECK (internal_slots BETWEEN 0 AND 12),
external_title TEXT,
external_slots INTEGER NOT NULL DEFAULT 3 CHECK (external_slots BETWEEN 0 AND 12),
external_url TEXT,
external_label TEXT
) STRICT;
CREATE TABLE section_blog_posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
section_id INTEGER NOT NULL REFERENCES page_sections (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
post_id TEXT NOT NULL REFERENCES blog_posts (id) ON DELETE CASCADE
) STRICT;
CREATE INDEX section_blog_posts_section_idx ON section_blog_posts (section_id, sort_order);
CREATE TABLE section_feeds (
id INTEGER PRIMARY KEY AUTOINCREMENT,
section_id INTEGER NOT NULL REFERENCES page_sections (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
url TEXT NOT NULL,
label TEXT
) STRICT;
CREATE INDEX section_feeds_section_idx ON section_feeds (section_id, sort_order);
-- ── featured_cards: owned by a section ───────────────────────────
CREATE TABLE featured_cards_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_kind TEXT NOT NULL CHECK (owner_kind IN ('page_section', '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,
size TEXT CHECK (size IN ('normal', 'wide', 'tall', 'large')),
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;
-- ── The Community blog into its section ──────────────────────────
INSERT INTO section_blog (section_id, internal_title, internal_slots, external_title, external_slots, external_url, external_label)
SELECT s.id, c.internal_title, c.internal_slots, c.external_title, c.external_slots, c.external_url, c.external_label
FROM page_sections s, community_page c
WHERE s.page_id = 'community' AND s.preset = 'community_blog' AND c.id = 'community';
INSERT INTO section_blog_posts (section_id, sort_order, post_id)
SELECT s.id, p.sort_order, p.post_id
FROM page_sections s JOIN community_page_pinned_posts p ON p.page_id = 'community'
WHERE s.page_id = 'community' AND s.preset = 'community_blog';
INSERT INTO section_feeds (section_id, sort_order, url, label)
SELECT s.id, f.sort_order, f.url, f.label
FROM page_sections s JOIN community_page_feeds f ON f.page_id = 'community'
WHERE s.page_id = 'community' AND s.preset = 'community_blog';
INSERT INTO featured_cards_new
(owner_kind, owner_id, sort_order, kind, ref_kind, ref_id, url, eyebrow, title, blurb, image, size)
SELECT 'page_section', CAST(s.id AS TEXT), f.sort_order, f.kind, f.ref_kind, f.ref_id, f.url, f.eyebrow, f.title, f.blurb, f.image, f.size
FROM featured_cards f
JOIN page_sections s ON s.page_id = 'community' AND s.preset = 'community_blog'
WHERE f.owner_kind = 'community_page'
AND s.id = (SELECT min(id) FROM page_sections WHERE page_id = 'community' AND preset = 'community_blog');
-- ── The front page into the home page's sections ─────────────────
-- The hero first.
INSERT INTO page_sections (page_id, sort_order, anchor, title, preset)
VALUES ('home', 0, 'hero', 'Welcome', 'hero');
INSERT INTO section_hero
(section_id, eyebrow, headline, subhead, primary_label, primary_url, secondary_label, secondary_url,
backdrop, slide_seconds, feature, livestream_url, livestream_title, video_url, video_title,
video_captions, video_still, event_id)
SELECT (SELECT id FROM page_sections WHERE page_id = 'home' AND anchor = 'hero'),
eyebrow, headline, subhead, primary_label, primary_url, secondary_label, secondary_url,
hero_backdrop, slide_seconds, hero_feature, livestream_url, livestream_title, video_url, video_title,
video_captions, video_still, hero_event_id
FROM front_page WHERE id = 'home';
INSERT INTO section_slides (section_id, sort_order, media, alt, caption, link_url)
SELECT (SELECT id FROM page_sections WHERE page_id = 'home' AND anchor = 'hero'), sort_order, media, alt, caption, link_url
FROM front_page_slides WHERE page_id = 'home';
-- A featured band, hidden, when the front page has cards but no band
-- for them, so they aren't lost.
INSERT INTO front_page_sections (page_id, sort_order, section, is_hidden)
SELECT 'home', 99, 'featured', 1
WHERE NOT EXISTS (SELECT 1 FROM front_page_sections WHERE page_id = 'home' AND section = 'featured')
AND EXISTS (SELECT 1 FROM featured_cards WHERE owner_kind = 'front_page');
-- Each band, in its order: its section type, anchor and heading.
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, preset, scope_id, event_type, view, is_hidden)
SELECT 'home',
b.sort_order + 1,
CASE b.section
WHEN 'countdown' THEN 'next-up'
WHEN 'stats' THEN 'numbers'
WHEN 'timeline' THEN 'story'
ELSE b.section
END,
substr(COALESCE(b.title, CASE b.section
WHEN 'countdown' THEN 'Next up'
WHEN 'retreats' THEN 'National Retreats'
WHEN 'calendar' THEN 'What''s on'
WHEN 'stats' THEN 'By the numbers'
WHEN 'timeline' THEN 'Our story so far'
WHEN 'connect' THEN 'Find your way in'
ELSE 'Featured'
END), 1, 60),
b.blurb,
CASE b.section
WHEN 'retreats' THEN 'events'
WHEN 'featured' THEN 'featured_cards'
ELSE b.section
END,
CASE WHEN b.section = 'retreats' THEN 'national' END,
CASE WHEN b.section = 'retreats' THEN 'retreat' END,
CASE WHEN b.section IN ('retreats', 'timeline') THEN 'carousel' END,
b.is_hidden
FROM front_page_sections b
WHERE b.page_id = 'home'
ORDER BY b.sort_order;
-- The retreats band's link through to the Retreats page, as a button
-- above its carousel.
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text, href)
SELECT 'page_section', CAST(id AS TEXT), 'body', 0, 'button', 'All retreats', '/retreats'
FROM page_sections WHERE page_id = 'home' AND anchor = 'retreats';
INSERT INTO section_countdown (section_id, event_id, scope_id, event_type)
SELECT (SELECT id FROM page_sections WHERE page_id = 'home' AND preset = 'countdown'),
countdown_event_id, countdown_scope_id, countdown_event_type
FROM front_page
WHERE id = 'home' AND EXISTS (SELECT 1 FROM page_sections WHERE page_id = 'home' AND preset = 'countdown');
INSERT INTO section_stats (section_id, sort_order, label, source, value, suffix, note)
SELECT (SELECT id FROM page_sections WHERE page_id = 'home' AND preset = 'stats'),
sort_order, label, source, value, suffix, note
FROM front_page_stats
WHERE page_id = 'home' AND EXISTS (SELECT 1 FROM page_sections WHERE page_id = 'home' AND preset = 'stats');
INSERT INTO section_paths (id, section_id, sort_order, label, icon, blurb)
SELECT id, (SELECT id FROM page_sections WHERE page_id = 'home' AND preset = 'connect'),
sort_order, label, icon, blurb
FROM front_page_paths
WHERE page_id = 'home' AND EXISTS (SELECT 1 FROM page_sections WHERE page_id = 'home' AND preset = 'connect');
INSERT INTO section_path_actions (path_id, sort_order, label, description, url)
SELECT a.path_id, a.sort_order, a.label, a.description, a.url
FROM front_page_path_actions a
WHERE a.path_id IN (SELECT id FROM section_paths);
INSERT INTO section_featured (section_id, columns)
SELECT (SELECT id FROM page_sections WHERE page_id = 'home' AND preset = 'featured_cards'), featured_columns
FROM front_page
WHERE id = 'home' AND EXISTS (SELECT 1 FROM page_sections WHERE page_id = 'home' AND preset = 'featured_cards');
INSERT INTO featured_cards_new
(owner_kind, owner_id, sort_order, kind, ref_kind, ref_id, url, eyebrow, title, blurb, image, size)
SELECT 'page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'home' AND preset = 'featured_cards'),
sort_order, kind, ref_kind, ref_id, url, eyebrow, title, blurb, image, size
FROM featured_cards
WHERE owner_kind = 'front_page'
AND EXISTS (SELECT 1 FROM page_sections WHERE page_id = 'home' AND preset = 'featured_cards');
-- An organization's own cards (072) come along as they are.
INSERT INTO featured_cards_new
(id, owner_kind, owner_id, sort_order, kind, ref_kind, ref_id, url, eyebrow, title, blurb, image, size)
SELECT id, owner_kind, owner_id, sort_order, kind, ref_kind, ref_id, url, eyebrow, title, blurb, image, size
FROM featured_cards WHERE owner_kind = 'organization';
-- Drafts of what's gone: the Front page editor is the home page's now.
DELETE FROM drafts WHERE entity = 'front_page';
-- ── What's gone ──────────────────────────────────────────────────
-- 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);
DROP TABLE front_page_path_actions;
DROP TABLE front_page_paths;
DROP TABLE front_page_stats;
DROP TABLE front_page_slides;
DROP TABLE front_page_sections;
DROP TABLE front_page;
DROP TABLE community_page_pinned_posts;
DROP TABLE community_page_feeds;
DROP TABLE community_page;
-- ── Triggers, last ───────────────────────────────────────────────
-- A section's blocks and its featured cards go with it.
CREATE TRIGGER page_sections_cleanup
AFTER DELETE ON page_sections
BEGIN
DELETE FROM content_blocks WHERE owner_kind = 'page_section' AND owner_id = CAST(old.id AS TEXT);
DELETE FROM featured_cards WHERE owner_kind = 'page_section' AND owner_id = CAST(old.id AS TEXT);
END;
CREATE TRIGGER featured_cards_owner_exists
BEFORE INSERT ON featured_cards
BEGIN
SELECT CASE
WHEN new.owner_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.owner_id)
THEN RAISE(ABORT, 'featured_cards: no such organization')
WHEN new.owner_kind = 'page_section'
AND NOT EXISTS (SELECT 1 FROM page_sections WHERE CAST(id AS TEXT) = new.owner_id)
THEN RAISE(ABORT, 'featured_cards: no such page section')
END;
END;
CREATE TRIGGER featured_cards_ref_exists
BEFORE INSERT ON featured_cards
BEGIN
SELECT CASE
WHEN new.ref_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such event')
WHEN new.ref_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such organization')
WHEN new.ref_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such person')
WHEN new.ref_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such team')
WHEN new.ref_kind = 'award'
AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such award')
END;
END;
CREATE TRIGGER featured_cards_ref_exists_update
BEFORE UPDATE OF ref_kind, ref_id ON featured_cards
BEGIN
SELECT CASE
WHEN new.ref_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such event')
WHEN new.ref_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such organization')
WHEN new.ref_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such person')
WHEN new.ref_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such team')
WHEN new.ref_kind = 'award'
AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such award')
END;
END;

View file

@ -24,7 +24,7 @@
heading and its search title can't drift.
The database: records' names, taglines, first paragraphs and
images. A blank site description falls back to the front page's
subhead.
hero's subhead.
── Rules ──
published, listed indexed, in the sitemap
@ -167,8 +167,18 @@ function firstParagraph(db, ownerKind, id, slot) {
const ORG_ROUTES = { region: "/regions", group: "/groups", partner: "/partners", national: "/organizations" };
/* The front page's first hero (083): its subhead is the site's
description when Site settings and site.json have none. */
const homeHero = (db) =>
db
.prepare(
`SELECT h.* FROM section_hero h JOIN page_sections s ON s.id = h.section_id
WHERE s.page_id = 'home' AND s.is_hidden = 0 ORDER BY s.sort_order LIMIT 1`,
)
.get();
function defaults(site, db, pathname) {
const home = db.prepare(`SELECT headline, subhead FROM front_page WHERE id = 'home'`).get();
const home = homeHero(db);
return {
status: 200,
title: site.title,
@ -370,18 +380,16 @@ export function metaFor(db, rawPath, user = null) {
// The home page's data, and its first hero photo when the hero is
// a slideshow, requested alongside the app's JavaScript instead of
// after it has run.
const hero = db.prepare(`SELECT hero_backdrop FROM front_page WHERE id = 'home'`).get();
const hero = homeHero(db);
const slide =
hero?.hero_backdrop === "photos"
? db
.prepare(`SELECT media FROM front_page_slides WHERE page_id = 'home' ORDER BY sort_order LIMIT 1`)
.get()
hero?.backdrop === "photos"
? db.prepare(`SELECT media FROM section_slides WHERE section_id = ? ORDER BY sort_order LIMIT 1`).get(hero.section_id)
: null;
const slideSrc = slide?.media ? (/^(https?:|\/)/.test(slide.media) ? slide.media : `${UPLOADS}/${slide.media}`) : null;
return {
...meta,
preload: [
{ href: "/api/front-page", as: "fetch" },
{ href: "/api/site-pages/home", as: "fetch" },
...(slideSrc ? [{ href: slideSrc, as: "image" }] : []),
],
jsonLd: {

View file

@ -24,13 +24,10 @@
import { Hono } from "hono";
import { asBool, json, loadBlocks, loadFeaturedCards, marks } from "../shape.js";
import { readFeeds } from "../feeds.js";
import { asBool, json, loadBlocks, marks } from "../shape.js";
const blog = new Hono();
const PAGE_ID = "community";
const splitTags = (tags) =>
(tags ?? "")
.split(",")
@ -38,7 +35,7 @@ const splitTags = (tags) =>
.filter(Boolean);
/* Published authors for a batch of posts, keyed by post id. */
function loadAuthors(db, ids) {
export function loadAuthors(db, ids) {
const byPost = new Map();
if (ids.length === 0) return byPost;
const rows = db
@ -67,7 +64,7 @@ function loadAuthors(db, ids) {
/* The first paragraph of each post with no excerpt of its own, the
card's fallback text, by post id. Only that one row per post: a
card doesn't need the rest of the body. */
function firstParagraphs(db, rows) {
export function firstParagraphs(db, rows) {
const ids = rows.filter((row) => !row.excerpt).map((row) => row.id);
if (ids.length === 0) return new Map();
const found = db
@ -84,7 +81,7 @@ function firstParagraphs(db, rows) {
return new Map(found.map((row) => [row.owner_id, row.text]));
}
function shapeSummary(row, authors, firstParagraph) {
export function shapeSummary(row, authors, firstParagraph) {
return {
id: row.id,
title: row.title,
@ -148,83 +145,4 @@ blog.get("/blog/:id", (c) => {
});
});
/* ── The Community page's section ──────────────────────────── */
blog.get("/community-blog", async (c) => {
const db = c.get("db");
const page = db.prepare(`SELECT * FROM community_page WHERE id = ?`).get(PAGE_ID);
if (!page) return c.json({ error: "The community page hasn't been set up." }, 500);
// Ours: pinned, then newest.
const pinned = db
.prepare(
`SELECT b.*
FROM community_page_pinned_posts pp
JOIN blog_posts b ON b.id = pp.post_id AND b.is_published = 1
WHERE pp.page_id = ?
ORDER BY pp.sort_order`,
)
.all(PAGE_ID);
const room = Math.max(0, page.internal_slots - pinned.length);
const pinnedIds = pinned.map((row) => row.id);
const newest = room
? db
.prepare(
`SELECT * FROM blog_posts
WHERE is_published = 1 AND is_listed = 1
${pinnedIds.length ? `AND id NOT IN (${marks(pinnedIds.length)})` : ""}
ORDER BY published_on IS NULL, published_on DESC, created_at DESC
LIMIT ?`,
)
.all(...pinnedIds, room)
: [];
const posts = [...pinned, ...newest];
const ids = posts.map((row) => row.id);
const authors = loadAuthors(db, ids);
const first = firstParagraphs(db, posts);
// Theirs: pinned cards, then the feeds' newest.
const cards = loadFeaturedCards(db, "community_page", PAGE_ID);
const feedRows = db
.prepare(`SELECT url, label FROM community_page_feeds WHERE page_id = ? ORDER BY sort_order`)
.all(PAGE_ID);
const shown = new Set(cards.map((card) => card.url).filter(Boolean));
const spare = Math.max(0, page.external_slots - cards.length);
const fromFeeds = spare && feedRows.length ? await readFeeds(feedRows) : [];
const latest = fromFeeds
.filter((item) => !shown.has(item.url))
.slice(0, spare)
.map((item) => ({
kind: "link",
ref: null,
url: item.url,
eyebrow: item.source,
title: item.title,
blurb: item.excerpt,
image: item.image ? { file: item.image, kind: "featured" } : null,
published: item.published,
}));
return json(c, {
community_blog: {
internal: {
title: page.internal_title,
posts: posts.map((row) =>
shapeSummary(row, authors.get(row.id) ?? [], first.get(row.id)),
),
},
external: {
title: page.external_title,
url: page.external_url,
label: page.external_label,
cards: [...cards, ...latest],
},
},
});
});
export default blog;

View file

@ -1,243 +0,0 @@
/* ═══════════════════════════════════════════════════════════════
FRONT PAGE ROUTE: read-only, mounted under /api
GET /front-page the home page's configuration, resolved
Everything the admin's Front page editor holds, shaped for the
page: hidden sections dropped, stats counted, paths carrying
their actions, and the countdown's event looked up.
The retreats carousel and the timeline rail are not in here.
They fetch /events and /history themselves, as they do on their
own pages, so the rules for which events and entries are public
live in one place each. This route only says whether those bands
appear and under what heading.
── Stats ──
A stat's source picks a query from STAT_QUERIES. Each counts
exactly what the matching public page shows: published, listed
rows, and for awards only public citations to published people
(an award's page names its recipients whether they're listed or
not, so the count does too). A count
that disagreed with the page it summarizes would be worse than
none. 'manual' and 'years_since' read the row's own value.
── Countdown ──
The pinned event if it is still published and not over, listed
or not; otherwise the next published, listed, non-canceled
event that hasn't ended. "Hasn't ended" is COALESCE(ends_on, starts_on) >= today,
so a running series with a start date in the past still counts.
The client works out the next meeting of a series from `series`.
countdown_scope_id and countdown_event_type narrow "the next
event" (National + Retreat skips a sooner regional class). Null
means any. They don't apply to a pinned event: the admin chose
that one by name.
── Hero event ──
With the 'event' feature, the hero draws the pinned hero_event_id
if it's still published and not over, else the countdown's event
(above), so the two never disagree. Its action links ride along
for the card's buttons.
── Featured ──
The featured band's cards, record cards filled in from their
records (loadFeaturedCards in shape.js, which the Community
blog will share).
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { asBool, json, loadFeaturedCards, loadLinks, shapeSeries, splitLinks } from "../shape.js";
const home = new Hono();
const PAGE_ID = "home";
const STAT_QUERIES = {
regions: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'region' AND is_published = 1 AND is_listed = 1`,
groups: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'group' AND is_published = 1 AND is_listed = 1`,
partners: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'partner' AND is_published = 1 AND is_listed = 1`,
events_held: `SELECT COUNT(*) AS n FROM v_events
WHERE is_published = 1 AND is_listed = 1 AND effective_status = 'past'`,
retreats_held: `SELECT COUNT(*) AS n FROM v_events
WHERE is_published = 1 AND is_listed = 1 AND effective_status = 'past'
AND event_type = 'retreat'`,
people: `SELECT COUNT(*) AS n FROM people WHERE is_published = 1 AND is_listed = 1`,
awards_given: `SELECT COUNT(*) AS n
FROM person_awards pa
JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
JOIN awards a ON a.id = pa.award_id AND a.is_published = 1
WHERE pa.is_public = 1`,
};
/* The number as a string, or null when there's nothing to print:
a manual stat nobody filled in, or a year that isn't one. */
function statValue(db, row) {
if (row.source === "manual") return row.value || null;
if (row.source === "years_since") {
const year = Number.parseInt(row.value ?? "", 10);
if (!Number.isInteger(year)) return null;
return String(Math.max(0, new Date().getFullYear() - year));
}
const sql = STAT_QUERIES[row.source];
return sql ? String(db.prepare(sql).get().n) : null;
}
/* The countdown's fields plus what the hero's event card also draws:
its tagline, place, photo and buttons. */
function shapeHeroEvent(db, row) {
if (!row) return null;
const { actions } = splitLinks(loadLinks(db, "event", [row.id]).get(row.id) ?? []);
return {
...shapeCountdown(row),
tagline: row.tagline,
photo: row.photo,
photo_alt: row.photo_alt,
org_logo: row.effective_org_logo,
links: actions,
};
}
function shapeCountdown(row) {
if (!row) return null;
return {
id: row.id,
title: row.title,
theme: row.theme,
starts_on: row.starts_on,
ends_on: row.ends_on,
date_label: row.date_label,
location_label: row.location_label,
is_online: asBool(row.is_online),
color: row.effective_color,
event_logo: row.event_logo,
series: shapeSeries(row),
};
}
home.get("/front-page", (c) => {
const db = c.get("db");
const page = db.prepare(`SELECT * FROM front_page WHERE id = ?`).get(PAGE_ID);
// The schema seeds the row and the engine refuses to delete it,
// so this is a database that hasn't been migrated. Say so.
if (!page) return c.json({ error: "The front page hasn't been set up." }, 500);
const byOrder = (table) =>
db.prepare(`SELECT * FROM ${table} WHERE page_id = ? ORDER BY sort_order`).all(PAGE_ID);
const sections = byOrder("front_page_sections")
.filter((row) => !asBool(row.is_hidden))
.map((row) => ({ section: row.section, title: row.title, blurb: row.blurb }));
const slides = byOrder("front_page_slides").map((row) => ({
media: row.media,
alt: row.alt,
caption: row.caption,
link_url: row.link_url,
}));
const stats = byOrder("front_page_stats")
.map((row) => ({
label: row.label,
value: statValue(db, row),
suffix: row.suffix,
note: row.note,
}))
.filter((stat) => stat.value !== null);
const actions = db.prepare(
`SELECT label, description, url FROM front_page_path_actions
WHERE path_id = ? ORDER BY sort_order`,
);
const paths = byOrder("front_page_paths")
.map((row) => ({
label: row.label,
icon: row.icon,
blurb: row.blurb,
actions: actions.all(row.id),
}))
// A path with nothing to do is a dead tab.
.filter((path) => path.actions.length > 0);
const notOver = `is_published = 1
AND effective_status != 'cancelled'
AND COALESCE(ends_on, starts_on) >= date('now')`;
const pinned = page.countdown_event_id
? db
.prepare(`SELECT * FROM v_events WHERE id = ? AND ${notOver}`)
.get(page.countdown_event_id)
: null;
const filters = [];
const params = [];
if (page.countdown_scope_id) {
filters.push("AND scope_id = ?");
params.push(page.countdown_scope_id);
}
if (page.countdown_event_type) {
filters.push("AND event_type = ?");
params.push(page.countdown_event_type);
}
const next =
pinned ??
db
.prepare(
`SELECT * FROM v_events
WHERE ${notOver} AND is_listed = 1 ${filters.join(" ")}
ORDER BY starts_on, title
LIMIT 1`,
)
.get(...params);
const heroEvent =
page.hero_feature === "event"
? (page.hero_event_id
? db
.prepare(`SELECT * FROM v_events WHERE id = ? AND ${notOver}`)
.get(page.hero_event_id)
: null) ?? next
: null;
return json(c, {
front_page: {
hero: {
backdrop: page.hero_backdrop,
feature: page.hero_feature,
eyebrow: page.eyebrow,
headline: page.headline,
subhead: page.subhead,
primary: page.primary_label && page.primary_url
? { label: page.primary_label, url: page.primary_url }
: null,
secondary: page.secondary_label && page.secondary_url
? { label: page.secondary_label, url: page.secondary_url }
: null,
slide_seconds: page.slide_seconds,
slides,
livestream: page.livestream_url
? { url: page.livestream_url, title: page.livestream_title }
: null,
video: page.video_url
? { url: page.video_url, title: page.video_title, captions: page.video_captions, still: page.video_still }
: null,
event: shapeHeroEvent(db, heroEvent),
},
sections,
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),
},
});
});
export default home;

View file

@ -7,8 +7,9 @@
GET /site-pages every page's section headings, by the
page's path, for the header's dropdowns
and the side nav
GET /site-pages/:id one page's title and intro and its
sections, in order: heading,
GET /site-pages/:id one page's title and intro and its shown
sections, in order, each with what its type
shows (sectionData.js): heading,
accent, preset (and an events preset's
filter and view), and its blocks; Not
found for a hidden page, below viewer
@ -22,6 +23,7 @@ import { Hono } from "hono";
import { currentUser } from "../auth.js";
import { navFor, seesHidden } from "../siteNav.js";
import { NO_STORE, json, loadBlocks } from "../shape.js";
import { withSectionData } from "../sectionData.js";
const sitePages = new Hono();
@ -34,17 +36,18 @@ sitePages.get("/site-pages", (c) => {
const rows = c
.get("db")
.prepare(
`SELECT p.path, s.anchor, s.title FROM page_sections s JOIN site_pages p ON p.id = s.page_id
`SELECT p.path, s.anchor, s.title, s.preset FROM page_sections s JOIN site_pages p ON p.id = s.page_id
WHERE s.is_hidden = 0
ORDER BY p.path, s.sort_order, s.id`,
)
.all();
const pages = {};
for (const row of rows) (pages[row.path] ??= []).push({ anchor: row.anchor, title: row.title });
for (const row of rows) (pages[row.path] ??= []).push({ anchor: row.anchor, title: row.title, preset: row.preset });
return json(c, { pages });
});
sitePages.get("/site-pages/:id", (c) => {
sitePages.get("/site-pages/:id", async (c) => {
const db = c.get("db");
const id = c.req.param("id");
const found = db.prepare(`SELECT title, description, is_hidden FROM site_pages WHERE id = ?`).get(id);
@ -56,7 +59,7 @@ sitePages.get("/site-pages/:id", (c) => {
const rows = db
.prepare(
`SELECT id, anchor, title, blurb, accent, preset, scope_id, event_type, view, org_kinds
FROM page_sections WHERE page_id = ? ORDER BY sort_order, id`,
FROM page_sections WHERE page_id = ? AND is_hidden = 0 ORDER BY sort_order, id`,
)
.all(id);
const blocks = loadBlocks(db, "page_section", rows.map((row) => String(row.id)));
@ -82,6 +85,8 @@ sitePages.get("/site-pages/:id", (c) => {
tags.set(section_id, [...(tags.get(section_id) ?? []), tag_id]);
}
const sections = await withSectionData(db, rows);
// A hidden page is only for those signed in: never kept.
const send = hidden ? (body) => c.json(body, 200, NO_STORE) : (body) => json(c, body);
return send({
@ -89,7 +94,7 @@ sitePages.get("/site-pages/:id", (c) => {
id,
title: found.title,
description: found.description,
sections: rows.map(({ id: sectionId, ...section }) => ({
sections: sections.map(({ id: sectionId, ...section }) => ({
...section,
blocks: blocks.get(String(sectionId)) ?? [],
org_ids: picked.get(sectionId) ?? [],

288
server/src/sectionData.js Normal file
View file

@ -0,0 +1,288 @@
/* ═══════════════════════════════════════════════════════════════
SECTION DATA
What a section type shows beyond its blocks, resolved for the page
(routes/sitePages.js, GET /site-pages/:id), from its settings
tables (083_section_settings.sql):
hero its words, buttons, backdrop, slides, and the
event its card shows (with the 'event' feature)
countdown the event it counts down to
stats its numbers, counted
connect its paths, each with its links
featured_cards its cards, record cards filled in from their
records
community_blog our posts (pinned, then newest) and community
posts (pinned cards, then its feeds' newest)
── Stats ──
A stat's source picks a query from STAT_QUERIES. Each counts
exactly what the matching public page shows: published, listed
rows, and for awards only public citations to published people.
A count that disagreed with the page it summarizes would be worse
than none. 'manual' and 'years_since' read the row's own value.
── Countdown ──
The pinned event if it is still published and not over, listed
or not; otherwise the next published, listed, non-canceled event
that hasn't ended (COALESCE(ends_on, starts_on) >= today, so a
running series still counts), narrowed by the section's scope and
type. The client works out a series' next meeting from `series`.
── Hero event ──
With the 'event' feature, the hero draws its pinned event if it's
still published and not over, else the page's countdown's event,
else the next event, so the two never disagree.
═══════════════════════════════════════════════════════════════ */
import { asBool, loadFeaturedCards, loadLinks, marks, shapeSeries, splitLinks } from "./shape.js";
import { readFeeds } from "./feeds.js";
import { firstParagraphs, loadAuthors, shapeSummary } from "./routes/blog.js";
const STAT_QUERIES = {
regions: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'region' AND is_published = 1 AND is_listed = 1`,
groups: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'group' AND is_published = 1 AND is_listed = 1`,
partners: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'partner' AND is_published = 1 AND is_listed = 1`,
events_held: `SELECT COUNT(*) AS n FROM v_events
WHERE is_published = 1 AND is_listed = 1 AND effective_status = 'past'`,
retreats_held: `SELECT COUNT(*) AS n FROM v_events
WHERE is_published = 1 AND is_listed = 1 AND effective_status = 'past'
AND event_type = 'retreat'`,
people: `SELECT COUNT(*) AS n FROM people WHERE is_published = 1 AND is_listed = 1`,
awards_given: `SELECT COUNT(*) AS n
FROM person_awards pa
JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
JOIN awards a ON a.id = pa.award_id AND a.is_published = 1
WHERE pa.is_public = 1`,
};
/* The number as a string, or null when there's nothing to print. */
function statValue(db, row) {
if (row.source === "manual") return row.value || null;
if (row.source === "years_since") {
const year = Number.parseInt(row.value ?? "", 10);
if (!Number.isInteger(year)) return null;
return String(Math.max(0, new Date().getFullYear() - year));
}
const sql = STAT_QUERIES[row.source];
return sql ? String(db.prepare(sql).get().n) : null;
}
function shapeCountdown(row) {
if (!row) return null;
return {
id: row.id,
title: row.title,
theme: row.theme,
starts_on: row.starts_on,
ends_on: row.ends_on,
date_label: row.date_label,
location_label: row.location_label,
is_online: asBool(row.is_online),
color: row.effective_color,
event_logo: row.event_logo,
series: shapeSeries(row),
};
}
/* The countdown's fields plus what the hero's event card also draws. */
function shapeHeroEvent(db, row) {
if (!row) return null;
const { actions } = splitLinks(loadLinks(db, "event", [row.id]).get(row.id) ?? []);
return {
...shapeCountdown(row),
tagline: row.tagline,
photo: row.photo,
photo_alt: row.photo_alt,
org_logo: row.effective_org_logo,
links: actions,
};
}
const NOT_OVER = `is_published = 1
AND effective_status != 'cancelled'
AND COALESCE(ends_on, starts_on) >= date('now')`;
const pinnedEvent = (db, id) =>
id ? db.prepare(`SELECT * FROM v_events WHERE id = ? AND ${NOT_OVER}`).get(id) ?? null : null;
/* A countdown's event: the pinned one, else the next of its scope and type. */
function countdownEvent(db, settings) {
const pinned = pinnedEvent(db, settings?.event_id);
if (pinned) return pinned;
const filters = [];
const params = [];
if (settings?.scope_id) {
filters.push("AND scope_id = ?");
params.push(settings.scope_id);
}
if (settings?.event_type) {
filters.push("AND event_type = ?");
params.push(settings.event_type);
}
return (
db
.prepare(
`SELECT * FROM v_events
WHERE ${NOT_OVER} AND is_listed = 1 ${filters.join(" ")}
ORDER BY starts_on, title
LIMIT 1`,
)
.get(...params) ?? null
);
}
const byOrder = (db, table, column, id) =>
db.prepare(`SELECT * FROM ${table} WHERE ${column} = ? ORDER BY sort_order, id`).all(id);
function heroOf(db, section, pageCountdown) {
const h = db.prepare(`SELECT * FROM section_hero WHERE section_id = ?`).get(section.id) ?? {};
const event =
h.feature === "event" ? pinnedEvent(db, h.event_id) ?? pageCountdown ?? countdownEvent(db, null) : null;
return {
backdrop: h.backdrop ?? "brand",
feature: h.feature ?? "none",
eyebrow: h.eyebrow ?? null,
headline: h.headline ?? "",
subhead: h.subhead ?? null,
primary: h.primary_label && h.primary_url ? { label: h.primary_label, url: h.primary_url } : null,
secondary: h.secondary_label && h.secondary_url ? { label: h.secondary_label, url: h.secondary_url } : null,
slide_seconds: h.slide_seconds ?? 7,
slides: byOrder(db, "section_slides", "section_id", section.id).map((row) => ({
media: row.media,
alt: row.alt,
caption: row.caption,
link_url: row.link_url,
})),
livestream: h.livestream_url ? { url: h.livestream_url, title: h.livestream_title } : null,
video: h.video_url
? { url: h.video_url, title: h.video_title, captions: h.video_captions, still: h.video_still }
: null,
event: shapeHeroEvent(db, event),
};
}
function pathsOf(db, section) {
const actions = db.prepare(
`SELECT label, description, url FROM section_path_actions WHERE path_id = ? ORDER BY sort_order, id`,
);
return (
byOrder(db, "section_paths", "section_id", section.id)
.map((row) => ({ label: row.label, icon: row.icon, blurb: row.blurb, actions: actions.all(row.id) }))
// A path with nothing to do is a dead tab.
.filter((path) => path.actions.length > 0)
);
}
async function blogOf(db, section) {
const page = db.prepare(`SELECT * FROM section_blog WHERE section_id = ?`).get(section.id) ?? {
internal_slots: 3,
external_slots: 3,
};
// Ours: pinned, then newest.
const pinned = db
.prepare(
`SELECT b.*
FROM section_blog_posts pp
JOIN blog_posts b ON b.id = pp.post_id AND b.is_published = 1
WHERE pp.section_id = ?
ORDER BY pp.sort_order`,
)
.all(section.id);
const room = Math.max(0, page.internal_slots - pinned.length);
const pinnedIds = pinned.map((row) => row.id);
const newest = room
? db
.prepare(
`SELECT * FROM blog_posts
WHERE is_published = 1 AND is_listed = 1
${pinnedIds.length ? `AND id NOT IN (${marks(pinnedIds.length)})` : ""}
ORDER BY published_on IS NULL, published_on DESC, created_at DESC
LIMIT ?`,
)
.all(...pinnedIds, room)
: [];
const posts = [...pinned, ...newest];
const authors = loadAuthors(db, posts.map((row) => row.id));
const first = firstParagraphs(db, posts);
// Theirs: pinned cards, then the feeds' newest.
const cards = loadFeaturedCards(db, "page_section", String(section.id));
const feedRows = db
.prepare(`SELECT url, label FROM section_feeds WHERE section_id = ? ORDER BY sort_order`)
.all(section.id);
const shown = new Set(cards.map((card) => card.url).filter(Boolean));
const spare = Math.max(0, page.external_slots - cards.length);
const fromFeeds = spare && feedRows.length ? await readFeeds(feedRows) : [];
const latest = fromFeeds
.filter((item) => !shown.has(item.url))
.slice(0, spare)
.map((item) => ({
kind: "link",
ref: null,
url: item.url,
eyebrow: item.source,
title: item.title,
blurb: item.excerpt,
image: item.image ? { file: item.image, kind: "featured" } : null,
published: item.published,
}));
return {
internal: {
title: page.internal_title,
posts: posts.map((row) => shapeSummary(row, authors.get(row.id) ?? [], first.get(row.id))),
},
external: {
title: page.external_title,
url: page.external_url,
label: page.external_label,
cards: [...cards, ...latest],
},
};
}
/* Each section with what its type shows, as `data`. A page's first
countdown is the event its heroes fall back to. */
export async function withSectionData(db, sections) {
const countdown = sections.find((s) => s.preset === "countdown");
const pageCountdown = countdown
? countdownEvent(db, db.prepare(`SELECT * FROM section_countdown WHERE section_id = ?`).get(countdown.id))
: null;
return Promise.all(
sections.map(async (section) => {
switch (section.preset) {
case "hero":
return { ...section, data: heroOf(db, section, pageCountdown) };
case "countdown": {
const settings = db.prepare(`SELECT * FROM section_countdown WHERE section_id = ?`).get(section.id);
const event = section === countdown ? pageCountdown : countdownEvent(db, settings);
return { ...section, data: shapeCountdown(event) };
}
case "stats":
return {
...section,
data: byOrder(db, "section_stats", "section_id", section.id)
.map((row) => ({ label: row.label, value: statValue(db, row), suffix: row.suffix, note: row.note }))
.filter((stat) => stat.value !== null),
};
case "connect":
return { ...section, data: pathsOf(db, section) };
case "featured_cards":
return {
...section,
data: {
cards: loadFeaturedCards(db, "page_section", String(section.id)),
columns: db.prepare(`SELECT columns FROM section_featured WHERE section_id = ?`).get(section.id)?.columns ?? null,
},
};
case "community_blog":
return { ...section, data: await blogOf(db, section) };
default:
return section;
}
}),
);
}

View file

@ -212,7 +212,7 @@ export function splitLinks(links = []) {
first; an empty list means "starts_on's weekday", which the
client resolves since it already holds starts_on. Occurrences
are not sent, they are derived, and the client derives them
against its own today. Shared by /events and /front-page.
against its own today. Shared by /events and the sections (sectionData.js).
───────────────────────────────────────────────────────────── */
const SERIES_WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];