SupremeTechnopriest/react-idle-timer

View on GitHub
docs/src/utils/mdx.ts

Summary

Maintainability
A
0 mins
Test Coverage
import slugger from 'github-slugger'

export function getTableOfContents (mdxContent: string) {
  const regexp = /^(### |## |\{\/\* ## )(.*)\n/gm

  // @ts-ignore
  const headings = [...mdxContent.matchAll(regexp)]
  let tableOfContents = []

  if (headings.length) {
    tableOfContents = headings.map((heading) => {
      const headingText = heading[2].trim()
      const headingType = heading[1].trim() === '##' ? 'h2' : 'h3'
      const headingLink = slugger.slug(headingText, false)

      return {
        text: headingText,
        id: headingLink,
        level: headingType
      }
    })
  }

  return tableOfContents
}