hast-util-properties-to-mdx-jsx-attributes
v1.0.0
Published
Transform hast properties into mdxJsxAttribute nodes
Downloads
42,454
Readme
hast-util-properties-to-mdx-jsx-attributes
Transform hast
properties to a list of
mdxJsxAttribute
nodes.
Table of Contents
Installation
npm install hast-util-properties-to-mdx-jsx-attributes
Usage
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
API
propertiesToMdxJsxAttributes(properties, options?)
Transform hast
properties to a list of
mdxJsxAttribute
nodes.
Arguments
properties
(Properties
) — The hast properties to transform.options
(object
) — Additional options to pass. The following options are supported:elementAttributeNameCase
('html' | 'react'
) — The casing to use for attribute names. This should match theelementAttributeNameCase
option specified in the MDX options. (Default:'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 called with the name of the MDX JSX attribute that’s being generated, the value that would be used if no transform function is passed, and the value as it was in the hast properties. It should return an ESTree expression or string to represent the value, ornull
orundefined
to generate an attribute with no value.
Returns
The hast properties as a list of
mdxJsxAttribute
nodes.
Compatibility
This project is compatible with Node.js 16 or greater.