{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "table-of-contents",
  "title": "Table Of Contents",
  "description": "An \"On this page\" list that marks the section in view and scrolls to a heading when a link is chosen.",
  "dependencies": [
    "motion"
  ],
  "files": [
    {
      "path": "registry/tealmac/table-of-contents.tsx",
      "content": "// Adapted from Ballmac UI (https://github.com/vamsiy78/ballmac-ui), MIT License, Copyright (c) 2026 Ballmac.\n\"use client\"\n\nimport * as React from \"react\"\nimport { motion, useReducedMotion } from \"motion/react\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst snappySpring = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 34,\n  mass: 0.8,\n} as const\n\n/** An element to scroll, or `null`/`undefined` for the window. */\ntype ScrollContainer = React.RefObject<HTMLElement | null> | null | undefined\n\nfunction prefersReducedMotion() {\n  return (\n    typeof window !== \"undefined\" &&\n    window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n  )\n}\n\n/** Finds an element by id, looking inside `box` first. */\nfunction findById(id: string, box?: HTMLElement | null) {\n  return (\n    box?.querySelector<HTMLElement>(`[id=\"${CSS.escape(id)}\"]`) ??\n    document.getElementById(id)\n  )\n}\n\n/** Scrolls to the element with this id, leaving `offset` pixels above it. Returns false when it does not exist. */\nfunction scrollToId(\n  id: string,\n  options: { offset?: number; container?: ScrollContainer } = {}\n) {\n  const { offset = 0, container } = options\n  const box = container?.current\n  const el = findById(id, box)\n  if (!el) return false\n  const behavior = prefersReducedMotion() ? \"auto\" : \"smooth\"\n  if (box) {\n    const top =\n      el.getBoundingClientRect().top -\n      box.getBoundingClientRect().top +\n      box.scrollTop -\n      offset\n    box.scrollTo({ top, behavior })\n  } else {\n    window.scrollTo({\n      top: el.getBoundingClientRect().top + window.scrollY - offset,\n      behavior,\n    })\n  }\n  return true\n}\n\nfunction useScrollListener(\n  container: ScrollContainer,\n  onScroll: (y: number) => void\n) {\n  const handler = React.useRef(onScroll)\n  React.useEffect(() => {\n    handler.current = onScroll\n  })\n  React.useEffect(() => {\n    const box = container?.current\n    const target: HTMLElement | Window = box ?? window\n    let frame = 0\n    const run = () => {\n      frame = 0\n      handler.current(box ? box.scrollTop : window.scrollY)\n    }\n    const onEvent = () => {\n      if (!frame) frame = requestAnimationFrame(run)\n    }\n    target.addEventListener(\"scroll\", onEvent, { passive: true })\n    window.addEventListener(\"resize\", onEvent, { passive: true })\n    frame = requestAnimationFrame(run)\n    return () => {\n      target.removeEventListener(\"scroll\", onEvent)\n      window.removeEventListener(\"resize\", onEvent)\n      if (frame) cancelAnimationFrame(frame)\n    }\n  }, [container])\n}\n\n/**\n * The id of the section the reader is in: the last id whose top has passed `offset` pixels from the top of the\n * viewport (or container). At the very end, the last id wins so short final sections can be reached.\n */\nfunction useScrollSpy(\n  ids: string[],\n  options: { offset?: number; container?: ScrollContainer } = {}\n) {\n  const { offset = 96, container } = options\n  const [active, setActive] = React.useState<string | undefined>(ids[0])\n  const key = ids.join(\"\\u0000\")\n  const list = React.useMemo(() => (key ? key.split(\"\\u0000\") : []), [key])\n  useScrollListener(container, () => {\n    if (!list.length) return\n    const box = container?.current\n    const boxTop = box ? box.getBoundingClientRect().top : 0\n    let current = list[0]\n    for (const id of list) {\n      const el = findById(id, box)\n      if (!el) continue\n      if (el.getBoundingClientRect().top - boxTop - offset <= 1) current = id\n      else break\n    }\n    const atEnd = box\n      ? box.scrollTop + box.clientHeight >= box.scrollHeight - 2\n      : window.scrollY + window.innerHeight >=\n        document.documentElement.scrollHeight - 2\n    const moved = box ? box.scrollTop > 0 : window.scrollY > 0\n    if (atEnd && list.length > 1 && moved) current = list[list.length - 1]\n    setActive(current)\n  })\n  return active\n}\n\ntype TocItem = {\n  /** The id of the heading in the page. */\n  id: string\n  /** Text of the link. */\n  title: string\n  /** Heading level (2 = top level, 3 = indented, and so on). */\n  level?: number\n}\n\ntype TableOfContentsProps = Omit<React.ComponentProps<\"nav\">, \"children\"> & {\n  /** Links to show. Leave out to collect headings from the page automatically. */\n  items?: TocItem[]\n  /** Where to look for headings when `items` is not given. Defaults to `<main>`, then the whole page. */\n  headingsFrom?: React.RefObject<HTMLElement | null>\n  /** Heading levels to collect automatically. */\n  levels?: number[]\n  /** Title above the list. Also the accessible name of the navigation. */\n  title?: string\n  /** Pixels reserved at the top for a sticky header; also where a section counts as \"reached\". */\n  offset?: number\n  /** A scrollable element to watch and scroll instead of the page. */\n  container?: ScrollContainer\n  /** Called when the reader chooses a link. */\n  onNavigate?: (id: string) => void\n}\n\nfunction slug(text: string) {\n  return text\n    .toLowerCase()\n    .trim()\n    .replace(/[^a-z0-9]+/g, \"-\")\n    .replace(/^-+|-+$/g, \"\")\n}\n\n/**\n * \"On this page\" navigation with a scroll spy. The current section is marked with a sliding indicator and\n * `aria-current=\"location\"`; choosing a link scrolls smoothly (instantly under reduced motion) below a sticky header.\n */\nfunction TableOfContents({\n  items: itemsProp,\n  headingsFrom,\n  levels = [2, 3],\n  title,\n  offset = 96,\n  container,\n  onNavigate,\n  className,\n  ...props\n}: TableOfContentsProps) {\n  title ??= \"On this page\"\n  const reduce = useReducedMotion()\n  const indicatorId = `toc-${React.useId()}`\n  const [found, setFound] = React.useState<TocItem[]>([])\n  const levelKey = levels.join(\",\")\n\n  React.useEffect(() => {\n    if (itemsProp) return\n    const frame = requestAnimationFrame(() => {\n      const scope =\n        headingsFrom?.current ?? document.querySelector(\"main\") ?? document.body\n      const selector = levelKey\n        .split(\",\")\n        .map((l) => `h${l}`)\n        .join(\",\")\n      const next: TocItem[] = []\n      scope.querySelectorAll<HTMLElement>(selector).forEach((heading) => {\n        const text = heading.textContent?.trim() ?? \"\"\n        if (!text) return\n        if (!heading.id) heading.id = slug(text)\n        next.push({\n          id: heading.id,\n          title: text,\n          level: Number(heading.tagName.slice(1)),\n        })\n      })\n      setFound(next)\n    })\n    return () => cancelAnimationFrame(frame)\n  }, [itemsProp, headingsFrom, levelKey])\n\n  const items = itemsProp ?? found\n  const ids = React.useMemo(() => items.map((i) => i.id), [items])\n  const active = useScrollSpy(ids, { offset, container })\n  const base = items.length ? Math.min(...items.map((i) => i.level ?? 2)) : 2\n  if (!items.length) return null\n  return (\n    <nav\n      aria-label={title}\n      data-slot=\"table-of-contents\"\n      className={cn(\"text-sm\", className)}\n      {...props}\n    >\n      <p className=\"text-foreground mb-3 text-xs font-semibold tracking-wide uppercase\">\n        {title}\n      </p>\n      <ul className=\"border-border relative grid gap-0.5 border-s\">\n        {items.map((item) => {\n          const isActive = item.id === active\n          return (\n            <li key={item.id}>\n              <a\n                href={`#${item.id}`}\n                aria-current={isActive ? \"location\" : undefined}\n                data-active={isActive || undefined}\n                onClick={(event) => {\n                  event.preventDefault()\n                  if (scrollToId(item.id, { offset: offset - 8, container })) {\n                    if (!container)\n                      history.replaceState(null, \"\", `#${item.id}`)\n                    onNavigate?.(item.id)\n                  }\n                }}\n                style={{\n                  paddingInlineStart: `${0.75 + ((item.level ?? 2) - base) * 0.75}rem`,\n                }}\n                className=\"text-muted-foreground hover:text-foreground focus-visible:ring-ring/50 data-[active]:text-foreground relative -ms-px block rounded-e-md py-1.5 pe-2 leading-snug transition-colors outline-none focus-visible:ring-[3px] data-[active]:font-medium\"\n              >\n                {isActive && (\n                  <motion.span\n                    layoutId={indicatorId}\n                    aria-hidden=\"true\"\n                    className=\"bg-primary absolute inset-y-1 start-0 w-0.5 rounded-full\"\n                    transition={reduce ? { duration: 0 } : snappySpring}\n                  />\n                )}\n                {item.title}\n              </a>\n            </li>\n          )\n        })}\n      </ul>\n    </nav>\n  )\n}\n\nexport { TableOfContents, type TableOfContentsProps, type TocItem }\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}