# Table of Contents

Document navigation with six indicator styles, section tracking, and an expandable minimap.

Navigate an article through heading links and keep the reading location visible as its content scrolls. The component uses native navigation and Zenos theme tokens, with no additional dependency.

```tsx
import { useId, useRef, useState } from "react";
import { Stack, Text, TableOfContents, useHeadings, type TableOfContentsVariant, type TableOfContentsClassNames, type Density } from "@zentara-co/zenos-ui";

const sections = [
  {
    text: "Overview",
    level: 2 as const,
    body: "Use a table of contents to help readers navigate a long document.",
  },
  {
    text: "Installation",
    level: 2 as const,
    body: "Import components from the public Zenos UI package and load the stylesheet once.",
  },
  {
    text: "Package setup",
    level: 3 as const,
    body: "Keep package imports at the application boundary so examples work in consumer projects.",
  },
  {
    text: "Theme setup",
    level: 3 as const,
    body: "Semantic colors follow the active theme. Use logical spacing for right-to-left layouts.",
  },
  {
    text: "Configuration",
    level: 2 as const,
    body: "Choose a visual variant and density that fit the surrounding document.",
  },
  {
    text: "Keyboard access",
    level: 2 as const,
    body: "Tab through native links and press Enter to navigate. The current link identifies the reading location.",
  },
  {
    text: "Motion",
    level: 2 as const,
    body: "Transitions stop when reduced motion is enabled. Headings can reserve space below a sticky header.",
  },
  {
    text: "Next steps",
    level: 2 as const,
    body: "Test your page with long headings, a narrow viewport, and each supported theme.",
  },
];

function ContentsDemo({
  classNames,
  label = "Document contents",
  variant = "line",
  numbered = false,
  limit,
  density = "compact",
  discover = false,
}: {
  classNames?: TableOfContentsClassNames;
  label?: string;
  variant?: TableOfContentsVariant;
  numbered?: boolean;
  limit?: number;
  density?: Density;
  discover?: boolean;
}) {
  const prefix = useId();
  const container = useRef<HTMLDivElement>(null);
  const [active, setActive] = useState(`${prefix}-0`);
  const headings = useHeadings(
    `[data-toc-article="${prefix}"] h2[id], [data-toc-article="${prefix}"] h3[id]`,
  );
  const items = discover
    ? headings
    : sections.map((section, index) => ({ ...section, id: `${prefix}-${index}` }));
  return (
    <Stack gap="3" className="w-full">
      <Text size="s" color="subtle">
        Reading: {sections.find((_, index) => `${prefix}-${index}` === active)?.text ?? "Overview"}
      </Text>
      <div className="grid min-w-0 gap-5 sm:grid-cols-[minmax(0,1fr)_minmax(0,180px)]">
        <div
          ref={container}
          tabIndex={0}
          role="region"
          aria-label="Example document"
          data-toc-article={prefix}
          className="h-72 min-w-0 overflow-auto rounded-lg border border-border-default p-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focused"
        >
          {sections.map((section, index) => (
            <section key={section.text} className="min-h-48 pb-8">
              <Text
                as={section.level === 3 ? "h3" : "h2"}
                id={`${prefix}-${index}`}
                weight="semibold"
                className="mb-3 scroll-mt-4"
              >
                {section.text}
              </Text>
              <Text size="s" color="subtle">
                {section.body}
              </Text>
            </section>
          ))}
        </div>
        <div className={variant === "minimap" ? "justify-self-end" : "min-w-0"}>
          <TableOfContents
            classNames={classNames}
            variant={variant}
            container={container}
            density={density}
            numbered={numbered}
            value={active}
            onValueChange={setActive}
            aria-label={label}
          >
            <TableOfContents.Title>On this page</TableOfContents.Title>
            <TableOfContents.List limit={limit}>
              {items.map((item) => (
                <TableOfContents.Item
                  key={item.id}
                  href={`#${encodeURIComponent(item.id)}`}
                  level={item.level}
                >
                  {item.text}
                </TableOfContents.Item>
              ))}
            </TableOfContents.List>
          </TableOfContents>
        </div>
      </div>
    </Stack>
  );
}

function TableOfContentsExample() {
  return <ContentsDemo />;
}
```

## Usage

```tsx
import { TableOfContents } from "@zentara-co/zenos-ui";

<TableOfContents defaultValue="overview" aria-label="Article contents">
  <TableOfContents.Title>On this page</TableOfContents.Title>
  <TableOfContents.List>
    <TableOfContents.Item href="#overview">Overview</TableOfContents.Item>
    <TableOfContents.Item href="#installation">Installation</TableOfContents.Item>
    <TableOfContents.Item href="#themes" level={3}>
      Themes
    </TableOfContents.Item>
  </TableOfContents.List>
