Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add function to generate TOC from document headings #474

Merged
merged 1 commit into from
Feb 28, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
};