22
33import { u as createTree } from 'unist-builder' ;
44import { valueToEstree } from 'estree-util-value-to-estree' ;
5+ import { AST_NODES } from '../constants.mjs' ;
56
67/**
78 * Creates an MDX JSX element with support for complex attribute values.
@@ -18,54 +19,59 @@ export const createJSXElement = (
1819 name ,
1920 { inline = true , children = [ ] , ...attributes } = { }
2021) => {
21- // Process children: convert string to text node or use array as is
22+ // Convert string children to text node or use array directly
2223 const processedChildren =
2324 typeof children === 'string'
2425 ? [ createTree ( 'text' , { value : children } ) ]
25- : ( children ?? [ ] ) ;
26+ : children ;
27+
28+ const elementType = inline
29+ ? AST_NODES . MDX . JSX_INLINE_ELEMENT
30+ : AST_NODES . MDX . JSX_BLOCK_ELEMENT ;
2631
27- // Create attribute nodes, handling complex objects and primitive values differently
2832 const attrs = Object . entries ( attributes ) . map ( ( [ key , value ] ) =>
2933 createAttributeNode ( key , value )
3034 ) ;
3135
32- // Create and return the appropriate JSX element type
33- return createTree ( inline ? 'mdxJsxTextElement' : 'mdxJsxFlowElement' , {
36+ return createTree ( elementType , {
3437 name,
3538 attributes : attrs ,
3639 children : processedChildren ,
3740 } ) ;
3841} ;
3942
4043/**
41- * Creates an MDX JSX attribute node from the input .
44+ * Creates an MDX JSX attribute node based on the value type .
4245 *
4346 * @param {string } name - The attribute name
44- * @param {any } value - The attribute value (can be any valid JS value)
47+ * @param {any } value - The attribute value
4548 * @returns {import('unist').Node } The MDX JSX attribute node
4649 */
4750function createAttributeNode ( name , value ) {
48- // For objects and arrays, create expression nodes to preserve structure
51+ // Use expression for objects and arrays
4952 if ( value !== null && typeof value === 'object' ) {
50- return createTree ( 'mdxJsxAttribute' , {
53+ return createTree ( AST_NODES . MDX . JSX_ATTRIBUTE , {
5154 name,
52- value : createTree ( 'mdxJsxAttributeValueExpression' , {
55+ value : createTree ( AST_NODES . MDX . JSX_ATTRIBUTE_EXPRESSION , {
5356 data : {
5457 estree : {
55- type : 'Program' ,
58+ type : AST_NODES . ESTREE . PROGRAM ,
5659 body : [
5760 {
58- type : 'ExpressionStatement' ,
61+ type : AST_NODES . ESTREE . EXPRESSION_STATEMENT ,
5962 expression : valueToEstree ( value ) ,
6063 } ,
6164 ] ,
62- sourceType : 'module' ,
6365 } ,
6466 } ,
6567 } ) ,
6668 } ) ;
6769 }
6870
69- // For primitives, use simple string conversion
70- return createTree ( 'mdxJsxAttribute' , { name, value : String ( value ) } ) ;
71+ // For primitives, use simple string conversion.
72+ // If undefined, pass nothing.
73+ return createTree ( AST_NODES . MDX . JSX_ATTRIBUTE , {
74+ name,
75+ value : value === undefined ? value : String ( value ) ,
76+ } ) ;
7177}
0 commit comments