Ensure anchor links are unique per document (#574)

This commit is contained in:
Sviatoslav 2018-05-04 05:36:12 +03:00 committed by Yangshun Tay
parent 2a83959ac1
commit 9c98142fea
12 changed files with 440 additions and 43 deletions

View file

@ -23,20 +23,29 @@ module.exports = (content, headingTags = 'h2', subHeadingTags = 'h3') => {
const subHeadingLevels = subHeadingTags
? [].concat(subHeadingTags).map(tagToLevel)
: [];
const allowedHeadingLevels = headingLevels.concat(subHeadingLevels);
const md = new Remarkable();
const headings = mdToc(content, {
filter: function(str, ele) {
return headingLevels.concat(subHeadingLevels).includes(ele.lvl);
},
}).json;
const headings = mdToc(content).json;
const toc = [];
const context = {};
let current;
headings.forEach(heading => {
// we need always generate slugs to ensure, that we will have consistent
// slug indexes for headings with the same names
const hashLink = toSlug(heading.content, context);
if (!allowedHeadingLevels.includes(heading.lvl)) {
return;
}
const rawContent = mdToc.titleize(heading.content);
const entry = {
hashLink: toSlug(heading.content),
content: md.renderInline(mdToc.titleize(heading.content)),
hashLink,
rawContent,
content: md.renderInline(rawContent),
children: [],
};