Chapter Rail
A reading map that moves while you read.
Your preview settings
{
"numbers": true,
"labels": "short"
}These are the exact settings driving this demo, including sample content and simulated states. For the installable component’s public API, see Usage and Props below.
Scroll the article slowly, then use the rail to jump between chapters.
A real browser viewport. Scroll within the preview when the sample needs more space. Configuration stays in sync between sizes.
01What it does
A scroll-linked chapter navigator for long-form pages. The marker interpolates through each section's actual progress, the labels quiet down or step forward, and every link remains a native anchor.
In this previewA five-chapter research note with enough copy to scroll. The rail is sticky in the article and becomes a horizontal chapter bar below 720px. The labels and numbering come from the preview controls.
Design decisions
The marker is interpolated from the active section's reading progress, not from an IntersectionObserver threshold, so it keeps drifting between chapter boundaries.
The component finds its own scroll container by walking up the tree. That makes the same source work in a page, a docs panel or a preview iframe without a provider.
Only transform, height and colour change. The listener is passive and coalesced into one animation frame, and it never writes to scrollTop.
02Install
Registry install
Run this in a React project with components.json. The component and its stylesheet land in components/lab/chapter-rail/.
npx shadcn@latest add https://lab.tanishk.me/r/chapter-rail.jsonFiles included
2- components/lab/chapter-rail/chapter-rail.tsxcomponent
- components/lab/chapter-rail/chapter-rail.cssstyles
Manual install: copy each file into the same folder and preserve its relative imports. Open the source
03Usage
import { ChapterRail } from "@/components/lab/chapter-rail/chapter-rail";
const chapters = [
{ id: "intro", label: "Introduction" },
{ id: "method", label: "Method" },
{ id: "findings", label: "Findings" },
];
export function Article() {
return (
<div style={{ display: "grid", gridTemplateColumns: "180px 1fr", gap: 40 }}>
<aside style={{ position: "sticky", top: 24, alignSelf: "start" }}>
<ChapterRail chapters={chapters} numbered />
</aside>
<article>
<section id="intro"><h2>Introduction</h2></section>
<section id="method"><h2>Method</h2></section>
<section id="findings"><h2>Findings</h2></section>
</article>
</div>
);
}04Props
| Prop | Type | Default | Notes |
|---|---|---|---|
chapters | { id: string; label: string; title?: string }[] | — | Section ids and their rail labels; title becomes the link's accessible name. |
label | string | "Chapters" | Accessible name for the navigation landmark. |
numbered | boolean | true | Show 01, 02… beside the labels. |
scrollContainer | HTMLElement | null | — | The scrolling element. Omit to use the nearest scrollable ancestor, then the window. |
className | string | — | Forwarded to the root for layout customization. |
05Accessibility
- Links are ordinary anchors with href values, so browser navigation, open-in-new-tab and history all work.
- The active chapter is exposed with aria-current="location"; the marker and progress line are decorative.
- No scroll hijacking, snapping or wheel interception is used. Clicking a chapter scrolls natively.
- On narrow viewports the rail becomes a compact horizontal navigator with a visible focus ring; reduced motion removes marker interpolation.
06Source
2 files, 490 lines. The combined copy is a reference; save each file separately for use.
components/lab/chapter-rail/chapter-rail.tsx— press enter to show or hide the source
"use client";
import {
useCallback,
useEffect,
useRef,
useState,
type CSSProperties,
} from "react";
import "./chapter-rail.css";
export type Chapter = {
/** The id of the section this chapter points at. */
id: string;
label: string;
/** Optional fuller title, used as the link's accessible name. */
title?: string;
};
export type ChapterRailProps = {
chapters: Chapter[];
/** Accessible name for the navigation landmark. */
label?: string;
/** Show 01, 02… beside each label. */
numbered?: boolean;
/**
* The element that owns scrolling. Omit to let the rail find the
* nearest scrollable ancestor, then fall back to the window.
*/
scrollContainer?: HTMLElement | null;
className?: string;
};
function isScrollable(element: HTMLElement) {
const style = window.getComputedStyle(element);
return (
/(auto|scroll|overlay)/.test(style.overflowY) &&
element.scrollHeight > element.clientHeight + 2
);
}
function findScroller(start: HTMLElement | null): HTMLElement | Window {
let node = start?.parentElement ?? null;
while (node && node !== document.body) {
if (isScrollable(node)) return node;
node = node.parentElement;
}
return window;
}
/**
* CHAPTER RAIL
*
* A reading map that follows the section you are actually in. The
* marker is interpolated from the section's own scroll progress, so it
* keeps moving while you read instead of jumping at section boundaries.
* Scrolling is entirely native: links are ordinary anchors, there is no
* snap and no scroll listener that writes to scrollTop.
*/
export function ChapterRail({
chapters,
label = "Chapters",
numbered = true,
scrollContainer,
className,
}: ChapterRailProps) {
const rootRef = useRef<HTMLElement>(null);
const trackRef = useRef<HTMLDivElement>(null);
const linkRefs = useRef(new Map<string, HTMLAnchorElement>());
const [active, setActive] = useState(0);
const [position, setPosition] = useState(0);
const [progress, setProgress] = useState(0);
const [horizontal, setHorizontal] = useState(false);
const frame = useRef<number | null>(null);
const scroller = useRef<HTMLElement | Window | null>(null);
const activeId = chapters[active]?.id;
const measure = useCallback(() => {
const root = rootRef.current;
if (!root || chapters.length === 0) return;
const owner = scroller.current;
const isWindow = owner === window;
const container = isWindow ? null : (owner as HTMLElement);
const doc = root.ownerDocument;
const containerTop = container
? container.getBoundingClientRect().top
: 0;
const scrollTop = isWindow ? window.scrollY : container!.scrollTop;
const viewportHeight = isWindow
? window.innerHeight
: container!.clientHeight;
const anchorLine = scrollTop + Math.min(viewportHeight * 0.34, 320);
const sections = chapters.map((chapter) =>
doc.getElementById(chapter.id),
);
let index = 0;
for (let i = 0; i < sections.length; i += 1) {
const section = sections[i];
if (!section) continue;
const top =
section.getBoundingClientRect().top - containerTop + scrollTop;
if (top <= anchorLine) index = i;
}
const current = sections[index];
const next = sections[index + 1];
const currentTop = current
? current.getBoundingClientRect().top - containerTop + scrollTop
: 0;
const currentHeight = current?.offsetHeight ?? 1;
const local = Math.max(
0,
Math.min(1, (anchorLine - currentTop) / Math.max(currentHeight, 1)),
);
/* A last section has no successor: let it hold the end of the rail. */
const span = index + (next ? local : 1);
const ratio = chapters.length <= 1 ? 0 : span / (chapters.length - 1);
const track = trackRef.current;
const rails = chapters
.map((chapter) => linkRefs.current.get(chapter.id))
.filter((node): node is HTMLAnchorElement => Boolean(node));
if (track && rails.length) {
const trackRect = track.getBoundingClientRect();
const centers = rails.map((node) => {
const rect = node.getBoundingClientRect();
return horizontal
? rect.left + rect.width / 2 - trackRect.left
: rect.top + rect.height / 2 - trackRect.top;
});
const first = centers[0];
const last = centers[centers.length - 1];
const safe = Math.max(0, Math.min(1, ratio));
setPosition(first + safe * (last - first));
setProgress(safe);
}
setActive(index);
}, [chapters, horizontal]);
const schedule = useCallback(() => {
if (frame.current !== null) return;
frame.current = window.requestAnimationFrame(() => {
frame.current = null;
measure();
});
}, [measure]);
useEffect(() => {
const root = rootRef.current;
if (!root) return;
const owner = scrollContainer ?? findScroller(root);
scroller.current = owner;
const target = owner === window ? window : owner;
target.addEventListener("scroll", schedule, { passive: true });
window.addEventListener("resize", schedule);
const media = window.matchMedia("(max-width: 720px)");
const syncOrientation = () => {
setHorizontal(media.matches);
window.requestAnimationFrame(measure);
};
syncOrientation();
media.addEventListener?.("change", syncOrientation);
let observer: ResizeObserver | null = null;
if (typeof ResizeObserver === "function") {
observer = new ResizeObserver(schedule);
observer.observe(root);
const doc = root.ownerDocument;
for (const chapter of chapters) {
const section = doc.getElementById(chapter.id);
if (section) observer.observe(section);
}
}
window.requestAnimationFrame(measure);
return () => {
target.removeEventListener("scroll", schedule);
window.removeEventListener("resize", schedule);
media.removeEventListener?.("change", syncOrientation);
observer?.disconnect();
if (frame.current !== null) {
window.cancelAnimationFrame(frame.current);
frame.current = null;
}
};
}, [chapters, measure, schedule, scrollContainer]);
const style = {
"--cr-pos": `${position}px`,
"--cr-progress": progress,
} as CSSProperties;
useEffect(() => {
if (!horizontal) return;
const link = linkRefs.current.get(activeId ?? "");
link?.scrollIntoView({ block: "nearest", inline: "nearest" });
}, [activeId, horizontal]);
return (
<nav
ref={rootRef}
className={`cr-root${className ? ` ${className}` : ""}`}
aria-label={label}
data-horizontal={horizontal ? "true" : "false"}
style={style}
>
<p className="cr-kicker">Reading map</p>
<div ref={trackRef} className="cr-track" aria-hidden="true">
<span className="cr-line" />
<span className="cr-line cr-line--progress" />
<span className="cr-marker" />
</div>
<ol className="cr-list" onScroll={schedule}>
{chapters.map((chapter, index) => (
<li key={chapter.id}>
<a
ref={(node) => {
if (node) linkRefs.current.set(chapter.id, node);
else linkRefs.current.delete(chapter.id);
}}
href={`#${chapter.id}`}
aria-current={index === active ? "location" : undefined}
aria-label={chapter.title ?? chapter.label}
>
{numbered ? (
<span className="cr-number" aria-hidden="true">
{String(index + 1).padStart(2, "0")}
</span>
) : null}
<span className="cr-label">{chapter.label}</span>
</a>
</li>
))}
</ol>
</nav>
);
}components/lab/chapter-rail/chapter-rail.css— press enter to show or hide the source
.cr-root {
--cr-ink: #232018;
--cr-muted: #7b7568;
--cr-line: rgba(35, 32, 24, 0.16);
--cr-accent: #8a2f27;
--cr-paper: #f4f0e6;
--cr-ease: cubic-bezier(0.22, 1, 0.36, 1);
position: relative;
display: grid;
grid-template-columns: 18px minmax(0, 1fr);
column-gap: 14px;
min-width: 0;
color: var(--cr-ink);
font: inherit;
}
.cr-kicker {
grid-column: 1 / -1;
margin: 0 0 18px;
font-family: ui-monospace, "SF Mono", "Cascadia Mono", Consolas, monospace;
font-size: 0.625rem;
letter-spacing: 0.14em;
text-transform: uppercase;
color: var(--cr-muted);
}
.cr-track {
position: relative;
grid-column: 1;
grid-row: 2;
width: 18px;
}
.cr-line {
position: absolute;
top: 12px;
bottom: 12px;
left: 8px;
width: 1px;
background: var(--cr-line);
}
.cr-line--progress {
bottom: auto;
height: calc((100% - 24px) * var(--cr-progress, 0));
background: var(--cr-accent);
transition: height 120ms linear;
}
.cr-marker {
position: absolute;
top: var(--cr-pos, 0px);
left: 3px;
width: 11px;
height: 11px;
margin-top: -5.5px;
border: 1px solid var(--cr-accent);
border-radius: 50%;
background: var(--cr-paper);
box-shadow: 0 0 0 4px color-mix(in srgb, var(--cr-accent) 12%, transparent);
transition: top 180ms var(--cr-ease);
}
.cr-list {
grid-column: 2;
grid-row: 2;
display: grid;
gap: 2px;
margin: 0;
padding: 0;
list-style: none;
}
.cr-list a {
display: flex;
align-items: baseline;
gap: 9px;
min-height: 34px;
padding: 7px 8px;
border-radius: 6px;
color: var(--cr-muted);
font-size: 0.8125rem;
line-height: 1.35;
text-decoration: none;
transition:
color 180ms var(--cr-ease),
background-color 180ms var(--cr-ease);
}
.cr-number {
flex: none;
font-family: ui-monospace, "SF Mono", "Cascadia Mono", Consolas, monospace;
font-size: 0.5625rem;
letter-spacing: 0.06em;
color: var(--cr-muted);
opacity: 0.72;
transition: color 180ms var(--cr-ease);
}
.cr-label {
min-width: 0;
overflow-wrap: anywhere;
transition:
transform 220ms var(--cr-ease),
font-weight 220ms var(--cr-ease);
}
.cr-list a:hover {
color: var(--cr-ink);
background: color-mix(in srgb, var(--cr-ink) 5%, transparent);
}
.cr-list a[aria-current="location"] {
color: var(--cr-ink);
font-weight: 600;
}
.cr-list a[aria-current="location"] .cr-label {
transform: translateX(2px);
}
.cr-list a[aria-current="location"] .cr-number {
color: var(--cr-accent);
opacity: 1;
}
.cr-list a:focus-visible {
outline: 2px solid var(--cr-accent);
outline-offset: 2px;
}
@media (max-width: 720px) {
.cr-root {
display: block;
padding: 10px 12px 12px;
border: 1px solid var(--cr-line);
border-radius: 10px;
background: color-mix(in srgb, var(--cr-paper) 92%, transparent);
backdrop-filter: blur(6px);
}
.cr-kicker {
margin: 0 0 9px;
font-size: 0.5625rem;
}
.cr-track {
position: absolute;
right: 14px;
bottom: 8px;
left: 14px;
top: auto;
width: auto;
height: 1px;
}
.cr-line {
top: 0;
bottom: auto;
left: 0;
width: 100%;
height: 1px;
}
.cr-line--progress {
width: calc(100% * var(--cr-progress, 0));
height: 1px;
transition: width 120ms linear;
}
.cr-marker {
top: -5px;
left: var(--cr-pos, 0px);
margin-top: 0;
margin-left: -5.5px;
transition: left 180ms var(--cr-ease);
}
.cr-list {
display: flex;
gap: 2px;
margin: 0 0 8px;
overflow-x: auto;
scrollbar-width: none;
}
.cr-list::-webkit-scrollbar {
display: none;
}
.cr-list li {
flex: 0 0 auto;
}
.cr-list a {
min-height: 32px;
padding: 5px 8px;
font-size: 0.75rem;
font-weight: 500;
white-space: nowrap;
}
.cr-list a[aria-current="location"] {
font-weight: 500;
}
.cr-list a[aria-current="location"] .cr-label {
transform: none;
}
.cr-number {
font-size: 0.5rem;
}
}
@media (max-width: 480px) {
.cr-number {
display: none;
}
.cr-list a {
padding: 5px 6px;
font-size: 0.6875rem;
}
}
@media (max-width: 380px) {
.cr-root {
padding: 8px 9px 10px;
}
.cr-list a {
padding: 4px 4px;
font-size: 0.625rem;
}
}
@media (prefers-reduced-motion: reduce) {
.cr-marker,
.cr-line--progress,
.cr-list a,
.cr-label,
.cr-number {
transition-duration: 0.01ms;
}
}