rehype-attr2
Version:
New syntax to add attributes to Markdown.
55 lines (54 loc) • 2.26 kB
JavaScript
import { visit } from 'unist-util-visit';
export const rehypeStagger = (options = {}) => {
const { elements = '*', startNum = 1, increment = 1, min = 0, max = 99, shouldIncrease = () => true, componentNames = '*', attributeName = 'stagger', } = options;
return (tree) => {
let count = startNum - increment;
visit(tree, ['element', 'mdxJsxFlowElement'], (node) => {
switch (node.type) {
case 'element':
if (elements !== '*' && !elements.includes(node.tagName)) {
return;
}
if (shouldIncrease(node.tagName)) {
count += increment;
count = clamp(count, min, max);
}
const style = node.properties?.style;
const styleValue = typeof style === 'object'
? Object.entries(style).map(([key, value]) => `${key}:${value}`).join(';')
: String(style || '');
node.properties = {
...node.properties,
style: withStagger(styleValue, count)
};
break;
// @ts-ignore
case 'mdxJsxFlowElement':
// @ts-ignore
if (componentNames !== '*' && !componentNames.includes(node.name)) {
return;
}
// @ts-ignore
if (shouldIncrease(node.name)) {
count += increment;
count = clamp(count, min, max);
}
// @ts-ignore
node.attributes = node.attributes || [];
// @ts-ignore
node.attributes.push({
type: 'mdxJsxAttribute',
name: attributeName,
value: count,
});
break;
}
});
};
};
const withStagger = (style, count) => {
return `--stagger:${count}; ${style}`.trim();
};
const clamp = (value, min, max) => {
return Math.max(Math.min(value, max), min);
};