Reading progress pill

A table of contents that turns into a floating pill as you read. At rest it is an inline list of section links. Once that list scrolls away, a compact pill appears at the top centre (bottom on phones) with a progress ring, the current section title, a 3/7 count and the estimated time left from the words still unread. Clicking the pill opens every section with the current one marked and a small progress bar each. At the end the ring turns into a check with an optional Back to top action. Headings are found automatically (h2 and h3) or passed in, and it works with the page or a scrolling container. Navigation landmarks, aria-current on the active link, an expandable button, Escape to close and focus moved to the heading after a jump; reduced motion scrolls instantly with no fades.

NavigationComponentTailwind v4

Source

"use client";

import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type RefObject } from "react";
import { createPortal } from "react-dom";
import { ArrowUp, Check, ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils";

export interface ReadingSection {
  /** Id of the heading element in the page. */
  id: string;
  title: string;
  level?: 2 | 3;
}

export interface ReadingProgressPillProps {
  /** The article (or its scrolling box). A ref or a selector. Omit to track the whole page. */
  container?: RefObject<HTMLElement | null> | string;
  /** Sections to list. Omit to find the h2 and h3 headings inside the container. */
  sections?: ReadingSection[];
  /** Space kept clear at the top when jumping to a heading, in px. */
  offset?: number;
  /** Where the floating pill sits. "auto" is top on wide screens and bottom on phones. */
  position?: "top" | "bottom" | "auto";
  showTime?: boolean;
  wordsPerMinute?: number;
  /** Offer a "Back to top" action once the end is reached. */
  backToTop?: boolean;
  label?: string;
  className?: string;
}

interface Snapshot {
  active: number;
  overall: number;
  parts: number[];
  minutesLeft: number;
  done: boolean;
}

const EMPTY: Snapshot = { active: 0, overall: 0, parts: [], minutesLeft: 0, done: false };

function slug(text: string) {
  return text.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 60) || "section";
}

function resolve(container: ReadingProgressPillProps["container"]) {
  if (!container) return null;
  return typeof container === "string" ? document.querySelector<HTMLElement>(container) : container.current;
}

function scrollParent(element: HTMLElement | null): HTMLElement | null {
  for (let node = element; node && node !== document.body; node = node.parentElement) {
    const { overflowY } = getComputedStyle(node);
    if ((overflowY === "auto" || overflowY === "scroll") && node.scrollHeight > node.clientHeight + 1) return node;
  }
  return null;
}

const countWords = (text: string) => (text.match(/\S+/g) || []).length;

function useMedia(query: string) {
  const [match, setMatch] = useState(false);
  useEffect(() => {
    const list = window.matchMedia?.(query);
    if (!list) return;
    const update = () => setMatch(list.matches);
    update();
    list.addEventListener("change", update);
    return () => list.removeEventListener("change", update);
  }, [query]);
  return match;
}

