Transform hast properties to a list of mdxJsxAttribute nodes.
MIT License
Transform hast
properties to a list of
mdxJsxAttribute
nodes.
npm install hast-util-properties-to-mdx-jsx-attributes
propertiesToMdxJsxAttributes
takes hast
properties, and transform them to a list of
mdxJsxAttribute
nodes. This
is useful when creating an MDX plugin where you want to enhance a hast element with JSX specific
features, but you don’t want to transform all child nodes.
For example, this plugin prefixes all id
attributes on hast elements with the id
prop passed to
the MDX document.
import { type Root } from 'hast'
import { propertiesToMdxJsxAttributes } from 'hast-util-properties-to-mdx-jsx-attributes'
import { type Plugin } from 'unified'
import { visit } from 'unist-util-visit'
const rehypeMdxPrefixId: Plugin<[], Root> = () => (ast) => {
visit(ast, 'element', (element, index, parent) => {
let hasId = false
const replacement = {
type: 'mdxJsxFlowElement',
name: element.tagName,
attributes: propertiesToMdxJsxAttributes(element.properties, {
transform(name, value) {
hasId = true
return {
type: 'BinaryExpression',
operator: '+',
left: { type: 'Identifier', name: 'id' },
right: {
type: 'MemberExpression',
computed: false,
optional: false,
object: { type: 'Identifier', name: 'props' },
property: { type: 'Literal', value }
}
}
}
}),
children: element.children
}
if (hasId) {
parent!.children[index!] = replacement
}
})
}
export default rehypeMdxPrefixId
propertiesToMdxJsxAttributes(properties, options?)
Transform hast
properties to a list of
mdxJsxAttribute
nodes.
properties
(Properties
) — The hastoptions
(object
) — Additional options to pass. The following options are supported:
elementAttributeNameCase
('html' | 'react'
) — The casing to use for attribute names. ThiselementAttributeNameCase
option specified in the'react'
)space
('html' | 'svg'
) — The space the hast properties are in. (Default: 'html'
)transform
(function
) — A function to transform an attribute value. The function gets callednull
or undefined
to generate an attribute with no value.The hast properties as a list of
mdxJsxAttribute
nodes.
This project is compatible with Node.js 16 or greater.