---
title: Scroll Spy for Astro
description: "Track scroll progress on a page or section with visual indicators. Choose from built in variants or add your own."
sidebar:
    label: "Scroll Spy"
    badge: new
seo:
    title: Scroll Spy for Astro | Shadcn & Tailwind CSS
related:
    - /components/progress
    - /components/scroll-area
    - /components/toc
---

Scroll through the examples below. Each indicator stays in view while its
section scrolls from start to finish. The next example then takes its place.
You can also [open the orbit indicator in a full-page preview](/ui/registry-previews/components/scroll-spy/scroll-spy-orbit).

## Composition

`ScrollSpy` is a polymorphic HTML container. It renders a `div` by default,
or the tag given with `as`. It does not use a custom element or a client framework.
With no children, the root passes `variant` and `orientation` to its built-in
track and indicator:

```astro
<ScrollSpy />
<ScrollSpy orientation="horizontal" />
<ScrollSpy variant="gooey" />
<ScrollSpy variant="orbit" />
```

The default vertical line sits at the right edge. The horizontal line sits at
the top. Both track vertical scroll distance, from 0 at the top to 1 at the bottom.
A page with no scroll range stays at 0.

The previews use `scrollTarget="html"` and a `progressTarget` section. A sticky
wrapper keeps the indicator visible during that section. These previews disable
viewport controls so the sticky wrapper follows the page scroll.

```astro
---
import { ScrollSpy } from "@/components/ui/scroll-spy"
---

<section data-progress-section class="relative min-h-[160vh] w-full">
  <div class="sticky top-24 flex min-h-[60vh] flex-col items-center justify-center gap-8 rounded-xl border bg-background p-6">
    <div class="text-center">
      <p class="font-medium">Line</p>
      <p class="text-sm text-muted-foreground">
        Scroll through this section to fill the indicator.
      </p>
    </div>
    <ScrollSpy
      scrollTarget="html"
      progressTarget="[data-progress-section]"
      position="relative"
      aria-hidden="true"
    />
    <p class="text-xs text-muted-foreground">
      0% at the start · 100% at the end
    </p>
  </div>
</section>
```

## Installation

### Command

```sh
bunx --bun shadcn@latest add @gnostic/scroll-spy
```

### Manual

Complete the [Installation guide](/docs/installation) first. Then copy the component files below.

Install the component packages:

```sh
bun add motion
```

#### src/components/ui/scroll-spy/index.ts

```ts
export { default as ScrollSpy } from './scroll-spy.astro'
export { default as ScrollSpyTrack } from './scroll-spy-track.astro'
export { default as ScrollSpyIndicator } from './scroll-spy-indicator.astro'
export { default as ScrollSpyItem } from './scroll-spy-item.astro'
export {
    scrollSpyVariants,
    type ScrollSpyVariantProps,
} from './scroll-spy-variants.ts'
export type {
    ScrollSpyItemProps,
    ScrollSpyTrackProps,
    ScrollSpyIndicatorProps,
    ScrollSpyOptions,
} from './types.ts'
export type {
    ScrollSpyController,
    ScrollSpyControllerOptions,
    ScrollSpyProgressDetail,
} from './scroll-spy.ts'
```

#### src/components/ui/scroll-spy/types.ts

```ts
import type { ScrollSpyVariantProps } from './scroll-spy-variants.ts'

/**
 * Props for the scroll spy root.
 * The root also accepts `class`, `style`, and the attributes of its element.
 */
export interface ScrollSpyOptions {
    /**
     * The appearance passed to the built-in track and indicator. Set it explicitly on custom slotted parts.
     * `toc` draws a path beside the links and highlights all visible targets.
     *
     * @default line
     */
    variant?: NonNullable<ScrollSpyVariantProps['variant']>
    /** The visual direction of the built-in parts. Both layouts track vertical scrolling. @default vertical */
    orientation?: NonNullable<ScrollSpyVariantProps['orientation']>
    /**
     * Fixed to the viewport, absolute in a positioned ancestor, or in normal flow.
     * The `toc` variant uses normal flow when this is omitted.
     *
     * @default fixed
     */
    position?: NonNullable<ScrollSpyVariantProps['position']>
    /** Distance between rail notch centers. Numbers are pixels; strings are CSS lengths. Omit for standard link targets. */
    gap?: number | string
    /** CSS selector for the scroll container. Defaults to the nearest scrollable ancestor, then document.scrollingElement. */
    scrollTarget?: string
    /** Track one section from its top to its bottom. The nearest matching ancestor is preferred. */
    progressTarget?: string
}

/** Props for the track and its built-in fill. */
export interface ScrollSpyTrackProps {
    /** The visual style to render. @default line */
    variant?: NonNullable<ScrollSpyVariantProps['variant']>
    /** The visual direction. @default vertical */
    orientation?: NonNullable<ScrollSpyVariantProps['orientation']>
    /** Render the line fill or orbit ring. Use false for custom content or an empty track. @default true */
    fill?: boolean
}

/** Props for section marks, gooey dots, or the orbiting dot. */
export interface ScrollSpyIndicatorProps {
    /** The visual style to render. @default rail */
    variant?: 'rail' | 'gooey' | 'orbit'
    /** The visual direction. @default vertical */
    orientation?: NonNullable<ScrollSpyVariantProps['orientation']>
}

/**
 * Props for one section link.
 * Anchor attributes such as `href`, `class`, and `aria-label` pass through.
 * `href` is required and must be a fragment, such as `#overview`.
 */
export interface ScrollSpyItemProps {
    /** A section rail link or a table-of-contents link. @default rail */
    variant?: 'rail' | 'toc'
    /** The direction of a rail item. TOC links stay in normal flow. @default vertical */
    orientation?: NonNullable<ScrollSpyVariantProps['orientation']>
    /**
     * Heading depth for the `toc` path.
     * Depth 2 is a page section. Depth 3 and 4 step the line inward.
     *
     * @default 2
     */
    depth?: number
}
```

#### src/components/ui/scroll-spy/scroll-spy-variants.ts

```ts
import { cva, type VariantProps } from 'class-variance-authority'

export const scrollSpyVariants = cva(
    'group/scroll-spy text-foreground pointer-events-none z-20 w-auto [--scroll-spy:0]',
    {
        variants: {
            variant: {
                line: '',
                rail: '',
                gooey: '',
                orbit: '',
                toc: 'w-56 max-w-full',
            },
            orientation: { vertical: '', horizontal: '' },
            position: {
                fixed: 'fixed',
                absolute: 'absolute',
                relative: 'relative',
            },
        },
        compoundVariants: [
            {
                orientation: 'vertical',
                position: ['fixed', 'absolute'],
                class: 'inset-e-4 top-1/2 -translate-y-1/2',
            },
            {
                orientation: 'horizontal',
                position: ['fixed', 'absolute'],
                class: 'inset-x-0 top-0 w-full',
            },
        ],
        defaultVariants: {
            variant: 'line',
            orientation: 'vertical',
            position: 'fixed',
        },
    },
)

export type ScrollSpyVariantProps = VariantProps<typeof scrollSpyVariants>

export const scrollSpyTrackVariants = cva('relative', {
    variants: {
        variant: {
            line: 'bg-border',
            rail: '',
            gooey: '',
            orbit: 'size-14',
            toc: 'w-full',
        },
        orientation: { vertical: '', horizontal: '' },
    },
    compoundVariants: [
        { variant: 'line', orientation: 'vertical', class: 'h-40 w-px' },
        { variant: 'line', orientation: 'horizontal', class: 'h-px w-full' },
        { variant: 'gooey', orientation: 'vertical', class: 'h-44 w-12' },
        { variant: 'gooey', orientation: 'horizontal', class: 'h-12 w-44' },
    ],
    defaultVariants: { variant: 'line', orientation: 'vertical' },
})

