-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathast.mjs
More file actions
79 lines (71 loc) · 2.3 KB
/
ast.mjs
File metadata and controls
79 lines (71 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
'use strict';
import { u as createTree } from 'unist-builder';
import { valueToEstree } from 'estree-util-value-to-estree';
import { AST_NODE_TYPES } from '../constants.mjs';
/**
* @typedef {Object} JSXOptions
* @property {boolean} [inline] - Whether the element is inline
* @property {(string | Array<import('unist').Node>)} [children] - Child content or nodes
*/
/**
* Creates an MDX JSX element with support for complex attribute values.
*
* @param {string} name - The name of the JSX element
* @param {JSXOptions & Record<string, any>} [options={}] - Options including type, children, and JSX attributes
* @returns {import('unist').Node} The created MDX JSX element node
*/
export const createJSXElement = (
name,
{ inline = true, children = [], ...attributes } = {}
) => {
// Convert string children to text node or use array directly
const processedChildren =
typeof children === 'string'
? [createTree('text', { value: children })]
: children;
const elementType = inline
? AST_NODE_TYPES.MDX.JSX_INLINE_ELEMENT
: AST_NODE_TYPES.MDX.JSX_BLOCK_ELEMENT;
const attrs = Object.entries(attributes).map(([key, value]) =>
createAttributeNode(key, value)
);
return createTree(elementType, {
name,
attributes: attrs,
children: processedChildren,
});
};
/**
* Creates an MDX JSX attribute node based on the value type.
*
* @param {string} name - The attribute name
* @param {any} value - The attribute value
* @returns {import('unist').Node} The MDX JSX attribute node
*/
function createAttributeNode(name, value) {
// Use expression for objects and arrays
if (value !== null && typeof value === 'object') {
return createTree(AST_NODE_TYPES.MDX.JSX_ATTRIBUTE, {
name,
value: createTree(AST_NODE_TYPES.MDX.JSX_ATTRIBUTE_EXPRESSION, {
data: {
estree: {
type: AST_NODE_TYPES.ESTREE.PROGRAM,
body: [
{
type: AST_NODE_TYPES.ESTREE.EXPRESSION_STATEMENT,
expression: valueToEstree(value),
},
],
},
},
}),
});
}
// For primitives, use simple string conversion.
// If undefined, pass nothing.
return createTree(AST_NODE_TYPES.MDX.JSX_ATTRIBUTE, {
name,
value: value == null ? value : String(value),
});
}