@alauda/doom
Version:
Doctor Doom making docs.
49 lines (48 loc) • 1.78 kB
JavaScript
import Slugger from 'github-slugger';
import { visitChildren } from 'unist-util-visit-children';
import { extractTextAndId } from '../../shared/index.js';
export const parseToc = (tree, allDepths) => {
let title = '';
const toc = [];
const slugger = new Slugger();
visitChildren((node, index) => {
if (node.type !== 'heading' || !node.depth || !node.children) {
return;
}
// Collect h1 ~ h4 by default
if (allDepths || node.depth < 5) {
let customId = '';
const text = node.children
.map((child) => {
if (child.type === 'link') {
return child.children?.map((item) => item.value).join('');
}
if (child.type === 'strong') {
return `**${child.children?.map((item) => item.value).join('')}**`;
}
if (child.type === 'text') {
const [textPart, idPart] = extractTextAndId(child.value);
customId = idPart;
return textPart;
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (child.type === 'inlineCode') {
return `\`${child.value}\``;
}
return '';
})
.join('');
if (!allDepths && node.depth === 1) {
if (!title) {
title = text;
}
}
else {
const id = customId ? customId : slugger.slug(text);
const { depth } = node;
toc.push({ id, text, depth, index });
}
}
})(tree);
return { title, toc };
};