export const scrollSpyIndicatorVariants = cva('', {
    variants: {
        variant: {
            rail: 'flex',
            gooey: 'absolute inset-0',
            orbit: 'absolute inset-1 transform-[rotate(calc(var(--scroll-spy)*1turn))] motion-reduce:hidden',
        },
        orientation: { vertical: '', horizontal: '' },
    },
    compoundVariants: [
        { variant: 'rail', orientation: 'vertical', class: 'flex-col' },
        { variant: 'rail', orientation: 'horizontal', class: 'flex-row' },
    ],
    defaultVariants: { variant: 'rail', orientation: 'vertical' },
})

export const scrollSpyItemVariants = cva(
    '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',
    {
        variants: {
            variant: {
                rail: 'aria-[current=location]:text-primary min-h-8 min-w-11 gap-3 px-2 group-data-gap/scroll-spy:flex-none',
                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',
            },
            orientation: { vertical: '', horizontal: '' },
        },
        compoundVariants: [
            {
                variant: 'rail',
                orientation: 'vertical',
                class: 'justify-end group-data-gap/scroll-spy:h-[max(1px,var(--scroll-spy-gap))] group-data-gap/scroll-spy:min-h-0',
            },
            {
                variant: 'rail',
                orientation: 'horizontal',
                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',
            },
        ],
        defaultVariants: { variant: 'rail', orientation: 'vertical' },
    },
)
```

#### src/components/ui/scroll-spy/scroll-spy.astro

```astro
---
import type { HTMLTag, Polymorphic } from "astro/types"
import { cn } from "cn"
import type { ScrollSpyOptions } from "./types.ts"
import { scrollSpyVariants } from "./scroll-spy-variants.ts"
import Track from "./scroll-spy-track.astro"
import Indicator from "./scroll-spy-indicator.astro"

type Props<Tag extends HTMLTag = "div"> = Polymorphic<{ as: Tag }> &
  ScrollSpyOptions

const {
  as: Tag = "div",
  variant = "line",
  orientation = "vertical",
  position: positionProp,
  gap,
  scrollTarget,
  progressTarget,
  class: className,
  style: styleProp,
  ...props
} = Astro.props

// The contents spine sits in normal flow. Other variants stay fixed.
const position = positionProp ?? (variant === "toc" ? "relative" : "fixed")
const railGap = typeof gap === "number" ? `${gap}px` : gap
const rootStyle =
  typeof styleProp === "string"
    ? `${railGap === undefined ? "" : `--scroll-spy-gap: ${railGap}; `}${styleProp}`
    : {
        "--scroll-spy-gap": railGap,
        ...(styleProp ? styleProp : {}),
      }
---

<Tag
  data-slot="scroll-spy"
  data-variant={variant}
  data-orientation={orientation}
  data-gap={railGap}
  data-scroll-target={scrollTarget}
  data-progress-target={progressTarget}
  class={cn(scrollSpyVariants({ variant, orientation, position }), className)}
  style={rootStyle}
  {...props}
>
  <slot>
    <Track {variant} {orientation}>
      {(variant === "rail" || variant === "gooey" || variant === "orbit") && (
        <Indicator {variant} {orientation} />
      )}
    </Track>
  </slot>
</Tag>

<script>
  import { create, type ScrollSpyController } from "./scroll-spy.ts"

  const controllers: ScrollSpyController[] = []
  const initialize = () => controllers.push(...create())

  initialize()
  document.addEventListener("astro:page-load", initialize)
  document.addEventListener("astro:before-swap", () => {
    for (const controller of controllers) controller.destroy()
    controllers.length = 0
  })
</script>

<style>
  @property --scroll-spy {
    syntax: "<number>";
    inherits: true;
    initial-value: 0;
  }
</style>
```

#### src/components/ui/scroll-spy/scroll-spy-track.astro

```astro
---
import type { HTMLTag, Polymorphic } from "astro/types"
import { cn } from "cn"
import type { ScrollSpyTrackProps } from "./types.ts"
import { scrollSpyTrackVariants } from "./scroll-spy-variants.ts"

type Props<Tag extends HTMLTag = "div"> = Polymorphic<{ as: Tag }> &
  ScrollSpyTrackProps

const {
  as: Tag = "div",
  variant = "line",
  orientation = "vertical",
  fill = true,
  class: className,
  ...props
} = Astro.props
---

<Tag
  data-slot="scroll-spy-track"
  data-variant={variant}
  data-orientation={orientation}
  class={cn(scrollSpyTrackVariants({ variant, orientation }), className)}
  {...props}
>
  {variant === "toc" && (
    <div
      data-slot="scroll-spy-toc"
      class="group/scroll-spy-toc pointer-events-none absolute inset-s-0 top-0 overflow-visible **:pointer-events-none rtl:-scale-x-100"
      aria-hidden="true"
    >
      <svg
        data-slot="scroll-spy-toc-svg"
        class="absolute overflow-visible"
        fill="none"
        stroke-linecap="butt"
        aria-hidden="true"
      >
        <path
          data-slot="scroll-spy-toc-path"
          class="stroke-foreground/10"
          stroke-width="1"
        />
        <path
          data-slot="scroll-spy-toc-highlight"
          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"
          stroke-width="1"
        />
      </svg>
    </div>
  )}
  {fill && variant === "line" && (
    <span
      data-slot="scroll-spy-fill"
      aria-hidden="true"
      class={cn(
        "pointer-events-none absolute inset-0 bg-primary",
        orientation === "horizontal"
          ? "origin-left transform-[scaleX(var(--scroll-spy))]"
          : "origin-top transform-[scaleY(var(--scroll-spy))]",
      )}
    />
  )}
  {fill && variant === "orbit" && (
    <svg
      data-slot="scroll-spy-fill"
      viewBox="0 0 56 56"
      class="pointer-events-none absolute inset-0 size-full -rotate-90 fill-none"
      aria-hidden="true"
      focusable="false"
    >
      <circle cx="28" cy="28" r="24" class="stroke-border" stroke-width="1.5" />
      <circle
        data-slot="scroll-spy-ring"
        cx="28"
        cy="28"
        r="24"
        pathLength="100"
        class="stroke-primary [stroke-dasharray:100] [stroke-dashoffset:calc(100*(1-var(--scroll-spy)))]"
        stroke-width="2"
        stroke-linecap="round"
      />
    </svg>
  )}
  <slot />
</Tag>
```

#### src/components/ui/scroll-spy/scroll-spy-indicator.astro

```astro
---
/**
 * Section marks, liquid/gooey dots, or orbiting dot. Its slot accepts custom content.
 *
 * @optional - not required
 */
import type { HTMLTag, Polymorphic } from "astro/types"
import { cn } from "cn"
import type { ScrollSpyIndicatorProps } from "./types.ts"
import { scrollSpyIndicatorVariants } from "./scroll-spy-variants.ts"

type Props<Tag extends HTMLTag = "div"> = Polymorphic<{ as: Tag }> &
  ScrollSpyIndicatorProps

const {
  as: Tag = "div",
  variant = "rail",
  orientation = "vertical",
  class: className,
  ...props
} = Astro.props

const filterId =
  variant === "gooey" ? `scroll-goo-${crypto.randomUUID()}` : undefined
---

<Tag
  data-slot="scroll-spy-indicator"
  data-variant={variant}
  data-orientation={orientation}
  class={cn(scrollSpyIndicatorVariants({ variant, orientation }), className)}
  {...props}