</TableOfContents>;
```

Give the corresponding headings unique IDs. Put `scroll-margin-top` on those headings to leave space below a fixed header. Native window links retain hash navigation, modifier clicks, and browser history. Pass a ref through `container` for an independently scrolling document: activation scrolls that element and updates the hash without moving the surrounding page.

Use `className="sticky top-20"` on the root when the page layout needs a fixed reading rail. The component does not choose the page's column layout or header offset.

## Six variants

Inspired by the visual treatments in [Koala UI's Table of Contents](https://www.koalaui.com/docs/components/table-of-contents), implemented with Zenos components and tokens.

- `line`: a short moving indicator beside a thin vertical track.
- `progress`: a track that fills through the current row.
- `pill`: a moving background behind the current link.
- `dash`: a leading rule that lengthens for the current link.
- `plain`: foreground and weight identify the current link.
- `minimap`: a compact document outline that expands into navigation.

All six lists below navigate the same scroll pane. Scroll it or activate a link to compare the indicators.

```tsx
import { useId, useRef } from "react";
import { Stack, Text, TableOfContents } from "@zentara-co/zenos-ui";

const sections = [
  {
    text: "Overview",
    level: 2 as const,
    body: "Use a table of contents to help readers navigate a long document.",
  },
  {
    text: "Installation",
    level: 2 as const,
    body: "Import components from the public Zenos UI package and load the stylesheet once.",
  },
  {
    text: "Package setup",
    level: 3 as const,
    body: "Keep package imports at the application boundary so examples work in consumer projects.",
  },
  {
    text: "Theme setup",
    level: 3 as const,
    body: "Semantic colors follow the active theme. Use logical spacing for right-to-left layouts.",
  },
  {
    text: "Configuration",
    level: 2 as const,
    body: "Choose a visual variant and density that fit the surrounding document.",
  },
  {
    text: "Keyboard access",
    level: 2 as const,
    body: "Tab through native links and press Enter to navigate. The current link identifies the reading location.",
  },
  {
    text: "Motion",
    level: 2 as const,
    body: "Transitions stop when reduced motion is enabled. Headings can reserve space below a sticky header.",
  },
  {
    text: "Next steps",
    level: 2 as const,
    body: "Test your page with long headings, a narrow viewport, and each supported theme.",
  },
];

function TableOfContentsVariantsExample() {
  const prefix = useId();
  const container = useRef<HTMLDivElement>(null);
  return (
    <Stack gap="5" className="w-full">
      <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
        {(["line", "progress", "pill", "dash", "plain", "minimap"] as const).map((variant) => (
          <div key={variant} className="min-w-0">
            <Text size="s" weight="semibold" className="mb-3">
              {variant}
            </Text>
            <div className={variant === "minimap" ? "flex justify-end" : ""}>
              <TableOfContents
                variant={variant}
                container={container}
                density="compact"
                defaultValue={`${prefix}-0`}
                aria-label={`${variant} contents`}
              >
                <TableOfContents.Title>On this page</TableOfContents.Title>
                <TableOfContents.List>
                  {sections.slice(0, 5).map((section, index) => (
                    <TableOfContents.Item
                      key={section.text}
                      href={`#${encodeURIComponent(`${prefix}-${index}`)}`}
                      level={section.level}
                    >
                      {section.text}
                    </TableOfContents.Item>
                  ))}
                </TableOfContents.List>
              </TableOfContents>
            </div>
          </div>
        ))}
      </div>
      <div
        ref={container}
        tabIndex={0}
        role="region"
        aria-label="Variant example document"
        className="h-48 overflow-auto rounded-lg border border-border-default p-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focused"
      >
        {sections.slice(0, 5).map((section, index) => (
          <section key={section.text} className="min-h-48 pb-8">
            <Text
              as={section.level === 3 ? "h3" : "h2"}
              id={`${prefix}-${index}`}
              weight="semibold"
              className="mb-3 scroll-mt-4"
            >
              {section.text}
            </Text>
            <Text size="s" color="subtle">
              {section.body}
            </Text>
          </section>
        ))}
      </div>
    </Stack>
  );
}
```

## Minimap

Place a minimap at the document's trailing edge; the panel opens inward, including in RTL layouts. Hover the dashes, focus the trigger with Tab, or tap it to reveal the links. Keyboard focus keeps the panel available; Escape dismisses it and returns focus to the trigger. Pointer activation lets the panel close when the pointer leaves.

Without JavaScript, the link list remains visible. The hydrated minimap is a button-controlled panel, with an accessible name and `aria-expanded` state.

The collapsed dashes sit 12px apart in either density. Expanded links retain the normal row height, and the trigger remains at least 44px tall.

```tsx
import { useId, useRef, useState } from "react";
import { Stack, Text, TableOfContents, useHeadings, type TableOfContentsVariant, type TableOfContentsClassNames, type Density } from "@zentara-co/zenos-ui";

