Skip to content
Pebble Pro is here at $49 one timeSee what’s included ↗
Pebble
ComponentsDocsMCPPricing
⌕ Find a component↗Log in
All components 673

Categories

Core inputs & forms46Buttons & actions33Navigation36Overlays & feedback49Data display33Charts & data viz40Cards & layout43Marketing blocks38App shells & pages37AI interfaces40Text & typography effects33Backgrounds & visual effects38Motion & transitions32Numbers & counters32Media34E-commerce333D & interactive36Themed sets40
Start with the essentials.Installation guide ↗Connect your agent ↗
← All componentsNavigation

Table of contents

Scrollspy table of contents with an ember segment that moves and stretches over the sections on screen, a read-progress rail, smooth jump links and a narrow disclosure layout.

Preview

Guide

Getting started with sync

Install the client

Add the sync client to your app with your package manager. It ships as one small module with no peer dependencies beyond your framework.

The client works in browsers, workers and edge runtimes. Node 20 or newer is required for server use.

Connect a workspace

Create a token in Settings, then pass it with your workspace ID. Tokens are scoped to one workspace and can be rotated at any time.

Authentication

Browser apps should exchange a short-lived token from your own server instead of shipping a long-lived one.

Regions

Pick the region closest to your users. Data stays in that region; the median round trip is 38 ms inside it.

Offline drafts

Edits made offline are queued locally and replayed in order when the connection returns.

Conflicts are merged per block. When two people change the same sentence, both versions are kept and flagged for review.

Listen for changes

Subscribe to a document to receive patches as they land. Each patch carries its author, a timestamp and the blocks it touched.

Limits

Documents up to 40,000 words stay under one frame per keystroke. Attachments are capped at 250 MB each.

Rate limits reset every minute and are reported in response headers.

On this page

  • Install the client
  • Connect a workspace
  • Authentication
  • Regions
  • Offline drafts
  • Listen for changes
  • Limits
  • Install the client
  • Connect a workspace
  • Authentication
  • Regions
  • Offline drafts
  • Listen for changes
  • Limits

Guide

Getting started with sync

Install the client

Add the sync client to your app with your package manager. It ships as one small module with no peer dependencies beyond your framework.

The client works in browsers, workers and edge runtimes. Node 20 or newer is required for server use.

Connect a workspace

Create a token in Settings, then pass it with your workspace ID. Tokens are scoped to one workspace and can be rotated at any time.

Authentication

Browser apps should exchange a short-lived token from your own server instead of shipping a long-lived one.

Regions

Pick the region closest to your users. Data stays in that region; the median round trip is 38 ms inside it.

Offline drafts

Edits made offline are queued locally and replayed in order when the connection returns.

Conflicts are merged per block. When two people change the same sentence, both versions are kept and flagged for review.

Listen for changes

Subscribe to a document to receive patches as they land. Each patch carries its author, a timestamp and the blocks it touched.

Limits

Documents up to 40,000 words stay under one frame per keystroke. Attachments are capped at 250 MB each.

Rate limits reset every minute and are reported in response headers.

Narrow layout

The list folds into a sticky disclosure that names the current section and shows read progress.

Install

Add the editable source with the shadcn CLI. Your project also needs the shared theme tokens this component uses. Setup and requirements. The Pebble installer is not published yet.

npx shadcn@latest add https://pebbleui.com/r/table-of-contents.json

Props

PropTypeDefaultDescription
items{ id: string; title: string; depth?: 0 | 1 }[]—Headings in document order. depth 1 indents a subsection.
containerRefObject<HTMLElement>—Scroll container holding the headings. Defaults to the window.
offsetnumber24Px under the top edge where a heading counts as passed, and where clicks land.
variant"auto" | "rail" | "disclosure""auto"Rail beside content, a disclosure, or auto (disclosure below lg).
labelstring"On this page"Heading of the list and the disclosure button label.
Build notes
- Measurement: on scroll (rAF-throttled) and resize, read each heading's
  `getBoundingClientRect().top`. Section _i_ spans from its heading to the next
  heading (the last to the end of the scroll content). A section is on screen
  when it overlaps `[view.top + offset, view.bottom]`. The active range is the
  first to last such index; nothing overlapping falls back to the first or
  last section.