>
  <slot>
    {variant === "gooey" && (
      <>
        <svg class="absolute size-0" aria-hidden="true" focusable="false">
          <defs>
            <filter
              id={filterId}
              x="-100%"
              y="-100%"
              width="300%"
              height="300%"
              color-interpolation-filters="sRGB"
            >
              <feGaussianBlur
                in="SourceGraphic"
                stdDeviation="6"
                result="blur"
              />
              <feColorMatrix
                in="blur"
                mode="matrix"
                values="1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 20 -5"
              />
            </filter>
          </defs>
        </svg>
        <div
          data-slot="scroll-spy-goo"
          class={cn(
            "absolute inset-0 flex items-center justify-around motion-reduce:filter-none! forced-colors:filter-none!",
            orientation === "horizontal" ? "flex-row" : "flex-col",
          )}
          style={{ filter: `url(#${filterId})` }}
          aria-hidden="true"
        >
          {Array.from({ length: 4 }, () => (
            <span class="size-3 shrink-0 rounded-full bg-background bg-linear-to-b from-muted to-primary" />
          ))}
          <span
            data-slot="scroll-spy-flow"
            class={cn(
              "absolute size-4.5 -translate-1/2 rounded-full bg-primary",
              orientation === "horizontal"
                ? "top-1/2 left-[calc(12.5%+var(--scroll-spy)*75%)]"
                : "left-1/2 top-[calc(12.5%+var(--scroll-spy)*75%)]",
            )}
          />
        </div>
      </>
    )}
    {variant === "orbit" && (
      <span
        data-slot="scroll-spy-dot"
        class="absolute -top-1 left-1/2 size-2 -translate-x-1/2 rounded-full bg-primary ring-4 ring-primary/15"
        aria-hidden="true"
      />
    )}
  </slot>
</Tag>
```

#### src/components/ui/scroll-spy/scroll-spy-item.astro

```astro
---
/**
 * Each item is a trackable target in the scroll spy timeline.
 *
 * @optional - not required
 */
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import type { ScrollSpyItemProps } from "./types.ts"
import { scrollSpyItemVariants } from "./scroll-spy-variants.ts"

type Props = HTMLAttributes<"a"> &
  ScrollSpyItemProps & {
    /** Fragment of the section this link tracks. */
    href: `#${string}`
  }

const {
  class: className,
  "aria-label": label,
  depth = 2,
  variant = "rail",
  orientation = "vertical",
  ...props
} = Astro.props
---

<a
  data-slot="scroll-spy-item"
  data-depth={depth}
  data-variant={variant}
  data-orientation={orientation}
  aria-label={
    label ??
    (Astro.slots.has("default") ? undefined : `Go to ${props.href.slice(1)}`)
  }
  class={cn(scrollSpyItemVariants({ variant, orientation }), className)}
  {...props}
>
  {Astro.slots.has("default") && (
    <span
      data-slot="scroll-spy-label"
      class={cn(
        "flex items-center gap-2 empty:hidden",
        variant === "rail" && [
          "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",
          "group-aria-[current=location]/scroll-spy-item:opacity-100  group-hover/scroll-spy-item:opacity-100 group-focus-visible/scroll-spy-item:opacity-100",
          "group-data-gap/scroll-spy:absolute group-data-gap/scroll-spy:pointer-events-none",
          orientation === "horizontal"
            ? "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"
            : "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",
        ],
      )}
    >
      <slot />
    </span>
  )}
  {variant === "rail" && (
    <span
      data-slot="scroll-spy-mark"
      class={cn(
        "shrink-0 bg-current transition-[width,height] duration-200 ease-[ease] motion-reduce:transition-none",
        orientation === "horizontal"
          ? "h-3 w-px group-aria-[current=location]/scroll-spy-item:h-8"
          : "h-px w-3 group-aria-[current=location]/scroll-spy-item:w-8",
      )}
      aria-hidden="true"
    />
  )}
</a>
```

#### src/components/ui/scroll-spy/scroll-spy.ts

```ts
import { scrollInfo } from 'motion'

import { trackProgress } from './scroll-spy-progress.ts'
import { trackToc } from './scroll-spy-toc.ts'

const SELECTOR = '[data-slot="scroll-spy"]'
const controllers = new WeakMap<HTMLElement, ScrollSpyController>()

/** Visual modes. CSS draws the first four. `toc` also draws an SVG path. */
const VARIANTS = ['line', 'rail', 'gooey', 'orbit', 'toc'] as const

type Variant = (typeof VARIANTS)[number]

/**
 * Options for one scroll spy.
 * The Astro root stores the same values as data attributes.
 */
interface Options {
    /**
     * Appearance.
     * `line`, `rail`, `gooey`, and `orbit` use `--scroll-spy` and the current link.
     * `toc` highlights the visible section links.
     */
    variant: Variant
    /** CSS selector for the scroll container. */
    scrollTarget?: string | undefined
    /** CSS selector for one measured section. */
    progressTarget?: string | undefined
}

export type ScrollSpyControllerOptions = Partial<Options>

export interface ScrollSpyController {
    /** Current progress from 0 to 1. Starts at 0 until the first measurement. */
    readonly progress: number
    destroy(): void
}

export interface ScrollSpyProgressDetail {
    /** Measured progress from 0 to 1. */
    progress: number
}

declare global {
    interface HTMLElementEventMap {
        'scroll-spy:progress': CustomEvent<ScrollSpyProgressDetail>
    }
    interface DocumentEventMap {
        'scroll-spy:progress': CustomEvent<ScrollSpyProgressDetail>
    }
}

/** One section link and the element its fragment names. */
interface SectionLink {
    link: HTMLAnchorElement
    section: HTMLElement
}

/** Scroll measurements this script reads from Motion. */
interface ScrollAxis {
    current: number
    scrollLength: number
    targetLength: number
    containerLength: number
}

/** The element that scrolls, and the optional section Motion measures. */
interface ScrollContext {
    container: HTMLElement | null
    source: HTMLElement
    target: HTMLElement | undefined
    motion: Parameters<typeof scrollInfo>[1]
}

/** Read the variant and scroll selectors from the root. */
function readOptions(root: HTMLElement): Options {
    let variant = root.dataset.variant as Variant

    if (!variant || !VARIANTS.includes(variant as Variant)) {
        variant = 'line'
    }

    return {
        variant,
        scrollTarget: trimmed(root.dataset.scrollTarget),
        progressTarget: trimmed(root.dataset.progressTarget),
    }
}

function trimmed(value: string | undefined) {
    const text = value?.trim()
    return text ? text : undefined
}

/** Bind each unbound scroll spy in the scope. */
export function create(scope: ParentNode = document): ScrollSpyController[] {
    const roots = [...scope.querySelectorAll<HTMLElement>(SELECTOR)]
    if (scope instanceof HTMLElement && scope.matches(SELECTOR))
        roots.unshift(scope)
    return roots
        .filter((root) => !controllers.has(root))
        .map((root) => createScrollSpy(root))
}