const sections = [
  {
    text: "Overview",
    level: 2 as const,
    body: "Use a table of contents to help readers navigate a long document.",
  },
  {
    text: "Installation",
    level: 2 as const,
    body: "Import components from the public Zenos UI package and load the stylesheet once.",
  },
  {
    text: "Package setup",
    level: 3 as const,
    body: "Keep package imports at the application boundary so examples work in consumer projects.",
  },
  {
    text: "Theme setup",
    level: 3 as const,
    body: "Semantic colors follow the active theme. Use logical spacing for right-to-left layouts.",
  },
  {
    text: "Configuration",
    level: 2 as const,
    body: "Choose a visual variant and density that fit the surrounding document.",
  },
  {
    text: "Keyboard access",
    level: 2 as const,
    body: "Tab through native links and press Enter to navigate. The current link identifies the reading location.",
  },
  {
    text: "Motion",
    level: 2 as const,
    body: "Transitions stop when reduced motion is enabled. Headings can reserve space below a sticky header.",
  },
  {
    text: "Next steps",
    level: 2 as const,
    body: "Test your page with long headings, a narrow viewport, and each supported theme.",
  },
];

function ContentsDemo({
  classNames,
  label = "Document contents",
  variant = "line",
  numbered = false,
  limit,
  density = "compact",
  discover = false,
}: {
  classNames?: TableOfContentsClassNames;
  label?: string;
  variant?: TableOfContentsVariant;
  numbered?: boolean;
  limit?: number;
  density?: Density;
  discover?: boolean;
}) {
  const prefix = useId();
  const container = useRef<HTMLDivElement>(null);
  const [active, setActive] = useState(`${prefix}-0`);
  const headings = useHeadings(
    `[data-toc-article="${prefix}"] h2[id], [data-toc-article="${prefix}"] h3[id]`,
  );
  const items = discover
    ? headings
    : sections.map((section, index) => ({ ...section, id: `${prefix}-${index}` }));
  return (
    <Stack gap="3" className="w-full">
      <Text size="s" color="subtle">
        Reading: {sections.find((_, index) => `${prefix}-${index}` === active)?.text ?? "Overview"}
      </Text>
      <div className="grid min-w-0 gap-5 sm:grid-cols-[minmax(0,1fr)_minmax(0,180px)]">
        <div
          ref={container}
          tabIndex={0}
          role="region"
          aria-label="Example document"
          data-toc-article={prefix}
          className="h-72 min-w-0 overflow-auto rounded-lg border border-border-default p-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focused"
        >
          {sections.map((section, index) => (
            <section key={section.text} className="min-h-48 pb-8">
              <Text
                as={section.level === 3 ? "h3" : "h2"}
                id={`${prefix}-${index}`}
                weight="semibold"
                className="mb-3 scroll-mt-4"
              >
                {section.text}
              </Text>
              <Text size="s" color="subtle">
                {section.body}
              </Text>
            </section>
          ))}
        </div>
        <div className={variant === "minimap" ? "justify-self-end" : "min-w-0"}>
          <TableOfContents
            classNames={classNames}
            variant={variant}
            container={container}
            density={density}
            numbered={numbered}
            value={active}
            onValueChange={setActive}
            aria-label={label}
          >
            <TableOfContents.Title>On this page</TableOfContents.Title>
            <TableOfContents.List limit={limit}>
              {items.map((item) => (
                <TableOfContents.Item
                  key={item.id}
                  href={`#${encodeURIComponent(item.id)}`}
                  level={item.level}
                >
                  {item.text}
                </TableOfContents.Item>
              ))}
            </TableOfContents.List>
          </TableOfContents>
        </div>
      </div>
    </Stack>
  );
}

function TableOfContentsMinimapExample() {
  return <ContentsDemo variant="minimap" label="Minimap article contents" />;
}
```

## Nested and numbered links

Use `level={3}` for a subsection. Numbering follows the order of direct `Item` children: sections use `1.`, `2.`, and subsections use `2.1`, `2.2`. Numbers are decorative; the ordered list supplies the accessible order. Keep items as direct children of `List`, including when mapping an array.

```tsx
import { useId, useRef, useState } from "react";
import { Stack, Text, TableOfContents, useHeadings, type TableOfContentsVariant, type TableOfContentsClassNames, type Density } from "@zentara-co/zenos-ui";