- Progress: `scrollTop / (scrollHeight − clientHeight)`, a `bg-foreground/20`
  fill on the 2 px `bg-border` rail.
- Indicator: in a layout effect, read the `offsetTop`/`offsetHeight` of the
  first and last active links, then animate the ember segment's `top` and
  `height` with a spring (380/34/0.7), so it travels and stretches as one
  object instead of jumping between links.
- Click: `scrollTo({ top: heading − offset + 1, behavior })` on the container
  (or window), then `focus({ preventScroll: true })`.
- Disclosure: a frosted raised strip; the progress ring is an SVG circle with
  `pathLength=1` and `strokeDasharray="{progress} 1"`. The list opens with a
  `grid-rows-[0fr]→[1fr]` transition and scrolls past 18 rem.
- `auto` renders both layouts and lets `lg:` choose; `rail` and `disclosure`
  render only their own.

<!-- PEBBLE-LICENSE -->
View source

registry/nav/table-of-contents/table-of-contents.tsx

"use client";

/* PEBBLE-LICENSE
Built by Pebble. Component: table-of-contents.

First-party license: MIT

The following first-party terms apply only to original Pebble material.

MIT License

Copyright (c) 2026 Praxys Solutions LLC (Pebble)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
END PEBBLE-LICENSE */

import * as React from "react";
import { MotionConfig, motion, useReducedMotion } from "motion/react";

import { cn } from "@/lib/utils";

// Pebble: a hairline rail beside the links. Read progress fills it in quiet
// ink from the top; an ember segment sits over the section(s) on screen and
// moves and stretches with a spring as you scroll, so a short section and a
// screen holding three sections both read at a glance. Narrow layouts fold
// the list into an "On this page" disclosure that names where you are.
const spring = { type: "spring", stiffness: 380, damping: 34, mass: 0.7 } as const;

export type TocItem = {
  /** id of the heading element in the document. */
  id: string;
  title: string;
  /** 0 for top-level sections, 1 for subsections (indented). */
  depth?: 0 | 1;
};

export type TableOfContentsProps = Omit<React.ComponentProps<"nav">, "children"> & {
  items: TocItem[];
  /** Scroll container holding the headings. Defaults to the window. */
  container?: React.RefObject<HTMLElement | null>;
  /** Px from the top of the scroll area under which a heading counts as passed. */
  offset?: number;
  /** Rail beside content, disclosure, or auto (disclosure below the lg breakpoint). */
  variant?: "auto" | "rail" | "disclosure";
  /** Heading and disclosure label. */
  label?: string;
};

type Range = { from: number; to: number };

export function TableOfContents({
  items,
  container,
  offset = 24,
  variant = "auto",
  label = "On this page",
  className,
  ...props
}: TableOfContentsProps) {
  const reduced = useReducedMotion() ?? false;
  const [range, setRange] = React.useState<Range>({ from: 0, to: 0 });
  const [progress, setProgress] = React.useState(0);
  const [open, setOpen] = React.useState(false);
  const listId = React.useId();
  const headingId = React.useId();

  React.useEffect(() => {
    const root = container?.current ?? null;
    const target: HTMLElement | Window = root ?? window;
    let frame = 0;
    const measure = () => {
      frame = 0;
      const view = root ? root.getBoundingClientRect() : { top: 0, bottom: window.innerHeight };
      const scrollTop = root ? root.scrollTop : window.scrollY;
      const scrollMax = root
        ? root.scrollHeight - root.clientHeight
        : document.documentElement.scrollHeight - window.innerHeight;
      setProgress(scrollMax > 0 ? Math.min(Math.max(scrollTop / scrollMax, 0), 1) : 1);

      const tops = items.map((item) => {
        const el = document.getElementById(item.id);
        return el ? el.getBoundingClientRect().top : Number.POSITIVE_INFINITY;
      });
      const scrollHeight = root ? root.scrollHeight : document.documentElement.scrollHeight;
      const contentEnd = view.top + scrollHeight - scrollTop;
      let from = -1;
      let to = -1;
      tops.forEach((top, i) => {
        const end = i + 1 < tops.length ? tops[i + 1] : contentEnd;
        // A section is on screen when it overlaps the area below the offset.
        if (top < view.bottom && end > view.top + offset) {
          if (from === -1) from = i;
          to = i;
        }
      });
      // Nothing overlaps (above the first heading, or past the end).
      if (from === -1) from = to = tops[0] >= view.bottom ? 0 : items.length - 1;
      setRange((prev) => (prev.from === from && prev.to === to ? prev : { from, to }));
    };
    const schedule = () => {
      if (!frame) frame = requestAnimationFrame(measure);
    };
    measure();
    target.addEventListener("scroll", schedule, { passive: true });
    window.addEventListener("resize", schedule);
    return () => {
      cancelAnimationFrame(frame);
      target.removeEventListener("scroll", schedule);
      window.removeEventListener("resize", schedule);
    };
  }, [items, container, offset]);

  const jump = (id: string) => {
    const el = document.getElementById(id);
    if (!el) return;
    const root = container?.current ?? null;
    const behavior: ScrollBehavior = reduced ? "auto" : "smooth";
    if (root) {
      const top =
        el.getBoundingClientRect().top - root.getBoundingClientRect().top + root.scrollTop;
      root.scrollTo({ top: top - offset + 1, behavior });
    } else {
      window.scrollTo({
        top: el.getBoundingClientRect().top + window.scrollY - offset + 1,
        behavior,
      });
    }
    // Move focus to the heading so keyboard and screen-reader users land there.
    if (!el.hasAttribute("tabindex")) el.setAttribute("tabindex", "-1");
    el.focus({ preventScroll: true });
  };

  const current = items[range.from];
  const list = (
    <TocList
      id={listId}
      items={items}
      range={range}
      progress={progress}
      onSelect={(id) => {
        jump(id);
        setOpen(false);
      }}
    />
  );

  return (
    <MotionConfig reducedMotion="user">
      <nav
        aria-labelledby={headingId}
        data-slot="table-of-contents"
        data-variant={variant}
        className={cn("group/toc text-[13px]", className)}
        {...props}
      >
        {/* Rail layout */}
        {variant !== "disclosure" && (
          <div className={cn(variant === "auto" && "max-lg:hidden")}>
            <p id={headingId} className="mb-3 text-xs font-medium text-foreground">
              {label}
            </p>
            {list}
          </div>
        )}
        {/* Disclosure layout */}
        {variant !== "rail" && (
          <div
            className={cn(
              variant === "auto" && "lg:hidden",
              "rounded-xl bg-card/90 shadow-raised-sm ring-1 inset-shadow-highlight ring-hairline backdrop-blur-md",
            )}
          >
            <button
              type="button"
              aria-expanded={open}
              aria-controls={`${listId}-d`}
              onClick={() => setOpen((v) => !v)}
              className="flex h-10 w-full cursor-pointer items-center gap-2 rounded-xl px-3 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"
            >
              <span
                className="shrink-0 text-xs font-medium"
                id={variant === "disclosure" ? headingId : undefined}
              >
                {label}
              </span>
              <span aria-hidden className="text-muted-foreground/60">
                ·
              </span>
              <span className="min-w-0 flex-1 truncate text-muted-foreground">
                {current?.title}
              </span>
              <span className="relative size-4 shrink-0" aria-hidden>
                <svg viewBox="0 0 16 16" className="size-4 -rotate-90">
                  <circle
                    cx="8"
                    cy="8"
                    r="6"
                    fill="none"
                    strokeWidth="2"
                    className="stroke-border"
                  />
                  <circle
                    cx="8"
                    cy="8"
                    r="6"
                    fill="none"
                    strokeWidth="2"
                    strokeLinecap="round"
                    pathLength={1}
                    strokeDasharray={`${progress} 1`}
                    className="stroke-accent"
                  />
                </svg>
              </span>
              <svg
                viewBox="0 0 16 16"
                fill="none"
                stroke="currentColor"
                strokeWidth="1.5"
                strokeLinecap="round"
                strokeLinejoin="round"
                aria-hidden
                className={cn(
                  "size-3.5 shrink-0 text-muted-foreground transition-transform duration-(--motion-base) ease-move motion-reduce:transition-none",
                  open && "rotate-180",
                )}
              >
                <path d="m4 6 4 4 4-4" />
              </svg>
            </button>
            <div
              id={`${listId}-d`}
              className={cn(
                "grid transition-[grid-template-rows,opacity] duration-(--motion-base) ease-enter motion-reduce:transition-none",
                open ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0",
              )}
              inert={!open}
            >
              <div className="overflow-hidden">
                <div className="max-h-[min(18rem,60vh)] overflow-y-auto border-t border-border px-3 py-3">
                  <TocList
                    id={`${listId}-dl`}
                    items={items}
                    range={range}
                    progress={progress}
                    onSelect={(id) => {
                      jump(id);
                      setOpen(false);
                    }}
                  />
                </div>
              </div>
            </div>
          </div>
        )}
      </nav>
    </MotionConfig>
  );
}

function TocList({
  id,
  items,
  range,
  progress,
  onSelect,
}: {
  id: string;
  items: TocItem[];
  range: Range;
  progress: number;
  onSelect: (id: string) => void;
}) {
  const listRef = React.useRef<HTMLUListElement>(null);
  const [box, setBox] = React.useState({ top: 0, height: 0 });

  React.useLayoutEffect(() => {
    const links = listRef.current?.querySelectorAll<HTMLElement>("[data-toc-index]");
    const first = links?.[range.from];
    const last = links?.[range.to];
    if (!first || !last) return;
    setBox({ top: first.offsetTop, height: last.offsetTop + last.offsetHeight - first.offsetTop });
  }, [range, items]);

  return (
    <ul ref={listRef} id={id} data-slot="toc-list" className="relative flex flex-col pl-3.5">
      {/* Rail: track, read progress, and the ember segment over what is on screen. */}
      <span aria-hidden className="absolute inset-y-0 left-0 w-0.5 rounded-full bg-border">
        <span
          data-slot="toc-progress"
          className="absolute inset-x-0 top-0 rounded-full bg-foreground/20"
          style={{ height: `${progress * 100}%` }}
        />
        <motion.span
          data-slot="toc-indicator"
          className="absolute inset-x-0 rounded-full bg-accent"
          initial={false}
          animate={{ top: box.top, height: box.height }}
          transition={spring}
        />
      </span>
      {items.map((item, i) => {
        const active = i >= range.from && i <= range.to;
        return (
          <li key={item.id}>
            <a
              href={`#${item.id}`}
              data-toc-index={i}
              aria-current={i === range.from ? "location" : undefined}
              data-active={active || undefined}
              onClick={(event) => {
                event.preventDefault();
                onSelect(item.id);
              }}
              className={cn(
                "block rounded-sm py-1.5 leading-snug text-muted-foreground outline-none",
                "transition-colors duration-(--motion-fast) hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
                "data-active:text-foreground",
                item.depth === 1 && "pl-3 text-[12.5px]",
              )}
            >
              {item.title}
            </a>
          </li>
        );
      })}
    </ul>
  );
}
Pebble

Small details.
Better interfaces.

React components to explore, make your own, and build on.

Library

  • Components
  • Installation
  • Pricing

Resources

  • For agents
  • About
  • Support

Legal

  • License
  • Terms
  • Privacy
  • Final sale

Built by Pebble

A product of Praxys Solutions LLC ↗

Pebble Pro is live

$49 one time, lifetime updates ↗