API Reference

📚 API Overview

Complete reference for the Astro Table of Contents integration. This page covers all available functions, components, types, and configuration options.

🔧 Integration API

tableOfContents(config)

Main integration function that configures the table of contents for your Astro project.

Parameters

Parameter Type Required Description
config TocConfig No Configuration object for the TOC integration

Returns

AstroIntegration - Astro integration object

Example

import { defineConfig } from 'astro/config';
import { tableOfContents } from 'astro-table-of-contents';

export default defineConfig({
    integrations: [
        tableOfContents({
            title: 'Table of Contents',
        }),
    ],
});

🧩 TableOfContents Component

<TableOfContents />

Astro component that renders an interactive table of contents based on headings in your content.

Props

Prop Type Default Description
title string undefined Custom title for this TOC instance
backgroundColor string 'transparent' Custom background color (CSS color value)
class string undefined Additional CSS classes for styling

Usage Example

---
import TableOfContents from 'astro-table-of-contents/component';
---

<TableOfContents 
  title="Page Contents"
  backgroundColor="#f8f9fa"
  class="custom-toc"
/>

⚠️ SSR Considerations

Title Prop in SSR Mode

Important: When using Astro in SSR mode (output: "server") or hybrid mode, the global title configuration from astro.config.mjs may not be accessible. In these cases, you must provide the title prop directly to the component.

// ✅ Recommended for SSR
<TableOfContents title="My Custom Title" />

// ❌ May not work in SSR (relies on config)
<TableOfContents /> // Will fallback to "Table of Contents"

🔧 Development Note: We are actively working on enhancing SSR compatibility to make global configuration accessible across all Astro rendering modes in future releases.

🔄 Generator Functions

generateToc(options)

Programmatically generates table of contents HTML from content.

Parameters

Parameter Type Required Description
options TocOptions Yes Options object containing content to parse

Returns

string - Generated HTML for the table of contents

Example

import { generateToc } from 'astro-table-of-contents';

const htmlContent = `
  <h1>Introduction</h1>
  <h2>Getting Started</h2>
  <h3>Installation</h3>
  <h3>Configuration</h3>
  <h2>Advanced Usage</h2>
`;

const tocHtml = generateToc({ content: htmlContent });
console.log(tocHtml);

buildHierarchy(headings, startIndex?, currentLevel?)

Builds hierarchical HTML structure from parsed heading data.

Parameters

Parameter Type Default Description
headings HeadingData[] - Array of parsed heading objects
startIndex number 0 Starting index in headings array
currentLevel number 1 Current heading level for hierarchy

Returns

HierarchyResult - Object with generated HTML and next index

🔍 Parser Functions

parseHeadings(content)

Extracts heading information from HTML content.

Parameters

Parameter Type Required Description
content string Yes HTML content to parse for headings

Returns

HeadingData[] - Array of heading objects with level, title, and id

📋 Type Definitions

TocConfig

Configuration interface for the table of contents integration.

interface TocConfig {
    title?: string;           // Default title for TOC
}

TocOptions

Options for manual TOC generation.

interface TocOptions {
    content: string;          // HTML content to parse
}

HeadingData

Structure representing a parsed heading.

interface HeadingData {
    level: number;            // Heading level (1-6)
    title: string;            // Text content of heading
    id: string;               // Generated or existing ID attribute
}

HierarchyResult

Return type for hierarchy building functions.

interface HierarchyResult {
    html: string;             // Generated HTML string
    nextIndex: number;        // Next index to process
}

🎨 HTML Templates

Template Functions

Functions that generate HTML structures for the table of contents.

tocContainerTemplate(content)

Wraps TOC content in the main container structure.

nestedListTemplate(content)

Creates nested list structure for hierarchical content.

tocItemTemplate(id, title)

Generates individual TOC item HTML.

Example Usage

import { 
    tocContainerTemplate, 
    nestedListTemplate, 
    tocItemTemplate 
} from 'astro-table-of-contents';

const item = tocItemTemplate('intro', 'Introduction');
const list = nestedListTemplate(item);
const container = tocContainerTemplate(list);

🎨 CSS Classes

Default CSS classes applied to the table of contents for styling customization.

Component Classes

Class Element Description
stron-toc Main container Root element of the TOC component
#toc-title Title element Clickable title that toggles collapse
collapsed Main container Applied when TOC is collapsed

Example Custom Styling

/* Custom TOC styling */
stron-toc {
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    background: #ffffff;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

stron-toc #toc-title {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 1rem;
    margin: -1rem -1rem 1rem -1rem;
}

stron-toc a {
    color: #4a5568;
    font-weight: 500;
}

stron-toc a:hover {
    color: #667eea;
    text-decoration: underline;
}

🔄 Middleware API

TOC Middleware

Automatic processing middleware that runs during the Astro build process.

processHtmlFilesForToc()

Processes HTML files and injects TOC where appropriate.

Features

  • Automatic heading detection and ID generation
  • Smart TOC placement based on content structure
  • Integration with Astro's build pipeline
  • Configurable through integration options

📦 Package Exports

Main Exports

// Main integration
import { tableOfContents } from 'astro-table-of-contents';

// Component
import TableOfContents from 'astro-table-of-contents/component';

// Middleware (for advanced usage)
import { tocMiddleware } from 'astro-table-of-contents/middleware';