rehype-attr2
Version:
New syntax to add attributes to Markdown.
25 lines (24 loc) • 1.01 kB
JavaScript
import { visit } from 'unist-util-visit';
import { createRandomString, toUrlSafeString } from './utils.js';
export const rehypeId = (options = {}) => {
const { targetElements = ['h1', 'h2', 'h3'], prefix = 'rh-', initialValue = 0, type = 'increment', } = options;
return (tree) => {
let count = initialValue;
visit(tree, 'element', (node) => {
if (!targetElements.includes(node.tagName)) {
return;
}
switch (type) {
case 'increment':
count += 1;
node.properties = { ...node.properties, ...{ id: `${prefix}${count}` } };
break;
case 'content':
// @ts-expect-error
const content = toUrlSafeString(node.children[0]?.value ?? createRandomString(4));
node.properties = { ...node.properties, ...{ id: `${prefix}${content}` } };
break;
}
});
};
};