UNPKG

@alauda/doom

Version:

Doctor Doom making docs.

49 lines (48 loc) 1.8 kB
import Slugger from '@rspress/shared/github-slugger'; import { extractTextAndId } from '@rspress/shared/node-utils'; import { visitChildren } from 'unist-util-visit-children'; 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 }; };