# Scroll index

> Minimal vertical hairline tick rail that tracks scroll progress and reveals floating section label pills on hover or focus.

- Kind: ui · Category: Navigation · Interactivity: script
- Install: `npx shadcn@latest add @haze/scroll-index`
- File: `src/components/haze/ui/scroll-index.astro`
- npm dependencies: none
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/ui/scroll-index

## Use when
- An editorial article or scrollable pane needs a right-edge tick-mark rail instead of a full sidebar list
- Readers want instant visual orientation and smooth section jumping with minimal visual footprint

## Avoid when
- All heading labels must stay permanently visible for scanning; use table-of-contents
- Readers need reading-time estimates and a completion progress bar; use toc-progress

## Alternatives
- [table-of-contents](https://hazeui.com/ui/table-of-contents.md)
- [toc-progress](https://hazeui.com/ui/toc-progress.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique caller-supplied ID for the index navigation landmark. |
| items | `{ id: string; label: string; major?: boolean }[]` | 6 sample sections | no | Section anchor IDs and labels; major draws a medium resting tick while minor draws a short hairline. |
| scrollContainer | `string` |  | no | Optional ID of a scrollable container element; tracks the window when omitted. |
| label | `string` | "Section index" | no | Accessible name for the navigation landmark. |
| side | `"left" \| "right"` | "left" | no | Side of the tick rail where floating section label pills reveal. |
| offset | `number` | 28 | no | Top threshold in pixels used to determine the currently active section. |
| class | `string` |  | no | Additional classes on the outer nav element. |

## Accessibility
- Renders real anchor links inside an ordered list so jumping to sections works without JavaScript.
- Marks the active section link with aria-current="location" and moves focus to the target heading on click.
- Falls back to instant scrolling and disables tick animations when prefers-reduced-motion is enabled.
- Key Tab / Shift+Tab: Enter or leave the vertical tick rail
- Key ArrowUp / ArrowDown: Move focus along the section ticks and reveal each floating label pill
- Key Home / End: Jump focus to the first or last section marker
- Key Enter: Scroll to the target section and move focus to its heading

## Agent prompts

### Install and use

Install the Haze UI component "Scroll index" with `npx shadcn@latest add @haze/scroll-index`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import ScrollIndex from "@/components/haze/ui/scroll-index.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/scroll-index.md

### Customize with real content

Adapt the Haze scroll-index ui for our product. Replace the demo values of these props with our real content: id, items, scrollContainer, label, side, offset, class. Keep the layout, the heading level rules and these accessibility details: Renders real anchor links inside an ordered list so jumping to sections works without JavaScript. Marks the active section link with aria-current="location" and moves focus to the target heading on click. Falls back to instant scrolling and disables tick animations when prefers-reduced-motion is enabled. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using scroll-index, check it fits: use it when an editorial article or scrollable pane needs a right-edge tick-mark rail instead of a full sidebar list; readers want instant visual orientation and smooth section jumping with minimal visual footprint. Avoid it when all heading labels must stay permanently visible for scanning; use table-of-contents; readers need reading-time estimates and a completion progress bar; use toc-progress. Alternatives: @haze/table-of-contents, @haze/toc-progress.

## Example requests that should lead here
- Add an editorial article card with a right-edge hairline tick-mark scroll index and floating hover labels
- Build a compact scrollspy tick rail that widens the active marker and smoothly scrolls on click

## Source

```astro
---
import { cn } from "../../../lib/haze/utils";

interface IndexItem {
  id: string;
  label: string;
  /** Render a medium resting tick for major section headings. */
  major?: boolean;
}

interface Props {
  /** Unique on the page. Identifies this index rail landmark. */
  id: string;
  items?: IndexItem[];
  /** Optional ID of a scrollable element; tracks the page viewport when omitted. */
  scrollContainer?: string;
  /** Accessible name for the navigation landmark. */
  label?: string;
  /** Side of the tick rail where floating label pills appear. */
  side?: "left" | "right";
  /** Top offset in pixels used to determine the active section. */
  offset?: number;
  class?: string;
}

const defaultItems: IndexItem[] = [
  { id: "index-rhythm", label: "Rhythm and density", major: true },
  { id: "index-alignment", label: "Optical alignment" },
  { id: "index-motion", label: "Restrained motion", major: true },
  { id: "index-feedback", label: "Micro-feedback" },
  { id: "index-contrast", label: "Surface contrast", major: true },
  { id: "index-closing", label: "Closing notes" },
];

const {
  id,
  items = defaultItems,
  scrollContainer,
  label = "Section index",
  side = "left",
  offset = 28,
  class: className,
} = Astro.props;
---

<nav
  id={id}
  data-haze-scroll-index
  data-scroll-container={scrollContainer}
  data-offset={offset}
  aria-label={label}
  class={cn("min-w-0", className)}
>
  <ol
    role="list"
    class={cn("flex flex-col gap-0", side === "left" ? "items-end" : "items-start")}
  >
    {
      items.map((item, index) => {
        const isFirst = index === 0;
        return (
          <li class="relative">
            <a
              href={`#${encodeURIComponent(item.id)}`}
              data-si-link
              data-si-index={index}
              aria-current={isFirst ? "location" : undefined}
              class={cn(
                "group relative flex h-6 min-w-7 items-center rounded-sm focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring",
                side === "left" ? "justify-end" : "justify-start",
              )}
            >
              <span
                aria-hidden="true"
                class={cn(
                  "block h-0.5 shrink-0 rounded-full transition-[width,background-color] duration-200 ease-snappy motion-reduce:transition-none",
                  item.major ? "w-3.5 bg-border-strong" : "w-2 bg-border",
                  "group-hover:w-5 group-hover:bg-foreground/80 group-focus-visible:w-5 group-focus-visible:bg-foreground/80",
                  "[[aria-current=location]_&]:w-6 [[aria-current=location]_&]:bg-foreground",
                )}
              ></span>
              <span
                class={cn(
                  "pointer-events-none absolute top-1/2 -translate-y-1/2 whitespace-nowrap rounded-md border border-frame bg-popover px-2 py-0.5 text-xs/4 font-medium text-popover-foreground opacity-0 shadow-key transition-[opacity,translate] duration-150 ease-snappy motion-reduce:transition-none",
                  "group-hover:translate-x-0 group-hover:opacity-100 group-focus-visible:translate-x-0 group-focus-visible:opacity-100",
                  side === "left" ? "right-full me-2 translate-x-1" : "left-full ms-2 -translate-x-1",
                )}
              >
                {item.label}
              </span>
            </a>
          </li>
        );
      })
    }
  </ol>
