-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
/
toc.js
79 lines (72 loc) · 2.22 KB
/
toc.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const {Remarkable} = require('remarkable');
const mdToc = require('markdown-toc');
const striptags = require('striptags');
const GithubSlugger = require('github-slugger');
const toSlug = require('./toSlug');
const tocRegex = new RegExp('<AUTOGENERATED_TABLE_OF_CONTENTS>', 'i');
/**
* Returns a table of content from the headings
*
* @return array
* Array of heading objects with `hashLink`, `content` and `children` fields
*
*/
function getTOC(content, headingTags = 'h2', subHeadingTags = 'h3') {
const tagToLevel = tag => Number(tag.slice(1));
const headingLevels = [].concat(headingTags).map(tagToLevel);
const subHeadingLevels = subHeadingTags
? [].concat(subHeadingTags).map(tagToLevel)
: [];
const allowedHeadingLevels = headingLevels.concat(subHeadingLevels);
const md = new Remarkable();
const headings = mdToc(content).json;
const toc = [];
const slugger = new GithubSlugger();
let current;
headings.forEach(heading => {
const rawContent = heading.content;
const safeContent = striptags(rawContent);
const rendered = md.renderInline(safeContent);
const hashLink = toSlug(rawContent, slugger);
if (!allowedHeadingLevels.includes(heading.lvl)) {
return;
}
const entry = {
hashLink,
rawContent,
content: rendered,
children: [],
};
if (headingLevels.includes(heading.lvl)) {
toc.push(entry);
current = entry;
} else if (current) {
current.children.push(entry);
}
});
return toc;
}
// takes the content of a doc article and returns the content with a table of
// contents inserted
function insertTOC(rawContent) {
if (!rawContent || !tocRegex.test(rawContent)) {
return rawContent;
}
const filterRe = /^`[^`]*`/;
const headers = getTOC(rawContent, 'h3', null);
const tableOfContents = headers
.filter(header => filterRe.test(header.rawContent))
.map(header => ` - [${header.rawContent}](#${header.hashLink})`)
.join('\n');
return rawContent.replace(tocRegex, tableOfContents);
}
module.exports = {
getTOC,
insertTOC,
};