-
-
Notifications
You must be signed in to change notification settings - Fork 8.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add function to generate TOC from document headings (#474)
- Loading branch information
1 parent
d2bff69
commit 6eb6580
Showing
1 changed file
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
}; |