Components / Chapter Rail

Chapter Rail

Sections still to come wait in a dim list in the bottom-right corner. As one scrolls in, its title lifts out, stands upright, travels up the right edge and curls letter by letter into a stack at the top right. Scrolling back plays it in reverse. Every title is a button that jumps to its section, and a ruler scrollbar on the far edge shows and scrubs the page position.

scrollnavigationtypographyAdded 2026-12-03Source

Scroll inside the frame, or open it full screen.

Installation

With the CLI

Copies the component into your project. Needs a components.json; see one-time setup.

npx shadcn@latest add https://components.aceternal.in/r/chapter-rail.json

By hand

  1. 1

    Create components/chapter-rail.tsx and paste in the source. It needs only React.

    chapter-rail.tsx
    "use client";
    
    /*
      ChapterRail: scroll-driven section titles and a ruler scrollbar on the right edge. Desktop only.
    
      - Sections still to come wait in a dim list in the bottom-right corner.
      - As a section scrolls in, its title lifts out of that list, stands upright, travels up the right
        edge as a vertical word, and curls over letter by letter into a stack in the top-right corner.
        The newest title is large; the ones passed shrink and dim above it. Scrolling back reverses it.
      - Every title is a button: the bottom list jumps forward, the top stack jumps back.
      - A ruler scrollbar (ticks 0-100 and a % marker) on the far right; click or drag it to scrub the page.
    
      Self-contained: React only, no Tailwind or CSS file needed. Works in Next.js (App Router) and Vite.
    
      Usage:
        <section data-chapter="Intro">…</section>
        <section data-chapter="Features">…</section>
        <ChapterRail />            // anywhere once on the page, e.g. at the top of <body> or <main>
    
      The first chapter counts as already arrived. Default colour is white with "difference" blending, so it
      reads on dark and light sections alike; for a single light theme pass color="#000" blend="normal".
      Motion is instant for visitors who prefer reduced motion.
    */
    import { useEffect, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent } from "react";
    
    export type ChapterRailProps = {
      /** CSS selector for the sections; the title comes from the `data-chapter` attribute or `getTitle`. */
      selector?: string;
      /** Read a title from a section; defaults to its `data-chapter` attribute. */
      getTitle?: (el: HTMLElement) => string;
      /** Text and line colour. */
      color?: string;
      /** mix-blend-mode for the titles and ruler. */
      blend?: CSSProperties["mixBlendMode"];
      /** Font for the titles; defaults to the page font. */
      fontFamily?: string;
      fontWeight?: number;
      /** Font for the ruler numbers. */
      monoFamily?: string;
      /** px: the newest title, passed titles and the waiting list, and the title while it travels. */
      sizeLarge?: number;
      sizeSmall?: number;
      sizeColumn?: number;
      /** px: top stack's distance from the top (clear your navbar), and the waiting list's from the bottom. */
      top?: number;
      bottom?: number;
      /** px: titles' distance from the right edge (keep it clear of the ruler). */
      right?: number;
      /** Show the ruler scrollbar, and its width in px. */
      ruler?: boolean;
      rulerWidth?: number;
      /** Blurred patches behind the two corners so titles stay readable over busy content. */
      backdrop?: boolean;
      /** Hidden below this viewport width, in px. */
      minWidth?: number;
      /** Smoothing per frame, 0-1: lower glides more. */
      ease?: number;
      /** Uppercase the titles. */
      uppercase?: boolean;
      zIndex?: number;
    };
    
    type Chapter = { el: HTMLElement; letters: string[]; widths: number[] };
    
    const clamp = (v: number, a = 0, b = 1) => Math.min(b, Math.max(a, v));
    const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
    const smooth = (t: number) => t * t * (3 - 2 * t);
    const NBSP = " ";
    
    export function ChapterRail({
      selector = "[data-chapter]",
      getTitle = (el) => el.dataset.chapter ?? "",
      color = "#fff",
      blend = "difference",
      fontFamily = "inherit",
      fontWeight = 900,
      monoFamily = "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",
      sizeLarge = 34,
      sizeSmall = 15,
      sizeColumn = 19,
      top = 84,
      bottom = 28,
      right = 84,
      ruler = true,
      rulerWidth = 56,
      backdrop = true,
      minWidth = 1024,
      ease = 0.12,
      uppercase = true,
      zIndex = 40,
    }: ChapterRailProps) {
      const [titles, setTitles] = useState<string[]>([]);
      const stackRef = useRef<HTMLDivElement>(null);
      const markerRef = useRef<HTMLDivElement>(null);
      const markerLabelRef = useRef<HTMLSpanElement>(null);
      const ticksRef = useRef<HTMLDivElement>(null);
      const linksRef = useRef<HTMLDivElement>(null);
      const hoverRef = useRef(-1);
      const kickRef = useRef<() => void>(() => {});
      const getTitleRef = useRef(getTitle);
      getTitleRef.current = getTitle;
    
      // Collect the chapters once the page is in the DOM.
      useEffect(() => {
        const els = [...document.querySelectorAll<HTMLElement>(selector)];
        setTitles(els.map((el) => getTitleRef.current(el)));
      }, [selector]);
    
      useEffect(() => {
        if (!titles.length || !stackRef.current) return;
        const stack = stackRef.current;
        const reduce = matchMedia("(prefers-reduced-motion: reduce)").matches;
        const els = [...document.querySelectorAll<HTMLElement>(selector)];
        const BIG = sizeLarge;
    
        // Measure every letter at the large size, in the real font.
        const probe = document.createElement("span");
        probe.className = "cr-letter";
        probe.style.cssText = `position:absolute;visibility:hidden;font-size:${BIG}px`;
        stack.appendChild(probe);
        const chapters: Chapter[] = els.map((el, i) => {
          const t = titles[i] ?? "";
          const letters = [...(uppercase ? t.toUpperCase() : t)];
          const widths = letters.map((ch) => {
            probe.textContent = ch === " " ? NBSP : ch;
            return probe.getBoundingClientRect().width;
          });
          return { el, letters, widths };
        });
        probe.remove();
    
        const spans = [...stack.querySelectorAll<HTMLSpanElement>("[data-ci]")];
        const byChapter = chapters.map((_, i) => spans.filter((s) => s.dataset.ci === String(i)));
        const ticks = [...(ticksRef.current?.children ?? [])] as HTMLElement[];
        const links = [...(linksRef.current?.children ?? [])] as HTMLElement[];
        const nudge: number[] = chapters.map(() => 0); // hover slide, eased
        const shown: number[] = chapters.map((_, i) => (i === 0 ? 1 : 0));
        let shownProgress = 0;
        let raf = 0;
    
        const targets = () => {
          const vh = innerHeight;
          const max = document.documentElement.scrollHeight - vh;
          const t = chapters.map((c, i) => {
            if (i === 0) return 1;
            // In scroll position: starts as the section's top enters the bottom of the screen and lands
            // as it nears the top; sections near the end land by the time the page can't scroll further.
            const at = c.el.getBoundingClientRect().top + scrollY;
            const start = at - vh;
            const end = Math.max(Math.min(at - vh * 0.15, max), start + 1);
            const v = clamp((scrollY - start) / (end - start));
            return reduce ? (v > 0.5 ? 1 : 0) : v;
          });
          return { t, p: max > 0 ? clamp(scrollY / max) : 0 };
        };
    
        const frame = () => {
          const { t, p } = targets();
          let moving = false;
          for (let i = 0; i < shown.length; i++) {
            const d = (t[i] ?? 0) - (shown[i] ?? 0);
            if (Math.abs(d) > 0.0005) moving = true;
            shown[i] = reduce ? (t[i] ?? 0) : (shown[i] ?? 0) + d * (Math.abs(d) < 0.002 ? 1 : ease * 1.6);
          }
          for (let i = 0; i < nudge.length; i++) {
            const goal = hoverRef.current === i ? 1 : 0;
            const d = goal - (nudge[i] ?? 0);
            if (Math.abs(d) > 0.002) moving = true;
            nudge[i] = reduce ? goal : (nudge[i] ?? 0) + d * 0.2;
          }
          const dp = p - shownProgress;
          if (Math.abs(dp) > 0.0005) moving = true;
          shownProgress = reduce ? p : shownProgress + dp * ease * 2;
    
          draw();
          raf = moving ? requestAnimationFrame(frame) : 0;
        };
    
        const draw = () => {
          const vw = innerWidth;
          const vh = innerHeight;
          const edge = vw - right;
          const colX = edge + 14; // the column a rising title travels up
          const count = chapters.length;
          // How far each chapter has landed in the top stack (the last 30% of its journey).
          const land = chapters.map((_, i) => smooth(clamp(((shown[i] ?? 0) - 0.7) / 0.3)));
          let y = top;
    
          chapters.forEach((c, i) => {
            const ti = shown[i] ?? 0;
            const landed = land[i] ?? 0;
            const current = landed * (1 - (land[i + 1] ?? 0)); // 1 while this is the newest chapter
            const hover = nudge[i] ?? 0;
            const sum = c.widths.reduce((a, b) => a + b, 0);
            const n = c.letters.length;
    
            // Top stack line, where the title lands.
            const size = lerp(sizeSmall, BIG, current);
            const sT = size / BIG;
            const lineH = size * 1.12;
            const totalT = sum * sT;
            const yT = y + lineH / 2;
    
            // Waiting list line, anchored to the bottom of the screen.
            const sB = sizeSmall / BIG;
            const totalB = sum * sB;
            const yB = vh - bottom - (count - 1 - i) * sizeSmall * 1.12 - sizeSmall * 0.56;
    
            // Vertical column: the word stands upright, reading upward, and travels from the list to the top.
            const sV = sizeColumn / BIG;
            const totalV = sum * sV;
            const travel = smooth(clamp((ti - 0.2) / 0.5));
            const colStart = yB - 20;
            const colEnd = Math.min(colStart, yT + 64 + totalV);
            const colBottom = lerp(colStart, colEnd, travel);
    
            let xT = edge - totalT - hover * 10;
            let xB = edge - totalB - hover * 8;
            let cumV = 0;
    
            byChapter[i]?.forEach((span, k) => {
              const w = c.widths[k] ?? 0;
              const tx = xT + (w * sT) / 2;
              xT += w * sT;
              const bx = xB + (w * sB) / 2;
              xB += w * sB;
              const vy = colBottom - (cumV + (w * sV) / 2);
              const vyStart = colStart - (cumV + (w * sV) / 2);
              cumV += w * sV;
    
              // The last letters lead round each corner; the first ones follow.
              const lag = n > 1 ? (n - 1 - k) / (n - 1) : 0;
              const rise = smooth(clamp((ti / 0.2) * 1.6 - lag * 0.6));
              const curl = smooth(clamp(((ti - 0.7) / 0.3) * 1.6 - lag * 0.6));
    
              let px: number, py: number, rot: number, sc: number;
              if (curl > 0) {
                // Over the top: up the column, then round into the stack line.
                const a = 1 - curl;
                px = a * a * colX + 2 * a * curl * colX + curl * curl * tx;
                py = a * a * vy + 2 * a * curl * yT + curl * curl * yT;
                rot = lerp(-90, 0, curl);
                sc = lerp(sV, sT, curl);
              } else if (rise < 1) {
                // Out of the waiting list: right, then up into the column.
                const a = 1 - rise;
                px = a * a * bx + 2 * a * rise * colX + rise * rise * colX;
                py = a * a * yB + 2 * a * rise * yB + rise * rise * vyStart;
                rot = lerp(0, -90, rise);
                sc = lerp(sB, sV, rise);
              } else {
                px = colX;
                py = vy;
                rot = -90;
                sc = sV;
              }
              const dim = 0.5;
              const rest = Math.max(lerp(0.45, 1, current), hover);
              const op = curl > 0 ? lerp(dim, rest, curl) : rise > 0 ? dim : Math.max(dim, hover);
              span.style.transform = `translate3d(${px}px, ${py}px, 0) translate(-50%, -50%) rotate(${rot}deg) scale(${sc})`;
              span.style.opacity = String(op);
            });
    
            // The clickable box: on the waiting list while waiting, on the stack once landed.
            const link = links[i];
            if (link) {
              const waiting = ti < 0.02;
              const live = waiting || landed > 0.6;
              const box = waiting
                ? { x: edge - totalB - 10, y: yB - sizeSmall * 0.6 - 2, w: totalB + 20, h: sizeSmall * 1.2 + 4 }
                : { x: edge - totalT - 12, y, w: totalT + 24, h: Math.max(lineH, 18) };
              link.style.transform = `translate3d(${box.x}px, ${box.y}px, 0)`;
              link.style.width = `${box.w}px`;
              link.style.height = `${box.h}px`;
              link.style.pointerEvents = live ? "auto" : "none";
              link.style.visibility = live ? "visible" : "hidden";
            }
    
            y += lineH * landed;
          });
    
          // Ruler: the marker follows the page; nearby ticks stretch toward it.
          const p = shownProgress;
          if (markerRef.current) markerRef.current.style.transform = `translateY(${p * (vh - 48) + 24}px)`;
          if (markerLabelRef.current) markerLabelRef.current.textContent = `${String(Math.round(p * 100)).padStart(3, "0")}%`;
          ticks.forEach((tick, i) => {
            tick.style.setProperty("--k", String(clamp(1 - Math.abs(i / 100 - p) * 100 / 6)));
          });
        };
    
        const kick = () => {
          if (!raf) raf = requestAnimationFrame(frame);
        };
        kickRef.current = kick;
        draw();
        kick();
        addEventListener("scroll", kick, { passive: true });
        addEventListener("resize", kick);
        document.fonts?.ready.then(kick);
        return () => {
          cancelAnimationFrame(raf);
          removeEventListener("scroll", kick);
          removeEventListener("resize", kick);
        };
      }, [titles, selector, sizeLarge, sizeSmall, sizeColumn, top, bottom, right, ease, uppercase]);
    
      const goTo = (i: number) => {
        const el = document.querySelectorAll<HTMLElement>(selector)[i];
        if (!el) return;
        const y = i === 0 ? 0 : el.getBoundingClientRect().top + scrollY;
        const reduce = matchMedia("(prefers-reduced-motion: reduce)").matches;
        window.scrollTo({ top: y, behavior: reduce ? "auto" : "smooth" });
      };
    
      const scrub = (e: ReactPointerEvent<HTMLDivElement>) => {
        const r = e.currentTarget.getBoundingClientRect();
        const f = clamp((e.clientY - r.top - 24) / (r.height - 48));
        const max = document.documentElement.scrollHeight - innerHeight;
        window.scrollTo({ top: f * max, behavior: e.type === "pointerdown" ? "smooth" : "auto" });
      };
    
      const hover = (i: number) => () => {
        hoverRef.current = i;
        kickRef.current();
      };
      const unhover = (i: number) => () => {
        if (hoverRef.current === i) hoverRef.current = -1;
        kickRef.current();
      };
    
      const layer: CSSProperties = { position: "fixed", inset: 0, pointerEvents: "none", zIndex };
      const corner = (at: "top" | "bottom"): CSSProperties => ({
        position: "fixed",
        right: 0,
        [at]: 0,
        width: at === "top" ? 520 : 460,
        height: at === "top" ? 300 : 220,
        pointerEvents: "none",
        zIndex: zIndex - 1,
        backdropFilter: "blur(9px)",
        WebkitBackdropFilter: "blur(9px)",
        maskImage: `radial-gradient(100% 100% at 100% ${at === "top" ? "0%" : "100%"}, black 30%, rgba(0,0,0,.6) 55%, rgba(0,0,0,.2) 78%, transparent 96%)`,
      });
    
      return (
        <>
          <style>{`
            .cr-root { display: none; }
            @media (min-width: ${minWidth}px) { .cr-root { display: block; } }
            .cr-letter { position: absolute; top: 0; left: 0; line-height: 1; white-space: pre; letter-spacing: -0.02em;
              font-family: ${fontFamily}; font-weight: ${fontWeight}; color: ${color}; will-change: transform, opacity; }
            .cr-link { position: absolute; top: 0; left: 0; padding: 0; border: 0; background: none; cursor: pointer; border-radius: 6px; }
            .cr-link:focus-visible { outline: 2px solid ${color}; outline-offset: 2px; }
          `}</style>
    
          {backdrop ? (
            <>
              <div aria-hidden className="cr-root" style={corner("top")} />
              <div aria-hidden className="cr-root" style={corner("bottom")} />
            </>
          ) : null}
    
          <div aria-hidden className="cr-root" style={{ ...layer, mixBlendMode: blend }}>
            <div ref={stackRef} style={{ position: "absolute", inset: 0 }}>
              {titles.map((title, ci) =>
                [...(uppercase ? title.toUpperCase() : title)].map((ch, k) => (
                  <span key={`${ci}-${k}`} data-ci={ci} className="cr-letter" style={{ fontSize: sizeLarge, opacity: 0 }}>
                    {ch === " " ? NBSP : ch}
                  </span>
                )),
              )}
            </div>
          </div>
    
          {/* Clickable titles: each box is placed over its line by draw(). */}
          <nav aria-label="Page sections" className="cr-root" style={{ ...layer, zIndex: zIndex + 1 }}>
            <div ref={linksRef}>
              {titles.map((title, i) => (
                <button
                  key={`${i}-${title}`}
                  type="button"
                  aria-label={`Jump to ${title}`}
                  className="cr-link"
                  style={{ visibility: "hidden" }}
                  onClick={() => goTo(i)}
                  onPointerEnter={hover(i)}
                  onPointerLeave={unhover(i)}
                  onFocus={hover(i)}
                  onBlur={unhover(i)}
                />
              ))}
            </div>
          </nav>
    
          {ruler ? (
            <div aria-hidden className="cr-root" style={{ ...layer, mixBlendMode: blend }}>
              <div
                style={{ position: "absolute", top: 0, bottom: 0, right: 0, width: rulerWidth, pointerEvents: "auto", cursor: "crosshair" }}
                onPointerDown={(e) => {
                  e.currentTarget.setPointerCapture(e.pointerId);
                  scrub(e);
                }}
                onPointerMove={(e) => {
                  if (e.buttons) scrub(e);
                }}
              >
                <div
                  ref={ticksRef}
                  style={{ position: "absolute", left: 0, right: 0, top: 24, bottom: 24, display: "flex", flexDirection: "column", justifyContent: "space-between" }}
                >
                  {Array.from({ length: 101 }, (_, i) => (
                    <div key={i} style={{ position: "relative", height: 1 }}>
                      <span
                        style={{
                          position: "absolute",
                          right: 0,
                          height: 1,
                          background: color,
                          transformOrigin: "right center",
                          width: i % 10 === 0 ? 18 : i % 5 === 0 ? 11 : 6,
                          opacity: `calc(${i % 5 === 0 ? 0.55 : 0.25} + var(--k, 0) * 0.45)`,
                          transform: "scaleX(calc(1 + var(--k, 0) * 0.9))",
                        }}
                      />
                      {i % 10 === 0 ? (
                        <span
                          style={{
                            position: "absolute",
                            right: 24,
                            transform: "translateY(-50%)",
                            fontFamily: monoFamily,
                            fontSize: 9,
                            letterSpacing: "0.08em",
                            color,
                            opacity: 0.5,
                          }}
                        >
                          {i}
                        </span>
                      ) : null}
                    </div>
                  ))}
                </div>
                <div ref={markerRef} style={{ position: "absolute", left: 0, right: 0, top: 0, willChange: "transform" }}>
                  <span style={{ position: "absolute", right: 0, height: 2, width: 34, transform: "translateY(-50%)", background: color }} />
                  <span
                    ref={markerLabelRef}
                    style={{ position: "absolute", right: 38, transform: "translateY(-50%)", fontFamily: monoFamily, fontSize: 10, fontWeight: 500, color }}
                  >
                    000%
                  </span>
                </div>
              </div>
            </div>
          ) : null}
        </>
      );
    }
    
  2. 2

    Import it from wherever you put it, for example @/components/chapter-rail.

