yufan.me/plugins/images.ts

51 lines
1.6 KiB
TypeScript
Raw Normal View History

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[];
};
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) => {
// 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)
.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;
}
}
}
return tree;
};
};