Skip to content

Table of contents

On this page: links to the h2 and h3 of an article, from Markdown headings or Portable Text.

Native .astro · no React · MIT · free, no account

Install

Terminal
npx shadcn@latest add https://www.themes.dev/astro/r/toc.json

The CLI needs a components.json (from npx shadcn init), which also writes the tokens these files use. No CLI? Copy the files below to the same paths.

Files

src/kit/components/Toc.astroAstro
---// "On this page": links to the h2 and h3 headings of an article. Pass Markdown's `headings` (from render()) or// headingsFromPortableText(body). Renders nothing for fewer than two headings.// <Toc headings={headings} />import type { Heading } from '../lib/headings'; interface Props {  headings: Heading[];  title?: string;  /** The deepest level listed: 3 lists h2 and h3. */  depth?: 2 | 3;  class?: string;}const { title = 'On this page', depth = 3, class: className } = Astro.props;const headings = Astro.props.headings.filter((h) => h.depth >= 2 && h.depth <= depth);--- {  headings.length >= 2 && (    <nav aria-labelledby="toc-title" class:list={['text-sm', className]}>      <p id="toc-title" class="mb-3 font-semibold">{title}</p>      <ol class="flex flex-col gap-2 border-l">        {headings.map((h) => (          <li class:list={[h.depth === 3 ? 'pl-7' : 'pl-4']}>            <a href={`#${h.slug}`} class="-ml-px block border-l border-transparent leading-[1.4] text-muted-foreground transition-colors hover:border-foreground hover:text-foreground">              {h.text}            </a>          </li>        ))}      </ol>    </nav>  )}
src/kit/lib/headings.tsTypeScript
// Headings for a table of contents. Markdown and MDX give them to you (render() returns `headings`); for Portable// Text, headingsFromPortableText() reads the h2 and h3 blocks and gives them the same slugs <PortableText> uses.export interface Heading {  depth: number;  slug: string;  text: string;} /** A URL-safe id from heading text: lower case, accents dropped, words joined by hyphens. */export function slugify(text: string) {  return text    .normalize('NFKD')    .replace(/[̀-ͯ]/g, '')    .toLowerCase()    .replace(/[^a-z0-9]+/g, '-')    .replace(/^-+|-+$/g, '');} type Block = { _type: string; style?: string; children?: { text?: string }[] }; /** Plain text of a Portable Text block. */export const blockText = (b: Block) => (b.children ?? []).map((c) => c.text ?? '').join(''); /** Unique slugs: a second "Pricing" becomes "pricing-2". Call with one Map per page. */export function uniqueSlug(text: string, seen: Map<string, number>) {  const base = slugify(text) || 'section';  const n = (seen.get(base) ?? 0) + 1;  seen.set(base, n);  return n === 1 ? base : `${base}-${n}`;} export function headingsFromPortableText(blocks: Block[] = []): Heading[] {  const seen = new Map<string, number>();  return blocks    .filter((b) => b._type === 'block' && (b.style === 'h2' || b.style === 'h3'))    .map((b) => {      const text = blockText(b);      return { depth: b.style === 'h2' ? 2 : 3, slug: uniqueSlug(text, seen), text };    });}