Table of contents
Section links on an angled rail that highlights the sections on screen.
Overview
Scroll this preview: the sections on screen are traced along the rail, and their links brighten. Click a link to glide to its section.
Scroll this preview: the sections on screen are traced along the rail, and their links brighten. Click a link to glide to its section.
Install
Scroll this preview: the sections on screen are traced along the rail, and their links brighten. Click a link to glide to its section.
Scroll this preview: the sections on screen are traced along the rail, and their links brighten. Click a link to glide to its section.
With the CLI
Scroll this preview: the sections on screen are traced along the rail, and their links brighten. Click a link to glide to its section.
Scroll this preview: the sections on screen are traced along the rail, and their links brighten. Click a link to glide to its section.
By hand
Scroll this preview: the sections on screen are traced along the rail, and their links brighten. Click a link to glide to its section.
Scroll this preview: the sections on screen are traced along the rail, and their links brighten. Click a link to glide to its section.
Usage
Scroll this preview: the sections on screen are traced along the rail, and their links brighten. Click a link to glide to its section.
Scroll this preview: the sections on screen are traced along the rail, and their links brighten. Click a link to glide to its section.
Theming
Scroll this preview: the sections on screen are traced along the rail, and their links brighten. Click a link to glide to its section.
Scroll this preview: the sections on screen are traced along the rail, and their links brighten. Click a link to glide to its section.
<TableOfContents items={items} scrollRoot={scroller} />Installation
CLI
pnpm dlx shadcn@latest add @riff/table-of-contentsManual
Copy the component
Save this as
components/ui/table-of-contents.tsx:'use client'; import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type MouseEvent, type RefObject, } from 'react'; import './table-of-contents.css'; type CustomProperties = CSSProperties & Record<`--${string}`, string | number>; /** Custom properties for `style`, typed without a global declaration. */ const cssVars = (values: CustomProperties): CSSProperties => values; export type TocItem = { /** The heading element's id. */ id: string; title: string; /** The heading level, such as 2 for an `h2`. */ level: number; }; type Rail = { path: string; length: number; stops: { top: number; bottom: number }[]; }; /** * Each item's indent: its level below the shallowest heading, never more than * one step deeper than the item before it, so an `h4` right after an `h2` * still nests by one. */ function depthsOf(levels: number[]) { const base = Math.min(...levels); let previous = -1; return levels.map((level) => { previous = Math.min(level - base, previous + 1); return previous; }); } /** * A vertical line through every link that steps sideways where nesting * changes, with where each link starts and ends along it, so a dash can trace * a run of links. */ function railFor( links: { depth: number; top: number; height: number }[], indent: number, inset: number, ): Rail { const points: { x: number; y: number }[] = []; let length = 0; const lineTo = (x: number, y: number) => { const previous = points.at(-1); if (previous) length += Math.hypot(x - previous.x, y - previous.y); points.push({ x, y }); return length; }; const xOf = (depth: number) => depth * indent + inset; const stops = links.map(({ depth, top, height }, index) => { const x = xOf(depth); const previous = points.at(-1); const steps = previous !== undefined && previous.x !== x; const start = steps ? length : lineTo(x, top); if (steps) lineTo(x, top + indent / 2); const next = links[index + 1]; const bend = next && xOf(next.depth) !== x ? indent / 2 : 0; return { top: start, bottom: lineTo(x, top + height - bend) }; }); const path = points .map(({ x, y }, index) => `${index === 0 ? 'M' : 'L'}${x} ${y}`) .join(''); return { path, length, stops }; } const pixels = (value: string) => { const number = Number.parseFloat(value) || 0; return value.trim().endsWith('rem') ? number * Number.parseFloat(getComputedStyle(document.documentElement).fontSize) : number; }; const reducedMotion = () => matchMedia('(prefers-reduced-motion: reduce)').matches; /** * "On this page" links on an angled rail. The sections on screen are traced * along the rail and their titles brighten as the reader scrolls. */ export function TableOfContents({ items, label = 'On this page', scrollRoot, contentRef, }: { items: readonly TocItem[]; label?: string; /** The element that scrolls the headings; the window when omitted. */ scrollRoot?: RefObject<HTMLElement | null>; /** Where the last section ends; the end of the scroll area when omitted. */ contentRef?: RefObject<HTMLElement | null>; }) { const track = useRef<HTMLDivElement>(null); const list = useRef<HTMLDivElement>(null); const [rail, setRail] = useState<Rail>(); const [[first, last], setRange] = useState<[number, number]>([-1, -1]); const [passed, setPassed] = useState(false); const depths = depthsOf(items.map((item) => item.level)); // The rail follows the rendered links, so wrapped titles bend it correctly. useLayoutEffect(() => { const element = track.current; if (!element) return; const measure = () => { const style = getComputedStyle(element); const links = [...element.querySelectorAll<HTMLElement>('a')]; setRail( railFor( links.map((link) => ({ depth: Number(link.dataset.depth), top: link.offsetTop, height: link.offsetHeight, })), pixels(style.getPropertyValue('--riff-toc-indent')), pixels(style.getPropertyValue('--riff-toc-width')) / 2, ), ); }; measure(); const observer = new ResizeObserver(measure); observer.observe(element); return () => observer.disconnect(); }, []); // Every section with at least 48px on screen is active. useEffect(() => { const root = scrollRoot?.current ?? null; const target: HTMLElement | Window = root ?? window; const headings = items.flatMap((item) => { const heading = document.getElementById(item.id); return heading ? [heading] : []; }); let blocks: { start: number; end: number }[] = []; let inset = 0; let frame = 0; const scrollTop = () => (root ? root.scrollTop : scrollY); const viewTop = () => (root ? root.getBoundingClientRect().top : 0); const viewHeight = () => (root ? root.clientHeight : innerHeight); const update = () => { frame = 0; const top = scrollTop() + inset; const bottom = scrollTop() + viewHeight(); const visible = blocks.flatMap((block, index) => Math.min(block.end, bottom) - Math.max(block.start, top) >= 48 ? [index] : [], ); const next: [number, number] = [visible[0] ?? -1, visible.at(-1) ?? -1]; setRange((current) => current[0] === next[0] && current[1] === next[1] ? current : next, ); const end = blocks.at(-1)?.end; setPassed(end !== undefined && top >= end); }; const measure = () => { const offset = scrollTop() - viewTop(); const [firstHeading] = headings; inset = firstHeading ? Number.parseFloat(getComputedStyle(firstHeading).scrollMarginTop) || 0 : 0; const contentEnd = contentRef?.current ? contentRef.current.getBoundingClientRect().bottom + offset : (root ?? document.documentElement).scrollHeight; blocks = headings.map((heading, index) => { const next = headings[index + 1]; return { start: heading.getBoundingClientRect().top + offset, end: next ? next.getBoundingClientRect().top + offset : contentEnd, }; }); update(); }; const schedule = () => { if (!frame) frame = requestAnimationFrame(update); }; const observer = new ResizeObserver(measure); observer.observe(root ?? document.body); measure(); target.addEventListener('scroll', schedule, { passive: true }); window.addEventListener('resize', measure); return () => { cancelAnimationFrame(frame); observer.disconnect(); target.removeEventListener('scroll', schedule); window.removeEventListener('resize', measure); }; }, [items, scrollRoot, contentRef]); // A list taller than its area scrolls itself to keep the first active link // a third of the way down; it never scrolls the page. useEffect(() => { const scroller = list.current; const active = track.current?.querySelectorAll('a')[first]; if (!scroller || !active || scroller.scrollHeight <= scroller.clientHeight) return; const top = active.offsetTop; const bottom = top + active.offsetHeight; if ( top < scroller.scrollTop || bottom > scroller.scrollTop + scroller.clientHeight ) scroller.scrollTo({ top: top - scroller.clientHeight / 3, behavior: reducedMotion() ? 'instant' : 'smooth', }); }, [first]); const select = (event: MouseEvent<HTMLAnchorElement>, id: string) => { const heading = document.getElementById(id); if ( !heading || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey ) return; event.preventDefault(); const behavior = reducedMotion() ? 'instant' : 'smooth'; const root = scrollRoot?.current; if (root) { const margin = Number.parseFloat(getComputedStyle(heading).scrollMarginTop) || 0; root.scrollTo({ top: heading.getBoundingClientRect().top - root.getBoundingClientRect().top + root.scrollTop - margin, behavior, }); } else { history.pushState(null, '', `#${id}`); heading.scrollIntoView({ behavior, block: 'start' }); } // Keyboard focus moves with the view. if (heading.tabIndex < 0 && !heading.hasAttribute('tabindex')) heading.tabIndex = -1; heading.focus({ preventScroll: true }); }; if (!items.length) return null; // The trail rests at whichever end the reader left when nothing is active. const start = rail?.stops[first]?.top ?? (passed ? (rail?.length ?? 0) : 0); const end = rail?.stops[last]?.bottom ?? start; return ( <nav className="riff-toc" aria-label={label}> <p className="riff-toc-label" aria-hidden="true"> {label} </p> <div ref={list} className="riff-toc-scroll"> <div ref={track} className="riff-toc-track" data-measured={rail ? '' : undefined} > {rail && ( <svg aria-hidden="true" className="riff-toc-rail" style={cssVars({ '--riff-toc-length': `${rail.length}px`, '--riff-toc-start': `${start}px`, '--riff-toc-run': `${end - start}px`, })} > <path className="riff-toc-rail-path" d={rail.path} /> <path className="riff-toc-trail" data-visible={rail.stops[first] ? '' : undefined} d={rail.path} /> </svg> )} <ul className="riff-toc-list"> {items.map((item, index) => { const depth = depths[index] ?? 0; const previous = depths[index - 1]; const next = depths[index + 1]; return ( <li key={item.id}> <a href={`#${item.id}`} className="riff-toc-link" onClick={(event) => select(event, item.id)} data-depth={depth} data-step={ previous !== undefined && previous !== depth ? '' : undefined } data-active={ index >= first && index <= last ? '' : undefined } aria-current={index === first ? 'location' : undefined} // Server HTML draws the rail in CSS from these depths. style={cssVars({ '--riff-toc-depth': depth, '--riff-toc-from': previous ?? depth, '--riff-toc-below': next !== undefined && next !== depth ? 1 : 0, })} > {item.title} </a> </li> ); })} </ul> </div> </div> </nav> ); }Copy its styles
Save this beside it as
table-of-contents.css:/* Host roles first, system colours after: the component reads your theme when it has these properties and stays legible when it does not. */ @layer components { /* 14px links on a 2px rail that steps 8px sideways per nesting level. */ .riff-toc { --riff-toc-indent: 0.5rem; --riff-toc-width: 2px; --riff-toc-tint: var( --color-border, color-mix(in srgb, currentColor 15%, transparent) ); display: flex; flex-direction: column; gap: 0.75rem; color: var(--color-muted-foreground, GrayText); font-size: 0.875rem; } .riff-toc-label { margin: 0; color: var(--color-foreground, CanvasText); font-weight: 500; } .riff-toc-scroll { max-height: var(--riff-toc-max-height, calc(100dvh - 8rem)); overflow-y: auto; scrollbar-width: none; } .riff-toc-track { position: relative; isolation: isolate; } .riff-toc-list { display: flex; flex-direction: column; margin: 0; padding: 0; list-style: none; } .riff-toc-link { position: relative; display: block; padding-block: 0.25rem; padding-inline: calc( 1.25rem + var(--riff-toc-depth, 0) * var(--riff-toc-indent) ) 0; color: inherit; line-height: 1.5; text-decoration: none; overflow-wrap: anywhere; transition: color 150ms cubic-bezier(0, 0, 0.2, 1); &[data-active] { color: var(--color-foreground, CanvasText); } &:focus-visible { border-radius: 0.25rem; outline: 2px solid var(--color-ring, Highlight); outline-offset: -2px; } } /* Before measurement the rail is drawn in CSS: each link's segment at its depth, and a diagonal one indent tall where the depth changes. */ .riff-toc-link::before, .riff-toc-link[data-step]::after { content: ''; position: absolute; border-radius: var(--riff-toc-width); background-color: var(--riff-toc-tint); pointer-events: none; } .riff-toc-link::before { inset-block: 0 calc(var(--riff-toc-below, 0) * var(--riff-toc-indent) / 2); left: calc(var(--riff-toc-depth, 0) * var(--riff-toc-indent)); width: var(--riff-toc-width); } .riff-toc-link[data-step] { --riff-toc-step: calc( (var(--riff-toc-depth, 0) - var(--riff-toc-from, 0)) * var(--riff-toc-indent) ); &::before { top: calc(var(--riff-toc-indent) / 2); } &::after { top: calc(-1 * var(--riff-toc-indent) / 2 - var(--riff-toc-width) / 2); left: calc( var(--riff-toc-from, 0) * var(--riff-toc-indent) + var(--riff-toc-width) / 2 ); width: hypot(var(--riff-toc-step), var(--riff-toc-indent)); height: var(--riff-toc-width); transform-origin: 0 50%; rotate: atan2(var(--riff-toc-indent), var(--riff-toc-step)); } } /* Once measured, one SVG stroke replaces the CSS pieces. */ .riff-toc-track[data-measured] .riff-toc-link { &::before, &::after { display: none; } } .riff-toc-rail { position: absolute; z-index: 1; inset: 0; width: 100%; height: 100%; overflow: visible; fill: none; pointer-events: none; stroke-linecap: round; stroke-linejoin: round; stroke-width: var(--riff-toc-width); } .riff-toc-rail-path { stroke: var(--riff-toc-tint); } /* The sections on screen, as a dash along the rail. */ .riff-toc-trail { stroke: var(--color-primary, Highlight); stroke-dasharray: var(--riff-toc-run, 0) var(--riff-toc-length, 0); stroke-dashoffset: calc(-1 * var(--riff-toc-start, 0px)); opacity: 0; transition: stroke-dasharray 200ms cubic-bezier(0, 0, 0.2, 1), stroke-dashoffset 200ms cubic-bezier(0, 0, 0.2, 1), opacity 200ms cubic-bezier(0, 0, 0.2, 1); &[data-visible] { opacity: 1; } } @media (hover: hover) { .riff-toc-link:hover { color: var(--color-foreground, CanvasText); } } @media (prefers-reduced-motion: reduce) { .riff-toc-link, .riff-toc-trail { transition: none; } } }
Usage
import { TableOfContents } from '@/components/ui/table-of-contents';
const items = [
{ id: 'overview', title: 'Overview', level: 2 },
{ id: 'install', title: 'Install', level: 2 },
{ id: 'cli', title: 'With the CLI', level: 3 },
];
<TableOfContents items={items} />;Pass one item per heading, with the heading’s id. The component finds the headings in the page, so it works with any Markdown or MDX pipeline that gives headings ids. Leave out scrollRoot to track the window.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
items | TocItem[] | Each heading: id, title and level. | |
label | string | 'On this page' | The heading above the links and the nav’s name. |
scrollRoot | RefObject<HTMLElement> | window | The element that scrolls the headings. |
contentRef | RefObject<HTMLElement> | Where the last section ends. |