NGU-Web/src/pages/BlogPost.tsx
Aidan Dona 31afa889d6 Page features: directory and blog post tabs, image converter, version names
- Featured event badge: above the event's card from lg up, left out on phones
- Version names from the tag (The Region Cards Update) in the site and admin footers
- Tools -> Image converter (JPG, PNG, WebP in the browser) and Download as in Media
- People directory sections take several tags, a tab each (migration 078)
- Tab blocks split a blog post into tabs; contents follow the open tab (migration 079)
- The side nav sun fades out as the page scrolls into the footer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 19:37:07 -05:00

315 lines
11 KiB
TypeScript

/* ═══════════════════════════════════════════════════════════════
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.
Tab blocks (079) split the body into tabs (contents.ts,
splitTabs): the blocks before the first are an intro above them,
and the contents list follows the open tab. A link to a heading
in another tab (#tab-…) opens that tab. Printed (Download PDF) or
in reading mode, every tab shows, each under its title.
═══════════════════════════════════════════════════════════════ */
import { useEffect, useId, useState, type KeyboardEvent } from "react"
import { Link, useLocation, 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 { mediaUrl } from "../lib/media.ts"
import { postDate, useBlogPost } from "../lib/useBlog.ts"
import { accentText, BRAND, readableOn, withAlpha } from "../lib/color.ts"
import { useReadingMode } from "../lib/readingMode.ts"
import { jumpTo } from "../lib/focus.ts"
import PostContents from "../components/PostContents.tsx"
import { headingAnchors, splitTabs, type PostTab } from "../lib/contents.ts"
import QrCode from "../components/QrCode.tsx"
import RequestLink from "../components/RequestLink.tsx"
import { siteUrl } from "../lib/site.ts"
import { FilePdf } from "@phosphor-icons/react"
const BODY = "var(--color-muted)"
/* 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)
const [tabIndex, setTabIndex] = useState(0)
const reading = useReadingMode()
const { hash } = useLocation()
// A link into another tab (#tab-…) opens it, then goes to the heading.
useEffect(() => {
if (!post || !hash.startsWith("#tab-")) return
const target = decodeURIComponent(hash.slice(1))
const found = splitTabs(post.blocks).tabs
const index = found.findIndex((tab) => target === tab.id || target.startsWith(tab.prefix))
if (index < 0) return
setTabIndex(index)
// The tab's own id is its printed title, hidden on screen: opening
// it is enough. A heading inside it is scrolled to once it shows.
if (target !== found[index].id) requestAnimationFrame(() => jumpTo(target))
}, [post, hash])
if (!post) {
return (
<PageState
loading={loading}
error={error}
notFound={notFound}
onRetry={reload}
noun="post"
backTo={BACK.to}
backLabel={BACK.label}
/>
)
}
const { intro, tabs } = splitTabs(post.blocks)
const current = Math.min(tabIndex, Math.max(tabs.length - 1, 0))
// Two headings or more make a list worth showing: the intro's and
// the open tab's.
const contents = post.show_contents
? tabs.length
? [...headingAnchors(intro).entries, ...headingAnchors(tabs[current].blocks, tabs[current].prefix).entries]
: headingAnchors(post.blocks).entries
: []
const withContents = contents.length >= 2
const postUrl = siteUrl(`/blog/${post.id}`)
const date = postDate(post.published_on)
const cover = mediaUrl(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: mediaUrl(author.photo),
})),
...(post.guest
? [
{
name: post.guest.name,
title: "Guest author",
photo: mediaUrl(post.guest.photo),
},
]
: []),
]
const sections: ShellSection[] = [
{
id: "post",
title: "Post",
accent: BRAND,
content: (
<div
className={
withContents
? "mx-auto grid max-w-6xl gap-8 px-6 lg:grid-cols-[14rem_minmax(0,1fr)] lg:gap-12 print:block"
: "contents"
}
>
{withContents && <PostContents entries={contents} />}
<article
className={
withContents
? "min-w-0 max-w-3xl space-y-8"
: "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="px-3 py-0.5 text-xs font-semibold"
style={{
background: "var(--color-tint)",
color: accentText(BRAND),
}}
>
{tag}
</span>
))}
<button
type="button"
onClick={() => window.print()}
className="ml-auto inline-flex items-center gap-1.5 btn border border-link px-3 py-1 text-link transition-colors hover:bg-tint print:hidden"
>
<FilePdf size={16} weight="bold" aria-hidden="true" />
Download PDF
</button>
<Link
to={BACK.to}
className="hover:underline print:hidden"
style={{ color: accentText(BRAND) }}
>
{BACK.label}
</Link>
</div>
{cover && (
<img
src={cover}
alt={post.cover_alt ?? ""}
className="aspect-video w-full object-cover"
/>
)}
{tabs.length ? (
<>
<ContentBlocks blocks={intro} accent={BRAND} />
<PostTabs tabs={tabs} current={current} onSelect={setTabIndex} all={reading} />
</>
) : (
<ContentBlocks blocks={post.blocks} accent={BRAND} />
)}
<div className="flex flex-wrap items-center gap-3 border-t border-brand/15 pt-6 text-sm text-muted print:hidden">
Have a story to share?
<RequestLink type="blog" label="Write for the blog" />
</div>
{/* Only on paper (Download PDF): where the post lives online,
as a link and as a code to scan. */}
<footer className="hidden break-inside-avoid items-center gap-6 border-t border-brand/20 pt-6 print:flex">
<QrCode value={postUrl} label={`QR code for ${postUrl}`} className="h-28 w-28 shrink-0" />
<p className="text-sm text-body">
Read this post online at
<br />
<span className="font-semibold text-link">{postUrl}</span>
</p>
</footer>
</article>
</div>
),
},
]
if (authors.length > 0) {
sections.push({
id: "authors",
title: authors.length === 1 ? "About the author" : "About the authors",
accent: BRAND,
content: (
<div className="mx-auto max-w-6xl px-6">
<PeopleTiles size="md" accent={BRAND} people={authors} />
</div>
),
})
}
return (
<PageShell
title={post.title}
intro={post.excerpt ?? undefined}
sections={sections}
/>
)
}
/* The post's tabs: a row of buttons, then the open tab's blocks. The
others stay in the page, hidden, so print shows them all; `all`
(reading mode) shows every tab, each under its title. */
function PostTabs({
tabs,
current,
onSelect,
all,
}: {
tabs: PostTab[]
current: number
onSelect: (index: number) => void
all: boolean
}) {
const baseId = useId()
// Arrows move one tab and wrap; Home and End jump to the ends.
const onKey = (e: KeyboardEvent<HTMLButtonElement>) => {
const last = tabs.length - 1
const next =
e.key === "ArrowRight" ? (current + 1) % tabs.length
: e.key === "ArrowLeft" ? (current + last) % tabs.length
: e.key === "Home" ? 0
: e.key === "End" ? last
: null
if (next === null) return
e.preventDefault()
onSelect(next)
document.getElementById(`${baseId}-tab-${next}`)?.focus()
}
return (
<div className="space-y-6">
{!all && (
<div role="tablist" aria-label="Parts of this post" className="flex flex-wrap gap-2 print:hidden">
{tabs.map((tab, index) => {
const selected = index === current
return (
<button
key={tab.id}
id={`${baseId}-tab-${index}`}
type="button"
role="tab"
aria-selected={selected}
aria-controls={`${baseId}-panel-${index}`}
tabIndex={selected ? 0 : -1}
onClick={() => onSelect(index)}
onKeyDown={onKey}
className="btn border px-5 py-2 text-sm transition-colors"
style={
selected
? { background: BRAND, borderColor: BRAND, color: readableOn(BRAND) }
: { borderColor: withAlpha(BRAND, 33), color: accentText(BRAND) }
}
>
{tab.title}
</button>
)
})}
</div>
)}
{tabs.map((tab, index) => (
<div
key={tab.id}
id={`${baseId}-panel-${index}`}
role={all ? undefined : "tabpanel"}
aria-labelledby={all ? undefined : `${baseId}-tab-${index}`}
className={all || index === current ? "space-y-6" : "hidden space-y-6 print:block"}
>
<h2
id={tab.id}
className={`text-3xl font-bold ${all ? "" : "hidden print:block"}`}
style={{ color: accentText(BRAND) }}
>
{tab.title}
</h2>
<ContentBlocks blocks={tab.blocks} accent={BRAND} anchorPrefix={tab.prefix} />
</div>
))}
</div>
)
}