Site color

Choose your site’s color palette.

Saved on this device.

PageToc

PageTocDocument outline

Write headings. Get a linked outline. When a client app changes the page, refresh the same TOC with one call.

Site navigation & services

The TOC beside this guide is the component in use. Its links come from the final rendered article, including headings produced by Regor. The playground below adds browser content to that same outline. On smaller screens, open on this page to see the links.

Start with headings

Use the default doc template and write your sections. PureStack supplies the PageToc; you do not need to add a second component.

---
template: doc
layout:
  showToc: true
---

# Getting started

## Install

### Choose a package manager

## Configure

The TOC starts at Install, nests Choose a package manager beneath it, and continues with Configure. The page's single h1 is treated as its document title and omitted from the list.

Setting Default doc layout
layout.showToc: true Show the panel when the rendered article has TOC entries. A lone h1 is not enough.
layout.showToc: false Omit the default panel and its TOC runtime.
layout.showToc: always Retain the panel and runtime even without entries, ready for client content.
No page override Use pageToc.enabled from site config.

Both true and always override a disabled site default. SSG collects the article from the existing rendered DOM; it does not render your content a second time to discover headings.

Try client updates

Add a section and watch this guide's TOC. The textbox starts with Client section 1. Each section uses the text currently in the textbox, then the textbox advances to Client section 2, Client section 3, and so on. An existing trailing number is incremented in place. Change the heading text and choose Rename last: the label changes while its existing ID stays stable. Move, exclude and remove sections to see the outline follow the DOM.

Turn off Refresh after every change to separate the two steps. The page changes immediately; its TOC keeps the previous links until you choose Refresh TOC. Clearing these sections leaves the guide's other entries intact.

The playground is a Regor app mounted with RegorApp. Its exported class context owns the state and actions. Focused controls and section components compose PureStack's FormInputField, FormCheck, Btn, Flex and Panel. Controls access the ancestor context with requireContext; a keyed r-for preserves section elements and their IDs. onMounted performs the initial scan, and later actions refresh directly after a batch has flushed its DOM bindings.

This page's live table of contentsCOMPOSITION

These are real h3 headings in this article. Use the actual page TOC to navigate to them.

View the complete playground source
<RegorApp
  id="page-toc-playground"
  class="d-block min-w-0"
  data-toc-playground
  src="./app.ts"/>
import {
  defineButtonComponents,
  defineFlexComponents,
  defineFormCheckComponent,
  defineFormInputField,
  definePanelComponents,
} from '@purestack/ts-components'
import { createApp, html } from 'regor'
import { defineTocPlaygroundControls } from './controls'
import { defineTocPlayground } from './playground'
import { defineTocPlaygroundSection } from './section'

const components = {
  TocPlayground: defineTocPlayground(),
  TocPlaygroundControls: defineTocPlaygroundControls(),
  TocPlaygroundSection: defineTocPlaygroundSection(),
  FormCheck: defineFormCheckComponent(),
  ...defineButtonComponents(),
  ...defineFlexComponents(),
  ...defineFormInputField(),
  ...definePanelComponents(),
}

for (const mount of document.querySelectorAll<HTMLElement>(
  'app[data-toc-playground]',
)) {
  createApp(
    { components, prefix: mount.id },
    {
      element: mount,
      template: html`<TocPlayground :prefix="prefix"/>`,
    },
  )
}
import type {} from '@purestack/ts-page-scripts'
import {
  batch,
  computed,
  defineComponent,
  html,
  observe,
  onMounted,
  type RefOrValue,
  ref,
  sref,
  unref,
} from 'regor'
import type { Section } from './section'

export class TocPlayground {
  readonly title = ref('Client section 1')
  readonly automatic = ref(true)
  readonly status = ref(
    "Add a section, then find it in this page's table of contents.",
  )
  readonly sections = sref<Section[]>([])
  readonly hasSections = computed(() => this.sections().length > 0)
  readonly lastExcluded = computed(
    () => this.sections().at(-1)?.excluded() ?? false,
  )
  private nextKey = 0

  constructor(readonly prefix: RefOrValue<string>) {
    observe(this.automatic, (enabled) => {
      if (enabled) this.refresh()
      else
        this.status(
          'Automatic refresh is off. Change a heading, then press Refresh TOC.',
        )
    })
    onMounted(this.refresh)
  }