</nav>

<script>
  function syncScrollIndex(root: HTMLElement) {
    const links = Array.from(root.querySelectorAll<HTMLAnchorElement>("[data-si-link]"));
    if (!links.length) return;
    const targets = links.map((link) => document.getElementById(decodeURIComponent(link.hash.slice(1))));
    const container = root.dataset.scrollContainer ? document.getElementById(root.dataset.scrollContainer) : null;
    const offset = Number(root.dataset.offset) || 0;
    const topEdge = (container?.getBoundingClientRect().top ?? 0) + offset;
    const scrollTop = container ? container.scrollTop : window.scrollY;
    const scrollHeight = container ? container.scrollHeight : document.documentElement.scrollHeight;
    const viewport = container ? container.clientHeight : window.innerHeight;
    const atBottom = scrollTop > 0 && scrollTop + viewport >= scrollHeight - 2;

    let active = 0;
    if (scrollTop <= 2) {
      active = 0;
    } else if (atBottom) {
      active = links.length - 1;
    } else {
      for (let i = 0; i < targets.length; i++) {
        const el = targets[i];
        if (el && el.getBoundingClientRect().top <= topEdge + 12) {
          active = i;
        }
      }
    }

    links.forEach((link, i) => {
      if (i === active) link.setAttribute("aria-current", "location");
      else link.removeAttribute("aria-current");
    });
  }

  function enhanceScrollIndex(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const links = Array.from(root.querySelectorAll<HTMLAnchorElement>("[data-si-link]"));
    if (!links.length) return;
    const container = root.dataset.scrollContainer ? document.getElementById(root.dataset.scrollContainer) : null;
    const reduced = window.matchMedia("(prefers-reduced-motion: reduce)");

    links.forEach((link, index) => {
      link.addEventListener("click", (event) => {
        if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
        const target = document.getElementById(decodeURIComponent(link.hash.slice(1)));
        if (!target) return;
        event.preventDefault();
        if (!target.hasAttribute("tabindex")) target.tabIndex = -1;
        const behavior: ScrollBehavior = reduced.matches ? "auto" : "smooth";
        if (container) {
          const offset = Number(root.dataset.offset) || 0;
          const nextTop = container.scrollTop + target.getBoundingClientRect().top - container.getBoundingClientRect().top - offset + 4;
          container.scrollTo({ top: Math.max(0, nextTop), behavior });
        } else {
          target.scrollIntoView({ block: "start", behavior });
        }
        links.forEach((item, i) => {
          if (i === index) item.setAttribute("aria-current", "location");
          else item.removeAttribute("aria-current");
        });
        target.focus({ preventScroll: true });
        history.replaceState(history.state, "", link.hash);
      });

      link.addEventListener("keydown", (event) => {
        let next: number | undefined;
        if (event.key === "ArrowDown") next = (index + 1) % links.length;
        else if (event.key === "ArrowUp") next = (index - 1 + links.length) % links.length;
        else if (event.key === "Home") next = 0;
        else if (event.key === "End") next = links.length - 1;
        if (next === undefined) return;
        event.preventDefault();
        links[next].focus();
      });
    });

    if (container) {
      let localFrame = 0;
      container.addEventListener(
        "scroll",
        () => {
          if (localFrame) return;
          localFrame = requestAnimationFrame(() => {
            localFrame = 0;
            syncScrollIndex(root);
          });
        },
        { passive: true },
      );
    }

    if ("IntersectionObserver" in window) {
      const targets = links
        .map((link) => document.getElementById(decodeURIComponent(link.hash.slice(1))))
        .filter((el): el is HTMLElement => Boolean(el));
      if (targets.length) {
        const observer = new IntersectionObserver(() => syncScrollIndex(root), {
          root: container,
          threshold: [0, 0.25, 0.5, 1],
        });
        targets.forEach((el) => observer.observe(el));
      }
    }

    root.setAttribute("data-enhanced", "");
    syncScrollIndex(root);
  }

  const updateAllScrollIndices = () => {
    document.querySelectorAll<HTMLElement>("[data-haze-scroll-index][data-enhanced]").forEach(syncScrollIndex);
  };

  const initScrollIndices = () => {
    document.querySelectorAll<HTMLElement>("[data-haze-scroll-index]").forEach(enhanceScrollIndex);
  };
  initScrollIndices();

  if (!document.documentElement.hasAttribute("data-haze-scroll-index-listener")) {
    document.documentElement.setAttribute("data-haze-scroll-index-listener", "");
    let frame = 0;
    document.addEventListener(
      "scroll",
      () => {
        if (frame) return;
        frame = requestAnimationFrame(() => {
          frame = 0;
          updateAllScrollIndices();
        });
      },
      true,
    );
    window.addEventListener("resize", updateAllScrollIndices, { passive: true });
    window.addEventListener("hashchange", updateAllScrollIndices);
    document.addEventListener("astro:page-load", initScrollIndices);
  }
</script>
```