/** Bind one scroll spy. Explicit options override its data attributes. */
export function createScrollSpy(
    root: HTMLElement,
    options: ScrollSpyControllerOptions = {},
): ScrollSpyController {
    const existing = controllers.get(root)
    if (existing) return existing

    const resolved = { ...readOptions(root), ...options }
    const links = ownedLinks(root)
    const clearLinks = () =>
        links.forEach((link) => {
            link.removeAttribute('aria-current')
            link.removeAttribute('data-active')
        })
    clearLinks()
    root.style.setProperty('--scroll-spy', '0')

    const context = resolveScroll(root, resolved)
    const marker =
        context && resolved.variant === 'toc'
            ? trackToc(root, links)
            : undefined
    const progress = context
        ? trackProgress(root, context.source, context.target)
        : undefined
    let destroyed = false
    let measured = false
    let currentProgress = 0
    let stopScroll: (() => void) | undefined

    const controller: ScrollSpyController = {
        get progress() {
            return currentProgress
        },
        destroy() {
            if (destroyed) return
            destroyed = true
            stopScroll?.()
            progress?.stop()
            marker?.stop()
            clearLinks()
            currentProgress = 0
            root.style.setProperty('--scroll-spy', '0')
            controllers.delete(root)
        },
    }
    controllers.set(root, controller)
    if (!context || !progress) return controller

    const sections = collectSections(links, context.container)
    let active: HTMLAnchorElement | undefined
    let visible: HTMLAnchorElement[] = []

    stopScroll = scrollInfo(({ y }) => {
        if (destroyed) return
        const value = progressValue(y.progress, y, Boolean(context.target))
        const hasRange = context.target
            ? y.targetLength > y.containerLength
            : y.scrollLength > 0
        progress.update(hasRange, value)
        if (sections.length && marker) {
            const nextVisible = visibleLinks(sections, context, y)
            if (
                nextVisible.length !== visible.length ||
                nextVisible.some((link, index) => link !== visible[index])
            ) {
                visible = nextVisible
                for (const link of links)
                    link.toggleAttribute('data-active', visible.includes(link))
                marker.place(visible)
            }
        }
        if (sections.length) {
            const next = marker
                ? visible[0]
                : activeLink(sections, context.container, y, value)
            if (next !== active) {
                active?.removeAttribute('aria-current')
                active = next
                active?.setAttribute('aria-current', 'location')
            }
        }
        if (!measured || value !== currentProgress) {
            measured = true
            currentProgress = value
            root.dispatchEvent(
                new CustomEvent('scroll-spy:progress', {
                    bubbles: true,
                    detail: { progress: value },
                }),
            )
        }
    }, context.motion)

    return controller
}

/** Links that belong to this root, not a nested scroll spy. */
function ownedLinks(root: HTMLElement) {
    return [
        ...root.querySelectorAll<HTMLAnchorElement>(
            '[data-slot="scroll-spy-item"]',
        ),
    ].filter((link) => link.closest(SELECTOR) === root)
}

/**
 * Find the scroll container and the optional measured section.
 * A selector that is missing or invalid returns undefined.
 */
function resolveScroll(
    root: HTMLElement,
    options: Options,
): ScrollContext | undefined {
    let container: HTMLElement | null = root.parentElement
    let target: HTMLElement | undefined
    try {
        if (options.scrollTarget) {
            const element = document.querySelector(options.scrollTarget)
            if (!(element instanceof HTMLElement)) return
            container = element
        } else {
            while (
                container &&
                container !== document.body &&
                container !== document.documentElement
            ) {
                if (
                    /(auto|scroll|hidden)/.test(
                        getComputedStyle(container).overflowY,
                    )
                )
                    break
                container = container.parentElement
            }
        }
        if (
            container === document.body ||
            container === document.documentElement
        )
            container = null
        if (options.progressTarget) {
            const element =
                root.closest(options.progressTarget) ??
                document.querySelector(options.progressTarget)
            if (
                !(element instanceof HTMLElement) ||
                (container && !container.contains(element))
            )
                return
            target = element
        }
    } catch {
        // An invalid selector must not select a different scroll source.
        return
    }

    const documentScroller = document.scrollingElement
    const source =
        container ??
        (documentScroller instanceof HTMLElement
            ? documentScroller
            : document.documentElement)
    return {
        container,
        source,
        target,
        motion: {
            container: source,
            ...(target ? { target, offset: ['start start', 'end end'] } : {}),
            trackContentSize: true,
        },
    }
}

/** Pair each fragment link with a section inside the scroll container. */
function collectSections(
    links: HTMLAnchorElement[],
    container: HTMLElement | null,
) {
    return links.flatMap((link) => {
        let id: string
        try {
            id = decodeURIComponent(link.hash.slice(1))
        } catch {
            return []
        }
        const section = document.getElementById(id)
        return section && (!container || container.contains(section))
            ? [{ link, section }]
            : []
    })
}

/**
 * Progress from 0 to 1.
 * An empty container, or a section shorter than the viewport, stays at 0.
 */
function progressValue(progress: number, axis: ScrollAxis, hasTarget: boolean) {
    const hasRange = hasTarget
        ? axis.targetLength > axis.containerLength
        : axis.scrollLength > 0
    return hasRange && Number.isFinite(progress)
        ? Math.min(1, Math.max(0, progress))
        : 0
}

/** Visible targets, or the last heading above the viewport between headings. */
function visibleLinks(
    sections: SectionLink[],
    { container, target }: ScrollContext,
    axis: ScrollAxis,
) {
    const top = container
        ? container.getBoundingClientRect().top + container.clientTop
        : 0
    const bottom = top + axis.containerLength
    if (bottom <= top) return []
    if (target) {
        const bounds = target.getBoundingClientRect()
        if (bounds.bottom <= top || bounds.top >= bottom) return []
    }
    const visible: HTMLAnchorElement[] = []
    let previous: HTMLAnchorElement | undefined
    for (const { link, section } of sections) {
        const bounds = section.getBoundingClientRect()
        if (bounds.height === 0) continue
        if (bounds.top < bottom && bounds.bottom > top) visible.push(link)
        if (bounds.bottom <= top) previous = link
    }
    return visible.length ? visible : previous ? [previous] : []
}

/**
 * The link for the section at the reading line.
 * The first link is current at the top. The last link is current at the bottom,
 * including a short final section.
 */
function activeLink(
    sections: SectionLink[],
    container: HTMLElement | null,
    axis: ScrollAxis,
    value: number,
) {
    const line =
        (container
            ? container.getBoundingClientRect().top + container.clientTop
            : 0) +
        axis.containerLength * 0.45
    let current: HTMLAnchorElement | undefined = sections[0]?.link
    if (
        value === 1 ||
        (axis.scrollLength > 0 && axis.current >= axis.scrollLength - 1)
    ) {
        current = sections.at(-1)?.link
    } else if (value > 0 && axis.current > 0) {
        for (const { link, section } of sections) {
            if (section.getBoundingClientRect().top <= line) current = link
        }
    }
    return current
}
```

#### src/components/ui/scroll-spy/scroll-spy-progress.ts

```ts
import { scroll, type scrollInfo } from 'motion'
import { animate } from 'motion/mini'

export type ScrollProgressController = {
    update: (hasRange: boolean, value: number) => void
    stop: () => void
}

/** Progress animation with range checks supplied by the scroll controller. */
export function trackProgress(
    /**
     * The root element to animate.
     */
    root: HTMLElement,
    /**
     * The source element to scroll.
     */
    source: HTMLElement,
    /**
     * The target element to scroll to.
     */
    target?: HTMLElement,
): ScrollProgressController {
    const native =
        typeof ScrollTimeline !== 'undefined' &&
        (!target || typeof ViewTimeline !== 'undefined')
    let manual = false
    let animation: ReturnType<typeof animate> | undefined
    let stopScroll: (() => void) | undefined
    let failed =
        typeof root.animate !== 'function' ||
        typeof CSS === 'undefined' ||
        typeof CSS.registerProperty !== 'function'

    if (native) {
        try {
            const style = target && getComputedStyle(source)
            const hasScrollPadding =
                style &&
                (Number.parseFloat(style.scrollPaddingTop) > 0 ||
                    Number.parseFloat(style.scrollPaddingBottom) > 0)
            manual =
                !CSS.supports('animation-timeline', 'scroll()') ||
                Boolean(
                    target &&
                    (hasScrollPadding ||
                        !CSS.supports(
                            'animation-range',
                            'contain 0% contain 100%',
                        ) ||
                        new ViewTimeline({
                            subject: target,
                            axis: 'y',
                            inset: '0px',
                        }).source !== source),
                )
        } catch {
            manual = true
        }
    }

    const reset = () => {
        stopScroll?.()
        stopScroll = undefined
        animation?.cancel()
        animation = undefined
        root.style.setProperty('--scroll-spy', '0')
    }

    const start = () => {
        animation = animate(
            root,
            { '--scroll-spy': [0, 1] },
            {
                duration: 1,
                ease: 'linear',
                autoplay: false,
            },
        )
        if (manual) return
        const options: Parameters<typeof scrollInfo>[1] = {
            container: source,
            ...(target ? { target, offset: ['start start', 'end end'] } : {}),
            trackContentSize: true,
        }
        stopScroll = scroll(animation, options)
        if (native) {
            // A partial implementation can accept a timeline without attaching it.
            if (
                !root
                    .getAnimations()
                    .some(({ timeline }) => timeline instanceof ScrollTimeline)
            ) {
                reset()
                manual = true
                start()
            } else {
                animation.play()
            }
        }
    }

    const update = (hasRange: boolean, value: number) => {
        if (!hasRange) {
            if (animation) reset()
            else root.style.setProperty('--scroll-spy', '0')
            return
        }
        if (!animation && !failed) {
            try {
                start()
            } catch {
                reset()
                failed = true
            }
        }
        if (failed) root.style.setProperty('--scroll-spy', String(value))
        else if (manual && animation) animation.time = value
    }

    update(!target || target.clientHeight > source.clientHeight, 0)
    return {
        update,
        stop: reset,
    }
}
```

#### src/components/ui/scroll-spy/scroll-spy-toc.ts

```ts
const SELECTOR = '[data-slot="scroll-spy"]'