const sections = [
  {
    text: "Overview",
    level: 2 as const,
    body: "Use a table of contents to help readers navigate a long document.",
  },
  {
    text: "Installation",
    level: 2 as const,
    body: "Import components from the public Zenos UI package and load the stylesheet once.",
  },
  {
    text: "Package setup",
    level: 3 as const,
    body: "Keep package imports at the application boundary so examples work in consumer projects.",
  },
  {
    text: "Theme setup",
    level: 3 as const,
    body: "Semantic colors follow the active theme. Use logical spacing for right-to-left layouts.",
  },
  {
    text: "Configuration",
    level: 2 as const,
    body: "Choose a visual variant and density that fit the surrounding document.",
  },
  {
    text: "Keyboard access",
    level: 2 as const,
    body: "Tab through native links and press Enter to navigate. The current link identifies the reading location.",
  },
  {
    text: "Motion",
    level: 2 as const,
    body: "Transitions stop when reduced motion is enabled. Headings can reserve space below a sticky header.",
  },
  {
    text: "Next steps",
    level: 2 as const,
    body: "Test your page with long headings, a narrow viewport, and each supported theme.",
  },
];

function ContentsDemo({
  classNames,
  label = "Document contents",
  variant = "line",
  numbered = false,
  limit,
  density = "compact",
  discover = false,
}: {
  classNames?: TableOfContentsClassNames;
  label?: string;
  variant?: TableOfContentsVariant;
  numbered?: boolean;
  limit?: number;
  density?: Density;
  discover?: boolean;
}) {
  const prefix = useId();
  const container = useRef<HTMLDivElement>(null);
  const [active, setActive] = useState(`${prefix}-0`);
  const headings = useHeadings(
    `[data-toc-article="${prefix}"] h2[id], [data-toc-article="${prefix}"] h3[id]`,
  );
  const items = discover
    ? headings
    : sections.map((section, index) => ({ ...section, id: `${prefix}-${index}` }));
  return (
    <Stack gap="3" className="w-full">
      <Text size="s" color="subtle">
        Reading: {sections.find((_, index) => `${prefix}-${index}` === active)?.text ?? "Overview"}
      </Text>
      <div className="grid min-w-0 gap-5 sm:grid-cols-[minmax(0,1fr)_minmax(0,180px)]">
        <div
          ref={container}
          tabIndex={0}
          role="region"
          aria-label="Example document"
          data-toc-article={prefix}
          className="h-72 min-w-0 overflow-auto rounded-lg border border-border-default p-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focused"
        >
          {sections.map((section, index) => (
            <section key={section.text} className="min-h-48 pb-8">
              <Text
                as={section.level === 3 ? "h3" : "h2"}
                id={`${prefix}-${index}`}
                weight="semibold"
                className="mb-3 scroll-mt-4"
              >
                {section.text}
              </Text>
              <Text size="s" color="subtle">
                {section.body}
              </Text>
            </section>
          ))}
        </div>
        <div className={variant === "minimap" ? "justify-self-end" : "min-w-0"}>
          <TableOfContents
            classNames={classNames}
            variant={variant}
            container={container}
            density={density}
            numbered={numbered}
            value={active}
            onValueChange={setActive}
            aria-label={label}
          >
            <TableOfContents.Title>On this page</TableOfContents.Title>
            <TableOfContents.List limit={limit}>
              {items.map((item) => (
                <TableOfContents.Item
                  key={item.id}
                  href={`#${encodeURIComponent(item.id)}`}
                  level={item.level}
                >
                  {item.text}
                </TableOfContents.Item>
              ))}
            </TableOfContents.List>
          </TableOfContents>
        </div>
      </div>
    </Stack>
  );
}

function TableOfContentsNumberedExample() {
  return <ContentsDemo numbered variant="plain" label="Numbered article contents" />;
}
```

## Fold long lists

`List.limit` adds an expand control when there are at least three extra items. A newly active hidden section reveals its row automatically. `moreLabel` receives the hidden count; `lessLabel` customizes the collapse text. These are buttons with `aria-expanded` and `aria-controls`.

```tsx
import { useId, useRef, useState } from "react";
import { Stack, Text, TableOfContents, useHeadings, type TableOfContentsVariant, type TableOfContentsClassNames, type Density } from "@zentara-co/zenos-ui";

const sections = [
  {
    text: "Overview",
    level: 2 as const,
    body: "Use a table of contents to help readers navigate a long document.",
  },
  {
    text: "Installation",
    level: 2 as const,
    body: "Import components from the public Zenos UI package and load the stylesheet once.",
  },
  {
    text: "Package setup",
    level: 3 as const,
    body: "Keep package imports at the application boundary so examples work in consumer projects.",
  },
  {
    text: "Theme setup",
    level: 3 as const,
    body: "Semantic colors follow the active theme. Use logical spacing for right-to-left layouts.",
  },
  {
    text: "Configuration",
    level: 2 as const,
    body: "Choose a visual variant and density that fit the surrounding document.",
  },
  {
    text: "Keyboard access",
    level: 2 as const,
    body: "Tab through native links and press Enter to navigate. The current link identifies the reading location.",
  },
  {
    text: "Motion",
    level: 2 as const,
    body: "Transitions stop when reduced motion is enabled. Headings can reserve space below a sticky header.",
  },
  {
    text: "Next steps",
    level: 2 as const,
    body: "Test your page with long headings, a narrow viewport, and each supported theme.",
  },
];

