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:
Zaldimmar 2026-09-29 09:21:48 -05:00
parent f59ab314e0
commit 92e7938b64
10 changed files with 264 additions and 44 deletions

View file

@ -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>
)

View 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>
</>
)
}