interface Marker {
    place(visible: HTMLAnchorElement[]): void
    stop(): void
}

/** Line x positions for heading depth. Depth 2, 3, and 4 match the Fumadocs TOC. */
const TOC_BASE = 8

/**
 * Horizontal position of the TOC path for one heading depth.
 * The link padding in scroll-spy-item.astro uses these values plus 12px.
 */
function tocLineOffset(depth: number) {
    if (depth <= 2) return TOC_BASE
    if (depth === 3) return TOC_BASE + 8
    return TOC_BASE + 16
}

/** Heading depth from the item. Missing or invalid values use a page section. */
function itemDepth(link: HTMLElement) {
    const depth = Number(link.dataset.depth)
    return Number.isFinite(depth) && depth > 0 ? depth : 2
}

interface TocLayout {
    positions: [top: number, bottom: number, x: number][]
}

/**
 * Draw the TOC path and highlight the range of visible links.
 * A muted path shows every heading. A clipped copy marks the visible range.
 * The curve follows the Fumadocs table of contents.
 */
export function trackToc(
    root: HTMLElement,
    links: HTMLAnchorElement[],
): Marker {
    const toc = [
        ...root.querySelectorAll<HTMLElement>('[data-slot="scroll-spy-toc"]'),
    ].find((element) => element.closest(SELECTOR) === root)
    const rest = toc?.querySelector<SVGPathElement>(
        '[data-slot="scroll-spy-toc-path"]',
    )
    const activePath = toc?.querySelector<SVGPathElement>(
        '[data-slot="scroll-spy-toc-highlight"]',
    )
    const svg = toc?.querySelector<SVGSVGElement>(
        '[data-slot="scroll-spy-toc-svg"]',
    )
    const track = toc?.closest<HTMLElement>('[data-slot="scroll-spy-track"]')
    if (!toc || !rest || !activePath || !svg || !track)
        return {
            place(_visible: HTMLAnchorElement[]) {},
            stop() {},
        }

    let layout: TocLayout | undefined
    let visible: HTMLAnchorElement[] = []

    const apply = () => {
        const first = visible[0]
        const last = visible.at(-1)
        const start = first && layout?.positions[links.indexOf(first)]
        const end = last && layout?.positions[links.indexOf(last)]
        if (!start || !end) {
            toc.removeAttribute('data-ready')
            return
        }
        toc.style.setProperty('--scroll-spy-track-top', `${start[0]}px`)
        toc.style.setProperty('--scroll-spy-track-bottom', `${end[1]}px`)
        toc.dataset.ready = ''
    }

    const draw = () => {
        const trackTop = track.getBoundingClientRect().top
        let width = 0
        let height = 0
        let d = ''
        const positions: TocLayout['positions'] = []
        links.forEach((link, index) => {
            const style = getComputedStyle(link)
            const x = tocLineOffset(itemDepth(link)) + 0.5
            const origin = link.getBoundingClientRect().top - trackTop
            const top = origin + Number.parseFloat(style.paddingTop)
            const bottom =
                origin +
                link.clientHeight -
                Number.parseFloat(style.paddingBottom)
            width = Math.max(width, x + 8)
            height = Math.max(height, bottom)
            if (index === 0) d += `M${x} ${top}L${x} ${bottom}`
            else {
                const [, upperBottom, upperX] = positions[index - 1]
                d += `C${upperX} ${top - 4} ${x} ${upperBottom + 4} ${x} ${top}L${x} ${bottom}`
            }
            positions.push([top, bottom, x])
        })
        if (!d || width === 0 || height === 0) {
            layout = undefined
            toc.removeAttribute('data-ready')
            return
        }
        rest.setAttribute('d', d)
        activePath.setAttribute('d', d)
        svg.setAttribute('viewBox', `0 0 ${width} ${height}`)
        svg.setAttribute('width', String(width))
        svg.setAttribute('height', String(height))
        toc.style.width = `${width}px`
        toc.style.height = `${height}px`
        layout = { positions }
        apply()
    }

    const observer = new ResizeObserver(draw)
    observer.observe(track)
    for (const link of links) observer.observe(link)
    draw()
    return {
        place(links: HTMLAnchorElement[]) {
            visible = links
            apply()
        },
        stop() {
            observer.disconnect()
            toc.removeAttribute('data-ready')
            toc.style.removeProperty('--scroll-spy-track-top')
            toc.style.removeProperty('--scroll-spy-track-bottom')
        },
    }
}
```

Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.


## Track and fill

Use parts when you need more control. Each part accepts `class`, `style`, native
HTML attributes, and a slot. The root, track, and indicator also accept `as`.

```astro
---
import {
  ScrollSpy,
  ScrollSpyTrack,
} from "@/components/ui/scroll-spy"
---

<ScrollSpy orientation="horizontal">
  <ScrollSpyTrack orientation="horizontal" class="h-1" />
</ScrollSpy>
```

`ScrollSpyTrack` includes the growing line or SVG ring. Use `fill={false}` to
omit it. Its slot accepts an indicator, section links, or custom content alongside
the built-in fill. The TOC track includes its SVG markup directly; it does not
need a separate TOC component file.

Custom slotted parts take `variant` and `orientation` as explicit props. These
props choose classes and markup during Astro rendering. The root does not pass
props into supplied slot content. Keep the visual props consistent with the root;
in particular, a TOC needs `variant="toc"` on the root, track, and items.

Tracks default to `line`; indicators and items default to `rail`. All parts
default to vertical orientation. A variant renders only the markup it uses.

The `--scroll-spy` CSS property is a number from 0 to 1. Custom content can
use it to draw a different shape without another scroll script.

## Indicators

`ScrollSpyIndicator` is optional. Its `rail` variant groups section
items. The `gooey` variant supplies four liquid dots and a moving blob. The
`orbit` variant supplies a dot that travels around the ring. A slot replaces
its default content, so you can supply your own marks or SVG.

### Gooey

The inactive dots use a gradient from muted to primary. A background layer
keeps the dots visible through the blur filter.

```astro
---
import { ScrollSpy } from "@/components/ui/scroll-spy"
---

<section data-progress-section class="relative min-h-[160vh] w-full">
  <div class="sticky top-24 flex min-h-[60vh] flex-col items-center justify-center gap-8 rounded-xl border bg-background p-6">
    <div class="text-center">
      <p class="font-medium">Gooey</p>
      <p class="text-sm text-muted-foreground">
        Scroll through this section to fill the indicator.
      </p>
    </div>
    <ScrollSpy
      variant="gooey"
      scrollTarget="html"
      progressTarget="[data-progress-section]"
      position="relative"
      aria-hidden="true"
    />
    <p class="text-xs text-muted-foreground">
      0% at the start · 100% at the end
    </p>
  </div>