function ContentsDemo({
  classNames,
  label = "Document contents",
  variant = "line",
  numbered = false,
  limit,
  density = "compact",
  discover = false,
}: {
  classNames?: TableOfContentsClassNames;
  label?: string;
  variant?: TableOfContentsVariant;
  numbered?: boolean;
  limit?: number;
  density?: Density;
  discover?: boolean;
}) {
  const prefix = useId();
  const container = useRef<HTMLDivElement>(null);
  const [active, setActive] = useState(`${prefix}-0`);
  const headings = useHeadings(
    `[data-toc-article="${prefix}"] h2[id], [data-toc-article="${prefix}"] h3[id]`,
  );
  const items = discover
    ? headings
    : sections.map((section, index) => ({ ...section, id: `${prefix}-${index}` }));
  return (
    <Stack gap="3" className="w-full">
      <Text size="s" color="subtle">
        Reading: {sections.find((_, index) => `${prefix}-${index}` === active)?.text ?? "Overview"}
      </Text>
      <div className="grid min-w-0 gap-5 sm:grid-cols-[minmax(0,1fr)_minmax(0,180px)]">
        <div
          ref={container}
          tabIndex={0}
          role="region"
          aria-label="Example document"
          data-toc-article={prefix}
          className="h-72 min-w-0 overflow-auto rounded-lg border border-border-default p-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focused"
        >
          {sections.map((section, index) => (
            <section key={section.text} className="min-h-48 pb-8">
              <Text
                as={section.level === 3 ? "h3" : "h2"}
                id={`${prefix}-${index}`}
                weight="semibold"
                className="mb-3 scroll-mt-4"
              >
                {section.text}
              </Text>
              <Text size="s" color="subtle">
                {section.body}
              </Text>
            </section>
          ))}
        </div>
        <div className={variant === "minimap" ? "justify-self-end" : "min-w-0"}>
          <TableOfContents
            classNames={classNames}
            variant={variant}
            container={container}
            density={density}
            numbered={numbered}
            value={active}
            onValueChange={setActive}
            aria-label={label}
          >
            <TableOfContents.Title>On this page</TableOfContents.Title>
            <TableOfContents.List limit={limit}>
              {items.map((item) => (
                <TableOfContents.Item
                  key={item.id}
                  href={`#${encodeURIComponent(item.id)}`}
                  level={item.level}
                >
                  {item.text}
                </TableOfContents.Item>
              ))}
            </TableOfContents.List>
          </TableOfContents>
        </div>
      </div>
    </Stack>
  );
}

function TableOfContentsFoldingExample() {
  return <ContentsDemo limit={3} label="Folded article contents" />;
}
```

## Discover headings

`useHeadings(selector, key?)` returns `{ id, text, level }` entries after mounting and updates as matching headings change. Scope the selector to the article so it excludes navigation and example headings. It ignores embedded controls when reading labels, preserves existing IDs, and maps deeper headings to subsection level. Pass the route key when an article layout persists across navigation.

For a custom reading indicator, `useScrollSpy(ids, { container? })` returns the active ID. The server render uses the first supplied ID; an empty list returns an empty string. Both hooks are exported from `@zentara-co/zenos-ui`.

```tsx
import { useId, useRef, useState } from "react";
import { Stack, Text, TableOfContents, useHeadings, type TableOfContentsVariant, type TableOfContentsClassNames, type Density } from "@zentara-co/zenos-ui";

const sections = [
  {
    text: "Overview",
    level: 2 as const,
    body: "Use a table of contents to help readers navigate a long document.",
  },
  {
    text: "Installation",
    level: 2 as const,
    body: "Import components from the public Zenos UI package and load the stylesheet once.",
  },
  {
    text: "Package setup",
    level: 3 as const,
    body: "Keep package imports at the application boundary so examples work in consumer projects.",
  },
  {
    text: "Theme setup",
    level: 3 as const,
    body: "Semantic colors follow the active theme. Use logical spacing for right-to-left layouts.",
  },
  {
    text: "Configuration",
    level: 2 as const,
    body: "Choose a visual variant and density that fit the surrounding document.",
  },
  {
    text: "Keyboard access",
    level: 2 as const,
    body: "Tab through native links and press Enter to navigate. The current link identifies the reading location.",
  },
  {
    text: "Motion",
    level: 2 as const,
    body: "Transitions stop when reduced motion is enabled. Headings can reserve space below a sticky header.",
  },
  {
    text: "Next steps",
    level: 2 as const,
    body: "Test your page with long headings, a narrow viewport, and each supported theme.",
  },
];