  refresh = () => {
    const toc = window.tsSsgPageToc
    if (!toc?.refresh) {
      this.status(
        'Live refresh is unavailable in this preview. Reload the page to try again.',
      )
      return
    }
    toc.refresh()
    batch(() => {
      for (const section of this.sections())
        section.id(section.heading()?.id ?? '')
      const included = this.sections().filter(
        (section) => !section.excluded(),
      ).length
      this.status(
        this.sections().length
          ? `TOC refreshed. ${included} of ${this.sections().length} playground sections included. Follow a TOC link to jump to its heading.`
          : 'TOC refreshed. Add a section to begin.',
      )
    })
  }

  add = () => {
    const value = this.readTitle()
    if (!value) return
    const section: Section = {
      key: ++this.nextKey,
      title: ref(value),
      excluded: ref(false),
      id: ref(''),
      heading: sref<HTMLHeadingElement | null>(null),
    }
    this.update(() => {
      this.sections([...this.sections(), section])
      this.title(
        /\d+$/.test(value)
          ? value.replace(/\d+$/, (number) => String(Number(number) + 1))
          : `${value} 1`,
      )
    })
  }

  rename = () => {
    const last = this.sections().at(-1)
    const value = this.readTitle()
    if (last && value) this.update(() => last.title(value))
  }

  reorder = () => {
    const last = this.sections().at(-1)
    if (!last || this.sections().length < 2) return
    this.update(() => this.sections([last, ...this.sections().slice(0, -1)]))
  }

  toggleExcluded = () => {
    const last = this.sections().at(-1)
    if (last) this.update(() => last.excluded(!last.excluded()))
  }

  remove = () => this.update(() => this.sections(this.sections().slice(0, -1)))
  clear = () => this.update(() => this.sections([]))

  private update(change: () => void) {
    // Regor flushes DOM bindings when batch returns, before refreshing the TOC.
    batch(change)
    if (this.automatic()) this.refresh()
    else this.status('Headings changed. Press Refresh TOC to update the links.')
  }

  private readTitle() {
    const value = this.title().trim()
    if (!value) {
      this.status('Enter a heading before adding or renaming a section.')
      document.getElementById(`${unref(this.prefix)}-title`)?.focus()
    }
    return value
  }
}

const playgroundTemplate = html`<Flex direction="column" class="gap-4">
  <TocPlaygroundControls/>
  <p class="text-muted m-0" r-if="!hasSections" data-toc-empty>
    No client headings yet. Add your first section above.
  </p>
  <Flex direction="column" class="gap-4" data-toc-sections>
    <TocPlaygroundSection
      r-for="section in sections"
      :key="section.key"
      :section="section"/>
  </Flex>
</Flex>`

export function defineTocPlayground() {
  return defineComponent<TocPlayground>(playgroundTemplate, {
    props: ['prefix'],
    context: (head) => new TocPlayground(head.props.prefix),
  })
}
import { defineComponent, html } from 'regor'
import { TocPlayground } from './playground'

export interface TocPlaygroundControls {
  playground: TocPlayground
}

const controlsTemplate = html`<Panel variant="surface" bodyClass="p-4" data-toc-ignore>
  <Flex direction="column" class="gap-4">
    <FormInputField
      :id="playground.prefix + '-title'"
      label="Heading text"
      :model="playground.title"/>
    <Flex wrap="true" class="gap-2">
      <Btn @click="playground.add" data-toc-action="add" tone="accent"
        >Add section</Btn>
      <Btn
        @click="playground.rename"
        :disabled="!playground.hasSections"
        data-toc-action="rename"
        variant="surface"
        >Rename last</Btn>
      <Btn
        @click="playground.reorder"
        :disabled="playground.sections.length < 2"
        data-toc-action="reorder"
        variant="surface"
        >Move last to first</Btn>
      <Btn
        @click="playground.toggleExcluded"
        :disabled="!playground.hasSections"
        data-toc-action="exclude"
        variant="surface"
        >{{ playground.lastExcluded ? 'Include last' : 'Exclude last' }}</Btn>
      <Btn
        @click="playground.remove"
        :disabled="!playground.hasSections"
        data-toc-action="remove"
        variant="surface"
        >Remove last</Btn>
      <Btn
        @click="playground.clear"
        :disabled="!playground.hasSections"
        data-toc-action="clear"
        variant="subtle"
        >Clear sections</Btn>
    </Flex>
    <Flex wrap="true" align="center" class="gap-3">
      <FormCheck
        :id="playground.prefix + '-automatic'"
        label="Refresh after every change"
        :checked="playground.automatic"
        data-toc-auto-refresh/>
      <Btn
        @click="playground.refresh"
        data-toc-action="refresh"
        variant="outlineFill"
        >Refresh TOC</Btn>
    </Flex>
    <p
      class="text-muted fs-sm m-0"
      role="status"
      aria-live="polite"
      aria-atomic="true"
      data-toc-status
    >
      {{ playground.status }}
    </p>
  </Flex>
</Panel>`

