# Table of contents

> In-page link list with two visual levels and an active marker that follows the URL fragment.

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

## Use when
- A long guide needs jump links to named sections and subsections
- Readers need a shareable link to the exact section they selected

## Avoid when
- The links go to separate pages. Use sidebar.
- The trail should reflect page ancestry. Use breadcrumb.

## Alternatives
- [sidebar](https://hazeui.com/ui/sidebar.md)
- [breadcrumb](https://hazeui.com/ui/breadcrumb.md)
- [scroll-progress](https://hazeui.com/ui/scroll-progress.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| items | `{ id: string; label: string; level?: 1 \| 2 }[]` |  | yes | Use each heading target's ID without a hash. Level two entries are indented. |
| label | `string` | "On this page" | no | Visible and accessible name of the navigation landmark. |
| current | `string` |  | no | Initial section ID. A matching browser fragment takes priority. |
| class | `string` |  | no | Additional classes for placement, including sticky positioning when appropriate. |

## Accessibility
- Links navigate natively to matching IDs, including when JavaScript is disabled.
- The matching fragment is marked with aria-current=location when scripts run.
- Use focusable targets when keyboard users should resume navigation at a selected section.
- Key Tab: Move between section links.
- Key Enter: Jump to the selected heading or region.

## Agent prompts

### Install and use

Install the Haze UI component "Table of contents" with `npx shadcn@latest add @haze/table-of-contents`. 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 TableOfContents from "@/components/haze/ui/table-of-contents.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/table-of-contents.md

### Customize with real content

Adapt the Haze table-of-contents ui for our product. Replace the demo values of these props with our real content: items, label, current, class. Keep the layout, the heading level rules and these accessibility details: Links navigate natively to matching IDs, including when JavaScript is disabled. The matching fragment is marked with aria-current=location when scripts run. Use focusable targets when keyboard users should resume navigation at a selected section. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using table-of-contents, check it fits: use it when a long guide needs jump links to named sections and subsections; readers need a shareable link to the exact section they selected. Avoid it when the links go to separate pages. use sidebar.; the trail should reflect page ancestry. use breadcrumb.. Alternatives: @haze/sidebar, @haze/breadcrumb, @haze/scroll-progress.

## Example requests that should lead here
- Add an On this page list to a long documentation article with one nested heading
- Highlight the linked section when someone opens a deep link to the setup guide

## Source

```astro
---
import { ListTree } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface HeadingLink { id: string; label: string; level?: 1 | 2 }
interface Props {
  items: HeadingLink[];
  label?: string;
  current?: string;
  class?: string;
}

const { items, label = "On this page", current, class: className } = Astro.props;
---

<nav aria-label={label} data-haze-table-of-contents class={cn("grid min-w-0 content-start gap-2", className)}>
  <p class="flex items-center gap-2 text-[0.8125rem]/5 font-medium wrap-anywhere">
    <ListTree class="size-4 shrink-0 text-muted-foreground" aria-hidden="true" />{label}
  </p>
  <div class="relative">
  <span data-toc-indicator aria-hidden="true" class="pointer-events-none absolute top-0 left-0 h-(--toc-h) w-0.5 translate-y-(--toc-y) rounded-full bg-foreground opacity-0 data-[on]:opacity-100 [[data-ready]_&]:transition-[translate,height,opacity] [[data-ready]_&]:duration-300 [[data-ready]_&]:ease-snappy motion-reduce:[[data-ready]_&]:transition-none forced-colors:forced-color-adjust-none forced-colors:bg-[Highlight]"></span>
  <ul role="list" class="grid gap-0.5 border-s border-border ps-1.5">
    {items.map((item) => (
      <li class={cn(item.level === 2 && "ms-3")}>
        <a href={`#${encodeURIComponent(item.id)}`} aria-current={item.id === current ? "location" : undefined} data-haze-toc-default={item.id === current || undefined}
          class="inline-flex min-h-8 items-center rounded-md px-2 py-1.5 text-[0.8125rem]/5 wrap-anywhere text-muted-foreground transition-colors duration-150 ease-snappy motion-reduce:transition-none hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring aria-[current=location]:bg-accent aria-[current=location]:font-medium aria-[current=location]:text-foreground forced-colors:aria-[current=location]:underline">
          {item.label}
        </a>
      </li>
    ))}
  </ul>
  </div>
</nav>

<script>
  function updateCurrentLocation() {
    for (const contents of document.querySelectorAll("[data-haze-table-of-contents]")) {
      const links = [...contents.querySelectorAll<HTMLAnchorElement>("a[href]")];
      const current = links.find((link) => link.hash === location.hash)
        ?? links.find((link) => link.hasAttribute("data-haze-toc-default"));
      for (const link of links) {
        if (link === current) link.setAttribute("aria-current", "location");
        else link.removeAttribute("aria-current");
      }
      const bar = contents.querySelector<HTMLElement>("[data-toc-indicator]");
      if (bar) {
        if (current) {
          bar.style.setProperty("--toc-y", `${current.offsetTop}px`);
          bar.style.setProperty("--toc-h", `${current.offsetHeight}px`);
          bar.setAttribute("data-on", "");
        } else bar.removeAttribute("data-on");
      }
    }
  }
  // The bar slides only after its first placement, so it does not sweep in from the top on load.
  function markReady() {
    requestAnimationFrame(() => requestAnimationFrame(() => document.querySelectorAll("[data-haze-table-of-contents]").forEach((contents) => contents.setAttribute("data-ready", ""))));
  }

  updateCurrentLocation();
  markReady();
  if (!document.documentElement.hasAttribute("data-haze-toc-listeners")) {
    document.documentElement.setAttribute("data-haze-toc-listeners", "");
    window.addEventListener("hashchange", updateCurrentLocation);
    window.addEventListener("resize", updateCurrentLocation);
    document.addEventListener("astro:page-load", () => { updateCurrentLocation(); markReady(); });
  }
</script>
```