function ContentsDemo({
  classNames,
  label = "Document contents",
  variant = "line",
  numbered = false,
  limit,
  density = "compact",
  discover = false,
}: {
  classNames?: TableOfContentsClassNames;
  label?: string;
  variant?: TableOfContentsVariant;
  numbered?: boolean;
  limit?: number;
  density?: Density;
  discover?: boolean;
}) {
  const prefix = useId();
  const container = useRef<HTMLDivElement>(null);
  const [active, setActive] = useState(`${prefix}-0`);
  const headings = useHeadings(
    `[data-toc-article="${prefix}"] h2[id], [data-toc-article="${prefix}"] h3[id]`,
  );
  const items = discover
    ? headings
    : sections.map((section, index) => ({ ...section, id: `${prefix}-${index}` }));
  return (
    <Stack gap="3" className="w-full">
      <Text size="s" color="subtle">
        Reading: {sections.find((_, index) => `${prefix}-${index}` === active)?.text ?? "Overview"}
      </Text>
      <div className="grid min-w-0 gap-5 sm:grid-cols-[minmax(0,1fr)_minmax(0,180px)]">
        <div
          ref={container}
          tabIndex={0}
          role="region"
          aria-label="Example document"
          data-toc-article={prefix}
          className="h-72 min-w-0 overflow-auto rounded-lg border border-border-default p-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focused"
        >
          {sections.map((section, index) => (
            <section key={section.text} className="min-h-48 pb-8">
              <Text
                as={section.level === 3 ? "h3" : "h2"}
                id={`${prefix}-${index}`}
                weight="semibold"
                className="mb-3 scroll-mt-4"
              >
                {section.text}
              </Text>
              <Text size="s" color="subtle">
                {section.body}
              </Text>
            </section>
          ))}
        </div>
        <div className={variant === "minimap" ? "justify-self-end" : "min-w-0"}>
          <TableOfContents
            classNames={classNames}
            variant={variant}
            container={container}
            density={density}
            numbered={numbered}
            value={active}
            onValueChange={setActive}
            aria-label={label}
          >
            <TableOfContents.Title>On this page</TableOfContents.Title>
            <TableOfContents.List limit={limit}>
              {items.map((item) => (
                <TableOfContents.Item
                  key={item.id}
                  href={`#${encodeURIComponent(item.id)}`}
                  level={item.level}
                >
                  {item.text}
                </TableOfContents.Item>
              ))}
            </TableOfContents.List>
          </TableOfContents>
        </div>
      </div>
    </Stack>
  );
}

function TableOfContentsHeadingsExample() {
  return <ContentsDemo discover variant="pill" label="Discovered article contents" />;
}
```

## Density

The explicit `density` prop overrides the nearest `DensityProvider`. Zenos defaults to comfortable density: rows are at least 40px high. Compact rows are 32px. Both grow to at least 44px for coarse pointers, and long labels can wrap.

```tsx
import { useId, useRef, useState } from "react";
import { Stack, Text, TableOfContents, useHeadings, type TableOfContentsVariant, type TableOfContentsClassNames, type Density } from "@zentara-co/zenos-ui";

const sections = [
  {
    text: "Overview",
    level: 2 as const,
    body: "Use a table of contents to help readers navigate a long document.",
  },
  {
    text: "Installation",
    level: 2 as const,
    body: "Import components from the public Zenos UI package and load the stylesheet once.",
  },
  {
    text: "Package setup",
    level: 3 as const,
    body: "Keep package imports at the application boundary so examples work in consumer projects.",
  },
  {
    text: "Theme setup",
    level: 3 as const,
    body: "Semantic colors follow the active theme. Use logical spacing for right-to-left layouts.",
  },
  {
    text: "Configuration",
    level: 2 as const,
    body: "Choose a visual variant and density that fit the surrounding document.",
  },
  {
    text: "Keyboard access",
    level: 2 as const,
    body: "Tab through native links and press Enter to navigate. The current link identifies the reading location.",
  },
  {
    text: "Motion",
    level: 2 as const,
    body: "Transitions stop when reduced motion is enabled. Headings can reserve space below a sticky header.",
  },
  {
    text: "Next steps",
    level: 2 as const,
    body: "Test your page with long headings, a narrow viewport, and each supported theme.",
  },
];

