{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "table-of-contents",
  "type": "registry:component",
  "title": "Table of Contents",
  "description": "The sections of a long page as a quiet rail, with one mark that moves to what you are reading.",
  "dependencies": [
    "@base-ui/react",
    "tailwind-variants"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "components/panelui/table-of-contents/index.tsx",
      "type": "registry:component",
      "target": "@components/panelui/table-of-contents/index.tsx",
      "content": "'use client';\n\n/**\n * TableOfContents — the sections of a long page, as a quiet rail that says\n * which one you are reading.\n *\n * ```tsx\n * <TableOfContents defaultValue=\"install\" offset={80}>\n *   <TableOfContents.Title>On this page</TableOfContents.Title>\n *   <TableOfContents.List>\n *     <TableOfContents.Item value=\"install\">\n *       <TableOfContents.Link href=\"#install\">Install</TableOfContents.Link>\n *     </TableOfContents.Item>\n *     <TableOfContents.Item value=\"configure\" depth={1}>\n *       <TableOfContents.Link href=\"#configure\">Configure</TableOfContents.Link>\n *     </TableOfContents.Item>\n *   </TableOfContents.List>\n * </TableOfContents>\n * ```\n *\n * ## One mark, and it moves\n *\n * The list sits against a hairline the height of the page's sections, and one\n * short segment in the primary colour travels to the section being read. The\n * links themselves stay muted until they are current, so the rail is what the\n * eye catches and the words are what it finds when it arrives.\n *\n * ## Or a line that follows the outline\n *\n * `variant=\"contour\"` draws the rail as a path that steps in with each level\n * and bends back out, so the outline's shape is in the line itself. Instead of\n * one segment it lights every section on screen, from the one at the reading\n * line to the last heading in view, with a dot on the end it is moving\n * towards. It suits a long page with deep nesting, where a reader wants to see\n * how much of the outline the screen is showing.\n *\n * ## It knows where you are\n *\n * With no `value` given, the component watches the elements its links point at\n * with an `IntersectionObserver` and keeps the active section at the reading\n * line — the top of the viewport, `offset` pixels down. Give it a `root` and it\n * watches inside that scroller instead, for a panel that scrolls on its own.\n * Pass `value` and the scroll spy stands aside: the caller decides.\n *\n * ## The links are ordinary links\n *\n * Every link is an anchor with a real `href`, so the browser's own scroll,\n * history and middle-click behaviour all work, and a router's `Link` can take\n * its place through `render`. The active one carries `aria-current=\"location\"`.\n * The rail and its moving segment are drawn in pseudo-elements, so nothing\n * decorative is announced.\n */\nimport {\n  createContext,\n  forwardRef,\n  useCallback,\n  useContext,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n  type ComponentProps,\n  type MouseEvent as ReactMouseEvent,\n  type Ref,\n  type RefObject,\n} from 'react';\nimport { tv } from 'tailwind-variants';\nimport { mergeProps } from '@base-ui/react/merge-props';\nimport { useRender } from '@base-ui/react/use-render';\nimport type { ElementType as RenderElementType } from 'react';\nimport {\n  contourPath,\n  contourWidth,\n  hashTarget,\n  sectionAt,\n  sectionsInView,\n  type ContourRow,\n  type TocSection,\n} from './spy';\n\n/** Draws a part as another element, or composes it with a component: `render={<a href=\"/\" />}`. */\ntype RenderProp<Tag extends RenderElementType> = { render?: useRender.ComponentProps<Tag>['render'] };\n\n/** One curve for the segment, so a jump reads as one movement rather than two. */\nconst EASE = 'ease-[cubic-bezier(0.3,0.7,0.1,1)]';\n/** How far each step of `depth` indents a row. */\nconst DEPTH_STEP = 12;\n/** Where the first level starts, clear of the rail. */\nconst INDENT = 16;\n/** How far the contour line steps in for each level. */\nconst CONTOUR_STEP = 10;\n/** Half the height of a contour bend, centred on the boundary between rows. */\nconst CONTOUR_BEND = 5;\n\nconst tableOfContentsVariants = tv({\n  slots: {\n    root: 'flex min-w-0 flex-col gap-2',\n    title: 'text-xs font-medium tracking-wider text-muted-foreground uppercase',\n    list: [\n      'relative m-0 flex list-none flex-col p-0',\n      // The rail is the height of the list; the segment is the height of the\n      // current row. Both are pseudo-elements, so the `<ol>` keeps only list\n      // items as children and nothing decorative reaches a screen reader.\n      \"before:pointer-events-none before:absolute before:inset-y-0 before:start-0 before:w-px before:bg-border before:content-['']\",\n      \"after:pointer-events-none after:absolute after:start-0 after:w-0.5 after:rounded-full after:bg-primary after:content-['']\",\n      'after:top-(--toc-indicator-top,0px) after:h-(--toc-indicator-height,0px)',\n      // Hidden until it has been measured, so it never slides in from the\n      // top of the list on first paint. Once placed, only its position and\n      // height animate; appearing is instant.\n      'after:opacity-0 data-ready:after:opacity-100',\n      `data-ready:after:transition-[top,height] data-ready:after:duration-200 ${EASE} motion-reduce:after:transition-none`,\n    ],\n    item: 'min-w-0',\n    link: [\n      'block rounded-sm py-1 text-sm text-muted-foreground outline-none',\n      'transition-colors duration-150 hover:text-foreground motion-reduce:transition-none',\n      'focus-visible:ring-2 focus-visible:ring-ring',\n    ],\n    // An identifier in a row, such as a prop name. It takes the row's colour,\n    // so it lights with the rest of the row.\n    code: 'rounded-md border border-border bg-muted px-1.5 py-0.5 font-mono text-xs',\n    contour: 'pointer-events-none absolute inset-y-0 start-0 overflow-visible rtl:-scale-x-100',\n    contourLit: [\n      'pointer-events-none absolute inset-y-0 start-0 overflow-visible rtl:-scale-x-100',\n      // Cut down to the lit stretch. Only the cut moves, so the path itself is\n      // never redrawn while the reader scrolls.\n      '[clip-path:inset(var(--toc-lit-top,0px)_-4px_calc(100%_-_var(--toc-lit-bottom,0px))_-4px)]',\n      'opacity-0 group-data-ready/toc:opacity-100',\n      `group-data-ready/toc:transition-[clip-path] group-data-ready/toc:duration-300 ${EASE} motion-reduce:transition-none`,\n    ],\n    contourDot: [\n      'pointer-events-none absolute start-0 top-0 size-[5px] rounded-full bg-foreground',\n      'translate-x-(--toc-dot-x,0px) translate-y-(--toc-dot-y,0px) rtl:-translate-x-(--toc-dot-x,0px)',\n      'opacity-0 group-data-ready/toc:opacity-100',\n      `group-data-ready/toc:transition-transform group-data-ready/toc:duration-300 ${EASE} motion-reduce:transition-none`,\n    ],\n  },\n  variants: {\n    variant: {\n      rail: {\n        link: 'data-active:font-medium data-active:text-foreground',\n      },\n      contour: {\n        // The line is the decoration here, so the list draws no rail of its\n        // own and every section in view reads in the foreground colour.\n        list: 'group/toc before:hidden after:hidden',\n        link: 'data-lit:text-foreground',\n      },\n    },\n  },\n  defaultVariants: { variant: 'rail' },\n});\n\n/** How the list marks where the reader is. */\nexport type TableOfContentsVariant = 'rail' | 'contour';\n\ninterface TableOfContentsContextValue {\n  /** The section being read, or `undefined` while nothing is active. */\n  value: string | undefined;\n  /** Makes a section active, from a link press or from the scroll spy. */\n  select: (value: string) => void;\n  /**\n   * Scrolls the root to a section's element and holds the mark on it until\n   * the scroll ends. Returns `false` when there is no root to scroll, so the\n   * browser's own jump is left to happen.\n   */\n  jump: (id: string, value: string, moveFocus: boolean) => boolean;\n  /** How the list marks where the reader is. */\n  variant: TableOfContentsVariant;\n  /**\n   * Every section on screen, in page order, starting with the active one.\n   * Only the contour lights more than one.\n   */\n  lit: readonly string[];\n}\n\nconst TableOfContentsContext = createContext<TableOfContentsContextValue | null>(null);\n\ninterface TableOfContentsItemContextValue {\n  /** The section this row stands for. */\n  value: string;\n  /** How far the row is indented. */\n  depth: number;\n}\n\nconst TableOfContentsItemContext = createContext<TableOfContentsItemContextValue | null>(null);\n\nfunction useTableOfContents(component: string): TableOfContentsContextValue {\n  const context = useContext(TableOfContentsContext);\n  if (!context) {\n    throw new Error(`${component} must be used within a <TableOfContents>`);\n  }\n  return context;\n}\n\nconst useIsomorphicLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;\n\n/**\n * One ref callback that sets every ref given, skipping the missing ones.\n *\n * A callback ref may return a cleanup (React 19); each is collected and\n * returned so React can run it on detach instead of it being dropped.\n */\nfunction mergeRefs<T>(...refs: (Ref<T> | undefined)[]): (node: T | null) => (() => void) | void {\n  return (node) => {\n    const cleanups: (() => void)[] = [];\n    const cleanupOwners = new Set<unknown>();\n    for (const ref of refs) {\n      if (typeof ref === 'function') {\n        const cleanup = ref(node);\n        if (typeof cleanup === 'function') {\n          cleanups.push(cleanup);\n          cleanupOwners.add(ref);\n        }\n      } else if (ref) {\n        (ref as { current: T | null }).current = node;\n      }\n    }\n    if (cleanups.length === 0) return undefined;\n    // Once a cleanup is returned React calls it instead of calling the ref\n    // again with null, so the detach every other ref expects happens here.\n    return () => {\n      for (const cleanup of cleanups) cleanup();\n      for (const ref of refs) {\n        if (typeof ref === 'function') {\n          if (!cleanupOwners.has(ref)) ref(null);\n        } else if (ref) {\n          (ref as { current: T | null }).current = null;\n        }\n      }\n    };\n  };\n}\n\nexport interface TableOfContentsProps\n  extends Omit<ComponentProps<'nav'>, 'className' | 'defaultValue' | 'onChange'> {\n  /** The active section, when the caller holds it. The scroll spy stands aside. */\n  value?: string;\n  /** The section active at first, when the caller does not hold it. */\n  defaultValue?: string;\n  /** Called with a section's `value` when a link is pressed or the spy moves on. */\n  onValueChange?: (value: string) => void;\n  /**\n   * Watch the page and keep the active section at the reading line. On by\n   * default when uncontrolled; pass `false` to leave the active section alone,\n   * or `true` with `value` to report scroll position without holding state.\n   */\n  observe?: boolean;\n  /**\n   * How far below the top of the scroll viewport counts as the reading line,\n   * in pixels. Raise it to clear a sticky header.\n   */\n  offset?: number;\n  /**\n   * The element that scrolls, when the page is not what scrolls. A section\n   * inside a panel needs the panel here; the viewport is the default.\n   */\n  root?: HTMLElement | null | RefObject<HTMLElement | null>;\n  /**\n   * How the list marks where the reader is. `rail` is a hairline with one\n   * segment on the active section. `contour` is a line that steps in and out\n   * with each level and lights every section on screen. Default `rail`.\n   */\n  variant?: TableOfContentsVariant;\n  /** Classes for the `<nav>`. */\n  className?: string;\n}\n\n/**\n * Holds the active section and, when uncontrolled, keeps it in step with the\n * page. Its `<nav>` is the landmark a screen reader jumps to.\n */\nconst TableOfContentsRoot = forwardRef<HTMLElement, Omit<TableOfContentsProps, 'ref'>>(function TableOfContentsRoot({\n  value: valueProp,\n  defaultValue,\n  onValueChange,\n  observe,\n  offset = 16,\n  root,\n  variant = 'rail',\n  className,\n  'aria-label': ariaLabel = 'Table of contents',\n  children,\n  ...props\n}: Omit<TableOfContentsProps, 'ref'>, forwardedRef) {\n  const [innerValue, setInnerValue] = useState<string | undefined>(defaultValue);\n  const controlled = valueProp !== undefined;\n  const value = controlled ? valueProp : innerValue;\n\n  // The spy and a press read the value as it is now, not as it was when the\n  // effect that owns them was created.\n  const currentValue = useRef(value);\n  const live = useRef({ controlled, onValueChange });\n  // Written after commit, so a render React throws away leaves nothing behind.\n  useIsomorphicLayoutEffect(() => {\n    currentValue.current = value;\n    live.current = { controlled, onValueChange };\n  });\n\n  // The sections on screen after the active one, for the contour. Held as a\n  // joined string so an unchanged set does not re-render the list.\n  const [inView, setInView] = useState('');\n\n  const select = useCallback((next: string) => {\n    if (next === currentValue.current) return;\n    currentValue.current = next;\n    if (!live.current.controlled) setInnerValue(next);\n    live.current.onValueChange?.(next);\n  }, []);\n\n  const spying = observe ?? !controlled;\n  const nav = useRef<HTMLElement>(null);\n  /*\n   * The section a press is scrolling to. While it is set, the spy reports\n   * what is on screen but does not move the mark: on the way to a section the\n   * line crosses every one before it, and a short section near the end may\n   * never reach the line at all.\n   */\n  const heading = useRef<string | null>(null);\n  const jumpFrom = useRef({ root, offset });\n  useIsomorphicLayoutEffect(() => {\n    jumpFrom.current = { root, offset };\n  });\n\n  const jump = useCallback(\n    (id: string, next: string, moveFocus: boolean) => {\n      const { root: source, offset: gap } = jumpFrom.current;\n      const scroller = source && 'current' in source ? source.current : source;\n      if (!scroller) return false;\n      const target = scroller.ownerDocument.getElementById(id);\n      if (!target || !scroller.contains(target)) return false;\n\n      // From the top of the scrollport, inside the border, to the target's\n      // top, less the reading line's offset: the target lands on the line.\n      const port = scroller.getBoundingClientRect().top + scroller.clientTop;\n      const top = scroller.scrollTop + target.getBoundingClientRect().top - port - Math.max(0, gap);\n      const reduce = scroller.ownerDocument.defaultView?.matchMedia('(prefers-reduced-motion: reduce)').matches;\n\n      heading.current = next;\n      select(next);\n      let timer = 0;\n      const release = () => {\n        heading.current = null;\n        window.clearTimeout(timer);\n        scroller.removeEventListener('scrollend', release);\n        for (const type of ['wheel', 'touchstart', 'keydown'] as const) scroller.removeEventListener(type, release);\n      };\n      scroller.addEventListener('scrollend', release, { once: true });\n      // The reader taking over ends the hold at once.\n      for (const type of ['wheel', 'touchstart', 'keydown'] as const)\n        scroller.addEventListener(type, release, { once: true, passive: true });\n      // A scroll that does not move, or a browser without `scrollend`.\n      timer = window.setTimeout(release, 1200);\n      scroller.scrollTo({ top: Math.max(0, top), behavior: reduce ? 'auto' : 'smooth' });\n\n      // Followed from the keyboard, focus goes to the section, as the\n      // browser's own jump would take it, so Tab carries on from there.\n      if (moveFocus) {\n        // A section is not a control, so it is focused without a ring round it,\n        // as the browser's own jump would leave it; both are put back on blur.\n        const outline = target.style.outline;\n        const tabbable = target.hasAttribute('tabindex');\n        if (!tabbable) target.setAttribute('tabindex', '-1');\n        target.style.outline = 'none';\n        target.addEventListener(\n          'blur',\n          () => {\n            target.style.outline = outline;\n            if (!tabbable) target.removeAttribute('tabindex');\n          },\n          { once: true }\n        );\n        target.focus({ preventScroll: true });\n      }\n\n      // The hash is the link's address, so it is shareable; replaced, not\n      // pushed, so Back leaves the page rather than walking its sections.\n      const { location, history } = scroller.ownerDocument.defaultView ?? window;\n      if (location.hash !== `#${id}`) history.replaceState(history.state, '', `#${encodeURIComponent(id)}`);\n      return true;\n    },\n    [select]\n  );\n  // Whether the spy has read the page once. The first read is placement,\n  // not a change of section, so it does not call `onValueChange`.\n  const placed = useRef(false);\n\n  useEffect(() => {\n    if (!spying || typeof window === 'undefined') return;\n    const container = nav.current;\n    if (!container || typeof IntersectionObserver === 'undefined') return;\n\n    const scroller = root && 'current' in root ? root.current : root;\n    const doc = container.ownerDocument;\n\n    /*\n     * Every link whose hash names an element in this document. The link's own\n     * row says which value to make active: a hash and the item it sits in need\n     * not be spelled the same, and the item is what the caller named.\n     */\n    const targets: { element: Element; value: string }[] = [];\n    const seen = new Set<Element>();\n    for (const anchor of container.querySelectorAll<HTMLAnchorElement>(\n      '[data-slot=\"table-of-contents-link\"]'\n    )) {\n      const id = hashTarget(anchor.getAttribute('href'));\n      const element = id ? doc.getElementById(id) : null;\n      if (!element || seen.has(element)) continue;\n      const item = anchor.closest<HTMLElement>('[data-slot=\"table-of-contents-item\"]');\n      const section = item?.dataset.value;\n      if (!section) continue;\n      seen.add(element);\n      targets.push({ element, value: section });\n    }\n    if (targets.length === 0) return;\n\n    // The line is measured from the scrollport, inside the scroller's\n    // border, which is where a scrolled-to section lands.\n    const line = () => {\n      const top = scroller ? scroller.getBoundingClientRect().top + scroller.clientTop : 0;\n      return top + Math.max(0, offset);\n    };\n    const atEnd = () => {\n      const el = scroller ?? doc.scrollingElement;\n      if (!el) return false;\n      const room = el.scrollHeight - el.clientHeight;\n      return room > 0 && el.scrollTop >= room - 1;\n    };\n    const floor = () =>\n      scroller ? scroller.getBoundingClientRect().bottom : window.innerHeight;\n\n    const measure = () => {\n      const at = line();\n      const sections: TocSection[] = targets.map(({ element, value: section }) => {\n        const rect = element.getBoundingClientRect();\n        return { value: section, top: rect.top, bottom: rect.bottom };\n      });\n      setInView(sectionsInView(sections, at, floor()).join('\\n'));\n      // A press is on its way somewhere: the mark is already there.\n      if (heading.current !== null) return;\n      // A pixel of slack, so a section scrolled to the line by a rounded\n      // scroll position still counts as reached.\n      const next = sectionAt(sections, at + 1, atEnd());\n      if (next === undefined) return;\n      // The first placement is not a change of section: the page opened where\n      // it opened. Every change after it is reported.\n      const first = !placed.current;\n      placed.current = true;\n      if (next === currentValue.current) return;\n      if (first) {\n        currentValue.current = next;\n        if (!live.current.controlled) setInnerValue(next);\n        return;\n      }\n      select(next);\n    };\n\n    const observer = new IntersectionObserver(measure, {\n      root: scroller ?? null,\n      // A section counts as in view once it reaches the reading line, not\n      // when it first touches the top edge.\n      rootMargin: `${-Math.max(0, offset)}px 0px 0px 0px`,\n      threshold: 0,\n    });\n    // A section is current until the next one reaches the line, which is not\n    // an intersection change of its own, so the contour also reads on scroll.\n    let frame = 0;\n    const onScroll = () => {\n      if (frame) return;\n      frame = requestAnimationFrame(() => {\n        frame = 0;\n        measure();\n      });\n    };\n    const scrollTarget: HTMLElement | Window = scroller ?? window;\n    if (variant === 'contour') scrollTarget.addEventListener('scroll', onScroll, { passive: true });\n\n    // The first read is synchronous: a page that opens halfway down should\n    // not show the first section until something happens to scroll.\n    measure();\n    for (const { element } of targets) observer.observe(element);\n    return () => {\n      observer.disconnect();\n      scrollTarget.removeEventListener('scroll', onScroll);\n      cancelAnimationFrame(frame);\n    };\n  }, [spying, offset, root, select, variant]);\n\n  const lit = useMemo(() => {\n    if (value === undefined) return [];\n    // Without the spy only the active section is known to be on screen.\n    const rest = spying && inView ? inView.split('\\n') : [];\n    return rest[0] === value ? rest : [value, ...rest.filter((each) => each !== value)];\n  }, [value, inView, spying]);\n\n  const context = useMemo(() => ({ value, select, jump, variant, lit }), [value, select, jump, variant, lit]);\n  const mergedRef = useMemo(() => mergeRefs(nav, forwardedRef), [forwardedRef]);\n\n  return (\n    <TableOfContentsContext.Provider value={context}>\n      <nav\n        data-slot=\"table-of-contents\"\n        aria-label={ariaLabel}\n        className={tableOfContentsVariants().root({ className })}\n        {...props}\n        // After the spread, so a caller's ref is joined to ours, not swapped for it.\n        ref={mergedRef}\n      >\n        {children}\n      </nav>\n    </TableOfContentsContext.Provider>\n  );\n});\nTableOfContentsRoot.displayName = 'TableOfContents';\n\nexport interface TableOfContentsTitleProps extends Omit<ComponentProps<'p'>, 'className'> {\n  /** Classes for the heading. */\n  className?: string;\n}\n\n/** The small heading above the list, such as \"On this page\". Optional. */\nfunction TableOfContentsTitle({ className, ...props }: TableOfContentsTitleProps) {\n  return (\n    <p data-slot=\"table-of-contents-title\" className={tableOfContentsVariants().title({ className })} {...props} />\n  );\n}\nTableOfContentsTitle.displayName = 'TableOfContents.Title';\n\nexport interface TableOfContentsListProps extends Omit<ComponentProps<'ol'>, 'className'> {\n  /** Classes for the `<ol>`. */\n  className?: string;\n}\n\n/**\n * The ordered list of sections. It draws the rail and the segment that marks\n * the current one, measured from the active item.\n */\nconst TableOfContentsList = forwardRef<HTMLOListElement, Omit<TableOfContentsListProps, 'ref'>>(function TableOfContentsList({ className, children, ...props }, forwardedRef) {\n  const { value, variant, lit } = useTableOfContents('TableOfContents.List');\n  const list = useRef<HTMLOListElement>(null);\n  const placed = useRef(false);\n  const track = useRef<SVGSVGElement>(null);\n  const litLayer = useRef<SVGSVGElement>(null);\n  /** Where the lit stretch started last time, to tell which way it moved. */\n  const lastStart = useRef<number | null>(null);\n  const heading = useRef<'up' | 'down'>('down');\n  const litKey = lit.join('\\n');\n\n  useIsomorphicLayoutEffect(() => {\n    const box = list.current;\n    if (!box) return;\n\n    let frame: number | undefined;\n    const ready = () => {\n      if (placed.current) {\n        box.setAttribute('data-ready', '');\n        return;\n      }\n      // Shown once it is in place, so it does not arrive by sliding down\n      // from the top of the list.\n      frame = requestAnimationFrame(() => {\n        placed.current = true;\n        box.setAttribute('data-ready', '');\n      });\n    };\n\n    const placeContour = () => {\n      const items = [\n        ...box.querySelectorAll<HTMLElement>(':scope > [data-slot=\"table-of-contents-item\"]'),\n      ];\n      if (items.length === 0) return;\n      const boxRect = box.getBoundingClientRect();\n      const rows: ContourRow[] = items.map((item) => {\n        const rect = item.getBoundingClientRect();\n        return {\n          top: rect.top - boxRect.top,\n          bottom: rect.bottom - boxRect.top,\n          depth: Number(item.dataset.depth ?? 0),\n        };\n      });\n      const path = contourPath(rows, CONTOUR_STEP, CONTOUR_BEND);\n      const width = `${contourWidth(rows, CONTOUR_STEP)}`;\n      for (const svg of [track.current, litLayer.current]) {\n        if (!svg) continue;\n        svg.setAttribute('width', width);\n        svg.firstElementChild?.setAttribute('d', path);\n      }\n\n      const indexes = items\n        .map((item, index) => (item.hasAttribute('data-lit') ? index : -1))\n        .filter((index) => index >= 0);\n      if (indexes.length === 0) {\n        box.removeAttribute('data-ready');\n        return;\n      }\n      const first = indexes[0]!;\n      const last = indexes[indexes.length - 1]!;\n      // The dot leads: on the bottom end while the reader moves down the page,\n      // on the top end while they move back up.\n      if (lastStart.current !== null && first !== lastStart.current) {\n        heading.current = first < lastStart.current ? 'up' : 'down';\n      }\n      lastStart.current = first;\n      const top = rows[first]!.top;\n      const bottom = rows[last]!.bottom;\n      const end = heading.current === 'up' ? rows[first]! : rows[last]!;\n      box.style.setProperty('--toc-lit-top', `${top}px`);\n      box.style.setProperty('--toc-lit-bottom', `${bottom}px`);\n      box.style.setProperty('--toc-dot-x', `${end.depth * CONTOUR_STEP - 2}px`);\n      box.style.setProperty(\n        '--toc-dot-y',\n        `${(heading.current === 'up' ? top : bottom) - 2.5}px`\n      );\n      ready();\n    };\n\n    const place = () => {\n      if (variant === 'contour') {\n        placeContour();\n        return;\n      }\n      const active = box.querySelector<HTMLElement>(\n        '[data-slot=\"table-of-contents-item\"][data-active]'\n      );\n      if (!active) {\n        box.removeAttribute('data-ready');\n        return;\n      }\n\n      const boxRect = box.getBoundingClientRect();\n      const activeRect = active.getBoundingClientRect();\n      box.style.setProperty('--toc-indicator-top', `${activeRect.top - boxRect.top}px`);\n      box.style.setProperty('--toc-indicator-height', `${activeRect.height}px`);\n      ready();\n    };\n\n    place();\n    const observer = new ResizeObserver(place);\n    observer.observe(box);\n    return () => {\n      if (frame !== undefined) cancelAnimationFrame(frame);\n      observer.disconnect();\n    };\n  }, [value, variant, litKey]);\n\n  const slots = tableOfContentsVariants({ variant });\n  const mergedRef = useMemo(() => mergeRefs(list, forwardedRef), [forwardedRef]);\n\n  return (\n    <ol\n      data-slot=\"table-of-contents-list\"\n      data-variant={variant}\n      className={slots.list({ className })}\n      {...props}\n      ref={mergedRef}\n    >\n      {children}\n      {variant === 'contour' ? (\n        // Inside the list for positioning, and kept out of it for everyone\n        // else: hidden from assistive technology and from the item queries.\n        <li aria-hidden=\"true\" role=\"presentation\" data-slot=\"table-of-contents-contour\" className=\"contents\">\n          <svg ref={track} className={slots.contour()} height=\"100%\">\n            <path fill=\"none\" className=\"stroke-border\" strokeWidth={1} />\n          </svg>\n          <svg ref={litLayer} className={slots.contourLit()} height=\"100%\">\n            <path fill=\"none\" className=\"stroke-foreground\" strokeWidth={1} />\n          </svg>\n          <span className={slots.contourDot()} />\n        </li>\n      ) : null}\n    </ol>\n  );\n});\nTableOfContentsList.displayName = 'TableOfContents.List';\n\nexport interface TableOfContentsItemProps extends Omit<ComponentProps<'li'>, 'className' | 'value'> {\n  /** The section this row stands for. Matches the root's `value`. */\n  value: string;\n  /**\n   * How deep the section sits. Each step indents the row and its link, for\n   * a section under a section.\n   */\n  depth?: number;\n  /** Classes for the `<li>`. */\n  className?: string;\n}\n\n/** One section in the list. Holds its `Link` and carries its `depth`. */\nfunction TableOfContentsItem({\n  value,\n  depth = 0,\n  className,\n  style,\n  children,\n  ...props\n}: TableOfContentsItemProps) {\n  const { value: active, variant, lit } = useTableOfContents('TableOfContents.Item');\n  const level = Math.max(0, Math.trunc(depth));\n  const indent = INDENT + level * DEPTH_STEP;\n  const item = useMemo(() => ({ value, depth: level }), [value, level]);\n\n  return (\n    <li\n      data-slot=\"table-of-contents-item\"\n      data-value={value}\n      data-depth={level}\n      data-active={active === value ? '' : undefined}\n      data-lit={variant === 'contour' && lit.includes(value) ? '' : undefined}\n      style={{ ...style, paddingInlineStart: indent }}\n      className={tableOfContentsVariants().item({ className })}\n      {...props}\n    >\n      <TableOfContentsItemContext.Provider value={item}>{children}</TableOfContentsItemContext.Provider>\n    </li>\n  );\n}\nTableOfContentsItem.displayName = 'TableOfContents.Item';\n\nexport interface TableOfContentsLinkProps extends Omit<ComponentProps<'a'>, 'className' | 'href'> {\n  /** The section this link jumps to, hash included: `#install`. */\n  href: string;\n  /** Classes for the `<a>`. */\n  className?: string;\n}\n\n/**\n * A link to one section. It is a real anchor, so the URL gains the hash and\n * middle-click opens the section in a new tab; `render` lets a router's link\n * take its place. With a `root`, a press scrolls that element to put the\n * section on the reading line; on the page, the browser scrolls. The current\n * one is marked with `aria-current=\"location\"`.\n */\nfunction TableOfContentsLink({\n  className,\n  render,\n  ...props\n}: TableOfContentsLinkProps & RenderProp<'a'>) {\n  const { value, select, jump, variant, lit } = useTableOfContents('TableOfContents.Link');\n  const item = useContext(TableOfContentsItemContext);\n  const section = item?.value ?? hashTarget(props.href);\n  const active = section !== null && section === value;\n\n  const handleClick = (event: ReactMouseEvent<HTMLAnchorElement>) => {\n    // A click that opens the section somewhere else leaves this page where it\n    // is, so the mark stays where it is too.\n    const elsewhere =\n      event.button !== 0 ||\n      event.metaKey ||\n      event.ctrlKey ||\n      event.shiftKey ||\n      event.altKey ||\n      event.currentTarget.target === '_blank';\n    if (elsewhere || !section) return;\n    // Inside a scroller, the list scrolls that scroller itself: the browser's\n    // jump would scroll the page around it too, and land the section by its\n    // `scroll-margin` rather than on the reading line.\n    const id = hashTarget(props.href);\n    // `detail` is 0 for a press that came from the keyboard.\n    if (id && jump(id, section, event.detail === 0)) {\n      event.preventDefault();\n      return;\n    }\n    // On the page the browser does the scrolling. The mark moves at once,\n    // rather than waiting for the spy to catch up on the way past.\n    select(section);\n  };\n\n  return useRender({\n    defaultTagName: 'a',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'table-of-contents-link',\n        'data-active': active ? '' : undefined,\n        'data-lit': variant === 'contour' && section !== null && lit.includes(section) ? '' : undefined,\n        'aria-current': active ? 'location' : undefined,\n        className: tableOfContentsVariants({ variant }).link({ className }),\n        onClick: handleClick,\n      },\n      props\n    ),\n  });\n}\nTableOfContentsLink.displayName = 'TableOfContents.Link';\n\nexport interface TableOfContentsCodeProps extends Omit<ComponentProps<'code'>, 'className'> {\n  /** Classes for the `<code>`. */\n  className?: string;\n}\n\n/**\n * An identifier inside a link, such as a prop name under an API heading. It\n * is drawn as a small pill in the link's own colour, so it dims and lights\n * with the row it sits in.\n */\nfunction TableOfContentsCode({ className, ...props }: TableOfContentsCodeProps) {\n  return (\n    <code data-slot=\"table-of-contents-code\" className={tableOfContentsVariants().code({ className })} {...props} />\n  );\n}\nTableOfContentsCode.displayName = 'TableOfContents.Code';\n\nexport const TableOfContents = Object.assign(TableOfContentsRoot, {\n  Title: TableOfContentsTitle,\n  List: TableOfContentsList,\n  Item: TableOfContentsItem,\n  Link: TableOfContentsLink,\n  Code: TableOfContentsCode,\n});\n\nexport {\n  TableOfContentsTitle,\n  TableOfContentsList,\n  TableOfContentsItem,\n  TableOfContentsLink,\n  TableOfContentsCode,\n};\n"
    },
    {
      "path": "components/panelui/table-of-contents/spy.ts",
      "type": "registry:component",
      "target": "@components/panelui/table-of-contents/spy.ts",
      "content": "/**\n * The arithmetic behind the scroll spy, kept apart from the observation.\n *\n * The component can only say what the browser measured; deciding which of\n * those measurements is the section being read is this file's whole job.\n * Reading a page is positional, not a matter of counting: the section the\n * reader is in is the one the reading line falls through, and when the line\n * is in a gap between sections it is the one most recently passed.\n */\n\n/** One section, as the viewport saw it at the moment of measuring. */\nexport interface TocSection {\n  /** The item's value, which is what the root tracks as active. */\n  value: string;\n  /** Distance from the top of the scroll viewport, in pixels. */\n  top: number;\n  /** Distance from the top of the scroll viewport to the section's end. */\n  bottom: number;\n}\n\n/**\n * The id an `href` points at, or `null` for a link with no hash.\n *\n * A same-page link is `#install`; a link copied out of the address bar is a\n * whole URL with `#install` on the end. Both name the same section, and both\n * are decoded, because an id may be written with spaces or a slash in it.\n */\nexport function hashTarget(href: string | null | undefined): string | null {\n  if (!href) return null;\n  const at = href.indexOf('#');\n  if (at === -1) return null;\n  const raw = href.slice(at + 1);\n  if (!raw) return null;\n  try {\n    return decodeURIComponent(raw);\n  } catch {\n    // A malformed escape is still an id worth trying, rather than no section.\n    return raw;\n  }\n}\n\n/**\n * Which section a reading line falls in.\n *\n * Sections may arrive in any order; they are sorted by where they start. A\n * line above the first section belongs to it, since that is the heading the\n * reader is about to reach, and a line below every section belongs to the last\n * one, so the rail never goes dark at the end of a page. `atEnd`, for a\n * scroller that can go no further, picks the last section outright.\n */\nexport function sectionAt(\n  sections: readonly TocSection[],\n  line: number,\n  atEnd = false\n): string | undefined {\n  if (sections.length === 0) return undefined;\n\n  const ordered = [...sections].sort((a, b) => a.top - b.top);\n  // Scrolled as far as it goes, the last section is the one being read, even\n  // when it is too short to ever reach the line: nothing below it can.\n  if (atEnd) return ordered[ordered.length - 1]?.value;\n  let passed: TocSection | undefined;\n  for (const section of ordered) {\n    if (section.top > line) break;\n    passed = section;\n    if (line < section.bottom) return section.value;\n  }\n  return passed?.value ?? ordered[0]?.value;\n}\n\n/**\n * Every section on screen, in page order, starting with the one at the\n * reading line and running to the last whose top is above `floor`, the bottom\n * of the scroll viewport.\n *\n * The section at the line comes first even when its heading has scrolled out\n * of sight: the reader is still inside it.\n */\nexport function sectionsInView(\n  sections: readonly TocSection[],\n  line: number,\n  floor: number\n): string[] {\n  const current = sectionAt(sections, line);\n  if (current === undefined) return [];\n  const ordered = [...sections].sort((a, b) => a.top - b.top);\n  const start = ordered.findIndex((section) => section.value === current);\n  const result = [current];\n  for (const section of ordered.slice(start + 1)) {\n    if (section.top >= floor) break;\n    if (!result.includes(section.value)) result.push(section.value);\n  }\n  return result;\n}\n\n/** One row of the list, as the contour line needs it. */\nexport interface ContourRow {\n  /** Distance from the top of the list to the row's top, in pixels. */\n  top: number;\n  /** Distance from the top of the list to the row's bottom. */\n  bottom: number;\n  /** How many levels in the row sits. */\n  depth: number;\n}\n\n/**\n * The contour line as an SVG path: straight down each row at its level's\n * offset, and a short S-bend across the boundary wherever the level changes.\n *\n * A bend is centred on the boundary between two rows and never taller than\n * half of either row, so a run of short rows still reads as a line rather\n * than a zigzag. Coordinates are in pixels from the list's top-left, with the\n * line drawn half a pixel in so a one-pixel stroke lands on the pixel grid.\n */\nexport function contourPath(rows: readonly ContourRow[], step: number, bend: number): string {\n  if (rows.length === 0) return '';\n  const x = (row: ContourRow) => round(Math.max(0, row.depth) * step + 0.5);\n  const parts = [`M${x(rows[0]!)} ${round(rows[0]!.top)}`];\n  for (let index = 0; index < rows.length; index++) {\n    const row = rows[index]!;\n    const next = rows[index + 1];\n    if (!next) {\n      parts.push(`L${x(row)} ${round(row.bottom)}`);\n      break;\n    }\n    if (x(next) === x(row)) continue;\n    const boundary = (row.bottom + next.top) / 2;\n    const reach = Math.max(\n      0,\n      Math.min(bend, (row.bottom - row.top) / 2, (next.bottom - next.top) / 2)\n    );\n    parts.push(\n      `L${x(row)} ${round(boundary - reach)}`,\n      `C${x(row)} ${round(boundary)} ${x(next)} ${round(boundary)} ${x(next)} ${round(boundary + reach)}`\n    );\n  }\n  return parts.join(' ');\n}\n\n/** How wide the contour's drawing has to be: the deepest level, plus the stroke. */\nexport function contourWidth(rows: readonly ContourRow[], step: number): number {\n  const deepest = rows.reduce((most, row) => Math.max(most, row.depth), 0);\n  return deepest * step + 2;\n}\n\nfunction round(value: number): number {\n  return Math.round(value * 10) / 10;\n}\n"
    }
  ]
}