Usage

page.tsx
import { ChapterRail } from "@/components/chapter-rail";

export default function Page() {
  return (
    <>
      <ChapterRail />
      <main>
        <section data-chapter="Intro">…</section>
        <section data-chapter="Features">…</section>
        <section data-chapter="Pricing">…</section>
      </main>
    </>
  );
}
  • Tag each top-level section with data-chapter="Title" in page order. The first one counts as already arrived, so make it the hero.
  • Keep titles short (1 to 3 words) and aim for 4 to 8 chapters.
  • React only: no Tailwind, CSS file or animation library. Works in Next.js (App Router and Pages) and Vite.
  • Hidden below 1024px wide, and instant for visitors who prefer reduced motion.
  • The default white with difference blending reads on dark and light sections alike.

Examples

Default

White with difference blending, so it reads on both the dark and the light sections.

Light theme

For an all-light page, use a solid colour and turn blending off.

Without the ruler

Just the titles. With the ruler gone, the titles can sit closer to the edge.

Your own type

Any font, weight and size, in sentence case instead of capitals.

How it works

  1. 01

    Waiting

    Titles of the sections still below the fold sit in a dim list in the bottom-right corner.

  2. 02

    Rising

    When a section's top enters the screen, its title slides out of the list, stands upright and travels up the right edge, in step with your scroll.

  3. 03

    Landing

    Near the top the letters curl round one at a time, last letter first, and land in the stack. The previous title shrinks and dims above it.

  4. 04

    Reversing

    Scroll back up and every step plays backwards, all the way into the list.

