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

48
src/lib/contents.ts Normal file
View 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 }
}