feat(v1): add 'slugPreprocessor' config option to allow users customize the hash links (#3124)

* fix(v1): remove HTML content from hash links

* fix one more test

* rewrite changes as new feature to prevent breaking changes
This commit is contained in:
Bartosz Kaszubowski 2020-07-28 14:17:28 +02:00 committed by GitHub
parent d1a27efe8c
commit aa7430e168
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 50 additions and 11 deletions

View file

@ -19,7 +19,12 @@ const tocRegex = new RegExp('<AUTOGENERATED_TABLE_OF_CONTENTS>', 'i');
* Array of heading objects with `hashLink`, `content` and `children` fields
*
*/
function getTOC(content, headingTags = 'h2', subHeadingTags = 'h3') {
function getTOC(
content,
headingTags = 'h2',
subHeadingTags = 'h3',
slugPreprocessor = undefined,
) {
const tagToLevel = (tag) => Number(tag.slice(1));
const headingLevels = [].concat(headingTags).map(tagToLevel);
const subHeadingLevels = subHeadingTags
@ -38,8 +43,11 @@ function getTOC(content, headingTags = 'h2', subHeadingTags = 'h3') {
headings.forEach((heading) => {
const rawContent = heading.content;
const rendered = md.renderInline(rawContent);
const hashLink = toSlug(rawContent, slugger);
const slugBase =
slugPreprocessor && typeof slugPreprocessor === 'function'
? slugPreprocessor(rawContent)
: rawContent;
const hashLink = toSlug(slugBase, slugger);
if (!allowedHeadingLevels.includes(heading.lvl)) {
return;
}
@ -61,12 +69,12 @@ function getTOC(content, headingTags = 'h2', subHeadingTags = 'h3') {
// takes the content of a doc article and returns the content with a table of
// contents inserted
function insertTOC(rawContent) {
function insertTOC(rawContent, slugPreprocessor = undefined) {
if (!rawContent || !tocRegex.test(rawContent)) {
return rawContent;
}
const filterRe = /^`[^`]*`/;
const headers = getTOC(rawContent, 'h3', null);
const headers = getTOC(rawContent, 'h3', null, slugPreprocessor);
const tableOfContents = headers
.filter((header) => filterRe.test(header.rawContent))
.map((header) => ` - [${header.rawContent}](#${header.hashLink})`)