export function ReadingProgressPill({
  container, sections: given, offset = 72, position = "auto", showTime = true, wordsPerMinute = 230, backToTop = true,
  label = "On this page", className,
}: ReadingProgressPillProps) {
  const uid = useId();
  const listId = `${uid}-list`;
  const navRef = useRef<HTMLElement>(null);
  const pillRef = useRef<HTMLDivElement>(null);
  const pillButton = useRef<HTMLButtonElement>(null);
  const [found, setFound] = useState<ReadingSection[]>([]);
  const sections = given ?? found;
  const [snap, setSnap] = useState<Snapshot>(EMPTY);
  const [floating, setFloating] = useState(false);
  const [open, setOpen] = useState(false);
  const [mounted, setMounted] = useState(false);
  const [frame, setFrame] = useState<{ top: number; bottom: number; centre: number } | null>(null);
  const reduce = useMedia("(prefers-reduced-motion: reduce)");
  const phone = useMedia("(max-width: 639px)");
  const atBottom = position === "bottom" || (position === "auto" && phone);
  const words = useRef<number[]>([]);
  // The element that scrolls (null for the page). Re-checked on every measure, since styles can arrive late.
  const [scrollBox, setScrollBox] = useState<HTMLElement | null>(null);

  useEffect(() => setMounted(true), []);
  // Whatever is already floating on first paint shows in place; entrance fades start after that.
  const settled = useRef(false);
  useEffect(() => {
    const timer = window.setTimeout(() => (settled.current = true), 900);
    return () => window.clearTimeout(timer);
  }, []);
  const [pillIn, setPillIn] = useState(false);
  const [textIn, setTextIn] = useState(false);

  // Find headings when no list is given, giving each an id and making it focusable for jumps.
  useLayoutEffect(() => {
    if (given) return;
    const root = resolve(container) ?? document.querySelector<HTMLElement>("main, article") ?? document.body;
    const used = new Set<string>();
    const list = Array.from(root.querySelectorAll<HTMLElement>("h2, h3")).filter((h) => !navRef.current?.contains(h)).map((heading) => {
      if (!heading.id) {
        let id = slug(heading.textContent || "");
        while (used.has(id) || document.getElementById(id)) id = `${id}-${used.size + 1}`;
        heading.id = id;
      }
      used.add(heading.id);
      return { id: heading.id, title: (heading.textContent || "").trim(), level: heading.tagName === "H3" ? 3 : 2 } as ReadingSection;
    });
    setFound((prev) => (prev.length === list.length && prev.every((s, i) => s.id === list[i].id) ? prev : list));
  }, [given, container]);

  const geometry = useCallback(() => {
    const root = resolve(container);
    const scroller = scrollParent(root) ?? (root && root.scrollHeight > root.clientHeight + 1 && getComputedStyle(root).overflowY !== "visible" ? root : null);
    const headings = sections.map((s) => document.getElementById(s.id));
    return { root, scroller, headings };
  }, [container, sections]);

  // Read position: active heading, overall and per-section progress, and time left.
  const measure = useCallback(() => {
    const { root, scroller, headings } = geometry();
    setScrollBox((prev) => (prev === scroller ? prev : scroller));
    if (!headings.length) return;
    const viewTop = scroller ? scroller.getBoundingClientRect().top : 0;
    const viewH = scroller ? scroller.clientHeight : window.innerHeight;
    const scrollTop = scroller ? scroller.scrollTop : window.scrollY;
    const toScroll = (el: Element) => el.getBoundingClientRect().top - viewTop + scrollTop;
    const area = root ?? document.body;
    const contentTop = scroller && (!root || root === scroller) ? 0 : toScroll(area);
    const contentBottom = scroller && (!root || root === scroller) ? scroller.scrollHeight : contentTop + area.scrollHeight;
    const tops = headings.map((h) => (h ? toScroll(h) : contentTop));
    const range = Math.max(1, contentBottom - contentTop - viewH);
    const overall = Math.min(1, Math.max(0, (scrollTop - contentTop) / range));
    // One reading line, a third of the way down the view, drives both the active section and section progress.
    const reading = scrollTop + Math.max(offset + 1, viewH / 3);
    const done = overall >= 0.995;
    let active = 0;
    tops.forEach((top, i) => {
      if (top <= reading) active = i;
    });
    if (done) active = tops.length - 1;
    const parts = tops.map((top, i) => {
      if (done) return 1;
      const end = tops[i + 1] ?? contentBottom;
      return Math.min(1, Math.max(0, (reading - top) / Math.max(1, end - top)));
    });
    const left = words.current.reduce((sum, count, i) => sum + count * (1 - (parts[i] ?? 0)), 0);
    const next: Snapshot = { active, overall, parts, minutesLeft: Math.ceil(left / wordsPerMinute), done };
    // The pill takes over once the inline list has scrolled away above the view.
    const nav = navRef.current?.getBoundingClientRect();
    setFloating(!!nav && nav.height > 0 && nav.bottom < viewTop + 1);
    setSnap((prev) =>
      prev.active === next.active && prev.done === next.done && prev.minutesLeft === next.minutesLeft && Math.abs(prev.overall - next.overall) < 0.002
        && prev.parts.length === next.parts.length && prev.parts.every((p, i) => Math.abs(p - next.parts[i]) < 0.005)
        ? prev
        : next,
    );
    if (scroller) {
      const rect = scroller.getBoundingClientRect();
      setFrame((prev) => (prev && prev.top === rect.top && prev.bottom === rect.bottom && prev.centre === rect.left + rect.width / 2
        ? prev
        : { top: rect.top, bottom: rect.bottom, centre: rect.left + rect.width / 2 }));
    } else setFrame(null);
  }, [geometry, offset, wordsPerMinute]);

  // Words per section, from each heading to the next.
  useEffect(() => {
    const { root, headings } = geometry();
    const area = root ?? document.body;
    words.current = headings.map((heading, i) => {
      if (!heading) return 0;
      const range = document.createRange();
      range.setStartBefore(heading);
      const next = headings[i + 1];
      if (next) range.setEndBefore(next);
      else range.setEndAfter(area.lastChild ?? area);
      return countWords(range.toString());
    });
    measure();
  }, [geometry, measure]);

  // Follow scrolling (of the page or any box) and resizing; headings crossing the reading line are observed too.
  useEffect(() => {
    const { headings, root } = geometry();
    const scroller = scrollBox;
    // Leading edge right away, then once more on the next frame to catch the final position.
    let pending = 0;
    let last = 0;
    const schedule = () => {
      const now = performance.now();
      if (now - last > 80) {
        last = now;
        measure();
      }
      cancelAnimationFrame(pending);
      pending = requestAnimationFrame(() => {
        last = performance.now();
        measure();
      });
    };
    document.addEventListener("scroll", schedule, { capture: true, passive: true });
    window.addEventListener("resize", schedule);
    const resizeObserver = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(schedule);
    if (root) resizeObserver?.observe(root);
    const headingObserver = new IntersectionObserver(schedule, { root: scroller, rootMargin: `-${offset}px 0px -50% 0px` });
    headings.forEach((h) => h && headingObserver.observe(h));
    const navObserver = new IntersectionObserver(schedule, { root: scroller });
    if (navRef.current) navObserver.observe(navRef.current);
    return () => {
      cancelAnimationFrame(pending);
      document.removeEventListener("scroll", schedule, { capture: true });
      window.removeEventListener("resize", schedule);
      resizeObserver?.disconnect();
      headingObserver.disconnect();
      navObserver.disconnect();
    };
  }, [geometry, measure, offset, scrollBox]);

  useEffect(() => {
    if (!floating) setOpen(false);
    setPillIn(floating && settled.current);
  }, [floating]);

  useEffect(() => {
    if (settled.current) setTextIn(true);
  }, [snap.active, snap.done]);

  // Close the list on Escape or an outside click.
  useEffect(() => {
    if (!open) return;
    function onKey(event: KeyboardEvent) {
      if (event.key !== "Escape") return;
      setOpen(false);
      pillButton.current?.focus();
    }
    function onDown(event: PointerEvent) {
      if (pillRef.current && event.target instanceof Node && !pillRef.current.contains(event.target)) setOpen(false);
    }
    document.addEventListener("keydown", onKey);
    document.addEventListener("pointerdown", onDown);
    return () => {
      document.removeEventListener("keydown", onKey);
      document.removeEventListener("pointerdown", onDown);
    };
  }, [open]);

  function jump(id: string) {
    const heading = document.getElementById(id);
    if (!heading) return;
    const { scroller } = geometry();
    const behavior: ScrollBehavior = reduce ? "auto" : "smooth";
    if (scroller) {
      const top = heading.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scroller.scrollTop - offset;
      scroller.scrollTo({ top, behavior });
    } else window.scrollTo({ top: heading.getBoundingClientRect().top + window.scrollY - offset, behavior });
    if (!heading.hasAttribute("tabindex")) heading.setAttribute("tabindex", "-1");
    heading.focus({ preventScroll: true });
    setOpen(false);
  }

  function toTop() {
    const { scroller, root } = geometry();
    const behavior: ScrollBehavior = reduce ? "auto" : "smooth";
    if (scroller) scroller.scrollTo({ top: 0, behavior });
    else window.scrollTo({ top: root ? root.getBoundingClientRect().top + window.scrollY - offset : 0, behavior });
    pillButton.current?.blur();
    navRef.current?.querySelector<HTMLElement>("a")?.focus({ preventScroll: true });
  }

  const total = sections.length;
  const current = sections[snap.active];
  const ring = 2 * Math.PI * 11;
  const placement = frame
    ? atBottom
      ? { bottom: Math.max(8, window.innerHeight - frame.bottom + 14), left: frame.centre }
      : { top: Math.max(8, frame.top + 14), left: frame.centre }
    : atBottom ? { bottom: 16, left: "50%" } : { top: 16, left: "50%" };

  const list = (compact: boolean) => (
    <ol className={cn(compact ? "space-y-0.5" : "space-y-1 border-l border-border")}>
      {sections.map((section, i) => {
        const active = i === snap.active;
        return (
          <li key={section.id}>
            <a
              href={`#${section.id}`}
              aria-current={active ? "location" : undefined}
              onClick={(event) => {
                event.preventDefault();
                jump(section.id);
              }}
              className={cn(
                "block text-sm outline-hidden transition-colors focus-visible:ring-[3px] focus-visible:ring-ring/50",
                compact ? "rounded-lg px-3 py-2 hover:bg-accent" : "-ml-px border-l-2 py-1 pr-2 hover:text-foreground",
                !compact && (section.level === 3 ? "pl-7" : "pl-4"),
                compact && section.level === 3 && "pl-6",
                active
                  ? cn("font-medium text-foreground", compact ? "bg-accent" : "border-primary")
                  : cn("text-muted-foreground", !compact && "border-transparent"),
              )}
            >
              <span className="flex items-center justify-between gap-3">
                <span className="truncate">{section.title}</span>
                {compact && snap.parts[i] >= 1 && <Check aria-hidden="true" className="size-3.5 shrink-0 text-muted-foreground" />}
              </span>
              {compact && (
                <span aria-hidden="true" className="mt-1.5 block h-0.5 overflow-hidden rounded-full bg-muted">
                  <span className="block h-full rounded-full bg-primary" style={{ width: `${(snap.parts[i] ?? 0) * 100}%` }} />
                </span>
              )}
            </a>
          </li>
        );
      })}
    </ol>
  );

  return (
    <>
      <nav ref={navRef} aria-label={label} className={cn("text-sm", className)}>
        <p className="mb-2 text-xs font-medium uppercase tracking-wider text-muted-foreground">{label}</p>
        {list(false)}
      </nav>

      {mounted && total > 0 && createPortal(
        <div
          ref={pillRef}
          role="navigation"
          aria-label="Reading progress"
          hidden={!floating}
          style={placement}
          className="fixed z-40 w-max max-w-[calc(100vw-1.5rem)] -translate-x-1/2"
        >
          <style>{`@keyframes reading-pill-in{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}`}</style>
          <div className={cn("flex items-center gap-1 rounded-full border border-border bg-popover/90 p-1 text-popover-foreground shadow-[0_10px_30px_-10px_rgb(0_0_0/0.35)] backdrop-blur-md", pillIn && !reduce && "animate-[reading-pill-in_.22s_ease-out]")}>
            <button
              ref={pillButton}
              type="button"
              aria-expanded={open}
              aria-controls={listId}
              aria-label={`${current?.title ?? ""}, section ${snap.active + 1} of ${total}. ${snap.done ? "Finished." : `${Math.round(snap.overall * 100)}% read.`} Show sections`}
              onClick={() => setOpen((value) => !value)}
              className="flex min-w-0 items-center gap-2.5 rounded-full py-1 pl-1 pr-3 outline-hidden hover:bg-accent focus-visible:ring-[3px] focus-visible:ring-ring/50"
            >
              <span className="relative grid size-7 shrink-0 place-items-center">
                <svg viewBox="0 0 28 28" className="absolute inset-0 -rotate-90" aria-hidden="true">
                  <circle cx="14" cy="14" r="11" fill="none" strokeWidth="2.5" className="stroke-muted" />
                  <circle
                    cx="14"
                    cy="14"
                    r="11"
                    fill="none"
                    strokeWidth="2.5"
                    strokeLinecap="round"
                    strokeDasharray={ring}
                    strokeDashoffset={ring * (1 - snap.overall)}
                    className={cn("stroke-primary", settled.current && !reduce && "transition-[stroke-dashoffset] duration-150")}
                  />
                </svg>
                {snap.done && (
                  <span className={cn("relative grid size-5 place-items-center rounded-full bg-primary text-primary-foreground", textIn && !reduce && "animate-[reading-pill-in_.25s_ease-out]")}>
                    <Check aria-hidden="true" className="size-3" strokeWidth={3} />
                  </span>
                )}
              </span>
              <span
                key={snap.active}
                className={cn("max-w-[11rem] truncate text-sm font-medium sm:max-w-[16rem]", textIn && !reduce && "animate-[reading-pill-in_.3s_ease-out]")}
              >
                {current?.title}
              </span>
              <span className="shrink-0 text-xs tabular-nums text-muted-foreground">
                {snap.active + 1}/{total}
              </span>
              {showTime && !snap.done && snap.minutesLeft > 0 && (
                <span className="hidden shrink-0 text-xs text-muted-foreground sm:inline">· {snap.minutesLeft} min left</span>
              )}
              <ChevronDown aria-hidden="true" className={cn("size-3.5 shrink-0 text-muted-foreground transition-transform", open && "rotate-180")} />
            </button>
            {backToTop && snap.done && (
              <button
                type="button"
                onClick={toTop}
                className="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full bg-primary px-3 text-xs font-medium text-primary-foreground outline-hidden hover:bg-primary/90 focus-visible:ring-[3px] focus-visible:ring-ring/50"
              >
                <ArrowUp aria-hidden="true" className="size-3.5" />
                Back to top
              </button>
            )}
          </div>

          <div
            id={listId}
            hidden={!open}
            className={cn(
              "absolute left-1/2 w-[min(20rem,calc(100vw-1.5rem))] -translate-x-1/2 rounded-2xl border border-border bg-popover p-1.5 text-popover-foreground shadow-[0_18px_48px_-16px_rgb(0_0_0/0.4)]",
              atBottom ? "bottom-full mb-2" : "top-full mt-2",
            )}
          >
            <p className="flex items-center justify-between px-3 pb-1 pt-2 text-xs text-muted-foreground">
              <span className="font-medium">{label}</span>
              <span className="tabular-nums">{snap.done ? "Finished" : `${Math.round(snap.overall * 100)}% read`}</span>
            </p>
            {list(true)}
          </div>
        </div>,
        document.body,
      )}
    </>
  );
}