summaryrefslogtreecommitdiff
path: root/packages/integrations/mdx/src/rehype-images-to-component.ts
blob: 6676ee3230a6acf25e0f9ba0f72b54b2962bffa7 (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
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import type { Properties, Root } from 'hast';
import type { MdxJsxAttribute, MdxjsEsm } from 'mdast-util-mdx';
import type { MdxJsxFlowElementHast } from 'mdast-util-mdx-jsx';
import { visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
import { jsToTreeNode } from './utils.js';

export const ASTRO_IMAGE_ELEMENT = 'astro-image';
export const ASTRO_IMAGE_IMPORT = '__AstroImage__';
export const USES_ASTRO_IMAGE_FLAG = '__usesAstroImage';

function createArrayAttribute(name: string, values: (string | number)[]): MdxJsxAttribute {
	return {
		type: 'mdxJsxAttribute',
		name: name,
		value: {
			type: 'mdxJsxAttributeValueExpression',
			value: name,
			data: {
				estree: {
					type: 'Program',
					body: [
						{
							type: 'ExpressionStatement',
							expression: {
								type: 'ArrayExpression',
								elements: values.map((value) => ({
									type: 'Literal',
									value: value,
									raw: String(value),
								})),
							},
						},
					],
					sourceType: 'module',
					comments: [],
				},
			},
		},
	};
}

/**
 * Convert the <img /> element properties (except `src`) to MDX JSX attributes.
 *
 * @param {Properties} props - The element properties
 * @returns {MdxJsxAttribute[]} The MDX attributes
 */
function getImageComponentAttributes(props: Properties): MdxJsxAttribute[] {
	const attrs: MdxJsxAttribute[] = [];

	for (const [prop, value] of Object.entries(props)) {
		if (prop === 'src') continue;

		/*
		 * <Image /> component expects an array for those attributes but the
		 * received properties are sanitized as strings. So we need to convert them
		 * back to an array.
		 */
		if (prop === 'widths' || prop === 'densities') {
			attrs.push(createArrayAttribute(prop, String(value).split(' ')));
		} else {
			attrs.push({
				name: prop,
				type: 'mdxJsxAttribute',
				value: String(value),
			});
		}
	}

	return attrs;
}

export function rehypeImageToComponent() {
	return function (tree: Root, file: VFile) {
		if (!file.data.astro?.localImagePaths?.length && !file.data.astro?.remoteImagePaths?.length)
			return;
		const importsStatements: MdxjsEsm[] = [];
		const importedImages = new Map<string, string>();

		visit(tree, 'element', (node, index, parent) => {
			if (node.tagName !== 'img' || !node.properties.src) return;

			const src = decodeURI(String(node.properties.src));

			const isLocalImage = file.data.astro?.localImagePaths?.includes(src);
			const isRemoteImage = file.data.astro?.remoteImagePaths?.includes(src);

			let element: MdxJsxFlowElementHast;
			if (isLocalImage) {
				let importName = importedImages.get(src);

				if (!importName) {
					importName = `__${importedImages.size}_${src.replace(/\W/g, '_')}__`;

					importsStatements.push({
						type: 'mdxjsEsm',
						value: '',
						data: {
							estree: {
								type: 'Program',
								sourceType: 'module',
								body: [
									{
										attributes: [],
										type: 'ImportDeclaration',
										source: {
											type: 'Literal',
											value: src,
											raw: JSON.stringify(src),
										},
										specifiers: [
											{
												type: 'ImportDefaultSpecifier',
												local: { type: 'Identifier', name: importName },
											},
										],
									},
								],
							},
						},
					});
					importedImages.set(src, importName);
				}

				// Build a component that's equivalent to <Image src={importName} {...attributes} />
				element = {
					name: ASTRO_IMAGE_ELEMENT,
					type: 'mdxJsxFlowElement',
					attributes: [
						...getImageComponentAttributes(node.properties),
						{
							name: 'src',
							type: 'mdxJsxAttribute',
							value: {
								type: 'mdxJsxAttributeValueExpression',
								value: importName,
								data: {
									estree: {
										type: 'Program',
										sourceType: 'module',
										comments: [],
										body: [
											{
												type: 'ExpressionStatement',
												expression: { type: 'Identifier', name: importName },
											},
										],
									},
								},
							},
						},
					],
					children: [],
				};
			} else if (isRemoteImage) {
				// Build a component that's equivalent to <Image src={url} {...attributes} />
				element = {
					name: ASTRO_IMAGE_ELEMENT,
					type: 'mdxJsxFlowElement',
					attributes: [
						...getImageComponentAttributes(node.properties),
						{
							name: 'src',
							type: 'mdxJsxAttribute',
							value: src,
						},
					],
					children: [],
				};
			} else {
				return;
			}

			parent!.children.splice(index!, 1, element);
		});

		// Add all the import statements to the top of the file for the images
		tree.children.unshift(...importsStatements);

		tree.children.unshift(
			jsToTreeNode(`import { Image as ${ASTRO_IMAGE_IMPORT} } from "astro:assets";`),
		);
		// Export `__usesAstroImage` to pick up `astro:assets` usage in the module graph.
		// @see the '@astrojs/mdx-postprocess' plugin
		tree.children.push(jsToTreeNode(`export const ${USES_ASTRO_IMAGE_FLAG} = true`));
	};
}