2021-05-17 14:29:16 +00:00
|
|
|
import { visit } from 'unist-util-visit';
|
2022-04-30 00:07:09 +00:00
|
|
|
import Slugger from 'github-slugger';
|
|
|
|
|
|
|
|
import type { MarkdownHeader, RehypePlugin } from './types.js';
|
2021-05-17 14:29:16 +00:00
|
|
|
|
|
|
|
export default function createCollectHeaders() {
|
2022-04-30 00:07:09 +00:00
|
|
|
const headers: MarkdownHeader[] = [];
|
|
|
|
const slugger = new Slugger();
|
2021-05-17 14:29:16 +00:00
|
|
|
|
2022-04-30 00:07:09 +00:00
|
|
|
function rehypeCollectHeaders(): ReturnType<RehypePlugin> {
|
|
|
|
return function (tree) {
|
2021-12-22 21:11:05 +00:00
|
|
|
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
|
|
|
node.properties = node.properties || {};
|
2022-04-30 00:07:09 +00:00
|
|
|
if (typeof node.properties.id !== 'string') {
|
|
|
|
node.properties.id = slugger.slug(text);
|
|
|
|
}
|
|
|
|
|
|
|
|
headers.push({ depth, slug: node.properties.id, text });
|
2021-12-22 21:11:05 +00:00
|
|
|
});
|
|
|
|
};
|
|
|
|
}
|
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
|
|
|
}
|