{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "table-of-contents",
  "title": "Table of Contents",
  "description": "An 'On this page' table of contents for articles and docs: it tracks the section in view, slides a marker along its rail (filling it like reading progress), indents subsections, and smooth-scrolls to a heading on click. Collects headings automatically.",
  "dependencies": [
    "motion",
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/table-of-contents/table-of-contents.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { motion, useReducedMotion } from \"motion/react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nexport type TableOfContentsSize = \"sm\" | \"md\" | \"lg\";\n\nexport interface TocItem {\n  /** The id of the heading element this entry scrolls to. */\n  id: string;\n  label: string;\n  /** 2 for a section, 3 for a subsection (indented), and so on. */\n  level?: number;\n}\n\nexport interface TableOfContentsProps {\n  /** The entries. Leave out and pass contentRef to collect them from the headings in the content. */\n  items?: TocItem[];\n  /** Content to read h2/h3 headings (with ids) from when items isn't given. */\n  contentRef?: React.RefObject<HTMLElement | null>;\n  /** The element that scrolls; defaults to the page. */\n  scrollRef?: React.RefObject<HTMLElement | null>;\n  /** Distance from the top of the scroll area at which a heading counts as the current one (e.g. a sticky header's height). */\n  offset?: number;\n  title?: string;\n  /** Fill the rail from the top down to the current entry, like reading progress. */\n  showProgress?: boolean;\n  /** Write the current section's #id into the address bar when an entry is clicked. */\n  updateHash?: boolean;\n  size?: TableOfContentsSize;\n  theme?: \"dark\" | \"light\";\n  className?: string;\n}\n\nconst PALETTES = {\n  dark: { text: \"#F5F4F1\", muted: \"rgba(245,244,241,0.5)\", rail: \"rgba(255,255,255,0.1)\", fill: \"rgba(245,244,241,0.55)\", thumb: \"#F5F4F1\", focus: \"rgba(245,244,241,0.85)\" },\n  light: { text: \"#0A0A0A\", muted: \"rgba(10,10,10,0.5)\", rail: \"rgba(10,10,10,0.1)\", fill: \"rgba(10,10,10,0.45)\", thumb: \"#0A0A0A\", focus: \"rgba(10,10,10,0.85)\" },\n};\n\nconst SIZES: Record<TableOfContentsSize, { font: number; row: number; indent: number; title: number }> = {\n  sm: { font: 12.5, row: 28, indent: 12, title: 10.5 },\n  md: { font: 13.5, row: 32, indent: 14, title: 11 },\n  lg: { font: 15, row: 36, indent: 16, title: 12 },\n};\n\nfunction collect(root: HTMLElement): TocItem[] {\n  return Array.from(root.querySelectorAll<HTMLElement>(\"h2[id], h3[id], h4[id]\")).map((h) => ({ id: h.id, label: h.textContent?.trim() ?? h.id, level: Number(h.tagName[1]) }));\n}\n\nexport function TableOfContents({\n  items,\n  contentRef,\n  scrollRef,\n  offset = 24,\n  title = \"On this page\",\n  showProgress = true,\n  updateHash = false,\n  size = \"md\",\n  theme = \"dark\",\n  className,\n}: TableOfContentsProps) {\n  const p = PALETTES[theme];\n  const s = SIZES[size];\n  const reduce = Boolean(useReducedMotion());\n  const listRef = React.useRef<HTMLOListElement>(null);\n  const [collected, setCollected] = React.useState<TocItem[]>([]);\n  const entries = items ?? collected;\n  const [activeId, setActiveId] = React.useState<string | null>(entries[0]?.id ?? null);\n  const [thumb, setThumb] = React.useState({ top: 0, height: 0 });\n  const minLevel = Math.min(...entries.map((e) => e.level ?? 2));\n\n  // Collect headings from the content once it's mounted (and again if it changes).\n  React.useEffect(() => {\n    if (items || !contentRef?.current) return;\n    const el = contentRef.current;\n    const read = () => setCollected(collect(el));\n    read();\n    const mo = new MutationObserver(read);\n    mo.observe(el, { childList: true, subtree: true, characterData: true });\n    return () => mo.disconnect();\n  }, [items, contentRef]);\n\n  // The current entry is the last heading whose top has passed the offset line; at the very bottom\n  // of the scroll area it's the last one, so short final sections can still become current.\n  React.useEffect(() => {\n    if (!entries.length) return;\n    const root = scrollRef?.current ?? null;\n    const target: HTMLElement | Window = root ?? window;\n    let raf = 0;\n    const update = () => {\n      raf = 0;\n      const top = root ? root.getBoundingClientRect().top : 0;\n      const atBottom = root ? root.scrollTop + root.clientHeight >= root.scrollHeight - 2 : window.scrollY + window.innerHeight >= document.documentElement.scrollHeight - 2;\n      let current = entries[0].id;\n      for (const e of entries) {\n        const el = document.getElementById(e.id);\n        if (el && el.getBoundingClientRect().top - top <= offset + 1) current = e.id;\n      }\n      if (atBottom) current = entries[entries.length - 1].id;\n      setActiveId(current);\n    };\n    const onScroll = () => {\n      if (!raf) raf = requestAnimationFrame(update);\n    };\n    update();\n    target.addEventListener(\"scroll\", onScroll, { passive: true });\n    window.addEventListener(\"resize\", onScroll);\n    return () => {\n      target.removeEventListener(\"scroll\", onScroll);\n      window.removeEventListener(\"resize\", onScroll);\n      if (raf) cancelAnimationFrame(raf);\n    };\n  }, [entries, scrollRef, offset]);\n\n  // Measure the active row in layout px so the thumb lines up even inside scaled containers.\n  React.useLayoutEffect(() => {\n    const row = listRef.current?.querySelector<HTMLElement>(`[data-toc-id=\"${CSS.escape(activeId ?? \"\")}\"]`);\n    if (row) setThumb({ top: row.offsetTop, height: row.offsetHeight });\n  }, [activeId, entries]);\n\n  const go = (e: React.MouseEvent<HTMLAnchorElement>, id: string) => {\n    const el = document.getElementById(id);\n    if (!el) return;\n    e.preventDefault();\n    const root = scrollRef?.current;\n    if (root) {\n      const scale = root.getBoundingClientRect().height / root.offsetHeight || 1;\n      const delta = (el.getBoundingClientRect().top - root.getBoundingClientRect().top) / scale;\n      root.scrollTo({ top: root.scrollTop + delta - offset, behavior: reduce ? \"auto\" : \"smooth\" });\n    } else {\n      window.scrollTo({ top: window.scrollY + el.getBoundingClientRect().top - offset, behavior: reduce ? \"auto\" : \"smooth\" });\n    }\n    if (updateHash) history.replaceState(null, \"\", `#${id}`);\n    setActiveId(id);\n  };\n\n  if (!entries.length) return null;\n\n  return (\n    <nav aria-label={title || \"Table of contents\"} className={cn(\"flex flex-col\", className)} style={{ fontFamily: \"Inter, sans-serif\", gap: 10 }}>\n      {title && (\n        <div className=\"font-semibold uppercase\" style={{ color: p.muted, fontSize: s.title, letterSpacing: \"0.08em\" }}>\n          {title}\n        </div>\n      )}\n      <div className=\"relative\">\n        <span aria-hidden=\"true\" className=\"absolute top-0 bottom-0 left-0\" style={{ width: 1, background: p.rail }} />\n        {showProgress && (\n          <motion.span aria-hidden=\"true\" className=\"absolute top-0 left-0\" style={{ width: 1, background: p.fill }} initial={false} animate={{ height: thumb.top + thumb.height }} transition={reduce ? { duration: 0 } : { type: \"spring\", stiffness: 300, damping: 36 }} />\n        )}\n        <motion.span\n          aria-hidden=\"true\"\n          className=\"absolute left-0\"\n          style={{ width: 2, marginLeft: -0.5, borderRadius: 2, background: p.thumb }}\n          initial={false}\n          animate={{ top: thumb.top + 6, height: Math.max(0, thumb.height - 12) }}\n          transition={reduce ? { duration: 0 } : { type: \"spring\", stiffness: 420, damping: 34 }}\n        />\n        <ol ref={listRef} className=\"m-0 list-none p-0\">\n          {entries.map((e) => {\n            const active = e.id === activeId;\n            return (\n              <li key={e.id} data-toc-id={e.id}>\n                <a\n                  href={`#${e.id}`}\n                  onClick={(ev) => go(ev, e.id)}\n                  aria-current={active ? \"location\" : undefined}\n                  className=\"block no-underline outline-none focus-visible:ring-2\"\n                  style={{\n                    padding: `${(s.row - s.font * 1.4) / 2}px 0 ${(s.row - s.font * 1.4) / 2}px ${14 + ((e.level ?? 2) - minLevel) * s.indent}px`,\n                    color: active ? p.text : p.muted,\n                    fontSize: (e.level ?? 2) > minLevel ? s.font - 0.5 : s.font,\n                    fontWeight: active ? 600 : 500,\n                    lineHeight: 1.4,\n                    borderRadius: 6,\n                    transition: \"color 0.2s ease\",\n                    [\"--tw-ring-color\" as string]: p.focus,\n                  }}\n                  onMouseEnter={(ev) => (ev.currentTarget.style.color = p.text)}\n                  onMouseLeave={(ev) => (ev.currentTarget.style.color = active ? p.text : p.muted)}\n                >\n                  {e.label}\n                </a>\n              </li>\n            );\n          })}\n        </ol>\n      </div>\n    </nav>\n  );\n}\n\nexport default TableOfContents;\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}