jdsteinbach / eleventy-plugin-toc

11ty plugin to generate a TOC from page content
61 stars 19 forks source link

feat: Added extractText config option #39

Open lmammino opened 1 year ago

lmammino commented 1 year ago

This PR suggests a new option that allows users to customize how the text gets extrapolated from every heading entry.

Example use case

I have a markdown plugin that changes all my entries adding a direct link placeholder that can be used to easily link to headers.

For example, a simple h2 like the following:

<h2>My Study notes</h2>

Becomes:

<h2 id="my-study-notes" tabindex="-1"><a class="direct-link" href="#my-study-notes">
  <span class="sr-only">Jump to heading</span>
  <span aria-hidden="true">#</span>
</a> My Study notes</h2>

Because of this plugin when I use eleventy-plugin-toc I will end up with an entry in my TOC that would look like this:

Jump to heading My Study notes

Rather than just My Study notes.

Example usage of the proposed feature

With this new feature it is possible to customize how the text is extracted, so to fix the problem described in the previous section I could do the following:

// eleventy config
const pluginTOC = require('eleventy-plugin-toc')

// ...
module.exports = function (eleventyConfig) {
  // ...
  eleventyConfig.addPlugin(pluginTOC, {
    extractText: function(el) {
      return el.text().replace('Jump to heading', '').replace('#', '').trim()
    }
  })
  // ...
}

PS: as a bonus, this PR removes some vulnerabilities by running npm audit fix