summaryrefslogtreecommitdiff
path: root/packages/markdown/remark/src/rehype-jsx.ts
blob: cccbd5548fbb274a819454d81a9d6e83e55e8ca3 (plain) (blame)
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
import { map } from 'unist-util-map';

const MDX_ELEMENTS = new Set(['mdxJsxFlowElement', 'mdxJsxTextElement']);
export default function rehypeJsx(): any {
	return function (node: any): any {
		return map(node, (child: any) => {
			if (child.type === 'element') {
				return { ...child, tagName: `${child.tagName}` };
			}
			if (MDX_ELEMENTS.has(child.type)) {
				return {
					...child,
					type: 'element',
					tagName: `${child.name}`,
					properties: child.attributes.reduce((acc: any[], entry: any) => {
						let attr = entry.value;
						if (attr && typeof attr === 'object') {
							attr = `{${attr.value}}`;
						} else if (attr === null) {
							attr = `{true}`;
						}
						return Object.assign(acc, { [entry.name]: attr });
					}, {}),
				};
			}
			return child;
		});
	};
}