2024-11-15 16:01:33 +08:00
|
|
|
import type { Literal, Node, Parent } from 'unist';
|
|
|
|
import { selectAll } from 'unist-util-select';
|
|
|
|
import options from '../options';
|
|
|
|
import { urlJoin } from '../src/helpers/tools';
|
|
|
|
|
2024-12-04 05:16:35 +08:00
|
|
|
type LinkNode = Node & {
|
|
|
|
url: string;
|
|
|
|
children?: ImageNode[];
|
|
|
|
};
|
|
|
|
|
2024-11-15 16:01:33 +08:00
|
|
|
type ImageNode = Parent & {
|
|
|
|
url: string;
|
|
|
|
alt: string;
|
|
|
|
name: string;
|
|
|
|
width?: number;
|
|
|
|
height?: number;
|
|
|
|
attributes: (Literal & { name: string })[];
|
|
|
|
};
|
|
|
|
|
|
|
|
export const astroImage = () => {
|
2024-12-04 05:16:35 +08:00
|
|
|
return (tree: Node) => {
|
2024-11-15 16:01:33 +08:00
|
|
|
// Find all the image node.
|
2024-12-04 05:16:35 +08:00
|
|
|
// Find all the image link nodes and replace the relative links.
|
|
|
|
selectAll('image', tree)
|
2024-11-15 16:01:33 +08:00
|
|
|
.map((node) => node as ImageNode)
|
2024-12-04 05:16:35 +08:00
|
|
|
.filter((imageNode) => imageNode.url.startsWith('/'))
|
|
|
|
.map((imageNode) => {
|
|
|
|
imageNode.type = 'mdxJsxFlowElement';
|
|
|
|
imageNode.name = 'Image';
|
|
|
|
|
|
|
|
imageNode.attributes = [
|
|
|
|
{ type: 'mdxJsxAttribute', name: 'alt', value: imageNode.alt },
|
|
|
|
{ type: 'mdxJsxAttribute', name: 'src', value: imageNode.url },
|
|
|
|
{ type: 'mdxJsxAttribute', name: 'width', value: imageNode.width },
|
|
|
|
{ type: 'mdxJsxAttribute', name: 'height', value: imageNode.height },
|
|
|
|
];
|
|
|
|
});
|
2024-12-04 01:16:19 +08:00
|
|
|
|
|
|
|
for (const node of selectAll('link', tree)) {
|
|
|
|
const link = node as LinkNode;
|
|
|
|
if (link.children !== undefined && link.children.length !== 0) {
|
|
|
|
const images = link.children.filter((child) => child.type === 'mdxJsxFlowElement' && child.name === 'Image');
|
|
|
|
if (images.length > 0) {
|
|
|
|
link.url = link.url.startsWith('/') ? urlJoin(options.assetsPrefix(), link.url) : link.url;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-11-15 16:01:33 +08:00
|
|
|
return tree;
|
|
|
|
};
|
|
|
|
};
|