mirror of
https://github.com/facebook/docusaurus.git
synced 2025-06-05 04:12:53 +02:00
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:
parent
d1a27efe8c
commit
aa7430e168
7 changed files with 50 additions and 11 deletions
|
@ -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})`)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue