NGU-Web/src/components/ContentBlocks.tsx
Zaldimmar bd271ef02d Organizations block: the Partners page's cards, picked one by one or every one of a kind
Migration 093 adds the 'organizations' block type (rebuilding
content_blocks for its CHECK, as 088 did), content_blocks.org_kind and
content_block_items.org_id. OrgListCards takes `nested` for a block:
no page gutter, names a level under the block's heading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 03:23:58 -06:00

646 lines
24 KiB
TypeScript

/* ═══════════════════════════════════════════════════════════════
CONTENT BLOCKS
Renders the `body` slot of content_blocks. Events, organizations,
teams, people and blog posts all own blocks and all render them
the same way, so this is written once and tinted by the caller's
accent. The admin's block editor previews each block through this
same component.
What each type reads (see 032_content_block_types.sql):
heading, subheading text
paragraph text (formatted), href makes it all a link
callout text (formatted), in a tinted box
quote text (formatted), cite is who said it
list items: text, detail, url
links items with a url, as outlined buttons
button text is the label, href where it goes
image media, alt, text is the caption, href
video href is the video, media a still, text
the caption; click to play
schedule items as entries in day tabs (day, time,
text, detail, url, location, person, and
a fold-out of description, media, map);
text is an optional intro. ScheduleBlock
table text: a row per line, cells split by |
cards items as link cards, up to three in a row:
text the title, detail, url, media the
picture
people team_id's members as people tiles, then
items as more tiles: person, text their
title (an unpublished person is left out)
map venue: its map, locations marked and
listed (MapBlock); a schedule's places
link to it
events items as event cards: event (from
event_id), text the title shown, detail
in place of the event's card text; a card
opens the event in full under them, its
own page's blocks too (EventsBlock)
divider nothing
"Formatted" is InlineText.tsx: **bold**, *italic*, [text](url),
line breaks, and a blank line for a new paragraph.
Reading mode (readingMode.ts): a linked image with no alt text
is a line linking with its caption, and a video's caption is its
link (VideoPlayer), not said twice.
An unknown `type` renders its text as a paragraph rather than
disappearing. A block somebody typed into the admin should be
visible even if the renderer hasn't caught up with it.
═══════════════════════════════════════════════════════════════ */
import { CaretDown } from '@phosphor-icons/react'
import { useEffect, useId, useRef, useState } from 'react'
import { Link } from 'react-router-dom'
import { mediaUrl } from '../lib/media.ts'
import PeopleTiles from './PeopleTiles.tsx'
import type { ContentBlock, ContentBlockItem, ItemEvent } from '../lib/useContent.ts'
import { Anchor, Inline, Paragraphs, isExternalUrl } from './InlineText.tsx'
import VideoPlayer from './VideoPlayer.tsx'
import ScheduleBlock, { Avatar } from './ScheduleBlock.tsx'
import MapBlock, { PageMaps } from './MapBlock.tsx'
import { eventHref, personHref } from '../lib/hrefs.ts'
import { occurrenceLabel } from '../lib/eventSeries.ts'
import { accentText, BRAND } from '../lib/color.ts'
import { headingAnchors } from '../lib/contents.ts'
import { SITE_NAME } from '../lib/site.ts'
import { useSmallImage } from '../lib/useSmallImage.ts'
import { useReadingMode } from '../lib/readingMode.ts'
import { WordMotion, Words } from './RotatingWords.tsx'
import OrgListCards from '../pages/sections/OrgList-Card.tsx'
const BODY = 'var(--color-muted)'
export default function ContentBlocks({
blocks,
accent = BRAND,
className = '',
anchorPrefix = '',
}: {
blocks?: ContentBlock[] | null
accent?: string
className?: string
/** Put before each heading's id: a blog post's tab (contents.ts, splitTabs). */
anchorPrefix?: string
}) {
if (!blocks?.length) return null
// Headings get ids so a post's contents (PostContents) and a shared
// link (#getting-there) can point at them.
const { idAt } = headingAnchors(blocks, anchorPrefix)
// The heading level a block's own headings take: under the last
// heading (h3) or subheading (h4) before it, else the section's h2.
let under = 2
const levels = blocks.map((block) => {
const level = (under + 1) as 3 | 4 | 5
if (block.type === 'heading') under = 3
if (block.type === 'subheading') under = 4
return level
})
// The venues mapped here, for a schedule's places to link to.
const maps = new Set(blocks.flatMap((block) => (block.type === 'map' && block.venue ? [block.venue.id] : [])))
return (
<PageMaps.Provider value={maps}>
<div className={`space-y-6 ${className}`}>
{blocks.map((block, index) => (
<WordMotion key={block.id ?? index} settings={block.words}>
<Block
block={block}
accent={accent}
anchor={idAt.get(index)}
level={levels[index]}
/>
</WordMotion>
))}
</div>
</PageMaps.Provider>
)
}
/* One link card: the whole card is the link. The site's name above
the title says where it goes (the host for an outside link). */
function LinkCard({ item }: { item: ContentBlockItem }) {
const url = item.url ?? ''
const img = useSmallImage(mediaUrl(item.media))
const where = isExternalUrl(url)
? (() => {
try {
const host = new URL(url).hostname.replace(/^www\./, '')
// A file from Tools → Media → Files (routes/files.js).
return /^(drive|docs)\.google\.com$/.test(host) ? 'Google Drive' : host
} catch {
return url
}
})()
: SITE_NAME
return (
<Anchor
href={url}
className="group flex h-full flex-col overflow-hidden border border-brand/15 bg-surface shadow-sm transition-shadow hover:shadow-lg"
>
{!img.failed && (
<img src={img.src} alt="" loading="lazy" onError={img.onError} className="aspect-video w-full object-cover" />
)}
<span className="flex flex-1 flex-col gap-1 p-4">
<span className="truncate text-xs font-semibold text-muted">{where}</span>
<span className="font-display text-base font-bold leading-snug text-ink group-hover:text-link">{item.text}</span>
{item.detail && <span className="line-clamp-3 text-sm leading-snug text-body">{item.detail}</span>}
</span>
</Anchor>
)
}
/* One event card (088): the event's picture, its type and date,
its title (or the item's text) and card text (or the item's
detail); the whole card links to the event. */
/* An event's type and date, eg. workshop · June 14, 2025 (shown
capitalized), or null with neither. */
export function eventLine(event: ItemEvent): string | null {
const when = event.date_label || (event.starts_on ? occurrenceLabel(event.starts_on) : null)
const kind = event.event_type && event.event_type !== 'other' ? event.event_type : null
return [kind, when].filter(Boolean).join(' · ') || null
}
function EventCard({
item,
accent,
open,
panelId,
onToggle,
}: {
item: ContentBlockItem
accent: string
open: boolean
panelId: string
onToggle: () => void
}) {
const event = item.event!
const img = useSmallImage(mediaUrl(event.image))
const color = event.color || accent
const line = eventLine(event)
return (
<button
type="button"
onClick={onToggle}
aria-expanded={open}
aria-controls={panelId}
className="group flex h-full w-full flex-col overflow-hidden border bg-raised text-left shadow-sm transition-shadow hover:shadow-lg"
style={{
borderColor: open ? accent : 'color-mix(in srgb, var(--color-brand) 15%, transparent)',
boxShadow: open ? `inset 0 -4px 0 ${accent}` : undefined,
}}
>
{!img.failed && (
<img src={img.src} alt="" loading="lazy" onError={img.onError} className="aspect-video w-full object-cover" />
)}
<span className="flex flex-1 flex-col gap-1 p-4">
{line && (
<span className="text-xs font-semibold capitalize" style={{ color: accentText(color) }}>
{line}
</span>
)}
<span className="font-display text-base font-bold leading-snug text-ink group-hover:text-link">
{item.text || event.title}
</span>
{(item.detail || event.blurb) && (
<span className="line-clamp-3 text-sm leading-snug text-body">{item.detail || event.blurb}</span>
)}
<span className="mt-auto inline-flex items-center gap-1 pt-2 text-sm font-semibold" style={{ color: accentText(color) }}>
{open ? 'Close' : 'More'}
<CaretDown aria-hidden="true" weight="bold" className={`h-4 w-4 transition-transform ${open ? 'rotate-180' : ''}`} />
</span>
</span>
</button>
)
}
/* An event in full (088): its photo, type and date, title, place and
person host, then its own page's blocks (else its card text), and
a link to its page. */
function EventInFull({ item, accent, level }: { item: ContentBlockItem; accent: string; level: 3 | 4 | 5 }) {
const event = item.event!
const color = event.color || accent
const photo = mediaUrl(event.photo || event.image)
const line = eventLine(event)
const Title = `h${level}` as 'h3'
const blurb = item.detail || event.blurb
return (
<section aria-label={item.text || event.title} className="space-y-6 bg-raised p-6 shadow-md">
{photo && <img src={photo} alt={event.photo_alt ?? ''} loading="lazy" className="aspect-video w-full object-cover" />}
<div>
{line && (
<p className="text-sm font-semibold capitalize" style={{ color: accentText(color) }}>
{line}
</p>
)}
<Title className="text-2xl font-bold text-ink">{item.text || event.title}</Title>
{(event.location_label || item.person) && (
<p className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-2 text-sm text-muted">
{event.location_label && <span>{event.location_label}</span>}
{item.person && (
<Link to={personHref(item.person.id)} className="inline-flex items-center gap-2 hover:underline">
<Avatar person={item.person} size="h-8 w-8" />
{item.person.name}
</Link>
)}
</p>
)}
</div>
{event.blocks?.length ? (
<ContentBlocks blocks={event.blocks} accent={color} anchorPrefix={`${event.id}-`} />
) : blurb ? (
<div className="space-y-3 leading-relaxed" style={{ color: BODY }}>
<Paragraphs text={blurb} accent={color} />
</div>
) : null}
<Anchor href={eventHref(event.id)} className="inline-block text-sm font-semibold underline" style={{ color: accentText(color) }}>
{event.title}: the event's page
</Anchor>
</section>
)
}
/* An events block (088): its events as cards; one opened shows in
full under them, scrolled into view. A featured one (090) is
already open, above the cards, under its own heading and
subheading. Reading mode has them all in full. */
function EventsBlock({ items, accent, level }: { items: ContentBlockItem[]; accent: string; level: 3 | 4 | 5 }) {
const [open, setOpen] = useState<number | null>(null)
const panelId = useId()
const panel = useRef<HTMLDivElement>(null)
const reading = useReadingMode()
useEffect(() => {
if (open != null) panel.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
}, [open])
const featured = reading ? items : items.filter((item) => item.featured)
const cards = reading ? [] : items.filter((item) => !item.featured)
return (
<div className="space-y-6">
{featured.map((item, i) => (
<FeaturedEvent key={i} item={item} accent={accent} level={level} />
))}
{cards.length > 0 && (
<>
<ul className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{cards.map((item, i) => (
<li key={i}>
<EventCard
item={item}
accent={accent}
open={open === i}
panelId={panelId}
onToggle={() => setOpen(open === i ? null : i)}
/>
</li>
))}
</ul>
<div ref={panel} id={panelId}>
{open != null && cards[open] && <EventInFull item={cards[open]} accent={accent} level={level} />}
</div>
</>
)}
</div>
)
}
/* A featured event: its heading and subheading, if set, then the
event in full, its title a level under the heading. */
function FeaturedEvent({ item, accent, level }: { item: ContentBlockItem; accent: string; level: 3 | 4 | 5 }) {
if (!item.heading && !item.subheading) return <EventInFull item={item} accent={accent} level={level} />
const Heading = `h${level}` as 'h3'
const color = item.event?.color || accent
return (
<div className="space-y-4">
<div>
{item.heading && (
<Heading className="text-2xl font-bold" style={{ color: accentText(color) }}>
{item.heading}
</Heading>
)}
{item.subheading && <p className="mt-1 text-lg text-body">{item.subheading}</p>}
</div>
<EventInFull item={item} accent={accent} level={item.heading ? (Math.min(level + 1, 5) as 3 | 4 | 5) : level} />
</div>
)
}
/* A table block's text as rows of cells: one row per line, cells
split by "|" (a literal bar is "\|"), blank lines skipped. A
leading and trailing bar, as in Markdown, is allowed. */
export function tableRows(text: string): string[][] {
return text
.split('\n')
.map((line) => line.trim())
.filter(Boolean)
.map((line) =>
line
.replace(/^\|/, '')
.replace(/(?<!\\)\|$/, '')
.split(/(?<!\\)\|/)
.map((cell) => cell.replace(/\\\|/g, '|').trim()),
)
}
function Caption({ text }: { text?: string | null }) {
if (!text) return null
return (
<figcaption className="mt-2 text-sm opacity-70" style={{ color: BODY }}>
{text}
</figcaption>
)
}
function Block({
block,
accent,
anchor,
level,
}: {
block: ContentBlock
accent: string
anchor?: string
level: 3 | 4 | 5
}) {
const text = block.text ?? ''
const reading = useReadingMode()
switch (block.type) {
// A blog post's tab marker (BlogPost.tsx splits the post at
// them); anywhere else, it reads as a heading.
case 'tab':
case 'heading':
return (
<h3 id={anchor} className="text-2xl font-bold" style={{ color: accentText(accent) }}>
<Words text={text} />
</h3>
)
case 'subheading':
return (
<h4 id={anchor} className="text-lg font-normal" style={{ color: accentText(accent) }}>
<Words text={text} />
</h4>
)
case 'list': {
// Bold text and a plain detail, unless the block is set Plain
// (092): plain text, gray detail.
const plain = block.list_style === 'plain'
return (
<ul className="space-y-2">
{(block.items ?? []).map((item, index) => (
<li key={index} className="flex gap-3">
<span aria-hidden="true" style={{ color: accentText(accent) }}>
•
</span>
<span style={{ color: plain ? BODY : 'var(--color-body)' }}>
<span className={plain ? undefined : 'font-bold'}>
{item.url ? (
<Anchor href={item.url} className="underline" style={{ color: accentText(accent) }}>
{item.text}
</Anchor>
) : (
<Inline text={item.text} accent={accent} />
)}
</span>
{item.detail && <span className={plain ? 'opacity-70' : undefined}>: {item.detail}</span>}
</span>
</li>
))}
</ul>
)
}
case 'links':
return (
<div className="flex flex-wrap gap-3">
{(block.items ?? [])
.filter((item) => item.url)
.map((item, index) => (
<Anchor
key={index}
href={item.url as string}
className="btn border px-4 py-1.5 text-sm transition-colors hover:bg-tint"
style={{ borderColor: accent, color: accentText(accent) }}
>
{item.text}
</Anchor>
))}
</div>
)
case 'button':
if (!text || !block.href) return null
return (
<div>
<Anchor
href={block.href}
className="inline-block btn px-6 py-2.5 text-white transition-transform hover:scale-105"
style={{ background: accent }}
>
{text}
</Anchor>
</div>
)
case 'quote':
return (
<figure className="border-l-2 pl-5" style={{ borderColor: accent }}>
<blockquote className="text-lg italic" style={{ color: BODY }}>
<Inline text={text} accent={accent} />
</blockquote>
{block.cite && (
<figcaption className="mt-2 text-sm font-semibold not-italic" style={{ color: accentText(accent) }}>
{block.cite}
</figcaption>
)}
</figure>
)
case 'cards': {
const cards = (block.items ?? []).filter((item) => item.url && item.text)
if (cards.length === 0) return null
return (
// One grid whatever the count: a lone card takes a column
// rather than the width, and more sit up to three in a row.
<ul className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{cards.map((item, i) => (
<li key={i}>
<LinkCard item={item} />
</li>
))}
</ul>
)
}
case 'table': {
const rows = tableRows(text)
if (rows.length === 0) return null
const [head, ...body] = rows
const width = Math.max(...rows.map((row) => row.length))
return (
// Wide tables scroll sideways inside their box on a phone
// rather than squeezing every column to a word. Focusable, so
// the arrow keys scroll it too (Safari won't on its own).
<div tabIndex={0} role="region" aria-label="Table" className="overflow-x-auto border border-brand/15">
<table className="min-w-full text-left text-sm leading-snug">
<thead className="bg-tint">
<tr>
{Array.from({ length: width }, (_, i) => (
<th key={i} scope="col" className="min-w-[8rem] px-4 py-3 font-semibold text-ink">
<Inline text={head[i] ?? ''} accent={accent} />
</th>
))}
</tr>
</thead>
<tbody>
{body.map((row, r) => (
<tr key={r} className={r % 2 ? 'bg-tint-soft' : ''}>
{Array.from({ length: width }, (_, i) =>
i === 0 ? (
<th key={i} scope="row" className="min-w-[8rem] px-4 py-3 align-top font-semibold text-ink">
<Inline text={row[i] ?? ''} accent={accent} />
</th>
) : (
<td key={i} className="min-w-[8rem] px-4 py-3 align-top" style={{ color: BODY }}>
<Inline text={row[i] ?? ''} accent={accent} />
</td>
),
)}
</tr>
))}
</tbody>
</table>
</div>
)
}
case 'callout':
if (!text) return null
return (
<aside
className="space-y-3 border-l-4 px-6 py-5 leading-relaxed"
style={{ borderColor: accent, background: `color-mix(in srgb, ${accent} 8%, var(--color-surface))`, color: 'var(--color-body)' }}
>
<Paragraphs text={text} accent={accent} />
</aside>
)
case 'image': {
const src = mediaUrl(block.media)
if (!src) return null
// The reader leaves out a picture with no alt, and its link with it.
if (reading && block.href && !block.alt) {
return (
<p>
<Anchor href={block.href}>{text || 'Open link'}</Anchor>
</p>
)
}
const img = (
<img
src={src}
// Alt describes the picture; the caption describes the
// moment. No alt means decorative, which alt="" says.
alt={block.alt ?? ''}
loading="lazy"
decoding="async"
className="w-full"
/>
)
return (
<figure>
{block.href ? <Anchor href={block.href}>{img}</Anchor> : img}
<Caption text={text} />
</figure>
)
}
case 'video':
if (!block.href) return null
return (
<figure>
<div className="overflow-hidden">
<VideoPlayer url={block.href} still={mediaUrl(block.media)} captions={mediaUrl(block.captions)} title={text || null} />
</div>
{!reading && <Caption text={text} />}
</figure>
)
case 'schedule':
if (!block.items?.length) return null
return (
<ScheduleBlock
items={block.items}
tags={block.tags}
intro={block.text}
accent={accent}
/>
)
case 'map':
if (!block.venue) return null
return <MapBlock venue={block.venue} accent={accent} />
case 'events': {
const events = (block.items ?? []).filter((item) => item.event)
if (events.length === 0) return null
return <EventsBlock items={events} accent={accent} level={level} />
}
case 'organizations': {
// Picked ones in their order, else every listed one of its kind.
const ids = (block.items ?? []).map((item) => item.org_id).filter((id): id is string => Boolean(id))
if (ids.length === 0 && !block.org_kind) return null
return (
<OrgListCards
kind={block.org_kind}
ids={ids}
accent={accent}
pageLabel="Their page"
empty="Organizations coming soon."
nested
/>
)
}
case 'people': {
const picked = (block.items ?? [])
.filter((item) => item.person)
.map((item) => ({ peopleslug: item.person!.id, title: item.text || null }))
if (!block.team_id && picked.length === 0) return null
return (
<div className="space-y-6">
{block.team_id && <PeopleTiles size="lg" teams={block.team_id} accent={accent} headingLevel={level} />}
{picked.length > 0 && <PeopleTiles size="lg" people={picked} accent={accent} headingLevel={level} />}
</div>
)
}
case 'divider':
return <hr className="border-0 h-px" style={{ background: accent, opacity: 0.3 }} />
case 'paragraph':
default:
if (!text) return null
return block.href ? (
<p className="leading-relaxed" style={{ color: BODY }}>
<Anchor href={block.href} className="underline" style={{ color: accentText(accent) }}>
{text}
</Anchor>
</p>
) : (
<div className="space-y-4">
<Paragraphs text={text} accent={accent} className="leading-relaxed" style={{ color: BODY }} />
</div>
)
}
}