mirror of
https://github.com/facebook/docusaurus.git
synced 2025-05-13 00:57:53 +02:00
Use markdown-toc (#524)
This commit is contained in:
parent
632ccfb8cd
commit
c437f7be37
5 changed files with 186 additions and 26 deletions
|
@ -6,6 +6,7 @@
|
|||
*/
|
||||
|
||||
const Remarkable = require('remarkable');
|
||||
const mdToc = require('markdown-toc');
|
||||
const toSlug = require('./toSlug');
|
||||
|
||||
const tagToLevel = tag => Number(tag.slice(1));
|
||||
|
@ -14,7 +15,7 @@ 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
|
||||
* Array of heading objects with `hashLink`, `content` and `children` fields
|
||||
*
|
||||
*/
|
||||
module.exports = (content, headingTags = 'h2', subHeadingTags = 'h3') => {
|
||||
|
@ -24,30 +25,22 @@ module.exports = (content, headingTags = 'h2', subHeadingTags = 'h3') => {
|
|||
: [];
|
||||
|
||||
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 headings = mdToc(content, {
|
||||
filter: function(str, ele) {
|
||||
return headingLevels.concat(subHeadingLevels).includes(ele.lvl);
|
||||
},
|
||||
}).json;
|
||||
|
||||
const toc = [];
|
||||
let current;
|
||||
headings.forEach(heading => {
|
||||
const entry = {
|
||||
hashLink: toSlug(heading.text),
|
||||
text: heading.text,
|
||||
hashLink: toSlug(heading.content),
|
||||
content: md.renderInline(mdToc.titleize(heading.content)),
|
||||
children: [],
|
||||
};
|
||||
|
||||
if (headingLevels.includes(heading.hLevel)) {
|
||||
if (headingLevels.includes(heading.lvl)) {
|
||||
toc.push(entry);
|
||||
current = entry;
|
||||
} else {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue