{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "table-of-contents",
  "title": "Table of Contents",
  "description": "Scroll-synced \"On This Page\" sidebar with a plane that flies along the heading trail, a sliding rail, or a spotlight list.",
  "dependencies": [
    "motion",
    "lucide-react"
  ],
  "registryDependencies": [
    "utils"
  ],
  "files": [
    {
      "path": "registry/new-york/table-of-contents/table-of-contents.tsx",
      "content": "\"use client\"\n\nimport { useEffect, useId, useMemo, useRef, useState } from \"react\"\nimport {\n  animate,\n  AnimatePresence,\n  motion,\n  useMotionValue,\n  useReducedMotion,\n  useSpring,\n  useTransform,\n  type Transition,\n} from \"motion/react\"\nimport { List, Plane } from \"lucide-react\"\nimport { cn } from \"@/lib/utils\"\n\nexport interface TocItem {\n  /** Id of the heading element this entry points to. */\n  id: string\n  title: string\n  /** Nesting depth. Default: 1 */\n  level?: 1 | 2 | 3\n}\n\nexport type TocVariant = \"trail\" | \"rail\" | \"spotlight\"\n\nexport interface TableOfContentsProps {\n  /** Headings to list, in document order. */\n  items: TocItem[]\n  /** Visual style. Default: \"trail\" */\n  variant?: TocVariant\n  /** Header label. Default: \"On This Page\" */\n  title?: string\n  /** Controlled active heading id. When omitted, the active heading is tracked from scroll. */\n  activeId?: string\n  /** Scroll container whose headings are observed. Default: window / document */\n  container?: HTMLElement | null\n  /** Distance in px from the top of the viewport or container at which a heading becomes active. Default: 96 */\n  offset?: number\n  /** Color of the active marker, line and glow (any CSS color). Default: \"currentColor\" */\n  accentColor?: string\n  /** Called with the heading id when an entry is clicked. */\n  onNavigate?: (id: string) => void\n  /** Smoothly scroll to the heading on click. When false, jumps instantly. Default: true */\n  smoothScroll?: boolean\n  className?: string\n}\n\ntype Row = { top: number; height: number }\ntype Point = { x: number; y: number }\n\ninterface VariantProps {\n  items: TocItem[]\n  index: number\n  title: string\n  accentColor: string\n  reduced: boolean\n  onSelect: (id: string) => void\n}\n\n// Inline `color: currentColor` would override the theme class, so skip it\nconst tint = (c: string) => (c === \"currentColor\" ? undefined : c)\nconst pad = (n: number) => String(n).padStart(2, \"0\")\n\nfunction findHeading(id: string, container?: HTMLElement | null) {\n  return container ? container.querySelector<HTMLElement>(`#${CSS.escape(id)}`) : document.getElementById(id)\n}\n\nfunction useActiveHeading(ids: string[], container: HTMLElement | null | undefined, offset: number, enabled: boolean) {\n  const [active, setActive] = useState<string>()\n  const lock = useRef(false)\n  const timer = useRef<ReturnType<typeof setTimeout>>(undefined)\n  const key = ids.join(\"|\")\n\n  useEffect(() => {\n    if (!enabled || !key) return\n    const list = key.split(\"|\")\n    let frame = 0\n\n    const compute = () => {\n      frame = 0\n      if (lock.current) return\n      const top = container ? container.getBoundingClientRect().top : 0\n      let current = list[0]\n      for (const id of list) {\n        const el = findHeading(id, container)\n        if (el && el.getBoundingClientRect().top - top <= offset + 1) current = id\n      }\n      // The last headings may never reach the offset line, so the end of the scroll selects the last one\n      const scrolled = container ? container.scrollTop : window.scrollY\n      const atEnd = container\n        ? container.scrollTop + container.clientHeight >= container.scrollHeight - 2\n        : window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 2\n      if (scrolled > 0 && atEnd) current = list[list.length - 1]\n      setActive(current)\n    }\n\n    const onScroll = () => {\n      if (lock.current) {\n        clearTimeout(timer.current)\n        timer.current = setTimeout(release, 140)\n      }\n      if (!frame) frame = requestAnimationFrame(compute)\n    }\n    const release = () => {\n      lock.current = false\n      onScroll()\n    }\n\n    const target: HTMLElement | Window = container ?? window\n    target.addEventListener(\"scroll\", onScroll, { passive: true })\n    window.addEventListener(\"resize\", onScroll)\n    frame = requestAnimationFrame(compute)\n    return () => {\n      target.removeEventListener(\"scroll\", onScroll)\n      window.removeEventListener(\"resize\", onScroll)\n      cancelAnimationFrame(frame)\n      clearTimeout(timer.current)\n      lock.current = false\n    }\n  }, [key, container, offset, enabled])\n\n  // Pin the clicked entry while the page scrolls past the headings in between\n  const jump = (id: string) => {\n    lock.current = true\n    setActive(id)\n    clearTimeout(timer.current)\n    timer.current = setTimeout(() => {\n      lock.current = false\n    }, 160)\n  }\n\n  return [active, jump] as const\n}\n\nfunction useRows(listRef: React.RefObject<HTMLElement | null>, items: TocItem[]) {\n  const [rows, setRows] = useState<Row[]>([])\n\n  useEffect(() => {\n    const list = listRef.current\n    if (!list) return\n    const els = Array.from(list.querySelectorAll<HTMLElement>(\"[data-toc-row]\"))\n    const ro = new ResizeObserver(() => setRows(els.map((el) => ({ top: el.offsetTop, height: el.offsetHeight }))))\n    ro.observe(list)\n    els.forEach((el) => ro.observe(el))\n    return () => ro.disconnect()\n  }, [listRef, items])\n\n  return rows\n}\n\nexport function TableOfContents({\n  items,\n  variant = \"trail\",\n  title = \"On This Page\",\n  activeId,\n  container,\n  offset = 96,\n  accentColor = \"currentColor\",\n  onNavigate,\n  smoothScroll = true,\n  className,\n}: TableOfContentsProps) {\n  const reduced = !!useReducedMotion()\n  const controlled = activeId !== undefined\n  const [tracked, jump] = useActiveHeading(\n    items.map((i) => i.id),\n    container,\n    offset,\n    !controlled\n  )\n  const current = controlled ? activeId : tracked\n  const index = Math.max(0, items.findIndex((i) => i.id === current))\n\n  const onSelect = (id: string) => {\n    onNavigate?.(id)\n    const el = findHeading(id, container)\n    if (!el) return\n    if (!controlled) jump(id)\n    const behavior: ScrollBehavior = smoothScroll && !reduced ? \"smooth\" : \"auto\"\n    if (container) {\n      const delta = el.getBoundingClientRect().top - container.getBoundingClientRect().top\n      container.scrollTo({ top: container.scrollTop + delta - offset + 1, behavior })\n    } else {\n      window.scrollTo({ top: window.scrollY + el.getBoundingClientRect().top - offset + 1, behavior })\n    }\n  }\n\n  const shared: VariantProps = { items, index, title, accentColor, reduced, onSelect }\n\n  return (\n    <nav aria-label={title} className={cn(\"w-full text-sm\", className)}>\n      {variant === \"rail\" ? <Rail {...shared} /> : variant === \"spotlight\" ? <Spotlight {...shared} /> : <Trail {...shared} />}\n    </nav>\n  )\n}\n\nfunction Header({ title }: { title: string }) {\n  return (\n    <div className=\"mb-3 flex items-center gap-2 font-medium text-foreground\">\n      <List className=\"size-4 text-muted-foreground\" aria-hidden />\n      {title}\n    </div>\n  )\n}\n\n// ---------------------------------------------------------------- trail\n\nconst DOT_X = 5\nconst STEP = 14\nconst dotX = (level = 1) => DOT_X + (level - 1) * STEP\n\nfunction buildPath(dots: Point[]) {\n  const pts: Point[] = [dots[0]]\n  const stops = [0]\n  let total = 0\n  const push = (p: Point) => {\n    const q = pts[pts.length - 1]\n    total += Math.hypot(p.x - q.x, p.y - q.y)\n    pts.push(p)\n  }\n  for (let i = 1; i < dots.length; i++) {\n    const a = dots[i - 1]\n    const b = dots[i]\n    // Jog diagonally halfway between two dots when the indentation changes\n    if (a.x !== b.x) {\n      const mid = (a.y + b.y) / 2\n      const h = Math.min(Math.abs(b.x - a.x), (b.y - a.y) * 0.6) / 2\n      push({ x: a.x, y: mid - h })\n      push({ x: b.x, y: mid + h })\n    }\n    push(b)\n    stops.push(total)\n  }\n  const d = pts.map((p, i) => `${i ? \"L\" : \"M\"}${p.x} ${p.y}`).join(\" \")\n  return { d, pts, stops, dots }\n}\n\nfunction pointAt(pts: Point[], length: number) {\n  let walked = 0\n  for (let i = 1; i < pts.length; i++) {\n    const a = pts[i - 1]\n    const b = pts[i]\n    const seg = Math.hypot(b.x - a.x, b.y - a.y)\n    if (!seg) continue\n    if (walked + seg >= length || i === pts.length - 1) {\n      const t = Math.min(1, Math.max(0, (length - walked) / seg))\n      return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t, angle: (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI }\n    }\n    walked += seg\n  }\n  return { ...pts[0], angle: 90 }\n}\n\nfunction Trail({ items, index, title, accentColor, reduced, onSelect }: VariantProps) {\n  const listRef = useRef<HTMLUListElement>(null)\n  const rows = useRows(listRef, items)\n  const geo = useMemo(\n    () =>\n      rows.length && rows.length === items.length\n        ? buildPath(rows.map((r, i) => ({ x: dotX(items[i].level), y: r.top + Math.min(r.height / 2, 16) })))\n        : null,\n    [rows, items]\n  )\n\n  const progress = useMotionValue(0)\n  const x = useMotionValue(0)\n  const y = useMotionValue(0)\n  const heading = useMotionValue(135)\n  const rotate = useSpring(heading, { stiffness: 260, damping: 26 })\n  const dash = useTransform(progress, (l) => `${l} 100000`)\n  const dir = useRef(1)\n  const placed = useRef(false)\n\n  // The plane sits on the path at `progress` and faces its direction of travel\n  useEffect(() => {\n    if (!geo) return\n    const sync = (l: number) => {\n      const p = pointAt(geo.pts, l)\n      x.set(p.x)\n      y.set(p.y)\n      heading.set(p.angle + 45 + (dir.current < 0 ? 180 : 0))\n    }\n    sync(progress.get())\n    return progress.on(\"change\", sync)\n  }, [geo, progress, x, y, heading])\n\n  useEffect(() => {\n    if (!geo) return\n    const target = geo.stops[index] ?? 0\n    if (!placed.current || reduced) {\n      placed.current = true\n      progress.jump(target)\n      heading.jump(pointAt(geo.pts, target).angle + 45)\n      rotate.jump(heading.get())\n      return\n    }\n    const distance = Math.abs(target - progress.get())\n    dir.current = target >= progress.get() ? 1 : -1\n    const controls = animate(progress, target, {\n      duration: Math.min(1.1, 0.35 + distance / 500),\n      ease: [0.65, 0, 0.35, 1],\n    })\n    controls.then(() => {\n      dir.current = 1\n      heading.set(pointAt(geo.pts, target).angle + 45)\n    })\n    return () => controls.stop()\n  }, [geo, index, reduced, progress, heading, rotate])\n\n  return (\n    <div>\n      <Header title={title} />\n      <ul ref={listRef} className=\"relative\">\n        {geo && (\n          <svg aria-hidden className=\"pointer-events-none absolute inset-0 size-full overflow-visible text-foreground\">\n            <path\n              d={geo.d}\n              fill=\"none\"\n              stroke=\"currentColor\"\n              strokeWidth={1.25}\n              strokeDasharray=\"3 4\"\n              className=\"text-muted-foreground opacity-40\"\n            />\n            <motion.path\n              d={geo.d}\n              fill=\"none\"\n              stroke={accentColor}\n              strokeWidth={1.5}\n              strokeLinecap=\"round\"\n              strokeLinejoin=\"round\"\n              style={{ strokeDasharray: dash }}\n            />\n            {geo.dots.map((p, i) =>\n              i === index ? null : (\n                <circle\n                  key={i}\n                  cx={p.x}\n                  cy={p.y}\n                  r={i < index ? 2.5 : 2.25}\n                  strokeWidth={1.25}\n                  className={cn(\"transition-colors duration-300\", i < index ? \"\" : \"fill-background text-muted-foreground\")}\n                  fill={i < index ? accentColor : undefined}\n                  stroke={i < index ? accentColor : \"currentColor\"}\n                />\n              )\n            )}\n          </svg>\n        )}\n        {geo && (\n          <motion.div\n            aria-hidden\n            className=\"pointer-events-none absolute left-0 top-0 -ml-2.5 -mt-2.5 grid size-5 place-items-center rounded-full bg-background text-foreground\"\n            style={{ x, y, rotate, color: tint(accentColor) }}\n          >\n            <Plane className=\"size-3.5\" fill=\"currentColor\" strokeWidth={1.25} />\n          </motion.div>\n        )}\n        {items.map((item, i) => (\n          <li key={item.id} data-toc-row>\n            <a\n              href={`#${item.id}`}\n              aria-current={i === index ? \"location\" : undefined}\n              onClick={(e) => {\n                e.preventDefault()\n                onSelect(item.id)\n              }}\n              className={cn(\n                \"block py-1.5 pr-2 leading-5 transition-colors duration-300\",\n                i === index\n                  ? \"font-semibold text-foreground\"\n                  : i < index\n                    ? \"text-muted-foreground hover:text-foreground\"\n                    : \"text-muted-foreground/60 hover:text-foreground\"\n              )}\n              style={{ paddingLeft: dotX(item.level) + 15 }}\n            >\n              {item.title}\n            </a>\n          </li>\n        ))}\n      </ul>\n    </div>\n  )\n}\n\n// ---------------------------------------------------------------- rail\n\nfunction Rail({ items, index, title, accentColor, reduced, onSelect }: VariantProps) {\n  const listRef = useRef<HTMLUListElement>(null)\n  const rows = useRows(listRef, items)\n  const [hover, setHover] = useState<number | null>(null)\n  const pill = useId()\n  const row = rows[index]\n  const spring: Transition = reduced ? { duration: 0 } : { type: \"spring\", stiffness: 380, damping: 32 }\n\n  return (\n    <div>\n      <Header title={title} />\n      <ul ref={listRef} className=\"relative\" onPointerLeave={() => setHover(null)}>\n        <span aria-hidden className=\"absolute inset-y-0 left-0 w-px bg-border\" />\n        {row && (\n          <motion.span\n            aria-hidden\n            className=\"absolute left-[-0.5px] w-0.5 rounded-full bg-foreground\"\n            style={{ backgroundColor: tint(accentColor) }}\n            initial={false}\n            animate={{ top: row.top, height: row.height }}\n            transition={spring}\n          />\n        )}\n        {items.map((item, i) => (\n          <li key={item.id} data-toc-row className=\"relative\">\n            <AnimatePresence>\n              {hover === i && (\n                <motion.span\n                  layoutId={pill}\n                  aria-hidden\n                  className=\"absolute inset-y-0.5 left-2 right-0 rounded-md bg-muted\"\n                  initial={{ opacity: 0 }}\n                  animate={{ opacity: 1 }}\n                  exit={{ opacity: 0 }}\n                  transition={reduced ? { duration: 0 } : { type: \"spring\", stiffness: 500, damping: 40 }}\n                />\n              )}\n            </AnimatePresence>\n            <a\n              href={`#${item.id}`}\n              aria-current={i === index ? \"location\" : undefined}\n              onPointerEnter={() => setHover(i)}\n              onClick={(e) => {\n                e.preventDefault()\n                onSelect(item.id)\n              }}\n              className={cn(\n                \"relative block py-1.5 pr-2 leading-5 transition-colors duration-200\",\n                i === index ? \"font-medium text-foreground\" : \"text-muted-foreground hover:text-foreground\"\n              )}\n              style={{ paddingLeft: 16 + ((item.level ?? 1) - 1) * 12 }}\n            >\n              {item.title}\n            </a>\n          </li>\n        ))}\n      </ul>\n    </div>\n  )\n}\n\n// ---------------------------------------------------------------- spotlight\n\nconst IDLE_DASH = { 1: 12, 2: 8, 3: 5 } as const\n\nfunction Spotlight({ items, index, title, accentColor, reduced, onSelect }: VariantProps) {\n  const t: Transition = reduced ? { duration: 0 } : { type: \"spring\", stiffness: 260, damping: 28 }\n\n  return (\n    <div>\n      <div className=\"mb-4 flex items-center justify-between gap-4 text-[11px] font-medium uppercase tracking-[0.18em] text-muted-foreground\">\n        <span>{title}</span>\n        <span className=\"flex items-center font-mono tabular-nums tracking-normal\">\n          <span className=\"relative inline-flex h-4 overflow-hidden text-foreground\">\n            <AnimatePresence mode=\"popLayout\" initial={false}>\n              <motion.span\n                key={index}\n                initial={{ y: \"100%\", opacity: 0 }}\n                animate={{ y: 0, opacity: 1 }}\n                exit={{ y: \"-100%\", opacity: 0 }}\n                transition={t}\n                className=\"leading-4\"\n              >\n                {pad(index + 1)}\n              </motion.span>\n            </AnimatePresence>\n          </span>\n          <span className=\"px-1 opacity-50\">/</span>\n          {pad(items.length)}\n        </span>\n      </div>\n      <ul className=\"flex flex-col\">\n        {items.map((item, i) => {\n          const active = i === index\n          const level = item.level ?? 1\n          const width = active ? 24 : IDLE_DASH[level]\n          return (\n            <li key={item.id}>\n              <motion.a\n                href={`#${item.id}`}\n                aria-current={active ? \"location\" : undefined}\n                onClick={(e) => {\n                  e.preventDefault()\n                  onSelect(item.id)\n                }}\n                initial={false}\n                animate={active ? \"active\" : \"idle\"}\n                whileHover=\"hover\"\n                className=\"flex items-center gap-3 py-1.5 leading-5 outline-none focus-visible:underline\"\n              >\n                <span aria-hidden className=\"relative flex h-2 w-6 shrink-0 items-center text-foreground\" style={{ color: tint(accentColor) }}>\n                  <motion.span\n                    className=\"absolute left-0 h-1.5 rounded-full bg-current blur-[5px]\"\n                    initial={false}\n                    animate={{ width, opacity: active ? 0.7 : 0 }}\n                    transition={t}\n                  />\n                  <motion.span\n                    className=\"absolute left-0 h-0.5 rounded-full bg-current\"\n                    initial={false}\n                    animate={{ width, opacity: active ? 1 : 0.35 }}\n                    transition={t}\n                  />\n                </span>\n                <motion.span\n                  className={cn(\"min-w-0\", active ? \"font-medium text-foreground\" : \"text-muted-foreground\")}\n                  style={{ marginLeft: (level - 1) * 10 }}\n                  variants={{\n                    idle: { opacity: 0.5, filter: \"blur(0.6px)\", x: 0 },\n                    active: { opacity: 1, filter: \"blur(0px)\", x: 2 },\n                    hover: active ? { opacity: 1, filter: \"blur(0px)\", x: 2 } : { opacity: 0.9, filter: \"blur(0px)\", x: 1 },\n                  }}\n                  transition={t}\n                >\n                  {item.title}\n                </motion.span>\n              </motion.a>\n            </li>\n          )\n        })}\n      </ul>\n    </div>\n  )\n}\n",
      "type": "registry:component"
    }
  ],
  "docs": "Docs, live playground and every prop: https://trytweenly.vercel.app/docs/components/table-of-contents",
  "type": "registry:component"
}