astro/packages/markdown/remark/src/remark-slug.ts
2021-12-22 16:11:05 -05:00

32 lines
837 B
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @typedef {import('mdast').Root} Root
* @typedef {import('hast').Properties} Properties
*/
import { toString } from 'mdast-util-to-string';
import { visit } from 'unist-util-visit';
import BananaSlug from 'github-slugger';
const slugs = new BananaSlug();
/**
* Plugin to add anchors headings using GitHubs algorithm.
*
* @type {import('unified').Plugin<void[], Root>}
*/
export default function remarkSlug() {
return (tree: any) => {
slugs.reset();
visit(tree, (node) => {
console.log(node);
});
visit(tree, 'heading', (node) => {
const data = node.data || (node.data = {});
const props = /** @type {Properties} */ data.hProperties || (data.hProperties = {});
let id = props.id;
id = id ? slugs.slug(String(id), true) : slugs.slug(toString(node));
data.id = id;
props.id = id;
});
};
}