export function defineTocPlaygroundControls() {
  return defineComponent<TocPlaygroundControls>(controlsTemplate, {
    context: (head) => ({ playground: head.requireContext(TocPlayground) }),
  })
}
import { defineComponent, html, type Ref, type SRef } from 'regor'

export interface Section {
  key: number
  title: Ref<string>
  excluded: Ref<boolean>
  id: Ref<string>
  heading: SRef<HTMLHeadingElement | null>
}

export interface TocPlaygroundSection {
  section: Section
}

const sectionTemplate = html`<Panel tone="accent" variant="surface" bodyClass="p-4">
  <Flex direction="column" class="gap-3">
    <h3
      class="m-0 fs-lg fw-600"
      :ref="section.heading"
      :id="section.id || undefined"
      :data-toc-ignore="section.excluded ? '' : undefined"
    >
      {{ section.title }}
    </h3>
    <p class="m-0 fs-xs wrap-anywhere">
      <code class="ws-normal">{{ section.id ? 'ID: #' + section.id : 'ID assigned on refresh' }}</code>
      · {{ section.excluded ? 'Excluded from the outline' : 'Included on refresh' }}
    </p>
    <p class="m-0">
      This heading is rendered by Regor in the browser. Its TOC link, nesting
      and active state come from the page runtime.
    </p>
  </Flex>
</Panel>`

export function defineTocPlaygroundSection() {
  return defineComponent<TocPlaygroundSection>(sectionTemplate, {
    props: ['section'],
  })
}

Start with no server headings

A browser app may not have content at build time. Use always so its panel and runtime are published before the first heading exists:

layout:
  showToc: always

The example below uses the standard doc layout and contains zero server-rendered headings. Its title is ordinary paragraph text. Add a section, open on this page, then clear all sections to return to “No sections yet.” The example has its own document and TOC, so it does not change this guide's outline.

Open the empty-page playground in a new tab
View the empty page's frontmatter and content
---
title: Client-only TOC playground
description: Start without server headings, then create and manage a table of contents from browser content.
template: doc
index: false
nav:
  hidden: true
layout:
  showNav: false
  showToc: always
  showFooter: false
---

<p class="text-eyebrow">PageToc live example</p>
<p class="text-title">An empty page, ready for client headings</p>

This page has no server-rendered h1, h2 or h3. Its frontmatter sets `layout.showToc: always`, so the table of contents starts with “No sections yet.” Open **on this page** if the panel is collapsed.

Add a section and follow its TOC link. The section uses the textbox value, then the textbox advances to the next name by adding or incrementing its trailing number. Rename, reorder, exclude or remove sections. Turn off automatic refresh to see that the TOC changes only when you explicitly refresh it. Clear everything to return to the empty state; the textbox keeps its current value.

<import-content src="./_playground.mdx"/>

