1const visit = require('unist-util-visit'); 2 3/** 4 * @typedef {import('@types/mdast').Root} Root - https://github.com/syntax-tree/mdast#root 5 * @typedef {import('@types/mdast').Heading} Heading - https://github.com/syntax-tree/mdast#heading 6 */ 7 8/** 9 * Find all headings within a MDX document, and export them as JS array. 10 * This uses the MDAST's `heading` and tries to guess the children's content. 11 * When the node has an ID, generated by `remark-slug`, the ID is added to the exported object. 12 * 13 * @param {object} options 14 * @param {string} [options.exportName="headings"] 15 */ 16module.exports = function remarkExportHeadings(options = {}) { 17 const { exportName = 'headings' } = options; 18 19 /** @param {Root} tree */ 20 return tree => { 21 const headings = []; 22 23 /** @param {Heading} node */ 24 const visitor = node => { 25 if (node.children.length > 0) { 26 headings.push({ 27 id: node.data?.id, 28 depth: node.depth, 29 type: node.children.find(node => node.type !== 'text')?.type || 'text', 30 title: node.children.map(child => child.value).join(' '), 31 }); 32 } 33 }; 34 35 visit(tree, 'heading', visitor); 36 37 tree.children.push({ 38 type: 'export', 39 value: `export const ${exportName} = ${JSON.stringify(headings)};`, 40 }); 41 }; 42}; 43