{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"table-of-content","title":"Table of Content","author":"CoDesign-Spa27","description":"A reading-aware page outline with an animated active marker, expandable subsections, and a progress rail.","dependencies":["motion","next"],"files":[{"path":"components/ui-components/table-of-content.tsx","content":"\"use client\";\n\nimport { AnimatePresence, motion, useMotionValue, useReducedMotion, useSpring } from \"motion/react\";\nimport { usePathname } from \"next/navigation\";\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport type DocsTocItem = {\n  id: string;\n  label: string;\n  level: 2 | 3;\n  parent: string | null;\n};\n\ntype DocsTocProps = {\n  className?: string;\n  /** When provided, renders a selectable outline without tracking page headings. */\n  items?: DocsTocItem[];\n};\n\nconst OFFSET = 120;\nconst TICK = 7;\nconst MAJOR = 5;\nconst SPRING = { type: \"spring\", stiffness: 520, damping: 42 } as const;\nconst INSTANT = { duration: 0 };\n\nconst clamp01 = (value: number) => Math.min(1, Math.max(0, value));\n\nfunction getScrollRoot(element: HTMLElement | null): HTMLElement | null {\n  let ancestor = element?.parentElement;\n\n  while (ancestor) {\n    if (\n      /(auto|scroll)/.test(getComputedStyle(ancestor).overflowY) &&\n      ancestor.scrollHeight > ancestor.clientHeight\n    ) {\n      return ancestor;\n    }\n\n    ancestor = ancestor.parentElement;\n  }\n\n  return null;\n}\n\nfunction getReadingLine(root: HTMLElement | null, lastHeading: HTMLElement | null) {\n  const start = root ? root.getBoundingClientRect().top + 40 : OFFSET;\n  if (!lastHeading) return start;\n\n  const remaining = root\n    ? Math.max(0, root.scrollHeight - root.clientHeight - root.scrollTop)\n    : Math.max(0, document.documentElement.scrollHeight - window.innerHeight - window.scrollY);\n  const lastHeadingAtEnd = lastHeading.getBoundingClientRect().top - remaining;\n  const neededShift = Math.max(0, lastHeadingAtEnd - start + 16);\n  const runway = (root?.clientHeight ?? window.innerHeight) / 2;\n\n  return start + neededShift * (1 - clamp01(remaining / Math.max(1, runway)));\n}\n\nfunction useItems(enabled: boolean) {\n  const pathname = usePathname();\n  const [items, setItems] = React.useState<DocsTocItem[]>([]);\n\n  React.useEffect(() => {\n    if (!enabled || !pathname) {\n      setItems([]);\n      return;\n    }\n\n    let parent: string | null = null;\n\n    const next = Array.from(document.querySelectorAll<HTMLElement>(\"[data-toc]\"))\n      .filter((element) => element.id)\n      .map((element): DocsTocItem => {\n        const level = element.dataset.toc === \"3\" ? 3 : 2;\n        if (level === 2) parent = element.id;\n\n        return {\n          id: element.id,\n          label: element.dataset.tocLabel ?? element.textContent?.trim() ?? \"\",\n          level,\n          parent: level === 3 ? parent : null,\n        };\n      });\n\n    setItems(next);\n  }, [enabled, pathname]);\n\n  return items;\n}\n\nfunction useTocTracking(\n  items: DocsTocItem[],\n  standalone: boolean,\n  active: string | null,\n  railRef: React.RefObject<HTMLUListElement | null>,\n  onActiveChange: React.Dispatch<React.SetStateAction<string | null>>,\n) {\n  const progress = useMotionValue(0);\n  const thumbTop = useMotionValue(0);\n  const thumbHeight = useMotionValue(0);\n\n  React.useEffect(() => {\n    const rail = railRef.current;\n\n    if (!rail || !items.length) {\n      if (!standalone) onActiveChange(null);\n      progress.set(0);\n      thumbHeight.set(0);\n      return;\n    }\n\n    const root = standalone ? null : getScrollRoot(document.getElementById(items[0].id));\n\n    let frame = 0;\n\n    const update = () => {\n      frame = 0;\n\n      const readingLine = getReadingLine(root, document.getElementById(items[items.length - 1].id));\n      let current = active ?? items[0].id;\n\n      if (!standalone) {\n        current = items[0].id;\n\n        for (const item of items) {\n          const heading = document.getElementById(item.id);\n\n          if (heading && heading.getBoundingClientRect().top <= readingLine) {\n            current = item.id;\n          }\n        }\n\n        onActiveChange(current);\n      }\n\n      // Match the heading directly; React may not have committed data-active yet.\n      const link = Array.from(rail.querySelectorAll<HTMLElement>(\"[data-toc-id]\")).find(\n        (element) => element.dataset.tocId === current,\n      );\n\n      if (!link) return;\n\n      thumbTop.set(link.getBoundingClientRect().top - rail.getBoundingClientRect().top + 4);\n      thumbHeight.set(Math.max(0, link.offsetHeight - 8));\n\n      let through = 1;\n\n      if (!standalone) {\n        const index = items.findIndex((item) => item.id === current);\n        const heading = document.getElementById(current);\n        const next = items[index + 1] ? document.getElementById(items[index + 1].id) : null;\n\n        if (heading && next) {\n          const start = heading.getBoundingClientRect().top;\n          const end = next.getBoundingClientRect().top;\n\n          through = clamp01((readingLine - start) / Math.max(1, end - start));\n        }\n      }\n\n      progress.set(\n        link.getBoundingClientRect().top -\n          rail.getBoundingClientRect().top +\n          through * link.offsetHeight,\n      );\n    };\n\n    const schedule = () => {\n      if (!frame) frame = requestAnimationFrame(update);\n    };\n\n    const observer = new ResizeObserver(schedule);\n    observer.observe(rail);\n\n    if (!standalone) {\n      root?.addEventListener(\"scroll\", schedule, { passive: true });\n      window.addEventListener(\"scroll\", schedule, { passive: true });\n    }\n\n    window.addEventListener(\"resize\", schedule);\n    schedule();\n\n    return () => {\n      cancelAnimationFrame(frame);\n      observer.disconnect();\n      root?.removeEventListener(\"scroll\", schedule);\n      window.removeEventListener(\"scroll\", schedule);\n      window.removeEventListener(\"resize\", schedule);\n    };\n  }, [items, standalone, active, railRef, onActiveChange, progress, thumbTop, thumbHeight]);\n\n  return { progress, thumbTop, thumbHeight };\n}\n\nfunction TocRuler({\n  railRef,\n  progress,\n  reduceMotion,\n}: {\n  railRef: React.RefObject<HTMLUListElement | null>;\n  progress: ReturnType<typeof useMotionValue<number>>;\n  reduceMotion: boolean;\n}) {\n  const rulerRef = React.useRef<HTMLLIElement>(null);\n  const [ticks, setTicks] = React.useState(0);\n  const smoothProgress = useSpring(progress, {\n    stiffness: 300,\n    damping: 40,\n  });\n\n  React.useEffect(() => {\n    const rail = railRef.current;\n    if (!rail) return;\n\n    const measure = () => setTicks(Math.floor(rail.offsetHeight / TICK) + 1);\n    const observer = new ResizeObserver(measure);\n\n    measure();\n    observer.observe(rail);\n\n    return () => observer.disconnect();\n  }, [railRef]);\n\n  React.useEffect(() => {\n    const source = reduceMotion ? progress : smoothProgress;\n    const write = (value: number) => rulerRef.current?.style.setProperty(\"--head\", String(value));\n\n    write(source.get());\n    return source.on(\"change\", write);\n  }, [progress, smoothProgress, reduceMotion]);\n\n  React.useEffect(() => {\n    const rail = railRef.current;\n    if (!rail) return;\n\n    const move = (event: PointerEvent) => {\n      if (reduceMotion) return;\n\n      rulerRef.current?.style.setProperty(\n        \"--probe\",\n        String(event.clientY - rail.getBoundingClientRect().top),\n      );\n    };\n\n    const leave = () => rulerRef.current?.style.setProperty(\"--probe\", \"-999\");\n\n    leave();\n    rail.addEventListener(\"pointermove\", move);\n    rail.addEventListener(\"pointerleave\", leave);\n\n    return () => {\n      rail.removeEventListener(\"pointermove\", move);\n      rail.removeEventListener(\"pointerleave\", leave);\n    };\n  }, [railRef, reduceMotion]);\n\n  return (\n    <li\n      ref={rulerRef}\n      aria-hidden=\"true\"\n      className=\"pointer-events-none absolute inset-y-0 -start-6 w-4 [--head:0] [--probe:-999]\"\n    >\n      {Array.from({ length: ticks }, (_, index) => index * TICK).map((position, index) => (\n        <span\n          key={position}\n          className=\"absolute end-0 h-px rounded-full transition-[width] duration-100 ease-out motion-reduce:transition-none\"\n          style={\n            {\n              top: position,\n              \"--y\": position,\n              \"--base\": index % MAJOR === 0 ? 8 : 4,\n              \"--near-head\": \"max(0, 1 - max(var(--y) - var(--head), var(--head) - var(--y)) / 28)\",\n              \"--near-probe\":\n                \"max(0, 1 - max(var(--y) - var(--probe), var(--probe) - var(--y)) / 24)\",\n              width:\n                \"calc(var(--base) * 1px + max(var(--near-head) * 10px, var(--near-probe) * 7px))\",\n              backgroundColor:\n                \"color-mix(in oklab, var(--highlight) calc(clamp(0, var(--head) - var(--y), 1) * 100%), var(--muted-foreground))\",\n            } as React.CSSProperties\n          }\n        />\n      ))}\n    </li>\n  );\n}\n\nexport function DocsToc({ className, items: providedItems }: DocsTocProps) {\n  const standalone = providedItems !== undefined;\n  const scannedItems = useItems(!standalone);\n  const items = providedItems ?? scannedItems;\n\n  const [selected, setSelected] = React.useState<string | null>(null);\n  const [observedActive, setObservedActive] = React.useState<string | null>(null);\n\n  const active = standalone\n    ? (items.find((item) => item.id === selected)?.id ?? items[0]?.id ?? null)\n    : observedActive;\n\n  const reduceMotion = Boolean(useReducedMotion());\n  const transition = reduceMotion ? INSTANT : SPRING;\n  const listRef = React.useRef<HTMLDivElement>(null);\n  const railRef = React.useRef<HTMLUListElement>(null);\n\n  const { progress, thumbTop, thumbHeight } = useTocTracking(\n    items,\n    standalone,\n    active,\n    railRef,\n    setObservedActive,\n  );\n  const smoothThumbTop = useSpring(thumbTop, { stiffness: 520, damping: 42 });\n  const smoothThumbHeight = useSpring(thumbHeight, { stiffness: 520, damping: 42 });\n\n  const sections = React.useMemo(() => {\n    const children = new Map<string, DocsTocItem[]>();\n\n    for (const item of items) {\n      if (item.level !== 3 || !item.parent) continue;\n\n      const group = children.get(item.parent) ?? [];\n      group.push(item);\n      children.set(item.parent, group);\n    }\n\n    return items\n      .filter((item) => item.level === 2)\n      .map((item) => ({\n        ...item,\n        children: children.get(item.id) ?? [],\n      }));\n  }, [items]);\n\n  const activeItem = items.find((item) => item.id === active);\n  const openSection = activeItem?.level === 3 ? activeItem.parent : activeItem?.id;\n\n  React.useEffect(() => {\n    if (!active) return;\n\n    const list = listRef.current;\n    const link = list?.querySelector<HTMLElement>(\"[data-active]\");\n    if (!list || !link) return;\n\n    const top =\n      link.getBoundingClientRect().top - list.getBoundingClientRect().top + list.scrollTop;\n\n    if (top < list.scrollTop + 24 || top > list.scrollTop + list.clientHeight - 48) {\n      list.scrollTo({\n        top: top - list.clientHeight / 3,\n        behavior: reduceMotion ? \"instant\" : \"smooth\",\n      });\n    }\n  }, [active, reduceMotion]);\n\n  function navigate(event: React.MouseEvent<HTMLAnchorElement>, id: string) {\n    if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {\n      return;\n    }\n\n    const target = document.getElementById(id);\n    if (!target) return;\n\n    event.preventDefault();\n    target.scrollIntoView({\n      behavior: reduceMotion ? \"instant\" : \"smooth\",\n    });\n    history.replaceState(null, \"\", `#${id}`);\n  }\n\n  function renderLink(item: DocsTocItem) {\n    const isActive = item.id === active;\n\n    const props = {\n      \"data-active\": isActive || undefined,\n      \"data-toc-id\": item.id,\n      className: cn(\n        \"relative block w-full py-1.5 text-left text-base\",\n        \"transition-[color] duration-150 ease-out\",\n        \"focus-visible:rounded-sm focus-visible:outline-2\",\n        \"focus-visible:outline-offset-2 focus-visible:outline-ring\",\n        item.level === 2 ? \"ps-3\" : \"ps-6 font-mono text-sm\",\n        isActive ? \"font-medium text-foreground\" : \"text-muted-foreground hover:text-foreground\",\n      ),\n    };\n\n    const content = <span className=\"block truncate\">{item.label}</span>;\n\n    return standalone ? (\n      <button {...props} type=\"button\" aria-pressed={isActive} onClick={() => setSelected(item.id)}>\n        {content}\n      </button>\n    ) : (\n      <a\n        {...props}\n        href={`#${item.id}`}\n        aria-current={isActive ? \"location\" : undefined}\n        onClick={(event) => navigate(event, item.id)}\n      >\n        {content}\n      </a>\n    );\n  }\n\n  if (!items.length) return null;\n\n  return (\n    <nav aria-label=\"On this page\" data-slot=\"docs-toc\" className={cn(\"flex flex-col\", className)}>\n      <span className=\"pb-2 text-sm text-muted-foreground\">On this page</span>\n\n      <div\n        ref={listRef}\n        className=\"no-scrollbar max-h-[calc(100dvh-10rem)] overflow-y-auto py-1 ps-6\"\n      >\n        <ul ref={railRef} className=\"relative flex flex-col border-s border-border\">\n          <TocRuler railRef={railRef} progress={progress} reduceMotion={reduceMotion} />\n          <motion.span\n            aria-hidden=\"true\"\n            className=\"pointer-events-none absolute -start-px z-10 w-[3px] rounded-full bg-highlight\"\n            style={{\n              y: reduceMotion ? thumbTop : smoothThumbTop,\n              height: reduceMotion ? thumbHeight : smoothThumbHeight,\n            }}\n          />\n\n          {sections.map((section) => (\n            <li key={section.id}>\n              {renderLink(section)}\n\n              <AnimatePresence initial={false}>\n                {section.children.length > 0 && openSection === section.id && (\n                  <motion.ul\n                    initial={{ height: 0 }}\n                    animate={{ height: \"auto\" }}\n                    exit={{ height: 0 }}\n                    transition={transition}\n                    className=\"overflow-hidden\"\n                  >\n                    {section.children.map((child) => (\n                      <li key={child.id}>{renderLink(child)}</li>\n                    ))}\n                  </motion.ul>\n                )}\n              </AnimatePresence>\n            </li>\n          ))}\n        </ul>\n      </div>\n    </nav>\n  );\n}\n","type":"registry:ui"}],"categories":["navigation","documentation","animation"],"type":"registry:ui"}