2021-05-17 14:29:16 +00:00
|
|
|
import { visit } from 'unist-util-visit';
|
2021-08-25 12:17:45 +00:00
|
|
|
import type { Root, Properties } from 'hast';
|
2021-05-17 14:29:16 +00:00
|
|
|
import slugger from 'github-slugger';
|
|
|
|
|
|
|
|
/** */
|
|
|
|
export default function createCollectHeaders() {
|
2021-12-22 21:11:05 +00:00
|
|
|
const headers: any[] = [];
|
2021-05-17 14:29:16 +00:00
|
|
|
|
2021-12-22 21:11:05 +00:00
|
|
|
function rehypeCollectHeaders() {
|
|
|
|
return function (tree: Root) {
|
|
|
|
visit(tree, (node) => {
|
|
|
|
if (node.type !== 'element') return;
|
|
|
|
const { tagName } = node;
|
|
|
|
if (tagName[0] !== 'h') return;
|
|
|
|
const [_, level] = tagName.match(/h([0-6])/) ?? [];
|
|
|
|
if (!level) return;
|
|
|
|
const depth = Number.parseInt(level);
|
2021-08-25 12:17:45 +00:00
|
|
|
|
2021-12-22 21:11:05 +00:00
|
|
|
let text = '';
|
2021-08-25 12:17:45 +00:00
|
|
|
|
2021-12-22 21:11:05 +00:00
|
|
|
visit(node, 'text', (child) => {
|
|
|
|
text += child.value;
|
|
|
|
});
|
2021-08-25 12:17:45 +00:00
|
|
|
|
2021-12-22 21:11:05 +00:00
|
|
|
let slug = node?.properties?.id || slugger.slug(text);
|
2021-08-25 12:17:45 +00:00
|
|
|
|
2021-12-22 21:11:05 +00:00
|
|
|
node.properties = node.properties || {};
|
|
|
|
node.properties.id = slug;
|
|
|
|
headers.push({ depth, slug, text });
|
|
|
|
});
|
|
|
|
};
|
|
|
|
}
|
2021-08-25 12:17:45 +00:00
|
|
|
|
2021-12-22 21:11:05 +00:00
|
|
|
return {
|
|
|
|
headers,
|
|
|
|
rehypeCollectHeaders,
|
|
|
|
};
|
2021-05-17 14:29:16 +00:00
|
|
|
}
|