[Return to the PageToc guide](./page-toc.mdx#try-client-updates).

Refresh from a client app

Use onMounted for the initial scan, when the component's headings are in the DOM. Regor applies ref updates synchronously, so later actions can update state and call refresh() immediately afterwards. When grouping changes with batch(), refresh after that call returns. A mounted hook runs once; it does not run again for title changes, reordering or removals.

Mount the app inside the page's content:

<RegorApp id="app-content" class="d-block" src="./app.ts"/>
import type {} from '@purestack/ts-page-scripts'
import { defineButtonComponents } from '@purestack/ts-components'
import { createApp, defineComponent, html, onMounted, type SRef, sref } from 'regor'

interface Section {
  key: number
  title: string
}

export interface SectionList {
  sections: SRef<Section[]>
  addSection: () => void
}

const sectionList = defineComponent<SectionList>(html`<div>
  <Btn tone="accent" @click="addSection">Add section</Btn>
  <section r-for="section in sections" :key="section.key">
    <h2>{{ section.title }}</h2>
  </section>
</div>`, {
  context: () => {
    const sections = sref<Section[]>([])
    let nextKey = 0
    const refresh = () => window.tsSsgPageToc?.refresh()

    onMounted(refresh)

    return {
      sections,
      addSection: () => {
        const key = ++nextKey
        sections([...sections(), { key, title: `Account settings ${key}` }])
        refresh()
      },
    }
  },
})

createApp({ components: { SectionList: sectionList, ...defineButtonComponents() } }, {
  selector: '#app-content',
  template: html`<SectionList/>`,
})

The refresh reads the current article, assigns IDs to new headings, rebuilds the links in DOM order, and updates active-section tracking. It preserves panel preferences and the IDs already on your headings.

Call it after adding, removing, renaming or reordering sections, or changing data-toc-ignore. Refresh once after a group of changes. To remove an app's entries on unmount, remove its content and refresh again.

For fetched content, await your loader in a component action or mounted hook, assign the resolved entries to the sections ref, then refresh. Keep loading and error state in your app. The same refresh() API works with any app that renders headings into the content container.

Headings from rendered content

The examples in this section participate in this guide's real TOC. Find the HTML heading, the component heading, both loop entries and the evaluated title in the sidebar. The conditional heading is absent; the ignored example and h4 detail stay outside the outline.

A heading written as HTML

This h3 has an authored ID. Its TOC link points to #toc-html-heading.

A heading rendered by a component

SectionHeader emits the heading during SSG. It participates in the same outline.

First heading from a loop

This section comes from a Regor loop over the page's frontmatter.

Second heading from a loop

This section comes from a Regor loop over the page's frontmatter.

A heading with evaluated text

The label and generated ID use the evaluated title above.

An example deliberately outside the TOC

This heading is visible, but its containing element has data-toc-ignore. It has no entry in the sidebar.

A detail below the TOC's heading range

h4, h5 and h6 remain ordinary content. They do not create TOC entries.

View the rendered-heading examples
<h3 id="toc-html-heading">A heading written as HTML</h3>
<p>This h3 has an authored ID. Its TOC link points to #toc-html-heading.</p>

<SectionHeader
  title="A heading rendered by a component"
  titleTag="h3"
  titleId="toc-component-heading"
  titleClass="fs-lg"/>
<p>
  SectionHeader emits the heading during SSG. It participates in the same
  outline.
</p>

<section r-for="section in pageContext.pageInfo.frontmatter.tocExamples">
  <h3 :id="section.id">{{ section.title }}</h3>
  <p>This section comes from a Regor loop over the page's frontmatter.</p>
</section>

### {{ pageContext.pageInfo.frontmatter.tocEvaluatedTitle }}

The label and generated ID use the evaluated title above.

<h3 r-if="false">This conditional heading is never rendered</h3>

<div class="p-3 b-1 rounded-md tone-border-surface" data-toc-ignore>
  <h3 class="mt-0">An example deliberately outside the TOC</h3>
  <p class="mb-0">
    This heading is visible, but its containing element has data-toc-ignore. It
    has no entry in the sidebar.
  </p>
</div>

<h4>A detail below the TOC's heading range</h4>
<p>h4, h5 and h6 remain ordinary content. They do not create TOC entries.</p>

Heading and ID rules

Rule Result
h1, h2 and h3 inside the content container Collected in DOM order and nested by heading level.
One h1 at the root of the outline Its children become the visible TOC entries. Multiple h1 roots remain visible.
h4 through h6, or a heading with no text No entry.
r-if="false" No rendered heading, so no entry.
r-show, CSS visibility or a closed disclosure The heading still exists in the DOM; hiding it visually does not exclude it.
A heading or ancestor with data-toc-ignore No entry, even when the heading is visible.
Heading with an existing ID Keep it, including after renaming or reordering.
Heading without an ID Derive an ID from the rendered title, adding a suffix to avoid existing page IDs.

Generated IDs use lowercase ASCII letters and digits, with punctuation and spaces becoming hyphens. Duplicate Installation headings receive IDs such as installation and installation-2. A title without ASCII letters or digits uses section and numbered suffixes. For translated titles, public deep links or headings that change often, author an explicit ID:

<h2 id="account-settings">Account settings</h2>

A generated ID is assigned once to that DOM element. Refreshing after a rename keeps it. Replacing the element with a new heading without an ID generates an ID for the new element. Authors are responsible for keeping explicitly supplied IDs unique.

Exclude an individual heading or a whole example:

<h3 data-toc-ignore>Preview label</h3>

<div data-toc-ignore>
  <h2>A heading inside an embedded interface</h2>
</div>

Choose the content container

The standard doc layout already marks its article. Custom templates can use data-page-content to identify the area whose headings should become entries:

<main>
  <article data-page-content>
    <!-- Static content and client app mounts go here. -->
  </article>
</main>

Discovery uses the first matching data-page-content container, then the standard .doc-main .doc-content article, then the first main, then the body. Headers, navigation and footers outside the selected container do not participate. The same discovery rules apply during SSG and browser refresh.

Appearance and layout

The docked panel takes its appearance from site config. A page can override its tone and initial collapsed state in frontmatter.

{
  "pageToc": {
    "enabled": true,
    "tone": "neutral",
    "variant": "surfaceAlt",
    "class": "spotlight-from-top-right"
  }
}
layout:
  showToc: true
  tocTone: accent
  tocCollapsed: true

On wide screens, the panel follows the document as you scroll. Use its pin control to collapse or restore it and drag its left edge to resize it. On smaller screens, on this page opens the panel; selecting a link, clicking outside or pressing Escape closes it. Collapse and width preferences are remembered in this browser. tocCollapsed supplies the page's initial state; a saved collapse preference takes precedence.

The active section's link carries aria-current="location". Links use native fragments, so deep links and keyboard navigation work. Refreshing the entries does not reset the panel's open state or width.

Explore all tones, variants and outline examples

These isolated examples keep their headings and TOCs inside their own documents.

Ten semantic tones

Eighteen visual variants

Stateless and stateful appearance

Nested, flat and empty outlines

A standalone TOC with real targets

Supply an explicit outline

Custom templates and standalone examples can pass outline instead of using the page's discovered headings. Every ID must identify a real target in that document. The built-in doc template already adds its own PageToc.

<PageToc
  title="In this example"
  :outline="[
    { id: 'overview', title: 'Overview', depth: 2, children: [
      { id: 'requirements', title: 'Requirements', depth: 3 }
    ] },
    { id: 'next-steps', title: 'Next steps', depth: 2 }
  ]"
