{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "scroll-spy",
  "title": "Scroll Spy",
  "description": "Astro scroll spy with Motion, numeric progress events, typed controllers, section links, and a table-of-contents spine.",
  "dependencies": [
    "class-variance-authority",
    "cn",
    "motion"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "packages/ui/src/components/ui/scroll-spy/index.ts",
      "content": "export { default as ScrollSpy } from './scroll-spy.astro'\nexport { default as ScrollSpyTrack } from './scroll-spy-track.astro'\nexport { default as ScrollSpyIndicator } from './scroll-spy-indicator.astro'\nexport { default as ScrollSpyItem } from './scroll-spy-item.astro'\nexport {\n    scrollSpyVariants,\n    type ScrollSpyVariantProps,\n} from './scroll-spy-variants.ts'\nexport type {\n    ScrollSpyItemProps,\n    ScrollSpyTrackProps,\n    ScrollSpyIndicatorProps,\n    ScrollSpyOptions,\n} from './types.ts'\nexport type {\n    ScrollSpyController,\n    ScrollSpyControllerOptions,\n    ScrollSpyProgressDetail,\n} from './scroll-spy.ts'\n",
      "type": "registry:file",
      "target": "~/src/components/ui/scroll-spy/index.ts"
    },
    {
      "path": "packages/ui/src/components/ui/scroll-spy/types.ts",
      "content": "import type { ScrollSpyVariantProps } from './scroll-spy-variants.ts'\n\n/**\n * Props for the scroll spy root.\n * The root also accepts `class`, `style`, and the attributes of its element.\n */\nexport interface ScrollSpyOptions {\n    /**\n     * The appearance passed to the built-in track and indicator. Set it explicitly on custom slotted parts.\n     * `toc` draws a path beside the links and highlights all visible targets.\n     *\n     * @default line\n     */\n    variant?: NonNullable<ScrollSpyVariantProps['variant']>\n    /** The visual direction of the built-in parts. Both layouts track vertical scrolling. @default vertical */\n    orientation?: NonNullable<ScrollSpyVariantProps['orientation']>\n    /**\n     * Fixed to the viewport, absolute in a positioned ancestor, or in normal flow.\n     * The `toc` variant uses normal flow when this is omitted.\n     *\n     * @default fixed\n     */\n    position?: NonNullable<ScrollSpyVariantProps['position']>\n    /** Distance between rail notch centers. Numbers are pixels; strings are CSS lengths. Omit for standard link targets. */\n    gap?: number | string\n    /** CSS selector for the scroll container. Defaults to the nearest scrollable ancestor, then document.scrollingElement. */\n    scrollTarget?: string\n    /** Track one section from its top to its bottom. The nearest matching ancestor is preferred. */\n    progressTarget?: string\n}\n\n/** Props for the track and its built-in fill. */\nexport interface ScrollSpyTrackProps {\n    /** The visual style to render. @default line */\n    variant?: NonNullable<ScrollSpyVariantProps['variant']>\n    /** The visual direction. @default vertical */\n    orientation?: NonNullable<ScrollSpyVariantProps['orientation']>\n    /** Render the line fill or orbit ring. Use false for custom content or an empty track. @default true */\n    fill?: boolean\n}\n\n/** Props for section marks, gooey dots, or the orbiting dot. */\nexport interface ScrollSpyIndicatorProps {\n    /** The visual style to render. @default rail */\n    variant?: 'rail' | 'gooey' | 'orbit'\n    /** The visual direction. @default vertical */\n    orientation?: NonNullable<ScrollSpyVariantProps['orientation']>\n}\n\n/**\n * Props for one section link.\n * Anchor attributes such as `href`, `class`, and `aria-label` pass through.\n * `href` is required and must be a fragment, such as `#overview`.\n */\nexport interface ScrollSpyItemProps {\n    /** A section rail link or a table-of-contents link. @default rail */\n    variant?: 'rail' | 'toc'\n    /** The direction of a rail item. TOC links stay in normal flow. @default vertical */\n    orientation?: NonNullable<ScrollSpyVariantProps['orientation']>\n    /**\n     * Heading depth for the `toc` path.\n     * Depth 2 is a page section. Depth 3 and 4 step the line inward.\n     *\n     * @default 2\n     */\n    depth?: number\n}\n",
      "type": "registry:file",
      "target": "~/src/components/ui/scroll-spy/types.ts"
    },
    {
      "path": "packages/ui/src/components/ui/scroll-spy/scroll-spy-variants.ts",
      "content": "import { cva, type VariantProps } from 'class-variance-authority'\n\nexport const scrollSpyVariants = cva(\n    'group/scroll-spy text-foreground pointer-events-none z-20 w-auto [--scroll-spy:0]',\n    {\n        variants: {\n            variant: {\n                line: '',\n                rail: '',\n                gooey: '',\n                orbit: '',\n                toc: 'w-56 max-w-full',\n            },\n            orientation: { vertical: '', horizontal: '' },\n            position: {\n                fixed: 'fixed',\n                absolute: 'absolute',\n                relative: 'relative',\n            },\n        },\n        compoundVariants: [\n            {\n                orientation: 'vertical',\n                position: ['fixed', 'absolute'],\n                class: 'inset-e-4 top-1/2 -translate-y-1/2',\n            },\n            {\n                orientation: 'horizontal',\n                position: ['fixed', 'absolute'],\n                class: 'inset-x-0 top-0 w-full',\n            },\n        ],\n        defaultVariants: {\n            variant: 'line',\n            orientation: 'vertical',\n            position: 'fixed',\n        },\n    },\n)\n\nexport type ScrollSpyVariantProps = VariantProps<typeof scrollSpyVariants>\n\nexport const scrollSpyTrackVariants = cva('relative', {\n    variants: {\n        variant: {\n            line: 'bg-border',\n            rail: '',\n            gooey: '',\n            orbit: 'size-14',\n            toc: 'w-full',\n        },\n        orientation: { vertical: '', horizontal: '' },\n    },\n    compoundVariants: [\n        { variant: 'line', orientation: 'vertical', class: 'h-40 w-px' },\n        { variant: 'line', orientation: 'horizontal', class: 'h-px w-full' },\n        { variant: 'gooey', orientation: 'vertical', class: 'h-44 w-12' },\n        { variant: 'gooey', orientation: 'horizontal', class: 'h-12 w-44' },\n    ],\n    defaultVariants: { variant: 'line', orientation: 'vertical' },\n})\n\nexport const scrollSpyIndicatorVariants = cva('', {\n    variants: {\n        variant: {\n            rail: 'flex',\n            gooey: 'absolute inset-0',\n            orbit: 'absolute inset-1 transform-[rotate(calc(var(--scroll-spy)*1turn))] motion-reduce:hidden',\n        },\n        orientation: { vertical: '', horizontal: '' },\n    },\n    compoundVariants: [\n        { variant: 'rail', orientation: 'vertical', class: 'flex-col' },\n        { variant: 'rail', orientation: 'horizontal', class: 'flex-row' },\n    ],\n    defaultVariants: { variant: 'rail', orientation: 'vertical' },\n})\n\nexport const scrollSpyItemVariants = cva(\n    'group/scroll-spy-item text-muted-foreground hover:text-foreground focus-visible:text-foreground focus-visible:ring-ring pointer-events-auto relative flex items-center rounded-sm outline-none focus-visible:ring-2',\n    {\n        variants: {\n            variant: {\n                rail: 'aria-[current=location]:text-primary min-h-8 min-w-11 gap-3 px-2 group-data-gap/scroll-spy:flex-none',\n                toc: 'data-active:text-primary w-full min-w-0 justify-start py-1.5 ps-5 pe-2 text-sm leading-6 data-[depth=3]:ps-8 data-[depth=4]:ps-11 data-[depth=5]:ps-11 data-[depth=6]:ps-11 [:where([data-slot=scroll-spy-track])>&]:first-of-type:pt-0 [:where([data-slot=scroll-spy-track])>&]:last-of-type:pb-0',\n            },\n            orientation: { vertical: '', horizontal: '' },\n        },\n        compoundVariants: [\n            {\n                variant: 'rail',\n                orientation: 'vertical',\n                class: 'justify-end group-data-gap/scroll-spy:h-[max(1px,var(--scroll-spy-gap))] group-data-gap/scroll-spy:min-h-0',\n            },\n            {\n                variant: 'rail',\n                orientation: 'horizontal',\n                class: 'flex-col justify-start py-2 group-data-gap/scroll-spy:h-11 group-data-gap/scroll-spy:w-[max(1px,var(--scroll-spy-gap))] group-data-gap/scroll-spy:min-w-0 group-data-gap/scroll-spy:p-0',\n            },\n        ],\n        defaultVariants: { variant: 'rail', orientation: 'vertical' },\n    },\n)\n",
      "type": "registry:file",
      "target": "~/src/components/ui/scroll-spy/scroll-spy-variants.ts"
    },
    {
      "path": "packages/ui/src/components/ui/scroll-spy/scroll-spy.astro",
      "content": "---\nimport type { HTMLTag, Polymorphic } from \"astro/types\"\nimport { cn } from \"cn\"\nimport type { ScrollSpyOptions } from \"./types.ts\"\nimport { scrollSpyVariants } from \"./scroll-spy-variants.ts\"\nimport Track from \"./scroll-spy-track.astro\"\nimport Indicator from \"./scroll-spy-indicator.astro\"\n\ntype Props<Tag extends HTMLTag = \"div\"> = Polymorphic<{ as: Tag }> &\n  ScrollSpyOptions\n\nconst {\n  as: Tag = \"div\",\n  variant = \"line\",\n  orientation = \"vertical\",\n  position: positionProp,\n  gap,\n  scrollTarget,\n  progressTarget,\n  class: className,\n  style: styleProp,\n  ...props\n} = Astro.props\n\n// The contents spine sits in normal flow. Other variants stay fixed.\nconst position = positionProp ?? (variant === \"toc\" ? \"relative\" : \"fixed\")\nconst railGap = typeof gap === \"number\" ? `${gap}px` : gap\nconst rootStyle =\n  typeof styleProp === \"string\"\n    ? `${railGap === undefined ? \"\" : `--scroll-spy-gap: ${railGap}; `}${styleProp}`\n    : {\n        \"--scroll-spy-gap\": railGap,\n        ...(styleProp ? styleProp : {}),\n      }\n---\n\n<Tag\n  data-slot=\"scroll-spy\"\n  data-variant={variant}\n  data-orientation={orientation}\n  data-gap={railGap}\n  data-scroll-target={scrollTarget}\n  data-progress-target={progressTarget}\n  class={cn(scrollSpyVariants({ variant, orientation, position }), className)}\n  style={rootStyle}\n  {...props}\n>\n  <slot>\n    <Track {variant} {orientation}>\n      {(variant === \"rail\" || variant === \"gooey\" || variant === \"orbit\") && (\n        <Indicator {variant} {orientation} />\n      )}\n    </Track>\n  </slot>\n</Tag>\n\n<script>\n  import { create, type ScrollSpyController } from \"./scroll-spy.ts\"\n\n  const controllers: ScrollSpyController[] = []\n  const initialize = () => controllers.push(...create())\n\n  initialize()\n  document.addEventListener(\"astro:page-load\", initialize)\n  document.addEventListener(\"astro:before-swap\", () => {\n    for (const controller of controllers) controller.destroy()\n    controllers.length = 0\n  })\n</script>\n\n<style>\n  @property --scroll-spy {\n    syntax: \"<number>\";\n    inherits: true;\n    initial-value: 0;\n  }\n</style>\n",
      "type": "registry:file",
      "target": "~/src/components/ui/scroll-spy/scroll-spy.astro"
    },
    {
      "path": "packages/ui/src/components/ui/scroll-spy/scroll-spy-track.astro",
      "content": "---\nimport type { HTMLTag, Polymorphic } from \"astro/types\"\nimport { cn } from \"cn\"\nimport type { ScrollSpyTrackProps } from \"./types.ts\"\nimport { scrollSpyTrackVariants } from \"./scroll-spy-variants.ts\"\n\ntype Props<Tag extends HTMLTag = \"div\"> = Polymorphic<{ as: Tag }> &\n  ScrollSpyTrackProps\n\nconst {\n  as: Tag = \"div\",\n  variant = \"line\",\n  orientation = \"vertical\",\n  fill = true,\n  class: className,\n  ...props\n} = Astro.props\n---\n\n<Tag\n  data-slot=\"scroll-spy-track\"\n  data-variant={variant}\n  data-orientation={orientation}\n  class={cn(scrollSpyTrackVariants({ variant, orientation }), className)}\n  {...props}\n>\n  {variant === \"toc\" && (\n    <div\n      data-slot=\"scroll-spy-toc\"\n      class=\"group/scroll-spy-toc pointer-events-none absolute inset-s-0 top-0 overflow-visible **:pointer-events-none rtl:-scale-x-100\"\n      aria-hidden=\"true\"\n    >\n      <svg\n        data-slot=\"scroll-spy-toc-svg\"\n        class=\"absolute overflow-visible\"\n        fill=\"none\"\n        stroke-linecap=\"butt\"\n        aria-hidden=\"true\"\n      >\n        <path\n          data-slot=\"scroll-spy-toc-path\"\n          class=\"stroke-foreground/10\"\n          stroke-width=\"1\"\n        />\n        <path\n          data-slot=\"scroll-spy-toc-highlight\"\n          class=\"stroke-primary opacity-0 [clip-path:polygon(0_var(--scroll-spy-track-top,0px),100%_var(--scroll-spy-track-top,0px),100%_var(--scroll-spy-track-bottom,0px),0_var(--scroll-spy-track-bottom,0px))] transition-[clip-path] duration-200 ease-[ease] group-data-ready/scroll-spy-toc:opacity-100 motion-reduce:transition-none\"\n          stroke-width=\"1\"\n        />\n      </svg>\n    </div>\n  )}\n  {fill && variant === \"line\" && (\n    <span\n      data-slot=\"scroll-spy-fill\"\n      aria-hidden=\"true\"\n      class={cn(\n        \"pointer-events-none absolute inset-0 bg-primary\",\n        orientation === \"horizontal\"\n          ? \"origin-left transform-[scaleX(var(--scroll-spy))]\"\n          : \"origin-top transform-[scaleY(var(--scroll-spy))]\",\n      )}\n    />\n  )}\n  {fill && variant === \"orbit\" && (\n    <svg\n      data-slot=\"scroll-spy-fill\"\n      viewBox=\"0 0 56 56\"\n      class=\"pointer-events-none absolute inset-0 size-full -rotate-90 fill-none\"\n      aria-hidden=\"true\"\n      focusable=\"false\"\n    >\n      <circle cx=\"28\" cy=\"28\" r=\"24\" class=\"stroke-border\" stroke-width=\"1.5\" />\n      <circle\n        data-slot=\"scroll-spy-ring\"\n        cx=\"28\"\n        cy=\"28\"\n        r=\"24\"\n        pathLength=\"100\"\n        class=\"stroke-primary [stroke-dasharray:100] [stroke-dashoffset:calc(100*(1-var(--scroll-spy)))]\"\n        stroke-width=\"2\"\n        stroke-linecap=\"round\"\n      />\n    </svg>\n  )}\n  <slot />\n</Tag>\n",
      "type": "registry:file",
      "target": "~/src/components/ui/scroll-spy/scroll-spy-track.astro"
    },
    {
      "path": "packages/ui/src/components/ui/scroll-spy/scroll-spy-indicator.astro",
      "content": "---\n/**\n * Section marks, liquid/gooey dots, or orbiting dot. Its slot accepts custom content.\n *\n * @optional - not required\n */\nimport type { HTMLTag, Polymorphic } from \"astro/types\"\nimport { cn } from \"cn\"\nimport type { ScrollSpyIndicatorProps } from \"./types.ts\"\nimport { scrollSpyIndicatorVariants } from \"./scroll-spy-variants.ts\"\n\ntype Props<Tag extends HTMLTag = \"div\"> = Polymorphic<{ as: Tag }> &\n  ScrollSpyIndicatorProps\n\nconst {\n  as: Tag = \"div\",\n  variant = \"rail\",\n  orientation = \"vertical\",\n  class: className,\n  ...props\n} = Astro.props\n\nconst filterId =\n  variant === \"gooey\" ? `scroll-goo-${crypto.randomUUID()}` : undefined\n---\n\n<Tag\n  data-slot=\"scroll-spy-indicator\"\n  data-variant={variant}\n  data-orientation={orientation}\n  class={cn(scrollSpyIndicatorVariants({ variant, orientation }), className)}\n  {...props}\n>\n  <slot>\n    {variant === \"gooey\" && (\n      <>\n        <svg class=\"absolute size-0\" aria-hidden=\"true\" focusable=\"false\">\n          <defs>\n            <filter\n              id={filterId}\n              x=\"-100%\"\n              y=\"-100%\"\n              width=\"300%\"\n              height=\"300%\"\n              color-interpolation-filters=\"sRGB\"\n            >\n              <feGaussianBlur\n                in=\"SourceGraphic\"\n                stdDeviation=\"6\"\n                result=\"blur\"\n              />\n              <feColorMatrix\n                in=\"blur\"\n                mode=\"matrix\"\n                values=\"1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 20 -5\"\n              />\n            </filter>\n          </defs>\n        </svg>\n        <div\n          data-slot=\"scroll-spy-goo\"\n          class={cn(\n            \"absolute inset-0 flex items-center justify-around motion-reduce:filter-none! forced-colors:filter-none!\",\n            orientation === \"horizontal\" ? \"flex-row\" : \"flex-col\",\n          )}\n          style={{ filter: `url(#${filterId})` }}\n          aria-hidden=\"true\"\n        >\n          {Array.from({ length: 4 }, () => (\n            <span class=\"size-3 shrink-0 rounded-full bg-background bg-linear-to-b from-muted to-primary\" />\n          ))}\n          <span\n            data-slot=\"scroll-spy-flow\"\n            class={cn(\n              \"absolute size-4.5 -translate-1/2 rounded-full bg-primary\",\n              orientation === \"horizontal\"\n                ? \"top-1/2 left-[calc(12.5%+var(--scroll-spy)*75%)]\"\n                : \"left-1/2 top-[calc(12.5%+var(--scroll-spy)*75%)]\",\n            )}\n          />\n        </div>\n      </>\n    )}\n    {variant === \"orbit\" && (\n      <span\n        data-slot=\"scroll-spy-dot\"\n        class=\"absolute -top-1 left-1/2 size-2 -translate-x-1/2 rounded-full bg-primary ring-4 ring-primary/15\"\n        aria-hidden=\"true\"\n      />\n    )}\n  </slot>\n</Tag>\n",
      "type": "registry:file",
      "target": "~/src/components/ui/scroll-spy/scroll-spy-indicator.astro"
    },
    {
      "path": "packages/ui/src/components/ui/scroll-spy/scroll-spy-item.astro",
      "content": "---\n/**\n * Each item is a trackable target in the scroll spy timeline.\n *\n * @optional - not required\n */\nimport type { HTMLAttributes } from \"astro/types\"\nimport { cn } from \"cn\"\nimport type { ScrollSpyItemProps } from \"./types.ts\"\nimport { scrollSpyItemVariants } from \"./scroll-spy-variants.ts\"\n\ntype Props = HTMLAttributes<\"a\"> &\n  ScrollSpyItemProps & {\n    /** Fragment of the section this link tracks. */\n    href: `#${string}`\n  }\n\nconst {\n  class: className,\n  \"aria-label\": label,\n  depth = 2,\n  variant = \"rail\",\n  orientation = \"vertical\",\n  ...props\n} = Astro.props\n---\n\n<a\n  data-slot=\"scroll-spy-item\"\n  data-depth={depth}\n  data-variant={variant}\n  data-orientation={orientation}\n  aria-label={\n    label ??\n    (Astro.slots.has(\"default\") ? undefined : `Go to ${props.href.slice(1)}`)\n  }\n  class={cn(scrollSpyItemVariants({ variant, orientation }), className)}\n  {...props}\n>\n  {Astro.slots.has(\"default\") && (\n    <span\n      data-slot=\"scroll-spy-label\"\n      class={cn(\n        \"flex items-center gap-2 empty:hidden\",\n        variant === \"rail\" && [\n          \"whitespace-nowrap rounded-sm bg-background/95 px-2 py-1 font-mono text-[0.625rem] uppercase tracking-wider opacity-0 transition-opacity duration-180 ease-[ease] motion-reduce:transition-none\",\n          \"group-aria-[current=location]/scroll-spy-item:opacity-100  group-hover/scroll-spy-item:opacity-100 group-focus-visible/scroll-spy-item:opacity-100\",\n          \"group-data-gap/scroll-spy:absolute group-data-gap/scroll-spy:pointer-events-none\",\n          orientation === \"horizontal\"\n            ? \"group-data-gap/scroll-spy:left-1/2 group-data-gap/scroll-spy:bottom-[calc(100%+0.75rem)] group-data-gap/scroll-spy:-translate-x-1/2\"\n            : \"group-data-gap/scroll-spy:inset-e-12 group-data-gap/scroll-spy:top-1/2 group-data-gap/scroll-spy:-translate-y-1/2\",\n        ],\n      )}\n    >\n      <slot />\n    </span>\n  )}\n  {variant === \"rail\" && (\n    <span\n      data-slot=\"scroll-spy-mark\"\n      class={cn(\n        \"shrink-0 bg-current transition-[width,height] duration-200 ease-[ease] motion-reduce:transition-none\",\n        orientation === \"horizontal\"\n          ? \"h-3 w-px group-aria-[current=location]/scroll-spy-item:h-8\"\n          : \"h-px w-3 group-aria-[current=location]/scroll-spy-item:w-8\",\n      )}\n      aria-hidden=\"true\"\n    />\n  )}\n</a>\n",
      "type": "registry:file",
      "target": "~/src/components/ui/scroll-spy/scroll-spy-item.astro"
    },
    {
      "path": "packages/ui/src/components/ui/scroll-spy/scroll-spy.ts",
      "content": "import { scrollInfo } from 'motion'\n\nimport { trackProgress } from './scroll-spy-progress.ts'\nimport { trackToc } from './scroll-spy-toc.ts'\n\nconst SELECTOR = '[data-slot=\"scroll-spy\"]'\nconst controllers = new WeakMap<HTMLElement, ScrollSpyController>()\n\n/** Visual modes. CSS draws the first four. `toc` also draws an SVG path. */\nconst VARIANTS = ['line', 'rail', 'gooey', 'orbit', 'toc'] as const\n\ntype Variant = (typeof VARIANTS)[number]\n\n/**\n * Options for one scroll spy.\n * The Astro root stores the same values as data attributes.\n */\ninterface Options {\n    /**\n     * Appearance.\n     * `line`, `rail`, `gooey`, and `orbit` use `--scroll-spy` and the current link.\n     * `toc` highlights the visible section links.\n     */\n    variant: Variant\n    /** CSS selector for the scroll container. */\n    scrollTarget?: string | undefined\n    /** CSS selector for one measured section. */\n    progressTarget?: string | undefined\n}\n\nexport type ScrollSpyControllerOptions = Partial<Options>\n\nexport interface ScrollSpyController {\n    /** Current progress from 0 to 1. Starts at 0 until the first measurement. */\n    readonly progress: number\n    destroy(): void\n}\n\nexport interface ScrollSpyProgressDetail {\n    /** Measured progress from 0 to 1. */\n    progress: number\n}\n\ndeclare global {\n    interface HTMLElementEventMap {\n        'scroll-spy:progress': CustomEvent<ScrollSpyProgressDetail>\n    }\n    interface DocumentEventMap {\n        'scroll-spy:progress': CustomEvent<ScrollSpyProgressDetail>\n    }\n}\n\n/** One section link and the element its fragment names. */\ninterface SectionLink {\n    link: HTMLAnchorElement\n    section: HTMLElement\n}\n\n/** Scroll measurements this script reads from Motion. */\ninterface ScrollAxis {\n    current: number\n    scrollLength: number\n    targetLength: number\n    containerLength: number\n}\n\n/** The element that scrolls, and the optional section Motion measures. */\ninterface ScrollContext {\n    container: HTMLElement | null\n    source: HTMLElement\n    target: HTMLElement | undefined\n    motion: Parameters<typeof scrollInfo>[1]\n}\n\n/** Read the variant and scroll selectors from the root. */\nfunction readOptions(root: HTMLElement): Options {\n    let variant = root.dataset.variant as Variant\n\n    if (!variant || !VARIANTS.includes(variant as Variant)) {\n        variant = 'line'\n    }\n\n    return {\n        variant,\n        scrollTarget: trimmed(root.dataset.scrollTarget),\n        progressTarget: trimmed(root.dataset.progressTarget),\n    }\n}\n\nfunction trimmed(value: string | undefined) {\n    const text = value?.trim()\n    return text ? text : undefined\n}\n\n/** Bind each unbound scroll spy in the scope. */\nexport function create(scope: ParentNode = document): ScrollSpyController[] {\n    const roots = [...scope.querySelectorAll<HTMLElement>(SELECTOR)]\n    if (scope instanceof HTMLElement && scope.matches(SELECTOR))\n        roots.unshift(scope)\n    return roots\n        .filter((root) => !controllers.has(root))\n        .map((root) => createScrollSpy(root))\n}\n\n/** Bind one scroll spy. Explicit options override its data attributes. */\nexport function createScrollSpy(\n    root: HTMLElement,\n    options: ScrollSpyControllerOptions = {},\n): ScrollSpyController {\n    const existing = controllers.get(root)\n    if (existing) return existing\n\n    const resolved = { ...readOptions(root), ...options }\n    const links = ownedLinks(root)\n    const clearLinks = () =>\n        links.forEach((link) => {\n            link.removeAttribute('aria-current')\n            link.removeAttribute('data-active')\n        })\n    clearLinks()\n    root.style.setProperty('--scroll-spy', '0')\n\n    const context = resolveScroll(root, resolved)\n    const marker =\n        context && resolved.variant === 'toc'\n            ? trackToc(root, links)\n            : undefined\n    const progress = context\n        ? trackProgress(root, context.source, context.target)\n        : undefined\n    let destroyed = false\n    let measured = false\n    let currentProgress = 0\n    let stopScroll: (() => void) | undefined\n\n    const controller: ScrollSpyController = {\n        get progress() {\n            return currentProgress\n        },\n        destroy() {\n            if (destroyed) return\n            destroyed = true\n            stopScroll?.()\n            progress?.stop()\n            marker?.stop()\n            clearLinks()\n            currentProgress = 0\n            root.style.setProperty('--scroll-spy', '0')\n            controllers.delete(root)\n        },\n    }\n    controllers.set(root, controller)\n    if (!context || !progress) return controller\n\n    const sections = collectSections(links, context.container)\n    let active: HTMLAnchorElement | undefined\n    let visible: HTMLAnchorElement[] = []\n\n    stopScroll = scrollInfo(({ y }) => {\n        if (destroyed) return\n        const value = progressValue(y.progress, y, Boolean(context.target))\n        const hasRange = context.target\n            ? y.targetLength > y.containerLength\n            : y.scrollLength > 0\n        progress.update(hasRange, value)\n        if (sections.length && marker) {\n            const nextVisible = visibleLinks(sections, context, y)\n            if (\n                nextVisible.length !== visible.length ||\n                nextVisible.some((link, index) => link !== visible[index])\n            ) {\n                visible = nextVisible\n                for (const link of links)\n                    link.toggleAttribute('data-active', visible.includes(link))\n                marker.place(visible)\n            }\n        }\n        if (sections.length) {\n            const next = marker\n                ? visible[0]\n                : activeLink(sections, context.container, y, value)\n            if (next !== active) {\n                active?.removeAttribute('aria-current')\n                active = next\n                active?.setAttribute('aria-current', 'location')\n            }\n        }\n        if (!measured || value !== currentProgress) {\n            measured = true\n            currentProgress = value\n            root.dispatchEvent(\n                new CustomEvent('scroll-spy:progress', {\n                    bubbles: true,\n                    detail: { progress: value },\n                }),\n            )\n        }\n    }, context.motion)\n\n    return controller\n}\n\n/** Links that belong to this root, not a nested scroll spy. */\nfunction ownedLinks(root: HTMLElement) {\n    return [\n        ...root.querySelectorAll<HTMLAnchorElement>(\n            '[data-slot=\"scroll-spy-item\"]',\n        ),\n    ].filter((link) => link.closest(SELECTOR) === root)\n}\n\n/**\n * Find the scroll container and the optional measured section.\n * A selector that is missing or invalid returns undefined.\n */\nfunction resolveScroll(\n    root: HTMLElement,\n    options: Options,\n): ScrollContext | undefined {\n    let container: HTMLElement | null = root.parentElement\n    let target: HTMLElement | undefined\n    try {\n        if (options.scrollTarget) {\n            const element = document.querySelector(options.scrollTarget)\n            if (!(element instanceof HTMLElement)) return\n            container = element\n        } else {\n            while (\n                container &&\n                container !== document.body &&\n                container !== document.documentElement\n            ) {\n                if (\n                    /(auto|scroll|hidden)/.test(\n                        getComputedStyle(container).overflowY,\n                    )\n                )\n                    break\n                container = container.parentElement\n            }\n        }\n        if (\n            container === document.body ||\n            container === document.documentElement\n        )\n            container = null\n        if (options.progressTarget) {\n            const element =\n                root.closest(options.progressTarget) ??\n                document.querySelector(options.progressTarget)\n            if (\n                !(element instanceof HTMLElement) ||\n                (container && !container.contains(element))\n            )\n                return\n            target = element\n        }\n    } catch {\n        // An invalid selector must not select a different scroll source.\n        return\n    }\n\n    const documentScroller = document.scrollingElement\n    const source =\n        container ??\n        (documentScroller instanceof HTMLElement\n            ? documentScroller\n            : document.documentElement)\n    return {\n        container,\n        source,\n        target,\n        motion: {\n            container: source,\n            ...(target ? { target, offset: ['start start', 'end end'] } : {}),\n            trackContentSize: true,\n        },\n    }\n}\n\n/** Pair each fragment link with a section inside the scroll container. */\nfunction collectSections(\n    links: HTMLAnchorElement[],\n    container: HTMLElement | null,\n) {\n    return links.flatMap((link) => {\n        let id: string\n        try {\n            id = decodeURIComponent(link.hash.slice(1))\n        } catch {\n            return []\n        }\n        const section = document.getElementById(id)\n        return section && (!container || container.contains(section))\n            ? [{ link, section }]\n            : []\n    })\n}\n\n/**\n * Progress from 0 to 1.\n * An empty container, or a section shorter than the viewport, stays at 0.\n */\nfunction progressValue(progress: number, axis: ScrollAxis, hasTarget: boolean) {\n    const hasRange = hasTarget\n        ? axis.targetLength > axis.containerLength\n        : axis.scrollLength > 0\n    return hasRange && Number.isFinite(progress)\n        ? Math.min(1, Math.max(0, progress))\n        : 0\n}\n\n/** Visible targets, or the last heading above the viewport between headings. */\nfunction visibleLinks(\n    sections: SectionLink[],\n    { container, target }: ScrollContext,\n    axis: ScrollAxis,\n) {\n    const top = container\n        ? container.getBoundingClientRect().top + container.clientTop\n        : 0\n    const bottom = top + axis.containerLength\n    if (bottom <= top) return []\n    if (target) {\n        const bounds = target.getBoundingClientRect()\n        if (bounds.bottom <= top || bounds.top >= bottom) return []\n    }\n    const visible: HTMLAnchorElement[] = []\n    let previous: HTMLAnchorElement | undefined\n    for (const { link, section } of sections) {\n        const bounds = section.getBoundingClientRect()\n        if (bounds.height === 0) continue\n        if (bounds.top < bottom && bounds.bottom > top) visible.push(link)\n        if (bounds.bottom <= top) previous = link\n    }\n    return visible.length ? visible : previous ? [previous] : []\n}\n\n/**\n * The link for the section at the reading line.\n * The first link is current at the top. The last link is current at the bottom,\n * including a short final section.\n */\nfunction activeLink(\n    sections: SectionLink[],\n    container: HTMLElement | null,\n    axis: ScrollAxis,\n    value: number,\n) {\n    const line =\n        (container\n            ? container.getBoundingClientRect().top + container.clientTop\n            : 0) +\n        axis.containerLength * 0.45\n    let current: HTMLAnchorElement | undefined = sections[0]?.link\n    if (\n        value === 1 ||\n        (axis.scrollLength > 0 && axis.current >= axis.scrollLength - 1)\n    ) {\n        current = sections.at(-1)?.link\n    } else if (value > 0 && axis.current > 0) {\n        for (const { link, section } of sections) {\n            if (section.getBoundingClientRect().top <= line) current = link\n        }\n    }\n    return current\n}\n",
      "type": "registry:file",
      "target": "~/src/components/ui/scroll-spy/scroll-spy.ts"
    },
    {
      "path": "packages/ui/src/components/ui/scroll-spy/scroll-spy-progress.ts",
      "content": "import { scroll, type scrollInfo } from 'motion'\nimport { animate } from 'motion/mini'\n\nexport type ScrollProgressController = {\n    update: (hasRange: boolean, value: number) => void\n    stop: () => void\n}\n\n/** Progress animation with range checks supplied by the scroll controller. */\nexport function trackProgress(\n    /**\n     * The root element to animate.\n     */\n    root: HTMLElement,\n    /**\n     * The source element to scroll.\n     */\n    source: HTMLElement,\n    /**\n     * The target element to scroll to.\n     */\n    target?: HTMLElement,\n): ScrollProgressController {\n    const native =\n        typeof ScrollTimeline !== 'undefined' &&\n        (!target || typeof ViewTimeline !== 'undefined')\n    let manual = false\n    let animation: ReturnType<typeof animate> | undefined\n    let stopScroll: (() => void) | undefined\n    let failed =\n        typeof root.animate !== 'function' ||\n        typeof CSS === 'undefined' ||\n        typeof CSS.registerProperty !== 'function'\n\n    if (native) {\n        try {\n            const style = target && getComputedStyle(source)\n            const hasScrollPadding =\n                style &&\n                (Number.parseFloat(style.scrollPaddingTop) > 0 ||\n                    Number.parseFloat(style.scrollPaddingBottom) > 0)\n            manual =\n                !CSS.supports('animation-timeline', 'scroll()') ||\n                Boolean(\n                    target &&\n                    (hasScrollPadding ||\n                        !CSS.supports(\n                            'animation-range',\n                            'contain 0% contain 100%',\n                        ) ||\n                        new ViewTimeline({\n                            subject: target,\n                            axis: 'y',\n                            inset: '0px',\n                        }).source !== source),\n                )\n        } catch {\n            manual = true\n        }\n    }\n\n    const reset = () => {\n        stopScroll?.()\n        stopScroll = undefined\n        animation?.cancel()\n        animation = undefined\n        root.style.setProperty('--scroll-spy', '0')\n    }\n\n    const start = () => {\n        animation = animate(\n            root,\n            { '--scroll-spy': [0, 1] },\n            {\n                duration: 1,\n                ease: 'linear',\n                autoplay: false,\n            },\n        )\n        if (manual) return\n        const options: Parameters<typeof scrollInfo>[1] = {\n            container: source,\n            ...(target ? { target, offset: ['start start', 'end end'] } : {}),\n            trackContentSize: true,\n        }\n        stopScroll = scroll(animation, options)\n        if (native) {\n            // A partial implementation can accept a timeline without attaching it.\n            if (\n                !root\n                    .getAnimations()\n                    .some(({ timeline }) => timeline instanceof ScrollTimeline)\n            ) {\n                reset()\n                manual = true\n                start()\n            } else {\n                animation.play()\n            }\n        }\n    }\n\n    const update = (hasRange: boolean, value: number) => {\n        if (!hasRange) {\n            if (animation) reset()\n            else root.style.setProperty('--scroll-spy', '0')\n            return\n        }\n        if (!animation && !failed) {\n            try {\n                start()\n            } catch {\n                reset()\n                failed = true\n            }\n        }\n        if (failed) root.style.setProperty('--scroll-spy', String(value))\n        else if (manual && animation) animation.time = value\n    }\n\n    update(!target || target.clientHeight > source.clientHeight, 0)\n    return {\n        update,\n        stop: reset,\n    }\n}\n",
      "type": "registry:file",
      "target": "~/src/components/ui/scroll-spy/scroll-spy-progress.ts"
    },
    {
      "path": "packages/ui/src/components/ui/scroll-spy/scroll-spy-toc.ts",
      "content": "const SELECTOR = '[data-slot=\"scroll-spy\"]'\n\ninterface Marker {\n    place(visible: HTMLAnchorElement[]): void\n    stop(): void\n}\n\n/** Line x positions for heading depth. Depth 2, 3, and 4 match the Fumadocs TOC. */\nconst TOC_BASE = 8\n\n/**\n * Horizontal position of the TOC path for one heading depth.\n * The link padding in scroll-spy-item.astro uses these values plus 12px.\n */\nfunction tocLineOffset(depth: number) {\n    if (depth <= 2) return TOC_BASE\n    if (depth === 3) return TOC_BASE + 8\n    return TOC_BASE + 16\n}\n\n/** Heading depth from the item. Missing or invalid values use a page section. */\nfunction itemDepth(link: HTMLElement) {\n    const depth = Number(link.dataset.depth)\n    return Number.isFinite(depth) && depth > 0 ? depth : 2\n}\n\ninterface TocLayout {\n    positions: [top: number, bottom: number, x: number][]\n}\n\n/**\n * Draw the TOC path and highlight the range of visible links.\n * A muted path shows every heading. A clipped copy marks the visible range.\n * The curve follows the Fumadocs table of contents.\n */\nexport function trackToc(\n    root: HTMLElement,\n    links: HTMLAnchorElement[],\n): Marker {\n    const toc = [\n        ...root.querySelectorAll<HTMLElement>('[data-slot=\"scroll-spy-toc\"]'),\n    ].find((element) => element.closest(SELECTOR) === root)\n    const rest = toc?.querySelector<SVGPathElement>(\n        '[data-slot=\"scroll-spy-toc-path\"]',\n    )\n    const activePath = toc?.querySelector<SVGPathElement>(\n        '[data-slot=\"scroll-spy-toc-highlight\"]',\n    )\n    const svg = toc?.querySelector<SVGSVGElement>(\n        '[data-slot=\"scroll-spy-toc-svg\"]',\n    )\n    const track = toc?.closest<HTMLElement>('[data-slot=\"scroll-spy-track\"]')\n    if (!toc || !rest || !activePath || !svg || !track)\n        return {\n            place(_visible: HTMLAnchorElement[]) {},\n            stop() {},\n        }\n\n    let layout: TocLayout | undefined\n    let visible: HTMLAnchorElement[] = []\n\n    const apply = () => {\n        const first = visible[0]\n        const last = visible.at(-1)\n        const start = first && layout?.positions[links.indexOf(first)]\n        const end = last && layout?.positions[links.indexOf(last)]\n        if (!start || !end) {\n            toc.removeAttribute('data-ready')\n            return\n        }\n        toc.style.setProperty('--scroll-spy-track-top', `${start[0]}px`)\n        toc.style.setProperty('--scroll-spy-track-bottom', `${end[1]}px`)\n        toc.dataset.ready = ''\n    }\n\n    const draw = () => {\n        const trackTop = track.getBoundingClientRect().top\n        let width = 0\n        let height = 0\n        let d = ''\n        const positions: TocLayout['positions'] = []\n        links.forEach((link, index) => {\n            const style = getComputedStyle(link)\n            const x = tocLineOffset(itemDepth(link)) + 0.5\n            const origin = link.getBoundingClientRect().top - trackTop\n            const top = origin + Number.parseFloat(style.paddingTop)\n            const bottom =\n                origin +\n                link.clientHeight -\n                Number.parseFloat(style.paddingBottom)\n            width = Math.max(width, x + 8)\n            height = Math.max(height, bottom)\n            if (index === 0) d += `M${x} ${top}L${x} ${bottom}`\n            else {\n                const [, upperBottom, upperX] = positions[index - 1]\n                d += `C${upperX} ${top - 4} ${x} ${upperBottom + 4} ${x} ${top}L${x} ${bottom}`\n            }\n            positions.push([top, bottom, x])\n        })\n        if (!d || width === 0 || height === 0) {\n            layout = undefined\n            toc.removeAttribute('data-ready')\n            return\n        }\n        rest.setAttribute('d', d)\n        activePath.setAttribute('d', d)\n        svg.setAttribute('viewBox', `0 0 ${width} ${height}`)\n        svg.setAttribute('width', String(width))\n        svg.setAttribute('height', String(height))\n        toc.style.width = `${width}px`\n        toc.style.height = `${height}px`\n        layout = { positions }\n        apply()\n    }\n\n    const observer = new ResizeObserver(draw)\n    observer.observe(track)\n    for (const link of links) observer.observe(link)\n    draw()\n    return {\n        place(links: HTMLAnchorElement[]) {\n            visible = links\n            apply()\n        },\n        stop() {\n            observer.disconnect()\n            toc.removeAttribute('data-ready')\n            toc.style.removeProperty('--scroll-spy-track-top')\n            toc.style.removeProperty('--scroll-spy-track-bottom')\n        },\n    }\n}\n",
      "type": "registry:file",
      "target": "~/src/components/ui/scroll-spy/scroll-spy-toc.ts"
    }
  ],
  "meta": {
    "framework": "astro",
    "source": "@gnostic/ui",
    "testedDependencies": {
      "class-variance-authority": "^0.7.1",
      "cn": "0.5.2",
      "motion": "^14.6.0"
    }
  },
  "docs": "https://gnosticai.com/ui/components/scroll-spy",
  "categories": [
    "ui"
  ],
  "type": "registry:ui"
}
