const visit = require(`unist-util-visit`) const slugs = require(`github-slugger`)() function toString(node) { return ( valueOf(node) || (node.children && node.children.map(toString).join("")) || "" ) } function valueOf(node) { return ( (node && node.value ? node.value : node.alt ? node.alt : node.title) || "" ) } function patch(context, key, value) { if (!context[key]) { context[key] = value } return context[key] } function stripLeadingNumber(value) { return value.replace(/^(\d*\-)(.*)/, "$2") } const svgIcon = `` module.exports = ( { markdownAST }, { icon = svgIcon, attr = "id", className = "anchor", maintainCase = false } ) => { slugs.reset() visit(markdownAST, `heading`, (node) => { const id = slugs.slug(toString(node), maintainCase) const strippedId = stripLeadingNumber(id) const data = patch(node, `data`, {}) patch(data, attr, strippedId) patch(data, `htmlAttributes`, {}) patch(data, `hProperties`, {}) patch(data.htmlAttributes, attr, strippedId) patch(data.hProperties, attr, strippedId) if (icon !== false) { node.children.unshift({ type: `link`, url: `#${strippedId}`, title: null, data: { hProperties: { "aria-hidden": true, class: className, }, hChildren: [ { type: `raw`, // The Octicon link icon is the default. But users can set their own icon via the "icon" option. value: icon, }, ], }, }) } }) return markdownAST }