@plugdash/tocgen

tocgen

260 words·2min read

What it does

Walks your Portable Text body on publish, picks out h2/h3/h4 blocks, and writes a nested entries tree to post.data.metadata.tocgen. Short posts (fewer than minHeadings) are skipped. Ships TableOfContents.astro with a sticky sidebar variant.

The docs sidebar on the right is tocgen running on this page. If you can see it, the plugin works.

Install

npm install @plugdash/tocgen

Register

Open astro.config.mjs at the root of your Astro project. Import the plugin at the top, then add it to the plugins array of the emdash() integration - the one that sits inside Astro's top-level integrations array:

// astro.config.mjs
import { defineConfig } from "astro/config"
import emdash from "emdash/astro"
import { tocgenPlugin } from "@plugdash/tocgen"

export default defineConfig({
  integrations: [
    emdash({
      plugins: [
        tocgenPlugin({ minHeadings: 3 }),
      ],
    }),
  ],
})

Add the component

---
import TableOfContents from "@plugdash/tocgen/TableOfContents.astro"
---
<TableOfContents post={post} sticky />

Live demo

Props

proptypedefaultdescription
postEmDash content itemRequired
stickybooleanfalseStick to viewport while scrolling
maxDepth2 | 3 | 43Deepest heading level to include

CSS custom properties

tokendescription
--plugdash-toc-sizeFont size
--plugdash-toc-indentNested indent
--plugdash-toc-hoverHover colour

For agents

After install, publish a post with at least minHeadings h2 headings. Verify post.data.metadata.tocgen.entries is a non-empty array. Heading IDs come from slugifying the heading text.

built with plugdash