Improve content blocks: new types, formatting, and a better editor

Blocks (migration 032): video (click to play, sharing the featured
cards' player), button and callout types; quotes get an attribution
and images alt text separate from the caption. Paragraphs, callouts,
quotes and list items take **bold**, *italic*, [text](url), line
breaks and blank-line paragraphs, parsed into elements (never HTML)
with only safe link schemes. A list item's detail no longer uses an
em-dash.

Editor: each block type shows only its fields, with a named type and
a description, and every open block previews itself with the site's
renderer. Any repeater row can now be duplicated or have a new row
inserted below it; nested collections take `when`, and help text can
depend on the row.

src/seed-showcase.js writes a local test post using every block type
and option. It refuses the production database.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-27 16:50:21 -05:00
parent c62dc84add
commit c5f12c769f
13 changed files with 723 additions and 169 deletions

View file

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

View file

@ -10,10 +10,9 @@
record links to the record's own page (hrefs.ts builds it)
link links to its URL, a new tab when it leaves the site
video a still with a play button; pressing it swaps in the
player, so the page loads no iframes until then. The
still is the card's image, else YouTube's thumbnail,
else a plain panel.
video VideoPlayer: a still with a play button that swaps in
the player when pressed. The still is the card's
image, else YouTube's thumbnail, else a plain panel.
A photo fills the picture area; a logo sits inside it on a soft
panel instead, since cropping a logo to 16:9 cuts it off.
@ -22,13 +21,11 @@
import { useState } from 'react'
import HomeLink from '../pages/sections/home/HomeLink.tsx'
import VideoPlayer from './VideoPlayer.tsx'
import { refHref } from '../lib/hrefs.ts'
import { logoForKind } from '../lib/media.ts'
import { playingSource, videoSource, videoThumbnail } from '../lib/embeds.ts'
import type { FeaturedCard } from '../lib/useFrontPage.ts'
const ACCENT = '#138ba0'
/* Image kinds that are photographs, drawn edge to edge. Anything
else is a logo, drawn whole. */
const PHOTO_KINDS = new Set(['event-background', 'featured', 'person'])
@ -71,68 +68,8 @@ function Picture({ card }: { card: FeaturedCard }) {
}
function VideoPicture({ card }: { card: FeaturedCard }) {
const [playing, setPlaying] = useState(false)
const source = videoSource(card.url)
if (playing && source) {
const live = playingSource(source)
return live.kind === 'file' ? (
<video src={live.src} controls autoPlay playsInline className="aspect-video w-full bg-black" />
) : (
<iframe
src={live.src}
title={card.title || 'Video'}
allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
allowFullScreen
className="aspect-video w-full border-0 bg-black"
/>
)
}
const own = card.image ? logoForKind(card.image.kind, card.image.file) : null
const still = own ?? videoThumbnail(card.url)
const face = (
<>
{still ? (
<img src={still} alt="" loading="lazy" className="aspect-video w-full object-cover" />
) : (
<div className="aspect-video w-full bg-gradient-to-br from-[#073d4a] to-[#04262e]" />
)}
<span
aria-hidden="true"
className="absolute inset-0 flex items-center justify-center bg-black/10 transition-colors group-hover:bg-black/25"
>
<span className="flex h-16 w-16 items-center justify-center rounded-full bg-white/90 shadow-lg transition-transform group-hover:scale-110">
<svg viewBox="0 0 24 24" className="ml-1 h-7 w-7" fill={ACCENT}>
<path d="M8 5v14l11-7z" />
</svg>
</span>
</span>
</>
)
// A link that can't be played here still goes somewhere.
if (!source) {
return card.url ? (
<HomeLink url={card.url} className="group relative block">
{face}
</HomeLink>
) : (
<div className="relative">{face}</div>
)
}
return (
<button
type="button"
onClick={() => setPlaying(true)}
aria-label={`Play ${card.title || 'video'}`}
className="group relative block w-full"
>
{face}
</button>
)
return <VideoPlayer url={card.url} still={own} title={card.title} />
}
function Card({ card }: { card: FeaturedCard }) {

View file

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

View file

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

View file

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