</section>
```

### Orbit

The track owns the ring; the indicator owns the orbiting dot. Use an orbit track
without an indicator for a plain ring. This example uses `scroll-spy:progress`
to update the percentage inside the ring. The number stays upright while the
dot moves around it.

```astro
---
import {
  ScrollSpy,
  ScrollSpyTrack,
  ScrollSpyIndicator,
} from "@/components/ui/scroll-spy"
---

<section data-progress-section class="relative min-h-[160vh] w-full">
  <div class="sticky top-24 flex min-h-[60vh] flex-col items-center justify-center gap-8 rounded-xl border bg-background p-6">
    <div class="text-center">
      <p class="font-medium">Orbit</p>
      <p class="text-sm text-muted-foreground">
        Scroll through this section to fill the indicator.
      </p>
    </div>
    <ScrollSpy
      data-orbit-progress
      variant="orbit"
      scrollTarget="html"
      progressTarget="[data-progress-section]"
      position="relative"
    >
      <ScrollSpyTrack variant="orbit" class="grid place-items-center">
        <ScrollSpyIndicator variant="orbit" />
        <output
          data-scroll-percentage
          aria-label="Section progress"
          aria-live="off"
          class="text-xs font-medium tabular-nums"
        >
          0%
        </output>
      </ScrollSpyTrack>
    </ScrollSpy>
    <p class="text-xs text-muted-foreground">
      0% at the start · 100% at the end
    </p>
  </div>
</section>

<script>
  import {
    createScrollSpy,
    type ScrollSpyController,
  } from "@/components/ui/scroll-spy/scroll-spy.ts"

  const controllers = new Set<ScrollSpyController>()

  function updatePercentage(root: HTMLElement, progress: number) {
    const output = root.querySelector<HTMLOutputElement>(
      "[data-scroll-percentage]",
    )
    if (output) output.value = `${Math.round(progress * 100)}%`
  }

  document.addEventListener("scroll-spy:progress", (event) => {
    const root = event.target
    if (
      root instanceof HTMLElement &&
      root.hasAttribute("data-orbit-progress")
    ) {
      updatePercentage(root, event.detail.progress)
    }
  })

  function initialize() {
    document
      .querySelectorAll<HTMLElement>("[data-orbit-progress]")
      .forEach((root) => {
        const controller = createScrollSpy(root)
        controllers.add(controller)
        updatePercentage(root, controller.progress)
      })
  }

  initialize()
  document.addEventListener("astro:page-load", initialize)
  document.addEventListener("astro:before-swap", () => {
    for (const controller of controllers) controller.destroy()
    controllers.clear()
  })
</script>
```

### Horizontal

Orientation changes the layout, not the scroll axis. A horizontal line or a row
of dots can show progress through the same vertical page.

```astro
---
import { ScrollSpy } from "@/components/ui/scroll-spy"
---

<section data-progress-section class="relative min-h-[160vh] w-full">
  <div class="sticky top-24 flex min-h-[60vh] flex-col items-center justify-center gap-8 rounded-xl border bg-background p-6">
    <div class="text-center">
      <p class="font-medium">Horizontal</p>
      <p class="text-sm text-muted-foreground">
        Scroll through this section to fill the indicator.
      </p>
    </div>
    <ScrollSpy
      scrollTarget="html"
      progressTarget="[data-progress-section]"
      orientation="horizontal"
      position="relative"
      class="w-full max-w-64"
      aria-hidden="true"
    />
    <p class="text-xs text-muted-foreground">
      0% at the start · 100% at the end
    </p>
  </div>
</section>
```

## Section links

Use `as="nav"` and give the navigation an accessible name. Items are native
anchors. Use `href="#section-id"` to refer to a section; `id` remains the native
ID of the link itself. This avoids duplicate IDs on the link and its target.

```astro
---
import {
  ScrollSpy,
  ScrollSpyTrack,
  ScrollSpyIndicator,
  ScrollSpyItem,
} from "@/components/ui/scroll-spy"

const items = [
  { id: "about", label: "About" },
  { id: "work", label: "Work" },
]
---

<ScrollSpy variant="rail" as="nav" aria-label="Page sections">
  <ScrollSpyTrack variant="rail">
    <ScrollSpyIndicator variant="rail">
      {items.map(item => (
        <ScrollSpyItem href={`#${item.id}`}>
          {item.label}
        </ScrollSpyItem>
      ))}
    </ScrollSpyIndicator>
  </ScrollSpyTrack>
</ScrollSpy>

<section id="about">...</section>
<section id="work">...</section>
```

Keep items in document order. Content can be text, an icon, or both. A current,
hovered, or focused item shows its content and expands its mark. To omit visible
labels, leave the slot empty and supply an `aria-label`:

```astro
---
import {
  ScrollSpy,
  ScrollSpyTrack,
  ScrollSpyIndicator,
  ScrollSpyItem,
} from "@/components/ui/scroll-spy"
const id = `rail-${crypto.randomUUID()}`
const sections = ["Start", "Middle", "Finish"]
---

<section data-progress-section class="relative flex gap-8 w-full">
  <div class="relative basis-1/4">
    <ScrollSpy
      variant="rail"
      as="nav"
      aria-label="Demo sections"
      scrollTarget="html"
      progressTarget="[data-progress-section]"
      position="relative"
      class="sticky top-1/2"
    >
      <ScrollSpyTrack variant="rail">
        <ScrollSpyIndicator variant="rail">
          {sections.map((label, i) => (
            <ScrollSpyItem href={`#${id}-${i}`} aria-label={label}>
              {label}
            </ScrollSpyItem>
          ))}
        </ScrollSpyIndicator>
      </ScrollSpyTrack>
    </ScrollSpy>
  </div>
  <div class="grow">
    {sections.map((label, i) => (
      <section
        id={`${id}-${i}`}
        class="flex min-h-[70vh] scroll-mt-24 items-start border-t py-8"
      >
        <p class="text-sm text-muted-foreground">
          {label} — scroll to the next section.
        </p>
      </section>
    ))}
  </div>
</section>
```

Empty items get a fallback accessible name from their fragment target. Supply a
clear `aria-label` for an icon-only item. No item list, labels, or section IDs
are needed when you only want total progress.

For a compact rail, set `gap={8}` on `ScrollSpy`. This sets an 8px distance
between notch centers. A number uses pixels; a string accepts a CSS length,
such as `gap="0.5rem"`. It works in both orientations. Labels sit beside a
vertical rail or above a horizontal rail, so they do not increase the spacing.
Omit `gap` to keep the standard link target sizes. For a dense rail, also provide
a section menu with larger touch targets.

## Table of contents

`variant="toc"` draws a path beside the links. The line steps inward when the
heading depth changes. All links whose targets intersect the scroll viewport
get `data-active`. The highlight covers the path from the first active link to
the last. There is no moving dot.

Link to heading IDs to track visible headings, or section IDs to track visible
section content. Between headings, the last heading above the viewport stays
active. Only the first active link gets `aria-current="location"`.
With `progressTarget`, the highlight clears when that target leaves the viewport.

Omit `position` to keep the list in normal flow. Add `sticky` when the list
should remain on screen.

Set `depth` to the heading level. Depth 2 is a page section. Depth 3 and 4
step the path inward. The default is 2.

```astro
---
import {
  ScrollSpy,
  ScrollSpyTrack,
  ScrollSpyItem,
} from "@/components/ui/scroll-spy"

const items = [
  { id: "overview", label: "Overview", depth: 2 },
  { id: "flags", label: "Flags", depth: 3 },
]
---

