Skip to main content

Table of Contents

The page's "On this page" list: its headings as in-page links, with the section in view marked. It fills the docs layout's contents column on wide screens; below that, its compact bar names the section in view at the top of the page and opens the whole list.

import {
  TableOfContents,
  useActiveHeading,
} from '@fairgarden/design/navigation/table-of-contents'

Pass items as the page's headings, { id, title, level }, in order: level 2 at the top, levels 3 and 4 nested under the heading before them. Pass activeId to mark the section in view. The component draws and does nothing else, so the marked section can come from anywhere; useActiveHeading provides it from scrolling. Links are plain #id anchors, which scroll to the heading and write the hash, unless you pass renderLink.

On this page

On this page

A nav named by its caps heading, "On this page" unless you pass label, over an ordered list of type-caption links on 44 px rows. The entries hang on a hairline guide at the list's start edge, and nested levels step in on their own guide. The section in view takes aria-current="location", the 3 px start-edge bar over the guide and weight 700: the same current-item marks as the sidebar, the drawer and the section bar's Jump list. Every entry reserves its bold width, so marking a section never rewraps a line. Hover follows the list-link rule. Inside the compact bar's panel the heading is hidden, since the bar already says it, and it stays the landmark's name. In print the list is hidden; the document's own headings carry its structure.

import * as React from 'react'
import {
  TableOfContents,
  type TableOfContentsItem,
} from '@fairgarden/design/navigation/table-of-contents'
import styles from './contents.module.css'

/** The headings of the handbook's Composting page: H2s, with their H3s nested. */
const headings: TableOfContentsItem[] = [
  { id: 'compost-what-goes-in', title: 'What goes in', level: 2 },
  { id: 'compost-greens', title: 'Greens', level: 3 },
  { id: 'compost-browns', title: 'Browns', level: 3 },
  { id: 'compost-the-three-bays', title: 'The three bays', level: 2 },
  { id: 'compost-turning-days', title: 'Turning days', level: 3 },
  { id: 'compost-worm-bins', title: 'Worm bins', level: 2 },
  { id: 'compost-sharing', title: 'Sharing finished compost with the other plots', level: 2 },
]

/** The page's contents with "The three bays" in view, at the docs layout's 240 px column width. */
export function TableOfContentsBasic() {
  return (
    <div className={styles.column}>
      <TableOfContents items={headings} activeId="compost-the-three-bays" />
    </div>
  )
}

The compact bar

The compact bar

With kind="bar" the contents shrink to one line for narrow screens: a field-like box holding "On this page" and the title of the section in view, truncated, with a chevron. Before scrollspy runs (and in the server HTML) it names the first section, and its height never changes, whichever section it names. Pressing it opens the whole list in a panel anchored under the bar, about a third of the viewport tall (at least 240 px, never more than the room below the bar), with the browser's own scrollbar kept clear of its rounded corners. The panel scrolls itself, never the page, so the section in view sits centered and marked, and focus lands on it. Following an entry goes to its heading (clear of a sticky bar, given a scroll-margin), closes the panel and moves focus to the heading; Escape or a press outside closes it and focus returns to the bar. The bar's ring, or its edge when pressed with a pointer, grows into the panel's frame as the panel opens and shrinks back as it closes, as the Select's does; pass morph={false}, or set --fgd-outline-morph: none, to turn that off, and under reduced motion the panel simply appears. The section in view is announced politely when it changes. With no items the component renders nothing. The docs layout draws the same toc element as this bar below 1440 px, pinned under its header, so you pass one contents element for both widths. In print the bar and the panel are hidden.

Why save seed

Why save seed

Seed saved from the plants that did best in our beds grows better in them next year, and it keeps the library shelves full.

Choosing plants

Save from the healthiest plants, never from the first to bolt or the last to ripen.

Open-pollinated varieties

Hybrids don’t come true from seed; the library’s packets say which varieties are open-pollinated.

Keeping varieties apart

Squash and corn cross with their neighbours; grow one variety a season, or bag the flowers.

Tomatoes

Tomatoes are the easiest start: every fruit holds a hundred seeds.

Picking the fruit

Pick one fully ripe fruit from each of three plants.

Fermenting the seed

Squeeze the seed and pulp into a jar with a little water and leave it three days, stirring daily.

Drying

Rinse the seed that sank, spread it on a plate and dry it for a week out of the sun.

Beans and peas

Beans and peas pollinate themselves, so any row will do.

Leaving pods on the vine

Leave a few plants unpicked until the pods rattle.

Threshing

Shell the pods over a sheet, or tread them in a pillowcase and winnow the chaff in a breeze.

Lettuce

Lettuce seed comes late in the summer from plants left to flower.

Letting it bolt

Mark two good plants in spring and let them grow tall; stake them before the flowers open.

Shaking the heads

When the fluffy heads appear, shake them into a paper bag every few days.

Squash

Squash needs the most care: it crosses easily and its seed must ripen inside the fruit.

Hand pollinating

Tape a female flower shut the evening before it opens, then dust it with a male flower of the same variety.

Scooping and washing

Leave the fruit a month after harvest, then scoop, wash and dry the plump seed.

Storing seed

Dry seed keeps for years in the cool and dark.

Envelopes and labels

Write the variety, the plot and the year on the envelope before the seed goes in.

The seed library shelves

Return a share to the library tin in the tool shed; the coordinators sort it each month.

Sharing

Everything saved goes round again in spring.

The spring swap

Bring your envelopes to the March work day and leave with someone else’s.

'use client'

import * as React from 'react'
import {
  TableOfContents,
  useActiveHeading,
  type TableOfContentsItem,
} from '@fairgarden/design/navigation/table-of-contents'
import { guide } from './guide'
import styles from './bar.module.css'

const items: TableOfContentsItem[] = guide.map(({ id, title, level }) => ({ id, title, level }))
const ids = items.map((item) => item.id)

/**
 * The compact bar over a long page: it names the section in view and
 * opens the whole list, scrolled so that section sits centered and marked.
 * The page here scrolls in a box of its own, so `useActiveHeading` watches
 * it (`root`) and the bar sticks to the box's top.
 */
export function TableOfContentsBar() {
  const pageRef = React.useRef<HTMLDivElement | null>(null)
  const activeId = useActiveHeading(ids, { root: pageRef })
  return (
    <div className={styles.frame}>
      <div ref={pageRef} className={styles.page} tabIndex={0} aria-label="Seed-saving guide">
        <div className={styles.bar}>
          <TableOfContents kind="bar" items={items} activeId={activeId} />
        </div>
        {guide.map((section) => {
          const Heading = section.level === 2 ? 'h2' : 'h3'
          return (
            <React.Fragment key={section.id}>
              <Heading id={section.id} className={section.level === 2 ? styles.h2 : styles.h3}>
                {section.title}
              </Heading>
              <p className={styles.p}>{section.body}</p>
            </React.Fragment>
          )
        })}
      </div>
    </div>
  )
}

Scrollspy

Scrollspy

useActiveHeading(ids) returns the id of the section in view. An IntersectionObserver watches the headings against a band from the top of the view down to the activation line, a quarter of the way down unless you pass line (in px or %); each time a heading crosses the line, the last heading above it becomes current. At the top of the page the first heading is current, and scrolled to the end, the last. A pass after each scroll ends catches jumps that cross no line. Pass root when the content scrolls in a box of its own, as in this demo. The hook only reads positions, and the list reserves every entry's bold width, so scrollspy moves nothing. It returns undefined on the server, so the server HTML marks no section.

Before you sow

Rake the bed level and water it the evening before. Seed sown into dry soil sits there waiting; seed sown into damp soil starts the same week.

Choosing seed

The seed library in the tool shed lends packets by the spoonful. Take what you will sow this month, and write the variety in the ledger by the door.

Sowing

Sow in drills a finger deep for beans and peas, a knuckle deep for roots and greens. Cover, firm the soil with the back of the rake, and label the row.

Thinning

When the seedlings have two true leaves, thin them to a hand’s width. The thinnings of lettuce, beet and chard make a good first salad.

Saving seed for next year

Leave the best plant of each row to flower and set seed. Once the pods are dry and rattle, pick them on a dry afternoon and bring the seed back to the library.

'use client'

import * as React from 'react'
import {
  TableOfContents,
  useActiveHeading,
  type TableOfContentsItem,
} from '@fairgarden/design/navigation/table-of-contents'
import styles from './scrollspy.module.css'

const headings: TableOfContentsItem[] = [
  { id: 'spy-before-you-sow', title: 'Before you sow', level: 2 },
  { id: 'spy-choosing-seed', title: 'Choosing seed', level: 3 },
  { id: 'spy-sowing', title: 'Sowing', level: 2 },
  { id: 'spy-thinning', title: 'Thinning', level: 2 },
  { id: 'spy-saving-seed', title: 'Saving seed for next year', level: 2 },
]

const ids = headings.map((heading) => heading.id)

const body: Record<string, string> = {
  'spy-before-you-sow':
    'Rake the bed level and water it the evening before. Seed sown into dry soil sits there waiting; seed sown into damp soil starts the same week.',
  'spy-choosing-seed':
    'The seed library in the tool shed lends packets by the spoonful. Take what you will sow this month, and write the variety in the ledger by the door.',
  'spy-sowing':
    'Sow in drills a finger deep for beans and peas, a knuckle deep for roots and greens. Cover, firm the soil with the back of the rake, and label the row.',
  'spy-thinning':
    'When the seedlings have two true leaves, thin them to a hand’s width. The thinnings of lettuce, beet and chard make a good first salad.',
  'spy-saving-seed':
    'Leave the best plant of each row to flower and set seed. Once the pods are dry and rattle, pick them on a dry afternoon and bring the seed back to the library.',
}

/**
 * Scrollspy in a box of its own: `useActiveHeading` watches the headings
 * inside the scrolling panel (its `root`) and marks the section in view.
 */
export function TableOfContentsScrollspy() {
  const panelRef = React.useRef<HTMLDivElement | null>(null)
  const activeId = useActiveHeading(ids, { root: panelRef })
  return (
    <div className={styles.split}>
      <div className={styles.frame}>
        <div ref={panelRef} className={styles.panel} tabIndex={0} aria-label="Seed sowing guide">
          {headings.map((heading) =>
            heading.level === 2 ? (
              <React.Fragment key={heading.id}>
                <h2 id={heading.id} className={styles.h2}>
                  {heading.title}
                </h2>
                <p className={styles.p}>{body[heading.id]}</p>
              </React.Fragment>
            ) : (
              <React.Fragment key={heading.id}>
                <h3 id={heading.id} className={styles.h3}>
                  {heading.title}
                </h3>
                <p className={styles.p}>{body[heading.id]}</p>
              </React.Fragment>
            )
          )}
        </div>
      </div>
      <div className={styles.column}>
        <TableOfContents items={headings} activeId={activeId} />
      </div>
    </div>
  )
}

API Reference

TableOfContents

The page’s contents [D202, D203].

kind="list" (default): a nav named by its caps heading (type-label) over an ol of in-page links in type-caption, H2s at the top level and H3 and H4 nested on the --role-hairline guide. The section in view (activeId) takes aria-current="location", the --border-size-2–25 start-edge bar and weight 700; every entry reserves that weight’s box, so marking a section never moves the list.

kind="bar": one field-box line, “On this page” and the section in view (the first before scrollspy runs), truncated, with a chevron. It opens the same list in an anchored panel about a third of the viewport tall, scrolled inside so the section in view sits centered and marked, with focus on it; following an entry goes to its heading and closes the panel; Escape and an outside press close it and focus returns to the bar. The bar’s ring or edge morphs into the panel’s frame [D204].

Presentational: pair it with useActiveHeading for scrollspy. The docs layout shows the list in a sticky column from --xl-n-above and the bar, pinned under the header, below. With no items it renders nothing. Hidden in print.

PropTypeDescription
label
string | undefined

The visible heading (the bar’s label) and the landmark’s name. Default “On this page”.

activeId
string | undefined

The id of the section in view: its entry takes aria-current="location", and the bar names it. Pass useActiveHeading(ids) for scrollspy. Omitted, no entry is marked and the bar names the first section.

items
TableOfContentsItem[] | undefined

The page’s headings in order, levels 2–4 (a level-3 nests under the level-2 before it).

kind
'list' | 'bar' | null | undefined

list (default): the full list. bar: one line naming the section in view, which opens the list in an anchored panel. Omitted, a host’s TableOfContentsContext may set it (the docs layout does).

morph
boolean | undefined

With kind="bar": the outline morph, the bar’s ring or edge growing into the panel’s frame on open and back on close [D204]. Default true; it never runs under reduced motion, in forced colors or in print.

primary
| 'ruby'
| 'olive'
| 'sage'
| 'slate'
| 'sand'
| 'gray'
| 'mauve'
| 'brown'
| 'bronze'
| 'gold'
| 'red'
| 'crimson'
| 'tomato'
| 'pink'
| 'plum'
| 'indigo'
| 'iris'
| 'violet'
| 'purple'
| null
| undefined

Override the scope’s primary. Never defaulted [D133].

renderLink
((href: string) => ReactElement) | undefined

Builds each anchor. Default: a plain <a href="#id">, which scrolls and writes the hash.

secondary
| 'ruby'
| 'olive'
| 'sage'
| 'slate'
| 'sand'
| 'gray'
| 'mauve'
| 'brown'
| 'bronze'
| 'gold'
| 'red'
| 'crimson'
| 'tomato'
| 'pink'
| 'plum'
| 'indigo'
| 'iris'
| 'violet'
| 'purple'
| 'amber'
| 'blue'
| 'cyan'
| 'grass'
| 'green'
| 'jade'
| 'lime'
| 'mint'
| 'orange'
| 'sky'
| 'teal'
| 'yellow'
| null
| undefined

Override the scope’s secondary. Never defaulted.

useActiveHeading

Scrollspy for a table of contents [D202]: the id of the heading whose section is in view, for TableOfContents’ activeId. An IntersectionObserver watches the headings against a band from the root’s top edge down to line; each time one crosses the line the hook takes the last heading above it (the first while none has passed, the last once the root is scrolled to its end). The heading a link just landed on (the URL’s hash) stays current while it sits above the line, so a short section chosen from the contents is the one marked. A scrollend pass re-reads the positions after jumps that cross no line.

It only reads layout and returns an id: nothing it drives changes size (the list reserves each entry’s current weight), so it causes no layout shift. It returns undefined on the server and before the first observation, so the server HTML marks no section.

ParameterTypeDescription
ids
string[]
options
UseActiveHeadingOptions | undefined
Returns
string | undefined

Additional types

tableOfContents
TableOfContentsContext

Provided by a host of the contents, such as the docs layout.

type TableOfContentsContext = React.Context<TableOfContentsContextValue>
TableOfContentsContextValue

What a host tells the contents inside it. The docs layout sets kind: 'bar' where it pins the compact bar (below --xl-n-above), so the one toc it is given draws as the column there and as the bar here.

type TableOfContentsContextValue = {
  /** The kind to draw when the component names none. */
  kind?: TableOfContentsKind;
  /** Hides the list's visible heading; it stays the landmark's name. */
  labelHidden?: boolean;
}
TableOfContentsItem

One heading on the page.

