summaryrefslogtreecommitdiff
path: root/packages/markdown/remark/src/rehype-jsx.ts
blob: 46c200b7087cda50386320ef86c02b7c00574884 (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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { visit } from 'unist-util-visit';

const MDX_ELEMENTS = ['mdxJsxFlowElement', 'mdxJsxTextElement'];
export default function rehypeJsx(): any {
	return function (node: any): any {
		visit(node, 'element', (child: any) => {
			child.tagName = `${child.tagName}`;
		});
		visit(node, MDX_ELEMENTS, (child: any, index: number | null, parent: any) => {
			if (index === null || !Boolean(parent))
				return;
			
			const attrs = child.attributes.reduce((acc: any[], entry: any) => {
				let attr = entry.value;
				if (attr && typeof attr === 'object') {
					attr = `{${attr.value}}`;
				} else if (attr && entry.type === 'mdxJsxExpressionAttribute') {
					attr = `{${attr}}`;
				} else if (attr === null) {
					attr = '';
				} else if (typeof attr === 'string') {
					attr = `"${attr}"`;
				}
				if (!entry.name) {
					return acc + ` ${attr}`;
				}
				return acc + ` ${entry.name}${attr ? '=' : ''}${attr}`;
			}, '');

			if (child.children.length === 0) {
				child.type = 'raw';
				child.value = `<${child.name}${attrs} />`;
				return;
			}

			// Replace the current child node with its children
			// wrapped by raw opening and closing tags
			const openingTag = {
				type: 'raw',
				value: `\n<${child.name}${attrs}>`,
			};
			const closingTag = {
				type: 'raw',
				value: `</${child.name}>\n`,
			};
			parent.children.splice(index, 1, openingTag, ...child.children, closingTag);
		});
	};
}