One requestAnimationFrame loop reads each section's position, eases towards it and moves the letters with transforms only. The loop sleeps when nothing is moving, so an idle page costs nothing. Sections near the end of the page finish landing by the time the page can't scroll any further.

Props

All optional.

PropTypeDefaultDescription
selectorstring"[data-chapter]"CSS selector for the sections.
getTitle(el: HTMLElement) => stringdata-chapterRead a section's title another way.
colorstring"#fff"Text and line colour.
blendCSS mix-blend-mode"difference"Use "normal" with a fixed colour for a single theme.
fontFamilystring"inherit"Title font, e.g. a CSS variable.
fontWeightnumber900Title weight.
monoFamilystringsystem monoRuler numbers font.
sizeLargenumber34The newest title, in px.
sizeSmallnumber15Passed and waiting titles, in px.
sizeColumnnumber19A title while it travels up the edge, in px.
topnumber84Stack distance from the top; clear your navbar.
bottomnumber28Waiting list distance from the bottom.
rightnumber84Titles' distance from the right edge.
rulerbooleantrueShow the ruler scrollbar.
rulerWidthnumber56Ruler width, in px.
backdropbooleantrueBlurred patches behind both corners.
minWidthnumber1024Hidden below this viewport width.
easenumber0.12Smoothing per frame; lower glides more.
uppercasebooleantrueShow titles in capitals.
zIndexnumber40Stacking order; keep it under modals.

Accessibility

  • The animated letters are hidden from screen readers. Each title also has a real button, named "Jump to …", inside a navigation landmark called "Page sections".
  • Buttons are reachable with Tab; a focused title lights up just like on hover.
  • Visitors who prefer reduced motion get the same layout with no flying letters: titles switch instantly.
  • Below the minWidth (1024px by default) it isn't rendered at all, so small screens keep their full width.

Troubleshooting

Nothing appears.

Check the window is at least minWidth wide (1024px by default) and that your sections have data-chapter attributes. In Next.js the file must keep its "use client" line.

Titles sit on top of my content.

Give your content about 150-190px of right padding at desktop widths, or make the titles smaller with sizeLarge and sizeSmall.

The stack covers my navbar.

Set top to your navbar's height plus about 20px.

I see both the ruler and the browser scrollbar.

Hide the native one: html { scrollbar-width: none } html::-webkit-scrollbar { display: none }.