NGU-Web/server/src/shape.js
Zaldimmar f46deac3cc Image block: a dark theme picture; presented pictures centered
- media_dark (102): shown in place of the image while the site is
  dark, the block's alt text and caption shared
- Present: pictures beside text centered on the slide's height, and a
  section of only pictures centered both ways

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 06:40:40 -06:00

622 lines
25 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
SHAPE
Blocks and links are polymorphic: any organization, event, person
or team can own them. Every list endpoint therefore needs the
same move, fetch the parent rows, then fetch all their children
in one query each and stitch.
The alternative is a query per row, which at a dozen events is
invisible and at two hundred is not. Three queries is three
queries whatever the row count, so it may as well be right now.
One limit worth knowing: SQLite caps bound parameters per
statement (999 on older builds). If a list ever exceeds that,
these need chunking. Nothing here comes close.
═══════════════════════════════════════════════════════════════ */
const placeholders = (n) => Array(n).fill("?").join(",");
const asBool = (value) => value === 1;
/* ── Links ─────────────────────────────────────────────────────
Map of owner_id → links, in sort order.
───────────────────────────────────────────────────────────── */
export function loadLinks(db, ownerKind, ids) {
const out = new Map();
if (ids.length === 0) return out;
// A person who took their links off the site (people.hide_links,
// 076) has none here.
const rows = db
.prepare(
`SELECT owner_id, kind, platform, label, url, is_primary
FROM links
WHERE owner_kind = ? AND owner_id IN (${placeholders(ids.length)})
AND NOT (owner_kind = 'person' AND owner_id IN (SELECT id FROM people WHERE hide_links = 1))
ORDER BY owner_id, sort_order`,
)
.all(ownerKind, ...ids);
for (const row of rows) {
const link = {
kind: row.kind,
platform: row.platform,
label: row.label,
url: row.url,
is_primary: asBool(row.is_primary),
};
const list = out.get(row.owner_id);
if (list) list.push(link);
else out.set(row.owner_id, [link]);
}
return out;
}
/* ── Blocks ────────────────────────────────────────────────────
Map of owner_id → blocks for one slot, items attached. A
"both" block (071) is in the card's and the body's.
Two queries: the blocks, then every item belonging to them.
Blocks with no children come back with an empty items array
rather than no key, so the renderer never has to check.
───────────────────────────────────────────────────────────── */
/* A block's presentation settings (095), or null with none set. */
function presentOf(row) {
const present = {
// Where it shows (099).
hide: row.present_show === "page",
only: row.present_show === "presentation",
text: row.present_text,
map_split: row.present_map_split === 1,
map_no_list: row.present_map_no_list === 1,
map_no_details: row.present_map_no_details === 1,
places: row.present_places,
place_keys: row.present_place_keys ? row.present_place_keys.split(",").filter(Boolean) : [],
};
return Object.values(present).some((value) => (Array.isArray(value) ? value.length : value)) ? present : null;
}
export function loadBlocks(db, ownerKind, ids, slot = "body", depth = 0) {
const out = new Map();
if (ids.length === 0) return out;
const blockRows = db
.prepare(
`SELECT id, owner_id, type, text, media, media_dark, href, alt, cite, captions, team_id, venue_id,
word_motion, word_direction, word_seconds, list_style, image_size, org_kind,
present_show, present_text, present_map_split, present_map_no_list,
present_map_no_details, present_places, present_place_keys
FROM content_blocks
WHERE owner_kind = ? AND slot IN (?, 'both') AND owner_id IN (${placeholders(ids.length)})
ORDER BY owner_id, sort_order`,
)
.all(ownerKind, slot, ...ids);
if (blockRows.length === 0) return out;
const byId = new Map();
for (const row of blockRows) {
const block = {
type: row.type,
text: row.text,
media: row.media,
media_dark: row.media_dark,
href: row.href,
alt: row.alt,
cite: row.cite,
captions: row.captions,
team_id: row.team_id,
venue_id: row.venue_id,
list_style: row.list_style,
image_size: row.image_size,
org_kind: row.org_kind,
// Its rotating words' motion (084), when it has its own.
words: row.word_motion || row.word_direction || row.word_seconds
? { motion: row.word_motion, direction: row.word_direction, seconds: row.word_seconds }
: null,
// How it's presented (095), when anything is set.
present: presentOf(row),
items: [],
};
byId.set(row.id, block);
const list = out.get(row.owner_id);
if (list) list.push(block);
else out.set(row.owner_id, [block]);
}
const blockIds = [...byId.keys()];
const ENTRY_FIELDS = `i.text, i.detail, i.url, i.start_time, i.end_time, i.time, i.location,
i.description, i.media, i.media_alt, i.map, i.map_image, i.featured, i.tags,
i.event_id, i.location_key,
p.id AS person_id, p.display_name AS person_name,
p.photo AS person_photo, p.tagline AS person_tagline`;
const itemRows = db
.prepare(
`SELECT i.id, i.block_id, i.day, i.kind, i.heading, i.subheading, i.org_id, ${ENTRY_FIELDS}
FROM content_block_items i
LEFT JOIN v_people_public p ON p.id = i.person_id AND p.is_published = 1
WHERE i.block_id IN (${placeholders(blockIds.length)})
ORDER BY i.block_id, i.sort_order`,
)
.all(...blockIds);
// The schedule fields are null on a list or link-row item; they
// ride along anyway rather than branching on the block's type.
const itemsById = new Map();
for (const row of itemRows) {
const item = {
...scheduleEntry(row),
day: row.day,
kind: row.kind ?? "entry",
heading: row.heading,
subheading: row.subheading,
org_id: row.org_id,
items: [],
};
itemsById.set(row.id, item);
byId.get(row.block_id)?.items.push(item);
}
// A block entry's sub-items (086).
const blockEntryIds = itemRows.filter((row) => row.kind === "block").map((row) => row.id);
if (blockEntryIds.length) {
const subRows = db
.prepare(
`SELECT i.item_id, ${ENTRY_FIELDS}
FROM content_block_subitems i
LEFT JOIN v_people_public p ON p.id = i.person_id AND p.is_published = 1
WHERE i.item_id IN (${placeholders(blockEntryIds.length)})
ORDER BY i.item_id, i.sort_order`,
)
.all(...blockEntryIds);
for (const row of subRows) itemsById.get(row.item_id)?.items.push(scheduleEntry(row));
}
// A schedule's own tags (087), and each entry's cut to the ones
// the block still has.
const tagRows = db
.prepare(
`SELECT block_id, tag_key, name, color, no_tab
FROM content_block_tags
WHERE block_id IN (${placeholders(blockIds.length)})
ORDER BY block_id, sort_order`,
)
.all(...blockIds);
for (const row of tagRows) {
const block = byId.get(row.block_id);
if (!block) continue;
block.tags ??= [];
block.tags.push({ key: row.tag_key, name: row.name, color: row.color, tab: row.no_tab === 0 });
}
for (const block of byId.values()) {
if (block.type !== "schedule") continue;
const known = new Set((block.tags ??= []).map((tag) => tag.key));
const cut = (entry) => {
entry.tags = entry.tags.filter((key) => known.has(key));
entry.items?.forEach(cut);
};
block.items.forEach(cut);
}
attachVenues(db, [...byId.values()]);
attachEvents(db, [...byId.values()], depth);
// A map block's sections (094): each names some of its venue's
// locations. With any, the block's venue is cut to the locations
// they name, in their order, so the page, its schedule's links
// and the presentation all see the same places, numbered alike.
const sectionRows = db
.prepare(
`SELECT block_id, name, location_keys
FROM content_block_map_sections
WHERE block_id IN (${placeholders(blockIds.length)})
ORDER BY block_id, sort_order`,
)
.all(...blockIds);
for (const row of sectionRows) {
const block = byId.get(row.block_id);
if (!block?.venue) continue;
const known = new Set(block.venue.locations.map((location) => location.key));
const keys = (row.location_keys ?? "").split(",").filter((key) => known.has(key));
if (keys.length) (block.map_sections ??= []).push({ name: row.name, keys });
}
for (const block of byId.values()) {
if (!block.map_sections) continue;
const byKey = new Map(block.venue.locations.map((location) => [location.key, location]));
const shown = [...new Set(block.map_sections.flatMap((section) => section.keys))];
block.venue = { ...block.venue, locations: shown.map((key) => byKey.get(key)) };
}
return out;
}
/* A map or schedule block's venue (088), its locations in order,
and each entry's location_key made its place on it: `place` is
the location, and the location's name stands in for a blank
typed Location. A key the venue no longer has is dropped. */
function attachVenues(db, blocks) {
const ids = [...new Set(blocks.map((block) => block.venue_id).filter(Boolean))];
if (ids.length === 0) return;
const venues = new Map(
db
.prepare(`SELECT id, name, address, map_image, map_alt FROM venues WHERE id IN (${placeholders(ids.length)})`)
.all(...ids)
.map((row) => [row.id, { ...row, locations: [] }]),
);
const locationRows = db
.prepare(
`SELECT venue_id, location_key AS key, name, detail, x, y, w, h, google_maps_url, apple_maps_url
FROM venue_locations
WHERE venue_id IN (${placeholders(ids.length)})
ORDER BY venue_id, sort_order`,
)
.all(...ids);
for (const { venue_id, ...location } of locationRows) venues.get(venue_id)?.locations.push(location);
for (const block of blocks) {
const venue = venues.get(block.venue_id);
block.venue = venue ?? null;
const place = (entry) => {
const location = venue?.locations.find((l) => l.key === entry.location_key) ?? null;
entry.place = location ? { venue_id: venue.id, key: location.key, name: location.name } : null;
if (location && !entry.location) entry.location = location.name;
entry.items?.forEach(place);
};
block.items.forEach(place);
}
}
/* The events named by items (088): an events block's cards, and a
schedule entry or sub-item that is a workshop, which takes what
it leaves blank from its event: the link, the description (its
card text), the graphic (its photo) and the person (a person
host). An unpublished event is no event.
An events block's event also brings its own page's blocks
(`blocks`), drawn when its card is opened. Only at the top
(`depth` 0): a workshop's blocks don't bring theirs, so two
events listing each other can't go round forever. */
function attachEvents(db, blocks, depth = 0) {
const entries = [];
const walk = (entry) => {
entries.push(entry);
entry.items?.forEach(walk);
};
blocks.forEach((block) => block.items.forEach(walk));
const ids = [...new Set(entries.map((entry) => entry.event_id).filter(Boolean))];
if (ids.length === 0) return;
const rows = db
.prepare(
`SELECT e.id, e.title, e.tagline, e.event_type, e.starts_on, e.ends_on, e.date_label,
e.effective_color AS color, COALESCE(e.card_image, e.photo) AS image, e.photo, e.photo_alt,
e.location_label,
p.id AS person_id, p.display_name AS person_name, p.photo AS person_photo,
p.tagline AS person_tagline
FROM v_events e
LEFT JOIN v_people_public p ON e.host_kind = 'person' AND p.id = e.host_id AND p.is_published = 1
WHERE e.is_published = 1 AND e.id IN (${placeholders(ids.length)})`,
)
.all(...ids);
const cards = loadBlocks(db, "event", rows.map((row) => row.id), "card");
const events = new Map(rows.map((row) => [row.id, row]));
const shown = blocks.filter((block) => block.type === "events").flatMap((block) => block.items);
const shownIds = [...new Set(shown.map((item) => item.event_id).filter((id) => events.has(id)))];
const bodies = depth === 0 && shownIds.length ? loadBlocks(db, "event", shownIds, "body", depth + 1) : new Map();
for (const entry of entries) {
const row = events.get(entry.event_id);
if (!row) {
entry.event = null;
continue;
}
const blurb = paragraphs(cards.get(row.id) ?? []).join("\n\n") || row.tagline || null;
entry.event = {
id: row.id,
title: row.title,
event_type: row.event_type,
starts_on: row.starts_on,
ends_on: row.ends_on,
date_label: row.date_label,
color: row.color,
image: row.image,
photo: row.photo,
photo_alt: row.photo_alt,
location_label: row.location_label,
blurb,
};
if (shown.includes(entry)) entry.event.blocks = bodies.get(row.id) ?? [];
entry.url ||= `/events/${row.id}`;
entry.description ||= blurb;
if (!entry.media && row.image) {
entry.media = row.image;
entry.media_alt = row.photo_alt;
}
if (!entry.person && row.person_id) {
entry.person = { id: row.person_id, name: row.person_name, photo: row.person_photo, tagline: row.person_tagline };
}
}
}
/* A schedule entry or sub-item as the page gets it. `time` is what
to show: the typed override, else the picked times (086). An
unpublished person comes back as no person. */
function scheduleEntry(row) {
return {
text: row.text,
detail: row.detail,
url: row.url,
time: row.time || clockRange(row.start_time, row.end_time),
start_time: row.start_time,
end_time: row.end_time,
location: row.location,
description: row.description,
media: row.media,
media_alt: row.media_alt,
map: row.map,
map_image: row.map_image,
featured: row.featured === 1,
tags: row.tags ? row.tags.split(",").filter(Boolean) : [],
event_id: row.event_id,
location_key: row.location_key,
person: row.person_id
? {
id: row.person_id,
name: row.person_name,
photo: row.person_photo,
tagline: row.person_tagline,
}
: null,
};
}
/* "19:00" → 7:00pm, and a range as 9:00 to 10:30am, or 11:30am to
1:00pm when it crosses noon. */
export function clockRange(start, end) {
if (!start) return null;
const clock = (hhmm) => {
const [h, m] = hhmm.split(":").map(Number);
return { text: `${h % 12 || 12}:${String(m).padStart(2, "0")}`, half: h < 12 ? "am" : "pm" };
};
const from = clock(start);
if (!end) return from.text + from.half;
const to = clock(end);
return `${from.text}${from.half === to.half ? "" : from.half} to ${to.text}${to.half}`;
}
/* ── Card description ──────────────────────────────────────────
The card slot is paragraphs by convention, so it collapses to
an array of strings, desc_a and desc_b become description[0]
and description[1]. A non-paragraph block in the card slot is
ignored here. Only cards show it: a record's page draws its
body blocks, "both" ones among them.
───────────────────────────────────────────────────────────── */
export function paragraphs(blocks = []) {
return blocks
.filter((block) => block.type === "paragraph" && block.text)
.map((block) => block.text);
}
/* ── Split entity links ────────────────────────────────────────
Socials are lifted out of the list because cards treat them
differently: Instagram is an icon, Register is a button. The
underlying rows are the same table.
───────────────────────────────────────────────────────────── */
/* ── Tags (070_tags.sql) ───────────────────────────────────────
Sets `tags` ([{ id, name }], in the record's order) on each of
these shaped organizations or events, in one query. */
const TAG_TABLES = { organization: ["organization_tags", "org_id"], event: ["event_tags", "event_id"] };
export function attachTags(db, kind, records) {
if (records.length === 0) return;
const [table, owner] = TAG_TABLES[kind];
const rows = db
.prepare(
`SELECT x.${owner} AS owner_id, t.id, t.name
FROM ${table} x
JOIN tags t ON t.id = x.tag_id
WHERE x.${owner} IN (${placeholders(records.length)})
ORDER BY x.sort_order, t.sort_order, t.name`,
)
.all(...records.map((record) => record.id));
for (const record of records) {
record.tags = rows.filter((row) => row.owner_id === record.id).map(({ id, name }) => ({ id, name }));
}
}
export function splitLinks(links = []) {
const websites = links.filter((link) => link.kind === "website");
// An email row's URL is the address, with or without mailto:.
const emails = links
.filter((link) => link.kind === "email")
.map((link) => ({ ...link, url: link.url.replace(/^mailto:/i, "") }));
return {
actions: links.filter((link) => link.kind === "action"),
socials: links.filter((link) => link.kind === "social"),
// Every one, for a record's own page; the first, for cards.
websites,
emails,
website: websites[0]?.url ?? null,
email: emails[0]?.url ?? null,
instagram:
links.find((link) => link.platform === "instagram")?.label ?? null,
};
}
/* ── Event series ──────────────────────────────────────────────
The repeating schedule, or null for a one-off. Weekdays
collapse from seven flags to a list of the ticked ones, Sunday
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 the sections (sectionData.js).
───────────────────────────────────────────────────────────── */
const SERIES_WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
export function shapeSeries(row) {
if (!asBool(row.is_series)) return null;
return {
frequency: row.series_frequency,
interval: row.series_interval,
weekdays: SERIES_WEEKDAYS.filter((day) => asBool(row[`series_${day}`])),
start_time: row.series_start_time,
end_time: row.series_end_time,
count: row.series_count,
};
}
/* ── Featured cards ────────────────────────────────────────────
One owner's cards (the front page's, a region's), in order, with
each record card filled in from its record. Shared so the
Community blog's cards will come out the same shape.
A record card's own title, blurb and image override the
record's. One query per kind that is actually referenced, so a
row of six cards is at most six queries.
`image` is { file, kind }, like the timeline's logo: the record
tables keep bare filenames in different public/ directories,
and logoForKind in media.ts knows which is which. The kinds are
the ref kinds, plus 'event-photo' and 'featured' (the
card's own image). `size` is its shape in the grid (073), null
for automatic. An unpublished
record's card is dropped; an unlisted one's stays, since
featuring it is attaching it by hand.
───────────────────────────────────────────────────────────── */
const FEATURED_REFS = {
event: {
sql: (marks) =>
`SELECT id, title, tagline AS blurb, date_label AS eyebrow,
photo, event_logo
FROM events WHERE is_published = 1 AND id IN (${marks})`,
image: (row) =>
row.photo
? { file: row.photo, kind: "event-photo" }
: row.event_logo
? { file: row.event_logo, kind: "event" }
: null,
},
organization: {
sql: (marks) =>
`SELECT id, name AS title, tagline AS blurb, kind AS org_kind, logo
FROM organizations WHERE is_published = 1 AND id IN (${marks})`,
image: (row) => (row.logo ? { file: row.logo, kind: "organization" } : null),
},
person: {
sql: (marks) =>
`SELECT id, display_name AS title, tagline AS blurb, photo
FROM v_people_public WHERE is_published = 1 AND id IN (${marks})`,
image: (row) => (row.photo ? { file: row.photo, kind: "person" } : null),
},
team: {
sql: (marks) =>
`SELECT t.id, t.name AS title, t.tagline AS blurb, t.logo
FROM teams t
JOIN organizations o ON o.id = t.org_id AND o.is_published = 1
WHERE t.is_published = 1 AND t.id IN (${marks})`,
image: (row) => (row.logo ? { file: row.logo, kind: "team" } : null),
},
award: {
sql: (marks) =>
`SELECT id, name AS title, description AS blurb, logo
FROM awards WHERE is_published = 1 AND id IN (${marks})`,
image: (row) => (row.logo ? { file: row.logo, kind: "award" } : null),
},
};
export function loadFeaturedCards(db, ownerKind, ownerId) {
return loadFeaturedCardsFor(db, ownerKind, [ownerId]).get(ownerId) ?? [];
}
/* Several owners' cards at once (every region in the region list),
as owner id → cards, in the same number of queries as one owner. */
export function loadFeaturedCardsFor(db, ownerKind, ownerIds) {
const byOwner = new Map();
if (ownerIds.length === 0) return byOwner;
const rows = db
.prepare(
`SELECT * FROM featured_cards
WHERE owner_kind = ? AND owner_id IN (${placeholders(ownerIds.length)})
ORDER BY owner_id, sort_order, id`,
)
.all(ownerKind, ...ownerIds);
// kind → id → record row
const records = new Map();
for (const [kind, spec] of Object.entries(FEATURED_REFS)) {
const ids = [
...new Set(rows.filter((r) => r.kind === "record" && r.ref_kind === kind).map((r) => r.ref_id)),
];
if (ids.length === 0) continue;
const found = db.prepare(spec.sql(placeholders(ids.length))).all(...ids);
records.set(kind, new Map(found.map((r) => [r.id, r])));
}
const own = (row) => (row.image ? { file: row.image, kind: "featured" } : null);
for (const row of rows) {
let cards = byOwner.get(row.owner_id);
if (!cards) byOwner.set(row.owner_id, (cards = []));
if (row.kind === "record") {
const record = records.get(row.ref_kind)?.get(row.ref_id);
if (!record) continue; // unpublished, or its organization is
cards.push({
kind: "record",
ref: { kind: row.ref_kind, id: row.ref_id, org_kind: record.org_kind ?? null },
url: null,
eyebrow: row.eyebrow ?? record.eyebrow ?? null,
title: row.title ?? record.title,
blurb: row.blurb ?? record.blurb ?? null,
image: own(row) ?? FEATURED_REFS[row.ref_kind].image(record),
size: row.size,
});
} else {
cards.push({
kind: row.kind, // 'link' | 'video'
ref: null,
url: row.url,
eyebrow: row.eyebrow,
title: row.title,
blurb: row.blurb,
image: own(row),
size: row.size,
});
}
}
return byOwner;
}
export { asBool };
/* One record's links, card blocks and body blocks: what every detail
page sends beside the record itself. */
export function loadOwned(db, ownerKind, id) {
return {
links: loadLinks(db, ownerKind, [id]).get(id) ?? [],
cards: loadBlocks(db, ownerKind, [id], "card").get(id) ?? [],
body: loadBlocks(db, ownerKind, [id], "body").get(id) ?? [],
};
}
/* Public reads may be cached a minute, and served a little stale
while a fresh copy is fetched. json() sends a body with it. */
export const CACHE = "public, max-age=60, stale-while-revalidate=300";
export const json = (c, body) => c.json(body, 200, { "Cache-Control": CACHE });
// Admin reads and anything personal: never kept by a browser or proxy.
export const NO_STORE = { "Cache-Control": "no-store" };
// "?,?,?" for an IN (...) list of n values.
export const marks = (n) => Array(n).fill("?").join(",");