|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +import { u as createTree } from 'unist-builder'; |
| 4 | +import { valueToEstree } from 'estree-util-value-to-estree'; |
| 5 | + |
| 6 | +/** |
| 7 | + * Creates an MDX JSX element with support for complex attribute values. |
| 8 | + * |
| 9 | + * @param {string} name - The name of the JSX element |
| 10 | + * @param {{ |
| 11 | + * inline?: boolean, |
| 12 | + * children?: string | import('unist').Node[], |
| 13 | + * [key: string]: any |
| 14 | + * }} [options={}] - Options including type, children, and JSX attributes |
| 15 | + * @returns {import('unist').Node} The created MDX JSX element node |
| 16 | + */ |
| 17 | +export const createJSXElement = ( |
| 18 | + name, |
| 19 | + { inline = true, children = [], ...attributes } = {} |
| 20 | +) => { |
| 21 | + // Process children: convert string to text node or use array as is |
| 22 | + const processedChildren = |
| 23 | + typeof children === 'string' |
| 24 | + ? [createTree('text', { value: children })] |
| 25 | + : (children ?? []); |
| 26 | + |
| 27 | + // Create attribute nodes, handling complex objects and primitive values differently |
| 28 | + const attrs = Object.entries(attributes).map(([key, value]) => |
| 29 | + createAttributeNode(key, value) |
| 30 | + ); |
| 31 | + |
| 32 | + // Create and return the appropriate JSX element type |
| 33 | + return createTree(inline ? 'mdxJsxTextElement' : 'mdxJsxFlowElement', { |
| 34 | + name, |
| 35 | + attributes: attrs, |
| 36 | + children: processedChildren, |
| 37 | + }); |
| 38 | +}; |
| 39 | + |
| 40 | +/** |
| 41 | + * Creates an MDX JSX attribute node from the input. |
| 42 | + * |
| 43 | + * @param {string} name - The attribute name |
| 44 | + * @param {any} value - The attribute value (can be any valid JS value) |
| 45 | + * @returns {import('unist').Node} The MDX JSX attribute node |
| 46 | + */ |
| 47 | +function createAttributeNode(name, value) { |
| 48 | + // For objects and arrays, create expression nodes to preserve structure |
| 49 | + if (value !== null && typeof value === 'object') { |
| 50 | + return createTree('mdxJsxAttribute', { |
| 51 | + name, |
| 52 | + value: createTree('mdxJsxAttributeValueExpression', { |
| 53 | + data: { |
| 54 | + estree: { |
| 55 | + type: 'Program', |
| 56 | + body: [ |
| 57 | + { |
| 58 | + type: 'ExpressionStatement', |
| 59 | + expression: valueToEstree(value), |
| 60 | + }, |
| 61 | + ], |
| 62 | + sourceType: 'module', |
| 63 | + }, |
| 64 | + }, |
| 65 | + }), |
| 66 | + }); |
| 67 | + } |
| 68 | + |
| 69 | + // For primitives, use simple string conversion |
| 70 | + return createTree('mdxJsxAttribute', { |
| 71 | + name, |
| 72 | + value: String(value), |
| 73 | + }); |
| 74 | +} |
0 commit comments