<ScrollSpy variant="toc" as="nav" aria-label="On this page">
  <ScrollSpyTrack variant="toc">
    {items.map(item => (
      <ScrollSpyItem variant="toc" href={`#${item.id}`} depth={item.depth}>
        {item.label}
      </ScrollSpyItem>
    ))}
  </ScrollSpyTrack>
</ScrollSpy>
```

### With the Toc component

[Toc](/ui/components/toc#with-scroll-spy) supplies a navigation wrapper, title,
and list structure. Its `TocMenuLink` renders the active state supplied by its
props. Scroll Spy supplies live heading tracking and the path highlight.

Compose `Toc`, `TocTitle`, `TocMenu`, and `TocMenuItem` with Scroll Spy.
Use `ScrollSpyItem variant="toc"` for each link. Keep `ScrollSpy` as a `div`
inside `Toc`, which already renders a `nav`.

```astro
<Toc aria-label="On this page">
  <TocTitle>On this page</TocTitle>
  <ScrollSpy variant="toc" scrollTarget="html">
    <ScrollSpyTrack variant="toc">
      <TocMenu>
        <TocMenuItem>
          <ScrollSpyItem variant="toc" href="#overview" depth={2}>
            Overview
          </ScrollSpyItem>
        </TocMenuItem>
      </TocMenu>
    </ScrollSpyTrack>
  </ScrollSpy>
</Toc>
```

The short sections below put several headings in view at once. The example uses
the Toc wrapper and list parts. Scroll to see the highlight change as headings
enter or leave the viewport.

```astro
---
import {
  ScrollSpy,
  ScrollSpyItem,
  ScrollSpyTrack,
} from "@/components/ui/scroll-spy"
import { Toc, TocMenu, TocMenuItem, TocTitle } from "@/components/ui/toc"

const id = `toc-${crypto.randomUUID()}`
const items = [
  {
    label: "Overview",
    depth: 2,
    text: "Start with the features your site needs.",
  },
  { label: "Install", depth: 2, text: "Add the package to your project." },
  { label: "Flags", depth: 3, text: "Set options for your build." },
  { label: "Addons", depth: 3, text: "Add optional tools when you need them." },
  { label: "Deploy", depth: 2, text: "Build the site for production." },
  { label: "Hosting", depth: 3, text: "Publish the build to your host." },
  {
    label: "Next steps",
    depth: 2,
    text: "Check the pages and links on your site.",
  },
]
---

<section
  data-progress-section
  class="relative grid w-full grid-cols-[minmax(7rem,2fr)_minmax(0,3fr)] gap-4 sm:grid-cols-[11rem_1fr] sm:gap-6"
>
  <div class="relative">
    <Toc aria-label="On this page" class="sticky top-24">
      <TocTitle>On this page</TocTitle>
      <ScrollSpy
        variant="toc"
        scrollTarget="html"
        progressTarget="[data-progress-section]"
      >
        <ScrollSpyTrack variant="toc">
          <TocMenu>
            {items.map((item, i) => (
              <TocMenuItem>
                <ScrollSpyItem
                  variant="toc"
                  href={`#${id}-${i}`}
                  depth={item.depth}
                >
                  {item.label}
                </ScrollSpyItem>
              </TocMenuItem>
            ))}
          </TocMenu>
        </ScrollSpyTrack>
      </ScrollSpy>
    </Toc>
  </div>
  <div>
    {items.map((item, i) => {
      const Heading = item.depth === 3 ? "h3" : "h2"
      return (
        <section class="flex min-h-[30vh] flex-col gap-3 border-t py-6">
          <Heading id={`${id}-${i}`} class="scroll-mt-24 text-base font-medium">
            {item.label}
          </Heading>
          <p class="text-sm leading-relaxed text-muted-foreground">
            {item.text}
          </p>
        </section>
      )
    })}
  </div>
</section>
```

`scroll-spy-toc.ts` is the internal path-drawing helper used by `ScrollSpyTrack`.
Use the exported Astro parts for composition. The TOC link content comes from
the slot in `ScrollSpyItem`, while `href` names the heading it tracks.

## Position and scroll source

| Position | Effect |
| --- | --- |
| `position="fixed"` | Keeps the indicator at the viewport edge. |
| `position="absolute"` | Anchors the indicator inside a positioned ancestor. |
| `position="relative"` | Keeps the indicator in normal flow. |
| Tailwind classes | Set offsets, or change positioning to `sticky`. |

The script finds the nearest ancestor with vertical `overflow: auto`, `scroll`,
or `hidden`. If there is none, it uses
[`document.scrollingElement`](https://developer.mozilla.org/en-US/docs/Web/API/Document/scrollingElement).
It uses the document's `<html>` element if that property is null.
A `relative` class controls the containing block for absolute positioning;
it does not make that element scrollable. Use `overflow-clip` when you need
clipping without a scroll source. Fixed positioning does not change which
ancestor the script tracks.

To select a scroll container yourself, pass a CSS selector to `scrollTarget`:

```astro
<div id="reader" class="h-96 overflow-y-auto">
  <article class="min-h-288">...</article>
</div>

<ScrollSpy scrollTarget="#reader" />
```

The indicator can be outside the selected container. The selector uses the first
matching HTML element in the document. Section links must point to sections
inside that container. Use `scrollTarget="html"` or `scrollTarget="body"` to
track the page explicitly.

The target must exist when the component initializes. An invalid selector or a
missing target leaves the indicator empty. It does not track a different source.
An omitted or blank selector keeps automatic parent detection.

### Track one section

Use `progressTarget` to measure one section within the scroll container. The
nearest matching ancestor is used first, then the first document match.

```astro
<section data-reading-section class="min-h-[160vh]">
  <div class="sticky top-24">
    <ScrollSpy
      scrollTarget="html"
      progressTarget="[data-reading-section]"
      position="relative"
    />
  </div>
</section>
```

For a nested scroll container, also set `position: relative` on that container
so Motion can measure the section's position.

Progress starts when the section top reaches the scroll viewport top. It ends
when the section bottom reaches the viewport bottom. The section must be taller
than the viewport; otherwise progress stays at 0. A missing or invalid target
also stays at 0. Omit `progressTarget` to measure the whole scroll container.

### With Scroll Area

[Scroll Area](/ui/components/scroll-area) works with the same component. Give its
scrolling viewport an ID through `viewportProps`, then use that ID as the target:

```astro
---
import { ScrollArea } from "@/components/ui/scroll-area"
import { ScrollSpy, ScrollSpyTrack } from "@/components/ui/scroll-spy"

const sections = [
  {
    title: "Choose a place",
    text: "Pick somewhere close enough to reach without a long journey. A nearby town, a walking trail, or a small stretch of coast can give you space to slow down.",
  },
  {
    title: "Pack less",
    text: "Take comfortable shoes, a warm layer, and a book you want to read. Leave room in your bag for food from a local shop or something you find along the way.",
  },
  {
    title: "Start on foot",
    text: "Walk without a fixed route for the first hour. Look for a quiet street, a public garden, or a place to sit. Small details are easier to notice when you have time.",
  },
  {
    title: "Make time for lunch",
    text: "Choose a place where you can sit for a while. Try a local dish, ask about the area, or watch the street from a window. There is no need to rush to the next stop.",
  },
  {
    title: "Leave an afternoon open",
    text: "Keep part of the day free. You might find a museum, follow a path, or return to the same bench with your book. A good weekend does not need a full schedule.",
  },
  {
    title: "Bring something back",
    text: "Before you leave, write down one thing you want to remember. It can be a view, a conversation, or a new idea. Give yourself enough time for a calm journey home.",
  },
]
---

