diff --git a/server/src/admin-schema/blog.js b/server/src/admin-schema/blog.js
index bece207..55f3da2 100644
--- a/server/src/admin-schema/blog.js
+++ b/server/src/admin-schema/blog.js
@@ -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"),
diff --git a/server/src/migrations/043_blog_contents.sql b/server/src/migrations/043_blog_contents.sql
new file mode 100644
index 0000000..2064521
--- /dev/null
+++ b/server/src/migrations/043_blog_contents.sql
@@ -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));
diff --git a/server/src/routes/blog.js b/server/src/routes/blog.js
index b3fa816..9407477 100644
--- a/server/src/routes/blog.js
+++ b/server/src/routes/blog.js
@@ -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,
diff --git a/server/src/seed-showcase.js b/server/src/seed-showcase.js
index c592ed9..5e61cf3 100644
--- a/server/src/seed-showcase.js
+++ b/server/src/seed-showcase.js
@@ -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,
diff --git a/src/components/ContentBlocks.tsx b/src/components/ContentBlocks.tsx
index 60385a2..560a5e3 100644
--- a/src/components/ContentBlocks.tsx
+++ b/src/components/ContentBlocks.tsx
@@ -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 (
{blocks.map((block, index) => (
-
+
))}
)
@@ -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 (
-
+
{text}
)
case 'subheading':
return (
-
+
{text}
)
diff --git a/src/components/PostContents.tsx b/src/components/PostContents.tsx
new file mode 100644
index 0000000..0ad8f4d
--- /dev/null
+++ b/src/components/PostContents.tsx
@@ -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(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, 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 (
+
+ {entries.map((entry) => (
+ -
+ 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}
+
+
+ ))}
+
+ )
+}
+
+export default function PostContents({ entries }: { entries: ContentsEntry[] }) {
+ const lit = useLit(entries)
+ return (
+ <>
+
+ On this page
+
+
+
+
+
+ >
+ )
+}
diff --git a/src/lib/adminSchema/blog.ts b/src/lib/adminSchema/blog.ts
index 39749ee..9a4280f 100644
--- a/src/lib/adminSchema/blog.ts
+++ b/src/lib/adminSchema/blog.ts
@@ -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",
diff --git a/src/lib/contents.ts b/src/lib/contents.ts
new file mode 100644
index 0000000..93cd6c3
--- /dev/null
+++ b/src/lib/contents.ts
@@ -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
+} {
+ const entries: ContentsEntry[] = []
+ const idAt = new Map()
+ const seen = new Map()
+ ;(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 }
+}
diff --git a/src/lib/useBlog.ts b/src/lib/useBlog.ts
index fb33f4f..69f1895 100644
--- a/src/lib/useBlog.ts
+++ b/src/lib/useBlog.ts
@@ -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[]
diff --git a/src/pages/BlogPost.tsx b/src/pages/BlogPost.tsx
index 7ada762..e44eff1 100644
--- a/src/pages/BlogPost.tsx
+++ b/src/pages/BlogPost.tsx
@@ -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: (
-
-
- {date &&
}
- {byline &&
By {byline}}
- {post.tags.map((tag) => (
-
+ {withContents && }
+
+
+ {date && (
+
+ )}
+ {byline && By {byline}}
+ {post.tags.map((tag) => (
+
+ {tag}
+
+ ))}
+
- {tag}
-
- ))}
-
- {BACK.label}
-
-
+ {BACK.label}
+
+
- {cover && (
-
- )}
+ {cover && (
+
+ )}
-
-
+
+
+
),
},
]
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: (
@@ -110,5 +155,11 @@ export default function BlogPost() {
})
}
- return
+ return (
+
+ )
}