Skip to content

Commit

Permalink
Add function to generate TOC from document headings (#474)
Browse files Browse the repository at this point in the history
  • Loading branch information
microbouji authored and JoelMarcey committed Feb 28, 2018
1 parent d2bff69 commit 6eb6580
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions lib/core/getTOC.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
const Remarkable = require('remarkable');
const toSlug = require('./toSlug');

const tagToLevel = tag => Number(tag.slice(1));

/**
* Returns a table of content from the headings
*
* @return array
* Array of heading objects with `hashLink`, `text` and `children` fields
*
*/
module.exports = (content, headingTags = 'h2', subHeadingTags = 'h3') => {
const headingLevels = [].concat(headingTags).map(tagToLevel);
const subHeadingLevels = subHeadingTags
? [].concat(subHeadingTags).map(tagToLevel)
: [];

const md = new Remarkable();
const tokens = md.parse(content, {});
const headings = [];
for (let i = 0; i < tokens.length; i++) {
if (
tokens[i].type == 'heading_open' &&
headingLevels.concat(subHeadingLevels).includes(tokens[i].hLevel)
) {
headings.push({
hLevel: tokens[i].hLevel,
text: tokens[i + 1].content,
});
}
}

const toc = [];
let current;
headings.forEach(heading => {
const entry = {
hashLink: toSlug(heading.text),
text: heading.text,
children: [],
};

if (headingLevels.includes(heading.hLevel)) {
toc.push(entry);
current = entry;
} else {
current && current.children.push(entry);
}
});

return toc;
};

0 comments on commit 6eb6580

Please sign in to comment.