Compare commits

..

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

21 changed files with 19 additions and 1279 deletions

View file

@ -29,7 +29,6 @@ what a dropdown in the admin editor says.
| ------------------------------------------------------------ | ---------------- | ------------------------------------ |
| A record: an event, organization, person, team, award, timeline entry | the database | editing it in the admin |
| The front page's words, photos, bands, stats and paths | the database | Admin → Front page |
| Blog posts, and the Community page's blog section (headings, pins, feeds) | the database | Admin → Blog |
| The **label** a dropdown shows in the admin | code | [one file](#renaming-what-a-dropdown-shows) |
| The **list of allowed values** behind a fixed dropdown | database CHECK + code | [a migration and three files](#adding-removing-or-renaming-a-stored-value) |
| Navigation, page section titles, colours, the site banner, history decades, the map grid | code | [the file named below](#other-content-that-lives-in-code) |
@ -184,7 +183,7 @@ also in `admin-schema.js` and a CHECK):
| Front page → Feature | none, livestream, video | **yes** | `HeroStage.tsx` |
| Front page → Sections → Section | countdown, retreats, calendar, stats, timeline, connect, featured | **yes**, `FRONT_PAGE_SECTIONS` | `SECTIONS` in `src/pages/Home.tsx`; see [below](#front-page-section-names) |
| Front page → Stats → Number Source | manual, years_since, regions, … | **yes**, `STAT_SOURCES` | `STAT_QUERIES` in `server/src/routes/home.js`; see [below](#front-page-stat-sources) |
| Front page → Featured cards → Card type (Blog → Community section → Pinned community posts offers link and video only) | record, link, video | **yes**, `FEATURED_KINDS` | `FeaturedCards.tsx` (how each kind draws), `loadFeaturedCards` in `server/src/shape.js` |
| Front page → Featured cards → Card type | record, link, video | **yes**, `FEATURED_KINDS` | `FeaturedCards.tsx` (how each kind draws), `loadFeaturedCards` in `server/src/shape.js` |
| Front page → Featured cards → Record type | event, organization, person, team, award | no | `FEATURED_REFS` in `server/src/shape.js` (what each fills the card with); the triggers in `030_featured_cards.sql` |
| Every list → Published / Listed / Featured filter | 1, 0 | **yes** | n/a |
@ -200,7 +199,6 @@ code):
| Event → Scope (+ list filter); Front page → Countdown → Only this scope | `event_scopes` | the `event_scopes` table (migration only) |
| Event hosts → Organization; affiliations; team and award "Organization" / "Awarded by"; person → Home organization | `organizations` | organizations, labelled by name |
| Event hosts / event people / team members / timeline people → Person | `people` | people |
| Blog → Community section → Pinned posts → Post | `blog_posts` | blog posts, newest first |
| Timeline → Record; Featured cards → Record | `record_refs` | every event, organization, award, person and team, narrowed by the type picked beside it |
| Affiliations → Team | `teams` | teams, filtered to the chosen organization |
| Person awards → Award | `awards` | awards, labelled "Award (Organization)" |

View file

@ -799,96 +799,6 @@ const frontPage = {
],
};
/* ── Blog (031_blog.sql) ─────────────────────────────────────────
Posts of our own, with a content-block body and people as
authors, and the Community page's blog section, a singleton like
the front page. The section's community posts are featured cards
owned by 'community_page'. ─────────────────────────────────── */
const blogPosts = {
key: "blog_posts",
table: "blog_posts",
idColumn: "id",
idKind: "slug",
concurrency: "updated_at",
list: {
columns: ["id", "title", "published_on", "tags", "is_published", "is_listed", "updated_at"],
filters: ["is_published", "is_listed"],
search: ["title", "id", "tags"],
order: "published_on IS NULL, published_on DESC, title",
},
columns: [
text("title", { required: true }),
text("excerpt"),
text("cover_image"),
date("published_on"),
text("tags"),
text("guest_author"),
text("guest_photo"),
bool("is_published"),
bool("is_listed"),
],
children: [
{
key: "authors",
table: "blog_post_authors",
owner: { column: "post_id" },
order: "sort_order",
columns: [text("person_id", { required: true })],
},
blocksChild("blog_post"),
],
};
const communityPage = {
key: "community_page",
table: "community_page",
idColumn: "id",
idKind: "slug",
singleton: "community",
concurrency: "updated_at",
list: {
columns: ["id", "blog_title", "updated_at"],
filters: [],
search: [],
order: "id",
},
columns: [
text("blog_title"),
text("blog_blurb"),
text("internal_title"),
int("internal_slots"),
text("external_title"),
int("external_slots"),
text("external_url"),
text("external_label"),
],
children: [
{
key: "pinned_posts",
table: "community_page_pinned_posts",
owner: { column: "page_id" },
order: "sort_order",
columns: [text("post_id", { required: true })],
},
featuredCardsChild("community_page"),
{
key: "feeds",
table: "community_page_feeds",
owner: { column: "page_id" },
order: "sort_order",
columns: [text("url", { required: true }), text("label")],
},
],
};
export const ENTITIES = {
organizations,
events,
@ -897,8 +807,6 @@ export const ENTITIES = {
awards,
timeline,
front_page: frontPage,
blog_posts: blogPosts,
community_page: communityPage,
};
/* ── Options for the form's select inputs ────────────────────── */
@ -911,7 +819,6 @@ export const OPTION_QUERIES = {
event_scopes: "SELECT id, name AS label FROM event_scopes ORDER BY sort_order",
events: "SELECT id, title AS label FROM events ORDER BY starts_on DESC, title",
people: "SELECT id, display_name AS label FROM people ORDER BY sort_name, display_name",
blog_posts: "SELECT id, title AS label FROM blog_posts ORDER BY published_on DESC, title",
// org_id rides along so the affiliation row can filter the list
// down to teams of the organization it already names.

View file

@ -1,150 +0,0 @@
/* ═══════════════════════════════════════════════════════════════
FEEDS
Reads the RSS and Atom feeds the Community page's blog section
lists (community_page_feeds), for its "newest community posts".
A Substack's feed is https://<name>.substack.com/feed.
Each feed is fetched through linkPreview.js's safeGet, so it gets
the same public-address checks, timeout and size cap as a link
preview. Results are kept in memory for CACHE_MS. A feed that
fails keeps serving what it last returned, and one that has never
worked contributes nothing: the section shows the pinned posts
and whatever the other feeds have, rather than an error.
Items come back as plain data: title, url, excerpt, image,
published (ISO), source. Only http(s) links and https images are
kept, so a feed can't put a javascript: link or a mixed-content
image on the page.
═══════════════════════════════════════════════════════════════ */
import { decodeEntities, safeGet } from "./linkPreview.js";
const CACHE_MS = 30 * 60 * 1000;
const MAX_FEED_BYTES = 3 * 1024 * 1024;
const MAX_ITEMS_PER_FEED = 20;
const EXCERPT_CHARS = 300;
const cache = new Map(); // url → { at, feed }
/* ── Parsing ───────────────────────────────────────────────── */
function unwrap(text) {
return text.replace(/^\s*<!\[CDATA\[([\s\S]*?)\]\]>\s*$/, "$1");
}
/* The text inside the first <tag>…</tag>, CDATA unwrapped. Tag
names may carry a namespace prefix (content:encoded). */
function inner(xml, tag) {
const match = xml.match(new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${tag}>`, "i"));
return match ? unwrap(match[1]) : null;
}
function attrOf(xml, tag, name, where = () => true) {
for (const match of xml.matchAll(new RegExp(`<${tag}\\b[^>]*>`, "gi"))) {
const el = match[0];
const value = el.match(new RegExp(`\\b${name}\\s*=\\s*("([^"]*)"|'([^']*)')`, "i"));
if (value && where(el)) return value[2] ?? value[3];
}
return null;
}
function plain(html) {
if (!html) return null;
const text = decodeEntities(html.replace(/<[^>]+>/g, " "));
if (!text) return null;
return text.length > EXCERPT_CHARS ? `${text.slice(0, EXCERPT_CHARS).trimEnd()}…` : text;
}
function safeUrl(raw, base, { httpsOnly = false } = {}) {
if (!raw) return null;
try {
const url = new URL(decodeEntities(raw), base);
if (url.protocol === "https:" || (!httpsOnly && url.protocol === "http:")) return url.toString();
} catch {
/* not a URL */
}
return null;
}
function isoDate(raw) {
if (!raw) return null;
const date = new Date(raw.trim());
return Number.isNaN(date.getTime()) ? null : date.toISOString();
}
function firstImage(html) {
return html?.match(/<img\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/i)?.[1] ?? null;
}
function parseFeed(xml, feedUrl) {
const isAtom = /<feed\b[^>]*xmlns=["']http:\/\/www\.w3\.org\/2005\/Atom/i.test(xml) && !/<rss\b/i.test(xml);
const channelTitle = decodeEntities(inner(xml.replace(/<(item|entry)\b[\s\S]*$/i, ""), "title") ?? "");
const blocks = xml.match(isAtom ? /<entry\b[\s\S]*?<\/entry>/gi : /<item\b[\s\S]*?<\/item>/gi) ?? [];
const items = [];
for (const block of blocks.slice(0, MAX_ITEMS_PER_FEED)) {
const link = isAtom
? attrOf(block, "link", "href", (el) => !/rel\s*=\s*["'](?!alternate)/i.test(el))
: inner(block, "link");
const url = safeUrl(link?.trim(), feedUrl);
const title = decodeEntities(inner(block, "title") ?? "");
if (!url || !title) continue;
const body = inner(block, "content:encoded") ?? inner(block, "content");
const summary = inner(block, "description") ?? inner(block, "summary");
const image =
attrOf(block, "enclosure", "url", (el) => /type\s*=\s*["']image\//i.test(el)) ??
attrOf(block, "media:content", "url") ??
attrOf(block, "media:thumbnail", "url") ??
firstImage(body) ??
firstImage(summary);
items.push({
title,
url,
excerpt: plain(summary) ?? plain(body),
image: safeUrl(image, feedUrl, { httpsOnly: true }),
published: isoDate(inner(block, "pubDate") ?? inner(block, "published") ?? inner(block, "updated")),
});
}
return { title: channelTitle || null, items };
}
/* ── Fetching ──────────────────────────────────────────────── */
async function fetchFeed(url) {
const result = await safeGet(url, {
maxBytes: MAX_FEED_BYTES,
accept: "application/rss+xml, application/atom+xml, application/xml;q=0.9, text/xml;q=0.9, */*;q=0.1",
});
return parseFeed(result.body.toString("utf8"), result.url.toString());
}
async function readFeed(url) {
const hit = cache.get(url);
if (hit && Date.now() - hit.at < CACHE_MS) return hit.feed;
try {
const feed = await fetchFeed(url);
cache.set(url, { at: Date.now(), feed });
return feed;
} catch (err) {
console.warn(`feed ${url}: ${err.message}`);
// Serve the last good copy, and don't retry on every request.
const stale = hit?.feed ?? { title: null, items: [] };
cache.set(url, { at: Date.now() - CACHE_MS + 5 * 60 * 1000, feed: stale });
return stale;
}
}
/* Every listed feed's items, newest first, each tagged with its
source: the row's label, else the feed's own title. */
export async function readFeeds(rows) {
const feeds = await Promise.all(rows.map((row) => readFeed(row.url)));
const items = feeds.flatMap((feed, i) =>
feed.items.map((item) => ({ ...item, source: rows[i].label || feed.title })),
);
return items.sort((a, b) => (b.published ?? "").localeCompare(a.published ?? ""));
}

View file

@ -22,7 +22,6 @@ import people from "./routes/people.js";
import history from "./routes/history.js";
import home from "./routes/home.js";
import directory from "./routes/directory.js";
import blog from "./routes/blog.js";
import feedback from "./routes/feedback.js";
import auth from "./routes/auth.js";
import admin from "./routes/admin.js";
@ -68,7 +67,6 @@ app.route("/api", people);
app.route("/api", history);
app.route("/api", home);
app.route("/api", directory);
app.route("/api", blog);
// Tighter limit on the write path than anything else gets.
app.use("/api/feedback", rateLimit({ windowMs: 60_000, max: 5 }));

View file

@ -22,8 +22,7 @@
· TIMEOUT_MS per request, and at most MAX_HTML_BYTES of page
or MAX_UPLOAD_BYTES of image is read
Editors and up only (routes/media.js). feeds.js reads RSS
through the same safeGet.
Editors and up only (routes/media.js).
═══════════════════════════════════════════════════════════════ */
import { lookup } from "node:dns/promises";
@ -103,7 +102,7 @@ async function vet(raw) {
/* ── One request, pinned to the vetted address ─────────────── */
function requestOnce({ url, address }, { maxBytes, accept, truncate = false }) {
function requestOnce({ url, address }, { maxBytes, accept }) {
const client = url.protocol === "https:" ? https : http;
return new Promise((resolve, reject) => {
@ -141,7 +140,7 @@ function requestOnce({ url, address }, { maxBytes, accept, truncate = false }) {
// A page's head is at the top; stop reading and use what
// arrived. An image that's too big is refused outright.
res.destroy();
if (truncate) {
if (accept.startsWith("text/html")) {
resolve({ body: Buffer.concat(chunks), type: res.headers["content-type"] ?? "" });
} else {
reject(new MediaError(413, "The preview image is too large."));
@ -164,8 +163,7 @@ function requestOnce({ url, address }, { maxBytes, accept, truncate = false }) {
});
}
/* Also used by feeds.js, so feeds get the same address checks. */
export async function safeGet(raw, options) {
async function safeGet(raw, options) {
let next = raw;
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
const target = await vet(next);
@ -180,7 +178,7 @@ export async function safeGet(raw, options) {
const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
export function decodeEntities(text) {
function decode(text) {
return text
.replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCodePoint(parseInt(hex, 16)))
.replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(Number(dec)))
@ -199,11 +197,11 @@ function readMeta(html) {
for (const tag of html.match(/<meta\b[^>]*>/gi) ?? []) {
const key = (attr(tag, "property") ?? attr(tag, "name") ?? "").toLowerCase();
const content = attr(tag, "content");
if (key && content != null && !(key in meta)) meta[key] = decodeEntities(content);
if (key && content != null && !(key in meta)) meta[key] = decode(content);
}
const title = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1];
return {
title: meta["og:title"] || meta["twitter:title"] || (title ? decodeEntities(title) : null) || null,
title: meta["og:title"] || meta["twitter:title"] || (title ? decode(title) : null) || null,
description:
meta["og:description"] || meta["twitter:description"] || meta.description || null,
image: meta["og:image:secure_url"] || meta["og:image"] || meta["twitter:image"] || null,
@ -214,7 +212,6 @@ function readMeta(html) {
export async function previewLink(raw) {
const page = await safeGet(raw, {
maxBytes: MAX_HTML_BYTES,
truncate: true,
accept: "text/html,application/xhtml+xml;q=0.9,*/*;q=0.1",
});
if (!/html/i.test(page.type)) {

View file

@ -1,254 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 031 BLOG
--
-- Posts of our own, at /blog/<id>, and the Community page's blog
-- section, which shows two subsections:
--
-- Our posts pinned blog_posts first, then the newest
-- published, listed ones, up to internal_slots
-- Community posts pinned featured_cards (owner 'community_page')
-- first, then the newest items from the RSS or
-- Atom feeds in community_page_feeds, up to
-- external_slots
--
-- blog_posts
-- A draft until published (is_published defaults to 0, as for
-- people): a half-written post shouldn't go live by accident.
-- is_listed works as it does everywhere (027): unticked, the post
-- is left out of "newest" but its page works and it can be pinned.
-- The body is content_blocks with owner_kind 'blog_post', slot
-- 'body'. Authors are people (blog_post_authors), or a guest named
-- on the post itself, or both. tags is a comma-separated list, eg.
-- 'Reflection, Event recap'; it is only displayed, never joined on.
--
-- content_blocks gains 'blog_post' as an owner. A CHECK can't be
-- altered in place, so the table is rebuilt; the *_cleanup triggers
-- on other tables name it, hence legacy_alter_table around the
-- rename. Its own index and owner trigger are recreated below.
--
-- featured_cards gains 'community_page' as an owner, the same way.
-- Nothing names it but its own triggers, recreated below.
--
-- community_page is a singleton like front_page: one row, made
-- here, which the admin edits and can't delete.
--
-- PRAGMA user_version; -- reads 30 before this file
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE blog_posts (
id TEXT PRIMARY KEY, -- slug: 'finding-unity-at-camp'
title TEXT NOT NULL,
excerpt TEXT, -- the card's text; else the body's start
cover_image TEXT, -- '/uploads/…', a filename, or a URL
published_on TEXT, -- 'YYYY-MM-DD'; newest first
tags TEXT, -- 'Reflection, Event recap'
guest_author TEXT, -- someone with no people row
guest_photo TEXT,
is_published INTEGER NOT NULL DEFAULT 0 CHECK (is_published IN (0, 1)),
is_listed INTEGER NOT NULL DEFAULT 1 CHECK (is_listed IN (0, 1)),
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
CREATE INDEX blog_posts_newest_idx ON blog_posts (is_published, is_listed, published_on DESC);
CREATE TABLE blog_post_authors (
post_id TEXT NOT NULL REFERENCES blog_posts (id) ON DELETE CASCADE,
person_id TEXT NOT NULL REFERENCES people (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (post_id, person_id)
) STRICT;
CREATE INDEX blog_post_authors_person_idx ON blog_post_authors (person_id);
CREATE TABLE community_page (
id TEXT PRIMARY KEY CHECK (id = 'community'),
blog_title TEXT, -- null → 'Community Blog'
blog_blurb TEXT,
internal_title TEXT, -- null → 'From NGU'
internal_slots INTEGER NOT NULL DEFAULT 3 CHECK (internal_slots BETWEEN 0 AND 12),
external_title TEXT, -- null → 'From our community'
external_slots INTEGER NOT NULL DEFAULT 3 CHECK (external_slots BETWEEN 0 AND 12),
external_url TEXT, -- the Substack home, for its button
external_label TEXT, -- null → 'Read more on Substack'
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
INSERT INTO community_page (id) VALUES ('community');
CREATE TABLE community_page_pinned_posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id TEXT NOT NULL REFERENCES community_page (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
post_id TEXT NOT NULL REFERENCES blog_posts (id) ON DELETE CASCADE,
UNIQUE (page_id, post_id)
) STRICT;
CREATE TABLE community_page_feeds (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id TEXT NOT NULL REFERENCES community_page (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
url TEXT NOT NULL, -- 'https://ngu.substack.com/feed'
label TEXT -- shown on its items; else the feed's own title
) STRICT;
-- ── content_blocks: add 'blog_post' ───────────────────────────
CREATE TABLE content_blocks_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_kind TEXT NOT NULL
CHECK (owner_kind IN ('organization', 'event', 'person', 'team', 'blog_post')),
owner_id TEXT NOT NULL,
slot TEXT NOT NULL DEFAULT 'body' CHECK (slot IN ('card', 'body')),
sort_order INTEGER NOT NULL DEFAULT 0,
type TEXT NOT NULL
CHECK (type IN ('heading', 'subheading', 'paragraph',
'list', 'links', 'quote', 'image', 'divider')),
text TEXT,
media TEXT,
href TEXT
) STRICT;
INSERT INTO content_blocks_new (id, owner_kind, owner_id, slot, sort_order, type, text, media, href)
SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href
FROM content_blocks;
PRAGMA legacy_alter_table = ON;
DROP TABLE content_blocks;
ALTER TABLE content_blocks_new RENAME TO content_blocks;
PRAGMA legacy_alter_table = OFF;
CREATE INDEX content_blocks_owner_idx
ON content_blocks (owner_kind, owner_id, slot, sort_order);
-- ── featured_cards: add 'community_page' ──────────────────────
CREATE TABLE featured_cards_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_kind TEXT NOT NULL CHECK (owner_kind IN ('front_page', 'community_page')),
owner_id TEXT NOT NULL,
sort_order INTEGER NOT NULL DEFAULT 0,
kind TEXT NOT NULL DEFAULT 'link'
CHECK (kind IN ('record', 'link', 'video')),
ref_kind TEXT CHECK (ref_kind IN ('event', 'organization', 'person', 'team', 'award')),
ref_id TEXT,
url TEXT,
eyebrow TEXT,
title TEXT,
blurb TEXT,
image TEXT,
CHECK ((ref_kind IS NULL) = (ref_id IS NULL)),
CONSTRAINT "A record card needs a record to point at."
CHECK (kind != 'record' OR ref_kind IS NOT NULL),
CONSTRAINT "A link or video card needs a URL."
CHECK (kind = 'record' OR url IS NOT NULL)
) STRICT;
INSERT INTO featured_cards_new
(id, owner_kind, owner_id, sort_order, kind, ref_kind, ref_id, url, eyebrow, title, blurb, image)
SELECT id, owner_kind, owner_id, sort_order, kind, ref_kind, ref_id, url, eyebrow, title, blurb, image
FROM featured_cards;
PRAGMA legacy_alter_table = ON;
DROP TABLE featured_cards;
ALTER TABLE featured_cards_new RENAME TO featured_cards;
PRAGMA legacy_alter_table = OFF;
CREATE INDEX featured_cards_owner_idx ON featured_cards (owner_kind, owner_id, sort_order);
-- ── Triggers last (see CLAUDE.md, Migrations) ──
CREATE TRIGGER content_blocks_owner_exists
BEFORE INSERT ON content_blocks
BEGIN
SELECT CASE
WHEN new.owner_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such event')
WHEN new.owner_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such organization')
WHEN new.owner_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such person')
WHEN new.owner_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such team')
WHEN new.owner_kind = 'blog_post'
AND NOT EXISTS (SELECT 1 FROM blog_posts WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such blog post')
END;
END;
CREATE TRIGGER featured_cards_ref_exists
BEFORE INSERT ON featured_cards
BEGIN
SELECT CASE
WHEN new.ref_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such event')
WHEN new.ref_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such organization')
WHEN new.ref_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such person')
WHEN new.ref_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such team')
WHEN new.ref_kind = 'award'
AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such award')
END;
END;
CREATE TRIGGER featured_cards_ref_exists_update
BEFORE UPDATE OF ref_kind, ref_id ON featured_cards
BEGIN
SELECT CASE
WHEN new.ref_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such event')
WHEN new.ref_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such organization')
WHEN new.ref_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such person')
WHEN new.ref_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such team')
WHEN new.ref_kind = 'award'
AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such award')
END;
END;
CREATE TRIGGER blog_posts_cleanup
AFTER DELETE ON blog_posts
BEGIN
DELETE FROM content_blocks WHERE owner_kind = 'blog_post' AND owner_id = old.id;
END;
CREATE TRIGGER blog_posts_touch
AFTER UPDATE ON blog_posts
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE blog_posts SET updated_at = datetime('now') WHERE id = new.id;
END;
CREATE TRIGGER community_page_touch
AFTER UPDATE ON community_page
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE community_page SET updated_at = datetime('now') WHERE id = new.id;
END;

View file

@ -1,198 +0,0 @@
/* ═══════════════════════════════════════════════════════════════
BLOG ROUTES: read-only, mounted under /api
GET /blog/:id one published post, its body and authors
GET /community-blog the Community page's blog section
A post is public once published. Unlisted (is_listed = 0) keeps
its page but leaves it out of the section's "newest", though it
can still be pinned there: pinning is attaching it by hand.
The section has two halves, each pinned first and then newest,
up to its slot count (pinned posts always show, even past it):
internal blog_posts
external featured cards owned by the community page, then
items from its RSS/Atom feeds (feeds.js), skipping
any URL a pinned card already shows. Shaped as
featured cards, so FeaturedCards.tsx draws both.
Authors are published people, in order, and/or the post's guest
name. An author who is unpublished is left off rather than
named, the same as on every roster.
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { asBool, loadBlocks, loadFeaturedCards, paragraphs } from "../shape.js";
import { readFeeds } from "../feeds.js";
const blog = new Hono();
const CACHE = "public, max-age=60, stale-while-revalidate=300";
const json = (c, body) => c.json(body, 200, { "Cache-Control": CACHE });
const marks = (n) => Array(n).fill("?").join(",");
const PAGE_ID = "community";
const splitTags = (tags) =>
(tags ?? "")
.split(",")
.map((tag) => tag.trim())
.filter(Boolean);
/* Published authors for a batch of posts, keyed by post id. */
function loadAuthors(db, ids) {
const byPost = new Map();
if (ids.length === 0) return byPost;
const rows = db
.prepare(
`SELECT a.post_id, p.id, p.display_name, p.pronouns, p.tagline, p.photo
FROM blog_post_authors a
JOIN people p ON p.id = a.person_id AND p.is_published = 1
WHERE a.post_id IN (${marks(ids.length)})
ORDER BY a.post_id, a.sort_order`,
)
.all(...ids);
for (const row of rows) {
const list = byPost.get(row.post_id) ?? [];
list.push({
id: row.id,
name: row.display_name,
pronouns: row.pronouns,
tagline: row.tagline,
photo: row.photo,
});
byPost.set(row.post_id, list);
}
return byPost;
}
function shapeSummary(row, authors, body) {
return {
id: row.id,
title: row.title,
// The card's text: the excerpt, else the body's first paragraph.
excerpt: row.excerpt || paragraphs(body)[0] || null,
cover_image: row.cover_image,
published_on: row.published_on,
tags: splitTags(row.tags),
authors: [
...authors.map((a) => ({ id: a.id, name: a.name })),
...(row.guest_author ? [{ id: null, name: row.guest_author }] : []),
],
};
}
/* ── One post ──────────────────────────────────────────────── */
blog.get("/blog/:id", (c) => {
const db = c.get("db");
const id = c.req.param("id");
const row = db.prepare(`SELECT * FROM blog_posts WHERE id = ? AND is_published = 1`).get(id);
if (!row) return c.json({ error: "No such post" }, 404);
const authors = loadAuthors(db, [id]).get(id) ?? [];
const body = loadBlocks(db, "blog_post", [id], "body").get(id) ?? [];
return json(c, {
post: {
id: row.id,
title: row.title,
excerpt: row.excerpt,
cover_image: row.cover_image,
published_on: row.published_on,
tags: splitTags(row.tags),
authors,
guest: row.guest_author ? { name: row.guest_author, photo: row.guest_photo } : null,
blocks: body,
is_listed: asBool(row.is_listed),
},
});
});
/* ── The Community page's section ──────────────────────────── */
blog.get("/community-blog", async (c) => {
const db = c.get("db");
const page = db.prepare(`SELECT * FROM community_page WHERE id = ?`).get(PAGE_ID);
if (!page) return c.json({ error: "The community page hasn't been set up." }, 500);
// Ours: pinned, then newest.
const pinned = db
.prepare(
`SELECT b.*
FROM community_page_pinned_posts pp
JOIN blog_posts b ON b.id = pp.post_id AND b.is_published = 1
WHERE pp.page_id = ?
ORDER BY pp.sort_order`,
)
.all(PAGE_ID);
const room = Math.max(0, page.internal_slots - pinned.length);
const pinnedIds = pinned.map((row) => row.id);
const newest = room
? db
.prepare(
`SELECT * FROM blog_posts
WHERE is_published = 1 AND is_listed = 1
${pinnedIds.length ? `AND id NOT IN (${marks(pinnedIds.length)})` : ""}
ORDER BY published_on IS NULL, published_on DESC, created_at DESC
LIMIT ?`,
)
.all(...pinnedIds, room)
: [];
const posts = [...pinned, ...newest];
const ids = posts.map((row) => row.id);
const authors = loadAuthors(db, ids);
const bodies = loadBlocks(db, "blog_post", ids, "body");
// Theirs: pinned cards, then the feeds' newest.
const cards = loadFeaturedCards(db, "community_page", PAGE_ID);
const feedRows = db
.prepare(`SELECT url, label FROM community_page_feeds WHERE page_id = ? ORDER BY sort_order`)
.all(PAGE_ID);
const shown = new Set(cards.map((card) => card.url).filter(Boolean));
const spare = Math.max(0, page.external_slots - cards.length);
const fromFeeds = spare && feedRows.length ? await readFeeds(feedRows) : [];
const latest = fromFeeds
.filter((item) => !shown.has(item.url))
.slice(0, spare)
.map((item) => ({
kind: "link",
ref: null,
url: item.url,
eyebrow: item.source,
title: item.title,
blurb: item.excerpt,
image: item.image ? { file: item.image, kind: "featured" } : null,
published: item.published,
}));
return json(c, {
community_blog: {
title: page.blog_title,
blurb: page.blog_blurb,
internal: {
title: page.internal_title,
posts: posts.map((row) =>
shapeSummary(row, authors.get(row.id) ?? [], bodies.get(row.id) ?? []),
),
},
external: {
title: page.external_title,
url: page.external_url,
label: page.external_label,
cards: [...cards, ...latest],
},
},
});
});
export default blog;

View file

@ -18,7 +18,6 @@
teams published, and so is the organization
awards published
people published
blog_posts published
and each leaves out unlisted records (is_listed = 0): the QR page
is public, and listing them here would undo the point of them.
@ -71,12 +70,6 @@ directory.get("/directory", (c) => {
WHERE is_published = 1 AND is_listed = 1
ORDER BY COALESCE(sort_name, display_name)`,
),
blog_posts: all(
`SELECT id, title AS name
FROM blog_posts
WHERE is_published = 1 AND is_listed = 1
ORDER BY published_on IS NULL, published_on DESC, title`,
),
},
},
200,

View file

@ -25,7 +25,6 @@ import OrganizationDetail from './pages/OrganizationDetail.tsx'
import TeamDetail from './pages/TeamDetail.tsx'
import AwardDetail from './pages/AwardDetail.tsx'
import PersonDetail from './pages/PersonDetail.tsx'
import BlogPost from './pages/BlogPost.tsx'
/*Admin Pages*/
import AdminLayout from "./pages/admin/AdminLayout.tsx";
@ -62,7 +61,6 @@ export default function App() {
<Route path="/teams/:id" element={<TeamDetail />} />
<Route path="/awards/:id" element={<AwardDetail />} />
<Route path="/people/:id" element={<PersonDetail />} />
<Route path="/blog/:id" element={<BlogPost />} />
<Route path="leadership" element={<Leadership />} />
<Route path="resources" element={<Resources />} />
<Route path="history" element={<History />} />

View file

@ -21,7 +21,6 @@ import {
awardLogo,
blockMedia,
eventBackground,
blogImage,
eventLogo,
featuredImage,
heroPhoto,
@ -1300,181 +1299,6 @@ const frontPage = {
],
};
/* ── Blog (031_blog.sql) ─────────────────────────────────────────
Posts at /blog/:id, and the Community page's blog section. The
section's community posts reuse the featured cards, limited to
links: a pinned Substack post is a link card, and Fetch preview
fills it from the post. */
/* A post's body is the content blocks without the card/body choice:
a post only has a body. */
const blogBlocksChild = {
...blocksChild,
label: "Post body",
note: "The post, top to bottom. The first paragraph doubles as the excerpt when that's left blank.",
fields: blocksChild.fields.filter((field) => field.path !== "slot"),
};
const blogPosts = {
key: "blog_posts",
label: "Blog posts",
singular: "blog post",
idLabel: "URL ID",
slugFrom: "title",
list: {
columns: [
{ key: "title", label: "Title", primary: true },
{ key: "published_on", label: "Date" },
{ key: "tags", label: "Tags" },
{ key: "is_published", label: "Live", widget: "bool" },
{ key: "is_listed", label: "Listed", widget: "bool" },
],
filters: [
{ key: "is_published", label: "Published", options: [["1", "Live"], ["0", "Draft"]] },
{ key: "is_listed", label: "Listed", options: [["1", "Listed"], ["0", "Link only"]] },
],
},
groups: [
{
legend: "Post",
fields: [
{ path: "title", label: "Title", required: true, full: true },
{ path: "published_on", label: "Date", widget: "date", help: "Newest first on the Community page" },
{ path: "tags", label: "Tags", help: "Comma separated, eg. Reflection, Event recap" },
{
path: "excerpt",
label: "Excerpt",
widget: "textarea",
full: true,
help: "A sentence or two for the card. Default: the body's first paragraph.",
},
{ path: "cover_image", label: "Cover image", widget: "image", resolve: blogImage, full: true },
],
},
{
legend: "Guest author",
note: "For a writer with no People record. People who wrote it go under Authors below; both can be set.",
fields: [
{ path: "guest_author", label: "Name" },
{ path: "guest_photo", label: "Photo", widget: "image", resolve: blogImage, full: true },
],
},
{
legend: "Publishing",
note: "A new post is a draft until Published is ticked. Unlisted posts keep their page and can still be pinned.",
fields: [PUBLISHED_FIELD, LISTED_FIELD],
},
],
children: [
{
key: "authors",
label: "Authors",
note: "Shown as person tiles at the end of the post, in this order.",
addLabel: "Add author",
title: (row, options) =>
options?.people?.find((p) => p.id === row.person_id)?.label ?? "New author",
blank: { person_id: "" },
fields: [
{
path: "person_id",
label: "Person",
widget: "select",
optionsFrom: "people",
required: true,
},
],
},
blogBlocksChild,
],
};
const communityPage = {
key: "community_page",
label: "Community blog section",
singular: "community blog section",
idLabel: "Page",
singleton: "community",
list: { columns: [], filters: [] },
groups: [
{
legend: "Section",
note: "The first section of the Community page.",
fields: [
{ path: "blog_title", label: "Heading", help: "Default: Community Blog" },
{ path: "blog_blurb", label: "Blurb", widget: "textarea", full: true },
],
},
{
legend: "Our posts",
note: "Pinned posts first, then the newest published, listed posts, up to the number of slots.",
fields: [
{ path: "internal_title", label: "Heading", help: "Default: From NGU" },
{ path: "internal_slots", label: "Slots", widget: "number", help: "0 to 12. Default: 3" },
],
},
{
legend: "Community posts",
note: "Pinned cards first, then the newest items from the feeds below, up to the number of slots.",
fields: [
{ path: "external_title", label: "Heading", help: "Default: From our community" },
{ path: "external_slots", label: "Slots", widget: "number", help: "0 to 12. Default: 3" },
{ path: "external_url", label: "Button link", help: "eg. https://ngu.substack.com", full: true },
{ path: "external_label", label: "Button text", help: "Default: Read more on Substack" },
],
},
],
children: [
{
key: "pinned_posts",
label: "Pinned posts (ours)",
note: "Always shown, before the newest.",
addLabel: "Pin a post",
title: (row, options) =>
options?.blog_posts?.find((p) => p.id === row.post_id)?.label ?? "New pin",
blank: { post_id: "" },
fields: [
{
path: "post_id",
label: "Post",
widget: "select",
optionsFrom: "blog_posts",
required: true,
},
],
},
{
...featuredCardsChild,
label: "Pinned community posts",
note: "Always shown, before the feeds' newest. Paste a post's link and press Fetch preview.",
addLabel: "Pin a post",
blank: { kind: "", url: "", title: "" },
fields: featuredCardsChild.fields.map((field) =>
field.path === "kind"
? { ...field, options: FEATURED_KINDS.filter(([kind]) => kind !== "record") }
: field,
),
},
{
key: "feeds",
label: "Feeds",
note: "RSS or Atom feeds whose newest posts fill the community slots. Read about every 30 minutes.",
addLabel: "Add feed",
title: (row) => row.label || row.url || "New feed",
blank: { url: "", label: "" },
fields: [
{ path: "url", label: "Feed URL", required: true, full: true, help: "eg. https://ngu.substack.com/feed" },
{ path: "label", label: "Source name", help: "Shown on its cards. Default: the feed's own title" },
],
},
],
};
export const ADMIN_ENTITIES: Record<string, any> = {
organizations,
events,
@ -1483,8 +1307,6 @@ export const ADMIN_ENTITIES: Record<string, any> = {
awards,
timeline,
front_page: frontPage,
blog_posts: blogPosts,
community_page: communityPage,
};
export function slugify(value) {

View file

@ -116,8 +116,6 @@ export const awardHref = (id?: string | null) => `/awards/${checkId(id, 'awardHr
export const personHref = (id?: string | null) => `/people/${checkId(id, 'personHref')}`
export const blogHref = (id?: string | null) => `/blog/${checkId(id, 'blogHref')}`
export function orgHref(id?: string | null, kind?: string | null): string {
return `${ORG_BASE[kind ?? ''] ?? '/organizations'}/${checkId(id, 'orgHref')}`
}
@ -165,9 +163,9 @@ export const ORG_KIND_LABEL: Record<string, string> = {
export function orgListHref(kind?: string | null): { to: string; label: string } {
switch (kind) {
case 'region':
return { to: '/community#regions', label: 'All regions' }
return { to: '/community#local', label: 'All regions' }
case 'chapter':
return { to: '/community#chapters', label: 'All chapters' }
return { to: '/community#local', label: 'All chapters' }
case 'partner':
return { to: '/community#partners', label: 'All partner organizations' }
default:

View file

@ -52,9 +52,6 @@ export const blockMedia = inDir('/media') // ⚠ guess
('/uploads/…'); a bare filename looks here. */
export const featuredImage = inDir('/featured')
/* blog_posts.cover_image and guest_photo. Normally uploads. */
export const blogImage = inDir('/blog')
/* ── By record kind ────────────────────────────────────────────
The timeline sends `logo: { file, kind }` rather than a path,
because v_timeline COALESCEs across five tables and only the

View file

@ -1,71 +0,0 @@
/* ═══════════════════════════════════════════════════════════════
BLOG DATA
GET /blog/:id and GET /community-blog, as routes/blog.js shapes
them. The section's community posts arrive as featured cards, so
FeaturedCards.tsx draws them unchanged.
═══════════════════════════════════════════════════════════════ */
import { detailPath } from './hrefs.ts'
import { useRecord, type Resource } from './useRecord.ts'
import type { ContentBlock } from './useContent.ts'
import type { FeaturedCard } from './useFrontPage.ts'
export type BlogAuthor = {
id: string
name: string
pronouns?: string | null
tagline?: string | null
photo?: string | null
}
export type BlogPostRecord = {
id: string
title: string
excerpt?: string | null
cover_image?: string | null
published_on?: string | null
tags: string[]
authors: BlogAuthor[]
guest: { name: string; photo?: string | null } | null
blocks: ContentBlock[]
is_listed: boolean
}
/** A post on the Community page's section. `id` is null on a guest. */
export type BlogPostSummary = {
id: string
title: string
excerpt?: string | null
cover_image?: string | null
published_on?: string | null
tags: string[]
authors: Array<{ id: string | null; name: string }>
}
export type CommunityBlog = {
title?: string | null
blurb?: string | null
internal: { title?: string | null; posts: BlogPostSummary[] }
external: {
title?: string | null
url?: string | null
label?: string | null
cards: FeaturedCard[]
}
}
export const useBlogPost = (id?: string | null): Resource<BlogPostRecord> =>
useRecord<BlogPostRecord>(detailPath('/blog', id), 'post')
export const useCommunityBlog = (): Resource<CommunityBlog> =>
useRecord<CommunityBlog>('/community-blog', 'community_blog')
/** '2026-09-01' → 'September 1, 2026'. Parsed as a local date, so
* it can't slip a day in a timezone west of UTC. */
export function postDate(value?: string | null): string | null {
const match = value?.match(/^(\d{4})-(\d{2})-(\d{2})/)
if (!match) return null
const date = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]))
return date.toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' })
}

View file

@ -351,7 +351,6 @@ export type Directory = {
teams: Array<DirectoryEntry & { org_name: string }>
awards: DirectoryEntry[]
people: DirectoryEntry[]
blog_posts: DirectoryEntry[]
}
export const useDirectory = (): Resource<Directory> =>

View file

@ -26,9 +26,8 @@ export const PAGE_SECTIONS = {
{ label: "Partner Events", hash: "#partner"},
],
"/community": [
{ label: "Community Blog", hash: "#blog" },
{ label: "Local Chapters", hash: "#chapters" },
{ label: "Unity Regions", hash: "#regions" },
{ label: "Local Chapters", hash: "#local" },
{ label: "Virtual Community", hash: "#virtual" },
{ label: "Partner Organizations", hash: "#partners" },
],
"/leadership": [

View file

@ -1,114 +0,0 @@
/* ═══════════════════════════════════════════════════════════════
BLOG POST: /blog/:id
One of our own posts: cover, date and tags, the content-block
body, then its authors as person tiles. Authors are published
people (linked to their pages) and, when the post names one, a
guest with no people record (a tile that links nowhere).
There's no /blog index on purpose: the Community page's blog
section is where posts are listed, so "back" goes there.
═══════════════════════════════════════════════════════════════ */
import { Link, useParams } from 'react-router-dom'
import PageShell, { type ShellSection } from '../components/PageShell.tsx'
import PageState from '../components/PageState.tsx'
import ContentBlocks from '../components/ContentBlocks.tsx'
import PeopleTiles from '../components/PeopleTiles.tsx'
import { blogImage, personPhoto } from '../lib/media.ts'
import { postDate, useBlogPost } from '../lib/useBlog.ts'
const ACCENT = '#138ba0'
const BODY = '#4a6b72'
/* Where "back" goes: the section on the Community page. */
const BACK = { to: '/community#blog', label: 'Community Blog' }
export default function BlogPost() {
const { id } = useParams()
const { data: post, loading, error, notFound, reload } = useBlogPost(id)
if (!post) {
return (
<PageState
loading={loading}
error={error}
notFound={notFound}
onRetry={reload}
noun="post"
backTo={BACK.to}
backLabel={BACK.label}
/>
)
}
const date = postDate(post.published_on)
const cover = blogImage(post.cover_image)
const byline = [
...post.authors.map((author) => author.name),
...(post.guest ? [post.guest.name] : []),
].join(', ')
const authors = [
...post.authors.map((author) => ({
id: author.id,
name: author.name,
tagline: author.tagline,
pronouns: author.pronouns,
photo: personPhoto(author.photo),
})),
...(post.guest ? [{ name: post.guest.name, title: 'Guest author', photo: blogImage(post.guest.photo) }] : []),
]
const sections: ShellSection[] = [
{
id: 'post',
title: 'Post',
accent: ACCENT,
background: '#ffffff',
content: (
<article className="mx-auto max-w-3xl space-y-8 px-6">
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-sm" style={{ color: BODY }}>
{date && <time dateTime={post.published_on ?? undefined}>{date}</time>}
{byline && <span>By {byline}</span>}
{post.tags.map((tag) => (
<span
key={tag}
className="rounded-full px-3 py-0.5 text-xs font-semibold"
style={{ background: '#eef9fb', color: ACCENT }}
>
{tag}
</span>
))}
<Link to={BACK.to} className="ml-auto hover:underline" style={{ color: ACCENT }}>
{BACK.label}
</Link>
</div>
{cover && (
<img src={cover} alt="" className="aspect-video w-full rounded-2xl object-cover" />
)}
<ContentBlocks blocks={post.blocks} accent={ACCENT} />
</article>
),
},
]
if (authors.length > 0) {
sections.push({
id: 'authors',
title: authors.length === 1 ? 'About the author' : 'About the authors',
accent: ACCENT,
background: '#eef9fb',
content: (
<div className="mx-auto max-w-6xl px-6">
<PeopleTiles size="md" accent={ACCENT} people={authors} />
</div>
),
})
}
return <PageShell title={post.title} intro={post.excerpt ?? undefined} sections={sections} />
}

View file

@ -3,23 +3,15 @@ import { useSectionManifest } from "../lib/sections.tsx";
import OrgListMap, { OrgMapToggle } from "./sections/OrgList-Map.tsx";
import OrgListVertical from "./sections/OrgList-Vertical.tsx";
import OrgListCards from "./sections/OrgList-Card.tsx";
import CommunityBlog from "./sections/CommunityBlog.tsx";
import { useCommunityBlog } from "../lib/useBlog.ts";
/* ═══════════════════════════════════════════════════════════════
COMMUNITY PAGE
The blog first, then two views of the organizations table. The
map is filtered to chapters; the vertical list is filtered to
regions. Same rows, same endpoint, different shape on the page.
The blog's heading and blurb are the admin's (Blog → Community
section), so that one entry is built here from the same cached
request CommunityBlog makes for its posts.
Two views of the organizations table. The map is filtered to
chapters; the vertical list is filtered to regions. Same rows,
same endpoint, different shape on the page.
═══════════════════════════════════════════════════════════════ */
const BLOG_DEFAULT_TITLE = "Community Blog";
const SECTIONS = [
{
id: "chapters",
@ -66,19 +58,7 @@ const SECTIONS = [
];
export default function CommunityPage() {
const { data: blog } = useCommunityBlog();
const sections = useSectionManifest([
{
id: "blog",
title: blog?.title || BLOG_DEFAULT_TITLE,
blurb: blog?.blurb ?? undefined,
accent: "#138ba0",
background: "#ffffff",
Component: CommunityBlog,
},
...SECTIONS,
]);
const sections = useSectionManifest(SECTIONS);
return (
<PageShell

View file

@ -15,7 +15,7 @@ const SECTIONS = [
id: 'make',
title: 'Make a QR code',
blurb:
'Pick a page from the main navigation, or any event, organization, team, award, person or blog post on the site. The code always points at the live site.',
'Pick a page from the main navigation, or any event, organization, team, award or person on the site. The code always points at the live site.',
accent: '#138ba0',
background: '#eef9fb',
content: (

View file

@ -70,17 +70,6 @@ export const CMS_NAV = [
label: "Front page",
blurb: "The hero, its photos or livestream, and which bands the home page draws.",
},
// Posts, and the Community page section that lists them. Two
// entities, one tab, like Organizations with Teams and Awards.
{
to: "/admin/blog_posts",
label: "Blog",
blurb: "Posts of our own, and the Community page's blog section.",
children: [
{ to: "/admin/blog_posts", label: "Posts" },
{ to: "/admin/community_page", label: "Community section" },
],
},
// Not an entity: the uploaded-image library every image field
// picks from. Its own page, AdminMedia.tsx.
{

View file

@ -1,145 +0,0 @@
/* ═══════════════════════════════════════════════════════════════
COMMUNITY BLOG
The Community page's blog section (Admin → Blog → Community
section). Two halves, each pinned first and then newest, as
routes/blog.js decides:
our posts cards for our own /blog/:id pages
community posts featured cards (pinned by hand, or the
newest from the listed feeds), drawn by
FeaturedCards, with a button to the Substack
The section's heading and blurb come from the same record; the
page reads them through the same cached request (Community.tsx).
A half with nothing in it isn't drawn.
═══════════════════════════════════════════════════════════════ */
import { Link } from 'react-router-dom'
import FeaturedCards from '../../components/FeaturedCards.tsx'
import PlatformIcon from '../../components/PlatformIcon.tsx'
import { blogHref } from '../../lib/hrefs.ts'
import { blogImage } from '../../lib/media.ts'
import { preview } from '../../lib/text.ts'
import { postDate, useCommunityBlog, type BlogPostSummary } from '../../lib/useBlog.ts'
import HomeLink from './home/HomeLink.tsx'
/* Headings for a half the admin didn't title. */
const DEFAULTS = {
internal: 'From NGU',
external: 'From our community',
externalLabel: 'Read more on Substack',
}
const EXCERPT_CHARS = 180
function PostCard({ post, accent }: { post: BlogPostSummary; accent: string }) {
const cover = blogImage(post.cover_image)
const date = postDate(post.published_on)
const authors = post.authors.map((author) => author.name).join(', ')
return (
<li className="relative flex flex-col overflow-hidden rounded-2xl border border-[#138ba0]/15 bg-white shadow-sm transition-shadow hover:shadow-lg">
{cover ? (
<img src={cover} alt="" loading="lazy" className="aspect-video w-full object-cover" />
) : (
<div className="aspect-video w-full bg-gradient-to-br from-[#eef9fb] to-[#d9f0f3]" />
)}
<div className="flex flex-1 flex-col p-6">
{(date || post.tags.length > 0) && (
<p className="text-xs font-bold uppercase tracking-[0.2em]" style={{ color: accent }}>
{[date, ...post.tags].filter(Boolean).join(' · ')}
</p>
)}
<h4 className="mt-2 font-display text-xl font-extrabold leading-snug text-[#073d4a]">
<Link
to={blogHref(post.id)}
className="after:absolute after:inset-0 after:rounded-2xl after:content-[''] hover:underline"
>
{post.title}
</Link>
</h4>
{post.excerpt && (
<p className="mt-2 leading-relaxed text-[#4a6b72]">{preview(post.excerpt, EXCERPT_CHARS)}</p>
)}
{authors && <p className="mt-auto pt-4 text-sm font-medium text-[#26454c]">By {authors}</p>}
</div>
</li>
)
}
function Subheading({ children, accent }: { children: string; accent: string }) {
return (
<h3 className="text-2xl font-800" style={{ color: accent }}>
{children}
</h3>
)
}
export default function CommunityBlog({ accent = '#138ba0' }: { accent?: string }) {
const { data: blog, loading, error, reload } = useCommunityBlog()
if (!blog) {
return (
<div className="mx-auto max-w-6xl px-6 text-[#4a6b72]">
{loading ? (
'Loading…'
) : (
<>
Couldn’t load the blog. {error}{' '}
<button type="button" onClick={reload} className="underline" style={{ color: accent }}>
Try again
</button>
</>
)}
</div>
)
}
const { internal, external } = blog
const hasInternal = internal.posts.length > 0
const hasExternal = external.cards.length > 0 || Boolean(external.url)
if (!hasInternal && !hasExternal) {
return <p className="mx-auto max-w-6xl px-6 text-center text-[#4a6b72]">· Posts coming soon ·</p>
}
return (
<div className="mx-auto max-w-6xl space-y-16 px-6">
{hasInternal && (
<div>
<Subheading accent={accent}>{internal.title || DEFAULTS.internal}</Subheading>
<ul className="mt-6 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
{internal.posts.map((post) => (
<PostCard key={post.id} post={post} accent={accent} />
))}
</ul>
</div>
)}
{hasExternal && (
<div>
<div className="flex flex-wrap items-end gap-4">
<Subheading accent={accent}>{external.title || DEFAULTS.external}</Subheading>
{external.url && (
<HomeLink
url={external.url}
className="ml-auto inline-flex items-center gap-2 rounded-full px-5 py-2 text-sm font-semibold text-white transition-transform hover:scale-105"
style={{ background: accent }}
>
<PlatformIcon platform={/substack\.com/i.test(external.url) ? 'substack' : null} />
{external.label || DEFAULTS.externalLabel}
</HomeLink>
)}
</div>
{external.cards.length > 0 && (
<div className="mt-6">
<FeaturedCards cards={external.cards} />
</div>
)}
</div>
)}
</div>
)
}

View file

@ -24,7 +24,7 @@ import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import QrCode from '../../components/QrCode.tsx'
import { NAV_ACTIONS, PAGE_LINKS, PAGE_SECTIONS } from '../../navConfig.ts'
import { awardHref, blogHref, eventHref, orgHref, personHref, teamHref } from '../../lib/hrefs.ts'
import { awardHref, eventHref, orgHref, personHref, teamHref } from '../../lib/hrefs.ts'
import { siteUrl } from '../../lib/site.ts'
import { useDirectory, type Directory } from '../../lib/useContent.ts'
@ -35,7 +35,7 @@ const MUTED = '#4a6b72'
anything bigger should use the SVG. */
const PNG_SIZE = 1024
type Kind = 'pages' | 'events' | 'organizations' | 'teams' | 'awards' | 'people' | 'blog_posts'
type Kind = 'pages' | 'events' | 'organizations' | 'teams' | 'awards' | 'people'
const KINDS: Array<[Kind, string]> = [
['pages', 'Main navigation'],
@ -44,7 +44,6 @@ const KINDS: Array<[Kind, string]> = [
['teams', 'Teams'],
['awards', 'Awards'],
['people', 'People'],
['blog_posts', 'Blog posts'],
]
/* Organizations are grouped by kind in the dropdown, in this order. */
@ -107,8 +106,6 @@ function groupsFor(kind: Kind, directory: Directory | null): Group[] {
return [{ choices: directory.awards.map((a) => ({ path: awardHref(a.id), label: a.name })) }]
case 'people':
return [{ choices: directory.people.map((p) => ({ path: personHref(p.id), label: p.name })) }]
case 'blog_posts':
return [{ choices: directory.blog_posts.map((b) => ({ path: blogHref(b.id), label: b.name })) }]
}
}