Give blog posts an optional table of contents
Blog posts -> Show contents (migration 043, off by default): with two or more headings, the post's headings sit in a sticky column beside it with the one being read lit (an IntersectionObserver, not a scroll listener), and fold out at the top on phones. Content-block headings now carry anchor ids, so a link can point at one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
f59ab314e0
commit
92e7938b64
10 changed files with 264 additions and 44 deletions
|
|
@ -26,6 +26,7 @@ export const blogPosts = {
|
|||
text("excerpt"),
|
||||
text("cover_image"),
|
||||
text("cover_alt"),
|
||||
bool("show_contents"),
|
||||
date("published_on"),
|
||||
text("tags"),
|
||||
text("guest_author"),
|
||||
|
|
|
|||
10
server/src/migrations/043_blog_contents.sql
Normal file
10
server/src/migrations/043_blog_contents.sql
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
-- ═══════════════════════════════════════════════════════════════
|
||||
-- 043 A POST'S TABLE OF CONTENTS
|
||||
--
|
||||
-- Blog posts → "Show contents": list the post's headings beside it
|
||||
-- (a fold-out on phones), the one being read lit. Off unless an
|
||||
-- editor turns it on, since a short post doesn't need one.
|
||||
-- ═══════════════════════════════════════════════════════════════
|
||||
|
||||
ALTER TABLE blog_posts ADD COLUMN show_contents INTEGER NOT NULL DEFAULT 0
|
||||
CHECK (show_contents IN (0, 1));
|
||||
|
|
@ -99,6 +99,7 @@ blog.get("/blog/:id", (c) => {
|
|||
excerpt: row.excerpt,
|
||||
cover_image: row.cover_image,
|
||||
cover_alt: row.cover_alt,
|
||||
show_contents: row.show_contents === 1,
|
||||
published_on: row.published_on,
|
||||
tags: splitTags(row.tags),
|
||||
authors,
|
||||
|
|
|
|||
|
|
@ -462,6 +462,7 @@ tx(db, () => {
|
|||
cover_image: IMAGE,
|
||||
published_on: db.prepare(`SELECT date('now') AS d`).get().d,
|
||||
tags: "Test, Showcase",
|
||||
show_contents: 1,
|
||||
guest_author: "A Guest Author",
|
||||
guest_photo: IMAGE,
|
||||
is_published: 1,
|
||||
|
|
|
|||
|
|
@ -39,6 +39,7 @@ import { Anchor, Inline, Paragraphs } from './InlineText.tsx'
|
|||
import VideoPlayer from './VideoPlayer.tsx'
|
||||
import ScheduleBlock from './ScheduleBlock.tsx'
|
||||
import { accentText, BRAND } from '../lib/color.ts'
|
||||
import { headingAnchors } from '../lib/contents.ts'
|
||||
|
||||
const BODY = 'var(--color-muted)'
|
||||
|
||||
|
|
@ -52,11 +53,14 @@ export default function ContentBlocks({
|
|||
className?: 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)
|
||||
|
||||
return (
|
||||
<div className={`space-y-6 ${className}`}>
|
||||
{blocks.map((block, index) => (
|
||||
<Block key={block.id ?? index} block={block} accent={accent} />
|
||||
<Block key={block.id ?? index} block={block} accent={accent} anchor={idAt.get(index)} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
|
|
@ -71,20 +75,23 @@ function Caption({ text }: { text?: string | null }) {
|
|||
)
|
||||
}
|
||||
|
||||
function Block({ block, accent }: { block: ContentBlock; accent: string }) {
|
||||
// Clear of the fixed header when jumped to.
|
||||
const ANCHOR_MARGIN = { scrollMarginTop: 'calc(var(--header-h, 5rem) + 1rem)' }
|
||||
|
||||
function Block({ block, accent, anchor }: { block: ContentBlock; accent: string; anchor?: string }) {
|
||||
const text = block.text ?? ''
|
||||
|
||||
switch (block.type) {
|
||||
case 'heading':
|
||||
return (
|
||||
<h3 className="text-2xl font-bold" style={{ color: accentText(accent) }}>
|
||||
<h3 id={anchor} className="text-2xl font-bold" style={{ color: accentText(accent), ...ANCHOR_MARGIN }}>
|
||||
{text}
|
||||
</h3>
|
||||
)
|
||||
|
||||
case 'subheading':
|
||||
return (
|
||||
<h4 className="text-lg font-semibold" style={{ color: accentText(accent) }}>
|
||||
<h4 id={anchor} className="text-lg font-semibold" style={{ color: accentText(accent), ...ANCHOR_MARGIN }}>
|
||||
{text}
|
||||
</h4>
|
||||
)
|
||||
|
|
|
|||
93
src/components/PostContents.tsx
Normal file
93
src/components/PostContents.tsx
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
POST CONTENTS
|
||||
|
||||
A post's table of contents, from its headings (lib/contents.ts).
|
||||
On a wide screen it's a sticky column beside the post, the
|
||||
heading you're reading lit; below lg it's a fold-out at the top.
|
||||
Which heading is lit comes from an IntersectionObserver, not a
|
||||
scroll listener: the last heading to cross the band just under
|
||||
the fixed header.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
import type { ContentsEntry } from '../lib/contents.ts'
|
||||
import { scrollBehavior } from '../lib/motion.ts'
|
||||
|
||||
function useLit(entries: ContentsEntry[]) {
|
||||
const [lit, setLit] = useState<string | null>(entries[0]?.id ?? null)
|
||||
const ids = entries.map((entry) => entry.id).join('|')
|
||||
|
||||
useEffect(() => {
|
||||
const els = ids
|
||||
.split('|')
|
||||
.map((id) => document.getElementById(id))
|
||||
.filter((el): el is HTMLElement => Boolean(el))
|
||||
if (els.length === 0) return
|
||||
// The band: from just under the header to 60% up the screen.
|
||||
const header = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--header-h')) || 80
|
||||
const observer = new IntersectionObserver(
|
||||
(records) => {
|
||||
const crossing = records.filter((r) => r.isIntersecting).map((r) => r.target.id)
|
||||
if (crossing.length) setLit(crossing[0])
|
||||
},
|
||||
{ rootMargin: `-${header + 16}px 0px -60% 0px` },
|
||||
)
|
||||
els.forEach((el) => observer.observe(el))
|
||||
return () => observer.disconnect()
|
||||
}, [ids])
|
||||
|
||||
return lit
|
||||
}
|
||||
|
||||
function jump(event: React.MouseEvent<HTMLAnchorElement>, id: string) {
|
||||
event.preventDefault()
|
||||
document.getElementById(id)?.scrollIntoView({ behavior: scrollBehavior(), block: 'start' })
|
||||
history.replaceState(null, '', `#${id}`)
|
||||
}
|
||||
|
||||
function List({ entries, lit }: { entries: ContentsEntry[]; lit: string | null }) {
|
||||
return (
|
||||
<ol className="space-y-1 text-sm">
|
||||
{entries.map((entry) => (
|
||||
<li key={entry.id} className={entry.level === 2 ? 'pl-4' : ''}>
|
||||
<a
|
||||
href={`#${entry.id}`}
|
||||
onClick={(event) => jump(event, entry.id)}
|
||||
aria-current={entry.id === lit ? 'location' : undefined}
|
||||
className={
|
||||
'block rounded-lg border-l-2 px-3 py-1.5 transition-colors ' +
|
||||
(entry.id === lit
|
||||
? 'border-link bg-tint font-semibold text-link'
|
||||
: 'border-transparent text-muted hover:text-link')
|
||||
}
|
||||
>
|
||||
{entry.text}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
)
|
||||
}
|
||||
|
||||
export default function PostContents({ entries }: { entries: ContentsEntry[] }) {
|
||||
const lit = useLit(entries)
|
||||
return (
|
||||
<>
|
||||
<details className="rounded-2xl border border-brand/20 bg-tint-soft p-4 lg:hidden">
|
||||
<summary className="cursor-pointer font-semibold text-ink">On this page</summary>
|
||||
<div className="mt-3">
|
||||
<List entries={entries} lit={lit} />
|
||||
</div>
|
||||
</details>
|
||||
<nav
|
||||
aria-label="On this page"
|
||||
className="sticky hidden self-start lg:block"
|
||||
style={{ top: 'calc(var(--header-h, 5rem) + 1.5rem)' }}
|
||||
>
|
||||
<p className="mb-2 px-3 text-sm font-semibold text-ink">On this page</p>
|
||||
<List entries={entries} lit={lit} />
|
||||
</nav>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
@ -53,6 +53,12 @@ export const blogPosts = {
|
|||
help: "A sentence or two for the card. Default: the body's first paragraph.",
|
||||
},
|
||||
{ path: "cover_image", label: "Cover image", widget: "image", resolve: mediaUrl, full: true },
|
||||
{
|
||||
path: "show_contents",
|
||||
label: "Show contents",
|
||||
widget: "checkbox",
|
||||
help: "Lists the post's headings beside it, the one being read lit (a fold-out on phones). Worth it for a long post with two or more headings.",
|
||||
},
|
||||
{
|
||||
path: "cover_alt",
|
||||
label: "Cover description",
|
||||
|
|
|
|||
48
src/lib/contents.ts
Normal file
48
src/lib/contents.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
CONTENTS
|
||||
|
||||
The headings in a list of content blocks, with the anchor id each
|
||||
one gets: ContentBlocks puts the ids on the headings, and
|
||||
PostContents lists them. Both call headingAnchors on the same
|
||||
blocks, so the links always match.
|
||||
|
||||
An id is the heading's text as a slug ("Getting there" →
|
||||
"getting-there"); a repeat gets -2, -3.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import type { ContentBlock } from './useContent.ts'
|
||||
|
||||
export type ContentsEntry = { id: string; text: string; level: 1 | 2 }
|
||||
|
||||
const slug = (text: string) =>
|
||||
text
|
||||
.toLowerCase()
|
||||
.normalize('NFKD')
|
||||
.replace(/[^\w\s-]/g, '')
|
||||
.trim()
|
||||
.replace(/[\s_]+/g, '-')
|
||||
.replace(/-+/g, '-')
|
||||
.slice(0, 60) || 'section'
|
||||
|
||||
/* One entry per heading or subheading block, in order, and the id
|
||||
for each block index that is one. */
|
||||
export function headingAnchors(blocks?: ContentBlock[] | null): {
|
||||
entries: ContentsEntry[]
|
||||
idAt: Map<number, string>
|
||||
} {
|
||||
const entries: ContentsEntry[] = []
|
||||
const idAt = new Map<number, string>()
|
||||
const seen = new Map<string, number>()
|
||||
;(blocks ?? []).forEach((block, index) => {
|
||||
if (block.type !== 'heading' && block.type !== 'subheading') return
|
||||
const text = (block.text ?? '').trim()
|
||||
if (!text) return
|
||||
const base = slug(text)
|
||||
const n = (seen.get(base) ?? 0) + 1
|
||||
seen.set(base, n)
|
||||
const id = n === 1 ? base : `${base}-${n}`
|
||||
idAt.set(index, id)
|
||||
entries.push({ id, text, level: block.type === 'heading' ? 1 : 2 })
|
||||
})
|
||||
return { entries, idAt }
|
||||
}
|
||||
|
|
@ -25,6 +25,8 @@ export type BlogPostRecord = {
|
|||
excerpt?: string | null
|
||||
cover_image?: string | null
|
||||
cover_alt?: string | null
|
||||
/** List the post's headings beside it. */
|
||||
show_contents?: boolean
|
||||
published_on?: string | null
|
||||
tags: string[]
|
||||
authors: BlogAuthor[]
|
||||
|
|
|
|||
|
|
@ -10,20 +10,22 @@
|
|||
section is where posts are listed, so "back" goes there.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { Link, useParams } from 'react-router-dom'
|
||||
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 { mediaUrl } from '../lib/media.ts'
|
||||
import { postDate, useBlogPost } from '../lib/useBlog.ts'
|
||||
import { accentText, BRAND } from '../lib/color.ts'
|
||||
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 } from "../lib/color.ts"
|
||||
import PostContents from "../components/PostContents.tsx"
|
||||
import { headingAnchors } from "../lib/contents.ts"
|
||||
|
||||
const BODY = 'var(--color-muted)'
|
||||
const BODY = "var(--color-muted)"
|
||||
|
||||
/* Where "back" goes: the section on the Community page. */
|
||||
const BACK = { to: '/community#blog', label: 'Community Blog' }
|
||||
const BACK = { to: "/community#blog", label: "Community Blog" }
|
||||
|
||||
export default function BlogPost() {
|
||||
const { id } = useParams()
|
||||
|
|
@ -43,12 +45,16 @@ export default function BlogPost() {
|
|||
)
|
||||
}
|
||||
|
||||
// Two headings or more make a list worth showing.
|
||||
const contents = post.show_contents ? headingAnchors(post.blocks).entries : []
|
||||
const withContents = contents.length >= 2
|
||||
|
||||
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(', ')
|
||||
].join(", ")
|
||||
|
||||
const authors = [
|
||||
...post.authors.map((author) => ({
|
||||
|
|
@ -58,50 +64,89 @@ export default function BlogPost() {
|
|||
pronouns: author.pronouns,
|
||||
photo: mediaUrl(author.photo),
|
||||
})),
|
||||
...(post.guest ? [{ name: post.guest.name, title: 'Guest author', photo: mediaUrl(post.guest.photo) }] : []),
|
||||
...(post.guest
|
||||
? [
|
||||
{
|
||||
name: post.guest.name,
|
||||
title: "Guest author",
|
||||
photo: mediaUrl(post.guest.photo),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
]
|
||||
|
||||
const sections: ShellSection[] = [
|
||||
{
|
||||
id: 'post',
|
||||
title: 'Post',
|
||||
id: "post",
|
||||
title: "Post",
|
||||
accent: BRAND,
|
||||
background: 'var(--color-surface)',
|
||||
background: "var(--color-surface)",
|
||||
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: 'var(--color-tint)', color: accentText(BRAND) }}
|
||||
<div
|
||||
className={
|
||||
withContents
|
||||
? "mx-auto grid max-w-6xl gap-8 px-6 lg:grid-cols-[14rem_minmax(0,1fr)] lg:gap-12"
|
||||
: "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="rounded-full px-3 py-0.5 text-xs font-semibold"
|
||||
style={{
|
||||
background: "var(--color-tint)",
|
||||
color: accentText(BRAND),
|
||||
}}
|
||||
>
|
||||
{tag}
|
||||
</span>
|
||||
))}
|
||||
<Link
|
||||
to={BACK.to}
|
||||
className="ml-auto hover:underline"
|
||||
style={{ color: accentText(BRAND) }}
|
||||
>
|
||||
{tag}
|
||||
</span>
|
||||
))}
|
||||
<Link to={BACK.to} className="ml-auto hover:underline" style={{ color: accentText(BRAND) }}>
|
||||
{BACK.label}
|
||||
</Link>
|
||||
</div>
|
||||
{BACK.label}
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{cover && (
|
||||
<img src={cover} alt={post.cover_alt ?? ""} className="aspect-video w-full rounded-2xl object-cover" />
|
||||
)}
|
||||
{cover && (
|
||||
<img
|
||||
src={cover}
|
||||
alt={post.cover_alt ?? ""}
|
||||
className="aspect-video w-full rounded-2xl object-cover"
|
||||
/>
|
||||
)}
|
||||
|
||||
<ContentBlocks blocks={post.blocks} accent={BRAND} />
|
||||
</article>
|
||||
<ContentBlocks blocks={post.blocks} accent={BRAND} />
|
||||
</article>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
if (authors.length > 0) {
|
||||
sections.push({
|
||||
id: 'authors',
|
||||
title: authors.length === 1 ? 'About the author' : 'About the authors',
|
||||
id: "authors",
|
||||
title: authors.length === 1 ? "About the author" : "About the authors",
|
||||
accent: BRAND,
|
||||
background: 'var(--color-tint)',
|
||||
background: "var(--color-tint)",
|
||||
content: (
|
||||
<div className="mx-auto max-w-6xl px-6">
|
||||
<PeopleTiles size="md" accent={BRAND} people={authors} />
|
||||
|
|
@ -110,5 +155,11 @@ export default function BlogPost() {
|
|||
})
|
||||
}
|
||||
|
||||
return <PageShell title={post.title} intro={post.excerpt ?? undefined} sections={sections} />
|
||||
return (
|
||||
<PageShell
|
||||
title={post.title}
|
||||
intro={post.excerpt ?? undefined}
|
||||
sections={sections}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue