1
0
mirror of synced 2025-12-22 19:34:15 -05:00
Files
docs/lib/render-content/plugins/use-english-headings.js
Kevin Heis b29e37318a Remove import x statements (#20594)
* Clear out most import x

* Update rimraf use

* Move up readme blocks in scripts
2021-07-29 20:28:30 +00:00

27 lines
976 B
JavaScript

import GithubSlugger from 'github-slugger'
import HtmlEntities from 'html-entities'
import toString from 'hast-util-to-string'
import { visit } from 'unist-util-visit'
const slugger = new GithubSlugger()
const entities = new HtmlEntities.XmlEntities()
const matcher = (node) => node.type === 'element' && ['h2', 'h3', 'h4'].includes(node.tagName)
// replace translated IDs and links in headings with English
export default function useEnglishHeadings({ englishHeadings }) {
if (!englishHeadings) return
return (tree) => {
visit(tree, matcher, (node) => {
slugger.reset()
// Get the plain text content of the heading node
const text = toString(node)
// find English heading in the collection
const englishHeading = englishHeadings[entities.encode(text)]
// get English slug
const englishSlug = slugger.slug(englishHeading)
// use English slug for heading ID and link
node.properties.id = englishSlug
})
}
}