<div class="flex w-full max-w-xl flex-col gap-4">
  <div>
    <p class="font-medium">Reading progress</p>
    <p class="text-sm text-muted-foreground">
      Scroll inside the panel to fill the progress bar.
    </p>
  </div>
  <ScrollSpy
    scrollTarget="#scroll-spy-reading-viewport"
    orientation="horizontal"
    position="relative"
    class="w-full"
    aria-hidden="true"
  >
    <ScrollSpyTrack
      orientation="horizontal"
      class="h-1 overflow-hidden rounded-full"
    />
  </ScrollSpy>
  <ScrollArea
    class="h-80 w-full rounded-xl border"
    aria-label="A quiet weekend"
    viewportProps={{ id: "scroll-spy-reading-viewport" }}
    overscrollContain
  >
    <article class="flex flex-col gap-6 p-6 text-sm leading-relaxed">
      <h3 class="text-lg font-semibold">A quiet weekend</h3>
      {sections.map(({ title, text }) => (
        <section class="flex flex-col gap-2">
          <h4 class="font-medium">{title}</h4>
          <p class="text-muted-foreground">{text}</p>
        </section>
      ))}
    </article>
  </ScrollArea>
</div>
```

The viewport must have enough content to scroll. Target the inner viewport,
not the outer `ScrollArea` wrapper. A `ScrollSpy` placed inside the viewport
can omit `scrollTarget` and use automatic parent detection. Progress tracks the
vertical scroll distance, including when the indicator uses a horizontal layout.

## Behavior and access

`animate` from `motion/mini` animates the registered `--scroll-spy` property.
[Motion's `scroll()` utility](https://motion.dev/docs/scroll) connects that
animation to a native `ScrollTimeline` or `ViewTimeline` where supported, and
uses JavaScript measurements otherwise.

`scrollInfo()` supplies the measurements for progress events, section links,
and range checks, including when a native timeline controls the fill.
For the rail, the component selects the active link at a reading line 45% down
the viewport. The first and last links are selected at the scroll boundaries,
including a short final section. Motion shares its scroll listener between
instances that use the same container.

A view timeline uses the target's nearest scroll container. When an explicit
`scrollTarget` selects an outer container, or scroll padding would change the
range, measured progress sets the mini animation's time instead. The same fallback handles incomplete native timeline
support. If animation creation fails, the script updates the local CSS property.
Progress belongs to each component root; there is no document-wide Motion value.

Native timelines update with the scroll range. Motion refreshes section
measurements when the viewport or scrollable content size changes. A section
that becomes shorter than the viewport resets to 0 on either path.
The script cancels Motion animations and listeners before Astro changes the page.
It does not observe document mutations. For a new client-created root outside
Astro navigation, call `createScrollSpy(root)` from `scroll-spy.ts` and retain
the returned controller. Call `controller.destroy()` before removing or
restarting that instance. The fill is decorative and does not announce every scroll update.
Links retain native keyboard and fragment navigation.

JavaScript initializes the timelines and manages section links. With JavaScript
off, native links still work and the fill stays empty.

All five variants share this scroll state. The TOC uses the same scroll listener
to check which targets are visible. Its path drawing lives in `scroll-spy-toc.ts`.
It does not need a separate visibility observer.

A reduced-motion preference removes mark transitions, the gooey filter, and the
orbiting dot. The line and ring still show progress. The component does not set
smooth scrolling.

## API reference

See the [installed source](/ui/r/scroll-spy.json) for the complete component files.

The root, track, and indicator default to `div` and accept an `as` prop.
`ScrollSpyItem` is an anchor with a required `href`
fragment, optional slot content, and native anchor attributes.

### Browser controller and progress event

Import the browser API from `@/components/ui/scroll-spy/scroll-spy.ts`.

| API                               | Result                                                                                           |
| --------------------------------- | ------------------------------------------------------------------------------------------------ |
| `create(scope = document)`        | Binds all unbound scroll-spy roots inside the scope and returns `ScrollSpyController[]`.         |
| `createScrollSpy(root, options?)` | Binds one root and returns its `ScrollSpyController`. Repeated calls return the same controller. |
| `controller.progress`             | Current numeric progress from 0 to 1. Starts at 0 until the first measurement.                   |
| `controller.destroy()`            | Stops tracking, clears the binding, and resets progress and link state. Safe to call again.      |

`ScrollSpyControllerOptions` can override `variant`, `scrollTarget`, and
`progressTarget` from the root's data attributes. To change a bound instance,
destroy it, then create it with the new options.

The root emits a bubbling `scroll-spy:progress` event after the first measurement
and when progress changes. Its typed detail is `{ progress: number }`.
Progress is 0 when there is no scroll range, and 1 at the end of the range.
Invalid or missing target selectors leave an inactive controller at 0.
The controller emits no events after destruction.

Use the current value to set an initial total, then listen for changes:

```ts
import { createScrollSpy } from "@/components/ui/scroll-spy/scroll-spy.ts"

const root = document.querySelector<HTMLElement>("#reading-progress")!
const output = document.querySelector<HTMLOutputElement>("#reading-percent")!
const controller = createScrollSpy(root)

function updateTotal(progress: number) {
    output.value = `${Math.round(progress * 100)}%`
}

updateTotal(controller.progress)
root.addEventListener("scroll-spy:progress", (event) => {
    if (event.target === root) updateTotal(event.detail.progress)
})
```

Supply `id="reading-progress"` on `ScrollSpy` and use
`<output id="reading-percent">0%</output>` for the total. Check `event.target`
when listening on an ancestor or a root that contains another scroll spy.

The previous `create(root)` API returned a cleanup function. Replace it with
`createScrollSpy(root)` and replace the cleanup call with `controller.destroy()`.

### ScrollSpyOptions

<AutoTypeTable
    path="../../packages/ui/src/components/ui/scroll-spy/types.ts"
    name="ScrollSpyOptions"
/>

### ScrollSpyTrackProps

<AutoTypeTable
    path="../../packages/ui/src/components/ui/scroll-spy/types.ts"
    name="ScrollSpyTrackProps"
/>

### ScrollSpyIndicatorProps

<AutoTypeTable
    path="../../packages/ui/src/components/ui/scroll-spy/types.ts"
    name="ScrollSpyIndicatorProps"
/>

### ScrollSpyItemProps

<AutoTypeTable
    path="../../packages/ui/src/components/ui/scroll-spy/types.ts"
    name="ScrollSpyItemProps"
/>

## Theme and layout

Parts use the primary, foreground, background, and border tokens. Use Tailwind
classes to set dimensions and offsets. Leave room beside content for
fixed section links. Keep the rail short enough to fit on the smallest screen.

The parts contain their Tailwind classes. There is no separate ScrollSpy
stylesheet. The root registers `--scroll-spy` as a number for the native progress
animation. Each instance stores its progress value on its own root.
The TOC uses `--scroll-spy-track-top` and `--scroll-spy-track-bottom` with local
zero defaults. These values do not need property registration: the transition
animates `clip-path`. Its slots are `scroll-spy-toc`, `scroll-spy-toc-svg`,
`scroll-spy-toc-path` for the full path, and `scroll-spy-toc-highlight` for the
visible range. The old spine and thumb slot names are removed.

The root uses CVA. Its `scrollSpyVariants` function and inferred
`ScrollSpyVariantProps` type are exported from the component index.

Replace `<ScrollSpyTrack><ScrollSpyFill /></ScrollSpyTrack>` with
`<ScrollSpyTrack />`. The separate fill component is removed. Set visual props on
custom slotted parts explicitly. `create()` handles scroll progress and active
links; it does not generate visual parts or change their classes.

The section rail takes its direction from [Albina Nikiforova's site](https://albinanikiforova.com/).
The contents spine takes its direction from the [Fumadocs table of contents](https://github.com/fuma-nama/fumadocs/blob/d6cfc48d62aa9ea413f0fc5033617c0c923681ec/packages/base-ui/src/components/toc/default.tsx), as used on the [Better-T-Stack docs](https://www.better-t-stack.dev/docs).
