mirror of
https://github.com/facebook/docusaurus.git
synced 2025-06-03 03:12:35 +02:00
Add function to generate TOC from document headings (#474)
This commit is contained in:
parent
d2bff6929e
commit
6eb658009b
1 changed files with 52 additions and 0 deletions
52
lib/core/getTOC.js
Normal file
52
lib/core/getTOC.js
Normal file
|
@ -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;
|
||||||
|
};
|
Loading…
Add table
Add a link
Reference in a new issue