/>

SSG and a browser refresh() both preserve an explicitly supplied outline. Only refresh(root) with this TOC as root rebuilds it from the content container, replacing its current entries. For scroll tracking, use h1–h3 elements as targets.

Browser API

The standard runtime exposes window.tsSsgPageToc. Its TypeScript declaration is exported with @purestack/ts-page-scripts.

Method Purpose
refresh(root?: Element | null): void Read the current content and rebuild links and section tracking. This is the app-facing API.
hydrate(root?: Element | null): void Bind behavior to an existing TOC. Component output calls this automatically; it does not rediscover headings.

Without root, refresh rebuilds every TOC without an explicit outline, and hydrate selects the first .page-toc. To target one instance, pass its nav element or a container around it. The argument selects the TOC, not the heading container; data-page-content selects the content.

const panel = document.querySelector('#custom-toc')
if (panel) window.tsSsgPageToc?.refresh(panel)

Troubleshooting

Symptom Check
A client-only page has no TOC Set layout.showToc: always before building. refresh() updates an existing panel; it does not create a missing layout.
The TOC shows old links Refresh after the DOM update, including after unmounting an app.
A heading does not appear Check its level, text, content container, data-toc-ignore ancestors and conditional rendering.
A hidden example appears in the TOC CSS visibility does not remove headings from the DOM. Add data-toc-ignore.
A link reaches the wrong element Check for duplicate authored IDs. Generated IDs avoid collisions with IDs already on the page.
A renamed heading keeps its old fragment Existing IDs are preserved intentionally. Keep that ID for stable links, or choose a new explicit ID.
A second TOC updates Pass the intended panel to refresh(root). The default target is the first .page-toc.

API reference

PageToc contract

Props below are the public template API. RefOrValue accepts a literal or a reactive ref; bind refs with a colon-prefixed attribute. Native attributes and events can be passed through the component root.

outline

PageOutlineItem[] | SRef<PageOutlineItem[]>
Default
Final page outline

Entries contain id, title, optional depth and children. Links are built as #id; children are rendered recursively. Omit this prop to use headings discovered from the rendered page. An explicit empty array shows the empty state.

title

string
Default
On this page

Trimmed visible panel title. Empty text uses the default.

tone

RefOrValue<SemanticTone>
Default
inherited

Semantic intent: neutral, accent, secondary, info, success, warning, danger, feature, custom or ghost. The active skin supplies the colors.

variant

RefOrValue<ComponentVariant>
Default
flat

Visual treatment of the panel. Accepts solid, surface, surfaceAlt, spotlight, glass, flat, flatAlt, flatSolid, outlineFill, outline, subtle, subtleBtn, link, sheen, underline, rail, bracket or none. The panel keeps its own rounded corners whatever the variant.

variantMode

RefOrValue<ComponentVariantMode>
Default
stateless

Use stateless for the contents panel; stateful enables the treatment’s hover and active styles on the whole panel. Links keep their own hover and active styles either way.

Composition

No slots. Register definePageTocComponents with Icon. SSG context supplies the outline when outline is omitted; the standard runtime handles active-section and panel behavior.