Skip to content

Table of contents ​

The TOC plugin creates an outline of the document's H2–H6 headings. Entries update as you edit or reorder headings, including after undo and redo. You can set the title, heading range, and list numbering for each TOC block.

Try it in the live demo

Install ​

bash
npm install @shelamkoff/rector@2 @shelamkoff/rector-toc-plugin

Add a TOC block ​

Use one source per editor. Register the TOC plugin with your other block plugins, then bind the source so it follows committed edits.

js
import { createEditor } from '@shelamkoff/rector'
import { createHeadingPlugin, createParagraphPlugin } from '@shelamkoff/rector/plugins'
import { createTocPlugin, createTocSource } from '@shelamkoff/rector-toc-plugin'

const source = createTocSource()
const editor = createEditor({
  holder: document.querySelector('#editor'),
  plugins: [
    createParagraphPlugin(),
    createHeadingPlugin(),
    createTocPlugin({ source }),
  ],
})
source.bindEditor(editor)
editor.blocks.insert({ type: 'toc' })

You can also insert the block from the toolbox and configure it in the block settings. Pass the same inlinePlugins array to Rector and createTocSource() if your headings contain inline widgets. Call editor.destroy() and source.destroy() when removing the editor.

Render a saved document ​

Use the saved result of editor.save() as documentData. Create a separate source for each rendered article. Use the same anchorPrefix for registering the TOC renderer and mounting the document. Choose a different prefix for each independent article on a page. Heading anchors use block IDs and survive title changes.

js
import { EditorRenderer } from '@shelamkoff/rector/renderer'
import { createTocRenderer, createTocSource, renderTocDocument } from '@shelamkoff/rector-toc-plugin'

const publicationSource = createTocSource()
const renderer = new EditorRenderer()
const anchorPrefix = 'article-'
renderer.registerRenderer(createTocRenderer({ source: publicationSource, anchorPrefix }))
renderTocDocument(renderer, documentData, document.querySelector('#article'), {
  source: publicationSource,
  anchorPrefix,
})

Call renderer.destroy() and publicationSource.destroy() when removing the article. Set injectStyles: false on Rector and TOC when your application imports styles via the bundler. Import both @shelamkoff/rector/styles.css and @shelamkoff/rector-toc-plugin/styles.css. Plugin reference

Rector is released under the MIT License.