summaryrefslogtreecommitdiff
path: root/packages/markdown/remark/src/rehype-images.ts
blob: 71783ca1a05085285c5afb43ccef074c713ed4e4 (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
import { visit } from 'unist-util-visit';
import type { MarkdownVFile } from './types.js';

export function rehypeImages() {
	return () =>
		function (tree: any, file: MarkdownVFile) {
			const imageOccurrenceMap = new Map();

			visit(tree, (node) => {
				if (node.type !== 'element') return;
				if (node.tagName !== 'img') return;

				if (node.properties?.src) {
					if (file.data.imagePaths?.has(node.properties.src)) {
						const { ...props } = node.properties;

						// Initialize or increment occurrence count for this image
						const index = imageOccurrenceMap.get(node.properties.src) || 0;
						imageOccurrenceMap.set(node.properties.src, index + 1);

						node.properties['__ASTRO_IMAGE_'] = JSON.stringify({ ...props, index });

						Object.keys(props).forEach((prop) => {
							delete node.properties[prop];
						});
					}
				}
			});
		};
}