astro/packages/markdown-support/src/rehype-collect-headers.ts
Robin Métral 397d8f3d84
Upgrade unified deps and improve unified plugins types (#1200)
* Upgrade @astrojs/markdown-support deps and update types

* Add changeset

* Update changeset

* Switch astro-markdown-plugins example to use rehype-autolink-headings

Usage of remark-autolink-headings is discouraged in favor of the rehype counterpart: https://github.com/remarkjs/remark-autolink-headings\#remark-autolink-headings

* Add stricter types for unified plugins

This includes a few suggestions from a code review:
- use vfile.toString instead of vfile.value.toString
- refactor plugins to follow unified best practices instead of returning functions that return a plugin
- use any instead of any[] for plugin options types

* Narrow down types to more specific hast or mdast typings
2021-08-25 08:17:45 -04:00

39 lines
1 KiB
TypeScript

import { visit } from 'unist-util-visit';
import type { Root, Properties } from 'hast';
import slugger from 'github-slugger';
/** */
export default function createCollectHeaders() {
const headers: any[] = [];
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);
let text = '';
visit(node, 'text', (child) => {
text += child.value;
});
let slug = node?.data?.id || slugger.slug(text);
node.data = node.data || {};
node.data.properties = node.data.properties || {};
node.data.properties = { ...(node.data.properties as Properties), slug };
headers.push({ depth, slug, text });
});
};
}
return {
headers,
rehypeCollectHeaders,
};
}