type TableOfContentsItem = {
  /** The heading's `id`: the entry links to `#id`. */
  id: string;
  /** The heading's text. */
  title: string;
  /** The heading level: 2, 3 or 4. */
  level: TableOfContentsLevel;
}
TableOfContentsKind

How the contents draw: the full list, or the compact bar that opens it.

type TableOfContentsKind = 'list' | 'bar'<'list' | 'bar' | null | undefined>
TableOfContentsLevel

Heading levels the list shows: H2 at its top level, H3 and H4 nested under it.

type TableOfContentsLevel = 2 | 3 | 4
TableOfContentsProps

Props for TableOfContents: nav props, the headings, the section in view, the kind and the color axes.

type TableOfContentsProps = {
  /** The page's headings in order, levels 2–4 (a level-3 nests under the level-2 before it). */
  items: TableOfContentsItem[];
  /**
   * The id of the section in view: its entry takes `aria-current="location"`,
   * and the bar names it. Pass `useActiveHeading(ids)` for scrollspy.
   * Omitted, no entry is marked and the bar names the first section.
   */
  activeId?: string;
  /** The visible heading (the bar's label) and the landmark's name. Default "On this page". */
  label?: string;
  /**
   * `list` (default): the full list. `bar`: one line naming the section in
   * view, which opens the list in an anchored panel. Omitted, a host's
   * `TableOfContentsContext` may set it (the docs layout does).
   */
  kind?: 'list' | 'bar' | null;
  /**
   * With `kind="bar"`: the outline morph, the bar's ring or edge growing
   * into the panel's frame on open and back on close [D204]. Default
   * `true`; it never runs under reduced motion, in forced colors or in
   * print.
   */
  morph?: boolean;
  /** Builds each anchor. Default: a plain `<a href="#id">`, which scrolls and writes the hash. */
  renderLink?: (href: string) => ReactElement;
  /** Override the scope's primary. Never defaulted [D133]. */
  primary?:
    | 'ruby'
    | 'olive'
    | 'sage'
    | 'slate'
    | 'sand'
    | 'gray'
    | 'mauve'
    | 'brown'
    | 'bronze'
    | 'gold'
    | 'red'
    | 'crimson'
    | 'tomato'
    | 'pink'
    | 'plum'
    | 'indigo'
    | 'iris'
    | 'violet'
    | 'purple'
    | null;
  /** Override the scope's secondary. Never defaulted. */
  secondary?:
    | 'ruby'
    | 'olive'
    | 'sage'
    | 'slate'
    | 'sand'
    | 'gray'
    | 'mauve'
    | 'brown'
    | 'bronze'
    | 'gold'
    | 'red'
    | 'crimson'
    | 'tomato'
    | 'pink'
    | 'plum'
    | 'indigo'
    | 'iris'
    | 'violet'
    | 'purple'
    | 'amber'
    | 'blue'
    | 'cyan'
    | 'grass'
    | 'green'
    | 'jade'
    | 'lime'
    | 'mint'
    | 'orange'
    | 'sky'
    | 'teal'
    | 'yellow'
    | null;
}
UseActiveHeadingOptions

Options for useActiveHeading.

type UseActiveHeadingOptions = {
  /**
   * The scroll container the headings move in. Default: the viewport. Pass
   * a ref when the content scrolls inside its own box (a panel, a demo).
   */
  root?: React.RefObject<Element | null>;
  /**
   * Where a heading becomes current: the activation line's distance below
   * the root's top edge, in `px` (`'80px'`) or as a percentage of the
   * root's height (`'25%'`). Default `'25%'`: a heading is current once
   * its top has passed the top quarter of the view, and stays current
   * until the next one passes.
   */
  line?: string;
  /** `false` pauses the hook (it then returns `undefined`). Default `true`. */
  enabled?: boolean;
}

Specification: DESIGN-SYSTEM.md §9.16 (table of contents) [D202, D203], in the docs layout of §11.15.