function ContentsDemo({
  classNames,
  label = "Document contents",
  variant = "line",
  numbered = false,
  limit,
  density = "compact",
  discover = false,
}: {
  classNames?: TableOfContentsClassNames;
  label?: string;
  variant?: TableOfContentsVariant;
  numbered?: boolean;
  limit?: number;
  density?: Density;
  discover?: boolean;
}) {
  const prefix = useId();
  const container = useRef<HTMLDivElement>(null);
  const [active, setActive] = useState(`${prefix}-0`);
  const headings = useHeadings(
    `[data-toc-article="${prefix}"] h2[id], [data-toc-article="${prefix}"] h3[id]`,
  );
  const items = discover
    ? headings
    : sections.map((section, index) => ({ ...section, id: `${prefix}-${index}` }));
  return (
    <Stack gap="3" className="w-full">
      <Text size="s" color="subtle">
        Reading: {sections.find((_, index) => `${prefix}-${index}` === active)?.text ?? "Overview"}
      </Text>
      <div className="grid min-w-0 gap-5 sm:grid-cols-[minmax(0,1fr)_minmax(0,180px)]">
        <div
          ref={container}
          tabIndex={0}
          role="region"
          aria-label="Example document"
          data-toc-article={prefix}
          className="h-72 min-w-0 overflow-auto rounded-lg border border-border-default p-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focused"
        >
          {sections.map((section, index) => (
            <section key={section.text} className="min-h-48 pb-8">
              <Text
                as={section.level === 3 ? "h3" : "h2"}
                id={`${prefix}-${index}`}
                weight="semibold"
                className="mb-3 scroll-mt-4"
              >
                {section.text}
              </Text>
              <Text size="s" color="subtle">
                {section.body}
              </Text>
            </section>
          ))}
        </div>
        <div className={variant === "minimap" ? "justify-self-end" : "min-w-0"}>
          <TableOfContents
            classNames={classNames}
            variant={variant}
            container={container}
            density={density}
            numbered={numbered}
            value={active}
            onValueChange={setActive}
            aria-label={label}
          >
            <TableOfContents.Title>On this page</TableOfContents.Title>
            <TableOfContents.List limit={limit}>
              {items.map((item) => (
                <TableOfContents.Item
                  key={item.id}
                  href={`#${encodeURIComponent(item.id)}`}
                  level={item.level}
                >
                  {item.text}
                </TableOfContents.Item>
              ))}
            </TableOfContents.List>
          </TableOfContents>
        </div>
      </div>
    </Stack>
  );
}

function TableOfContentsDensityExample() {
  return <ContentsDemo density="comfortable" variant="dash" label="Comfortable article contents" />;
}
```

## Controlled state and styling

`value` holds the active heading ID; `onValueChange` reports clicks and scroll changes. `defaultValue` provides the initial uncontrolled selection. Keep the callback responsive when using controlled state so the indicator follows the document.

Parts forward native attributes and refs. `Title` accepts `as` for a custom element. All parts accept `className` and `style`. Restyle the list's `::before` indicator with `before:bg-*`; `--toc-indicator-y` and `--toc-indicator-h` expose its measured position. `data-indicator="visible"` marks a resolved active row. `data-indicator-motion` enables transitions after the first measurement.

Line and progress indicators use `background-brand-subtle-default`, matching the documentation sidebar's red accent in both themes. Pill backgrounds keep their neutral fill.

Use `classNames` on the root to style shared parts: `root`, `title`, `list`, `item`, `trigger`, `panel`, `more`, and `minimap`. A part's own `className` takes precedence over the shared classes. Use `before:` utilities in `classNames.list` to customize the indicator, and `data-[active]:` utilities in `classNames.item` to style the selected link.

```tsx
<TableOfContents
  className="w-64"
  classNames={{
    list: "before:bg-background-accent-teal-bolder-default before:w-1",
    item: "rounded-md hover:bg-background-neutral-hover",
  }}
>
  {/* Title, List, and Item parts */}
</TableOfContents>
```

```tsx
import { useId, useRef, useState } from "react";
import { Stack, Text, TableOfContents, useHeadings, type TableOfContentsVariant, type TableOfContentsClassNames, type Density } from "@zentara-co/zenos-ui";

const sections = [
  {
    text: "Overview",
    level: 2 as const,
    body: "Use a table of contents to help readers navigate a long document.",
  },
  {
    text: "Installation",
    level: 2 as const,
    body: "Import components from the public Zenos UI package and load the stylesheet once.",
  },
  {
    text: "Package setup",
    level: 3 as const,
    body: "Keep package imports at the application boundary so examples work in consumer projects.",
  },
  {
    text: "Theme setup",
    level: 3 as const,
    body: "Semantic colors follow the active theme. Use logical spacing for right-to-left layouts.",
  },
  {
    text: "Configuration",
    level: 2 as const,
    body: "Choose a visual variant and density that fit the surrounding document.",
  },
  {
    text: "Keyboard access",
    level: 2 as const,
    body: "Tab through native links and press Enter to navigate. The current link identifies the reading location.",
  },
  {
    text: "Motion",
    level: 2 as const,
    body: "Transitions stop when reduced motion is enabled. Headings can reserve space below a sticky header.",
  },
  {
    text: "Next steps",
    level: 2 as const,
    body: "Test your page with long headings, a narrow viewport, and each supported theme.",
  },
];

