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
|
|
|
|
2022-05-24 22:02:11 +00:00
|
|
|
let raw = '';
|
2021-12-22 21:11:05 +00:00
|
|
|
let text = '';
|
2022-05-24 22:02:11 +00:00
|
|
|
let isJSX = false;
|
|
|
|
visit(node, (child) => {
|
|
|
|
if (child.type === 'element') {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (child.type === 'raw') {
|
|
|
|
// HACK: serialized JSX from internal plugins, ignore these for slug
|
|
|
|
if (child.value.startsWith('\n<') || child.value.endsWith('>\n')) {
|
|
|
|
raw += child.value.replace(/^\n|\n$/g, '');
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (child.type === 'text' || child.type === 'raw') {
|
|
|
|
raw += child.value;
|
|
|
|
text += child.value;
|
|
|
|
isJSX = isJSX || child.value.includes('{');
|
|
|
|
}
|
2021-12-22 21:11:05 +00:00
|
|
|
});
|
2021-08-25 12:17:45 +00:00
|
|
|
|
2022-05-24 22:02:11 +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') {
|
2022-05-24 22:02:11 +00:00
|
|
|
if (isJSX) {
|
|
|
|
// HACK: for ids that have JSX content, use $$slug helper to generate slug at runtime
|
|
|
|
node.properties.id = `$$slug(\`${text.replace(/\{/g, '${')}\`)`;
|
|
|
|
(node as any).type = 'raw';
|
|
|
|
(node as any).value = `<${node.tagName} id={${node.properties.id}}>${raw}</${node.tagName}>`;
|
|
|
|
} else {
|
|
|
|
node.properties.id = slugger.slug(text);
|
|
|
|
}
|
2022-04-30 00:07:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
}
|