Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"canvas-confetti": "^1.9.4",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"github-slugger": "^2.0.0",
"gray-matter": "^4.0.3",
"lucide-react": "^1.21.0",
"next": "16.3.3",
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 8 additions & 4 deletions src/app/blog/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ function BackLink() {
}

const proseClassName =
'prose prose-neutral max-w-none dark:prose-invert prose-headings:font-bold prose-a:text-blue-600 prose-img:rounded-xl dark:prose-a:text-blue-400'
'prose prose-neutral max-w-none dark:prose-invert prose-headings:font-bold prose-a:text-blue-600 prose-img:rounded-xl prose-headings:scroll-mt-24 dark:prose-a:text-blue-400'

async function LocalPost({ post }: { post: Post }) {
// Dynamic import with a static prefix + `.mdx` suffix lets Turbopack build a
Expand All @@ -104,7 +104,7 @@ async function LocalPost({ post }: { post: Post }) {

return (
<div className="mx-auto max-w-5xl py-10">
<div className="lg:grid lg:grid-cols-[1fr_200px] lg:gap-8">
<div className="lg:grid lg:grid-cols-[1fr_240px] lg:gap-12">
<div>
<BackLink />
<header className="mb-8">
Expand All @@ -128,11 +128,15 @@ async function LocalPost({ post }: { post: Post }) {
</div>
</header>

<article className={proseClassName}>
<article id="post-content" className={proseClassName}>
<MDXContent />
</article>
</div>
<TableOfContents headings={post.headings} />
<TableOfContents
headings={post.headings}
contentId="post-content"
readingTime={post.readingTime}
/>
</div>
</div>
)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import { describe, test, expect } from 'vitest'
import {
computeReadingLine,
computeReadingProgress,
locateSection,
minutesLeft,
railOffset,
} from '../table-of-contents.utils'

describe('computeReadingProgress', () => {
const base = { viewportHeight: 800, contentTop: 200, contentHeight: 2800 }
// start = 200, end = 200 + 2800 - 800 = 2200

test('0 before the article starts', () => {
expect(computeReadingProgress({ ...base, scrollY: 0 })).toBe(0)
})

test('0 exactly at the start', () => {
expect(computeReadingProgress({ ...base, scrollY: 200 })).toBe(0)
})

test('halfway', () => {
expect(computeReadingProgress({ ...base, scrollY: 1200 })).toBe(0.5)
})

test('1 at the end', () => {
expect(computeReadingProgress({ ...base, scrollY: 2200 })).toBe(1)
})

test('clamped past the end (footer, overscroll)', () => {
expect(computeReadingProgress({ ...base, scrollY: 9999 })).toBe(1)
})

test('article shorter than the viewport', () => {
const short = { viewportHeight: 800, contentTop: 200, contentHeight: 300 }
expect(computeReadingProgress({ ...short, scrollY: 0 })).toBe(0)
expect(computeReadingProgress({ ...short, scrollY: 200 })).toBe(1)
})
})

describe('computeReadingLine', () => {
const base = { viewportHeight: 800, contentTop: 200, contentHeight: 2800, offset: 120 }

test('sits `offset` below the viewport top early on', () => {
expect(computeReadingLine({ ...base, scrollY: 300 })).toBe(420)
})

test('reaches the end of the article at 100%', () => {
expect(computeReadingLine({ ...base, scrollY: 2200 })).toBe(3000)
})

test('never moves backwards as the reader scrolls down', () => {
let previous = -Infinity
for (let scrollY = 0; scrollY <= 2400; scrollY += 50) {
const line = computeReadingLine({ ...base, scrollY })
expect(line).toBeGreaterThanOrEqual(previous)
previous = line
}
})
})

describe('locateSection', () => {
// Article spans 0..1000 with headings at 100, 400, 900.
const tops = [100, 400, 900]

test('no headings', () => {
expect(locateSection([], 0, 1000, 500)).toEqual({ index: -1, fraction: 0 })
})

test('intro, before the first heading', () => {
expect(locateSection(tops, 0, 1000, 50)).toEqual({ index: -1, fraction: 0.5 })
})

test('on a heading', () => {
expect(locateSection(tops, 0, 1000, 400)).toEqual({ index: 1, fraction: 0 })
})

test('partway through a section', () => {
expect(locateSection(tops, 0, 1000, 250)).toEqual({ index: 0, fraction: 0.5 })
})

test('last section runs to the end of the article', () => {
expect(locateSection(tops, 0, 1000, 950)).toEqual({ index: 2, fraction: 0.5 })
})

test('past the end clamps to 1', () => {
expect(locateSection(tops, 0, 1000, 5000)).toEqual({ index: 2, fraction: 1 })
})
})

describe('railOffset', () => {
const nodes = [10, 40, 100]
const railEnd = 130

test('no nodes', () => {
expect(railOffset([], 0, { index: 0, fraction: 0.5 })).toBe(0)
})

test('intro parks on the first node', () => {
expect(railOffset(nodes, railEnd, { index: -1, fraction: 0.9 })).toBe(10)
})

test('interpolates between nodes', () => {
expect(railOffset(nodes, railEnd, { index: 1, fraction: 0.5 })).toBe(70)
})

test('last section travels to the end of the rail', () => {
expect(railOffset(nodes, railEnd, { index: 2, fraction: 1 })).toBe(130)
})
})

describe('minutesLeft', () => {
test('full time at the start', () => {
expect(minutesLeft(10, 0)).toBe(10)
})

test('rounds up', () => {
expect(minutesLeft(10, 0.66)).toBe(4)
})

test('0 when done', () => {
expect(minutesLeft(10, 1)).toBe(0)
})

test('clamps out-of-range progress', () => {
expect(minutesLeft(5, -1)).toBe(5)
expect(minutesLeft(5, 2)).toBe(0)
})
})
141 changes: 141 additions & 0 deletions src/components/table-of-contents/mobile-outline.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
'use client'

import React from 'react'
import * as Dialog from '@radix-ui/react-dialog'
import { ChevronUpIcon, Cross1Icon } from '@radix-ui/react-icons'
import { cn } from '@/utils'
import type { Heading } from '@/lib/headings'
import styles from './table-of-contents.module.css'
import { Outline, OutlineFooter, OutlineHeader, ProgressRing, SPRING } from './outline'
import { useScrollingUp } from './use-reading-state'
import type { SectionPosition } from './table-of-contents.utils'

type MobileOutlineProps = {
headings: Heading[]
section: SectionPosition
progress: number
readingTime: number
onJump: (id: string, index: number) => void
onBackToTop: () => void
}

/**
* Small screens: a floating pill showing the current section and progress.
* Tapping it opens the full outline in a bottom sheet.
*/
export function MobileOutline({
headings,
section,
progress,
readingTime,
onJump,
onBackToTop,
}: MobileOutlineProps) {
const [open, setOpen] = React.useState(false)
const scrollingUp = useScrollingUp()
// Scrolling while the sheet's scroll lock is active fights the browser, so
// navigation is queued and run once the sheet has fully closed.
const afterClose = React.useRef<(() => void) | null>(null)

if (headings.length === 0) return null

const percent = Math.round(progress * 100)
const current = headings[section.index]?.text

// Out of the way while reading downwards; back when the reader scrolls up,
// reaches the end, or has only just started (so they know it exists).
const visible = open || (progress > 0 && (scrollingUp || progress >= 1 || progress < 0.03))

const closeThen = (action: () => void) => {
afterClose.current = action
setOpen(false)
}

return (
<Dialog.Root open={open} onOpenChange={setOpen}>
<Dialog.Trigger asChild>
<button
type="button"
tabIndex={visible ? 0 : -1}
aria-label={`Table of contents, ${percent}% read${current ? `. Current section: ${current}` : ''}`}
style={{
bottom: 'max(1rem, env(safe-area-inset-bottom))',
transitionTimingFunction: SPRING,
}}
className={cn(
'fixed left-1/2 z-20 flex max-w-[calc(100vw-2rem)] -translate-x-1/2 items-center gap-2.5 lg:hidden',
'rounded-full border bg-background/85 py-2 pr-3 pl-2.5 text-sm shadow-lg shadow-black/5 backdrop-blur-md',
'transition-[translate,opacity,scale] duration-500 active:scale-95 motion-reduce:transition-none',
'focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none',
visible ? 'translate-y-0 opacity-100' : 'pointer-events-none translate-y-[calc(100%+2rem)] opacity-0',
)}
>
<ProgressRing value={progress} className="shrink-0" />
<span className="max-w-[60vw] truncate font-medium">{current ?? 'On this page'}</span>
<ChevronUpIcon className="size-4 shrink-0 text-muted-foreground" />
</button>
</Dialog.Trigger>

<Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 z-50 bg-(--color-backdrop) backdrop-blur-[2px] duration-300 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0 lg:hidden" />
<Dialog.Content
// The portal renders outside the component tree, so the gradient
// variables have to be re-declared on the sheet itself.
className={cn(
styles.root,
'fixed inset-x-0 bottom-0 z-50 flex max-h-[85dvh] flex-col rounded-t-2xl border-t bg-background px-5 pt-3 shadow-2xl lg:hidden',
'duration-300 ease-out data-[state=closed]:animate-out data-[state=closed]:slide-out-to-bottom data-[state=open]:animate-in data-[state=open]:slide-in-from-bottom',
'focus:outline-none',
)}
style={{ paddingBottom: 'max(1.25rem, env(safe-area-inset-bottom))' }}
onCloseAutoFocus={(event) => {
const action = afterClose.current
if (!action) return
// Don't bounce focus back to the pill; the page is about to move.
event.preventDefault()
afterClose.current = null
action()
}}
>
<div aria-hidden className="mx-auto mb-4 h-1 w-10 shrink-0 rounded-full bg-border" />

<OutlineHeader
className="mb-4"
progress={progress}
title={
<div className="flex items-center gap-2">
<Dialog.Close
aria-label="Close table of contents"
className="-ml-1.5 rounded-md p-1.5 text-muted-foreground transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
>
<Cross1Icon className="size-4" />
</Dialog.Close>
<Dialog.Title className="font-header text-base font-semibold tracking-tight">
On this page
</Dialog.Title>
</div>
}
/>
<Dialog.Description className="sr-only">
Jump to a section of this article.
</Dialog.Description>

<Outline
size="lg"
headings={headings}
section={section}
className="max-h-[55dvh]"
onJump={(id, index) => closeThen(() => onJump(id, index))}
/>

<OutlineFooter
className="mt-3"
progress={progress}
readingTime={readingTime}
onBackToTop={() => closeThen(onBackToTop)}
/>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
)
}
Loading
Loading