function ContentsDemo({
  classNames,
  label = "Document contents",
  variant = "line",
  numbered = false,
  limit,
  density = "compact",
  discover = false,
}: {
  classNames?: TableOfContentsClassNames;
  label?: string;
  variant?: TableOfContentsVariant;
  numbered?: boolean;
  limit?: number;
  density?: Density;
  discover?: boolean;
}) {
  const prefix = useId();
  const container = useRef<HTMLDivElement>(null);
  const [active, setActive] = useState(`${prefix}-0`);
  const headings = useHeadings(
    `[data-toc-article="${prefix}"] h2[id], [data-toc-article="${prefix}"] h3[id]`,
  );
  const items = discover
    ? headings
    : sections.map((section, index) => ({ ...section, id: `${prefix}-${index}` }));
  return (
    <Stack gap="3" className="w-full">
      <Text size="s" color="subtle">
        Reading: {sections.find((_, index) => `${prefix}-${index}` === active)?.text ?? "Overview"}
      </Text>
      <div className="grid min-w-0 gap-5 sm:grid-cols-[minmax(0,1fr)_minmax(0,180px)]">
        <div
          ref={container}
          tabIndex={0}
          role="region"
          aria-label="Example document"
          data-toc-article={prefix}
          className="h-72 min-w-0 overflow-auto rounded-lg border border-border-default p-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focused"
        >
          {sections.map((section, index) => (
            <section key={section.text} className="min-h-48 pb-8">
              <Text
                as={section.level === 3 ? "h3" : "h2"}
                id={`${prefix}-${index}`}
                weight="semibold"
                className="mb-3 scroll-mt-4"
              >
                {section.text}
              </Text>
              <Text size="s" color="subtle">
                {section.body}
              </Text>
            </section>
          ))}
        </div>
        <div className={variant === "minimap" ? "justify-self-end" : "min-w-0"}>
          <TableOfContents
            classNames={classNames}
            variant={variant}
            container={container}
            density={density}
            numbered={numbered}
            value={active}
            onValueChange={setActive}
            aria-label={label}
          >
            <TableOfContents.Title>On this page</TableOfContents.Title>
            <TableOfContents.List limit={limit}>
              {items.map((item) => (
                <TableOfContents.Item
                  key={item.id}
                  href={`#${encodeURIComponent(item.id)}`}
                  level={item.level}
                >
                  {item.text}
                </TableOfContents.Item>
              ))}
            </TableOfContents.List>
          </TableOfContents>
        </div>
      </div>
    </Stack>
  );
}

function TableOfContentsCustomExample() {
  return (
    <ContentsDemo
      label="Custom article contents"
      classNames={{
        root: "rounded-lg border border-border-default bg-background-neutral-card p-3",
        title: "text-text-accent-teal-bolder",
        list: "before:bg-background-accent-teal-bolder-default before:w-1",
        item: "rounded-md hover:bg-background-neutral-hover data-[active]:text-text-accent-teal-bolder",
      }}
    />
  );
}
```

## Accessibility

Each navigation landmark needs a distinct accessible name. The current link has `aria-current="location"`; it remains a native anchor with normal Tab and Enter behavior. No arrow-key widget behavior is added to the list. Motion stops under reduced-motion preferences. Panel and folding controls stay keyboard accessible, and visible links remain available during server rendering.

## Anatomy

```text
TableOfContents.Root
TableOfContents.Title
TableOfContents.List
TableOfContents.Item
```

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| classNames | TableOfContentsClassNames | — | Shared classes for root, title, list, item, trigger, panel, more, and minimap. Local className overrides shared classes. Use before: utilities on list for the indicator. |
| variant | line \| progress \| pill \| dash \| plain \| minimap | line | Active-section indicator treatment. |
| density | compact \| comfortable | inherited | 32px or 40px minimum rows; 44px for coarse pointers. Follows DensityProvider. |
| numbered | boolean | false | Adds section and subsection numbers in list order. |
| value / defaultValue | string | — | Controlled active heading ID or initial selection. |
| onValueChange | (id: string) => void | — | Reports heading changes from scrolling or activation. |
| container | RefObject<HTMLElement \| null> | — | Tracks a scroll pane and confines link scrolling to it. |
| List.limit | number | — | Folds long lists. Lists only two items over the limit remain visible. |
| List.moreLabel / lessLabel | (hidden: number) => ReactNode / ReactNode | — | Customizes the expand and collapse controls. |
| Item.href | string | — | Heading hash or normal destination. Nonlocal destinations retain native link behavior. |
| Item.level | 2 \| 3 | 2 | Section or indented subsection. |
| Title.as | ElementType | p | Changes the title element and preserves its native props and ref. |
| native props | React.native nav, ol, and anchor props | — | Forwards native attributes, events, aria-*, data-*, className, style, and ref. |

Unless narrowed above, each DOM-rendering part also accepts its underlying native or Base UI props, including className, style, aria-*, and data-*.

Source: https://zenos-ui.pages.dev/components/table-of-contents/