2022-07-08 21:37:55 +00:00
---
2022-07-22 23:01:56 +00:00
import { getPicture } from '../dist/index.js';
2022-09-01 21:24:07 +00:00
import { warnForMissingAlt } from './index.js';
2022-07-27 15:39:05 +00:00
import type { ImgHTMLAttributes, HTMLAttributes } from './index.js';
import type { ImageMetadata, OutputFormat, TransformOptions } from '../dist/index.js';
2022-07-08 21:37:55 +00:00
2022-08-06 04:39:26 +00:00
interface LocalImageProps
extends Omit<HTMLAttributes, 'src' | 'width' | 'height'>,
Omit<TransformOptions, 'src'>,
Pick<astroHTML.JSX.ImgHTMLAttributes, 'loading' | 'decoding'> {
2022-07-08 21:37:55 +00:00
src: ImageMetadata | Promise<{ default: ImageMetadata }>;
2022-09-01 21:24:07 +00:00
/** Defines an alternative text description of the image. Set to an empty string (alt="") if the image is not a key part of the content (it's decoration or a tracking pixel). */
alt: string;
2022-07-08 21:37:55 +00:00
sizes: HTMLImageElement['sizes'];
widths: number[];
formats?: OutputFormat[];
}
2022-08-06 04:39:26 +00:00
interface RemoteImageProps
extends Omit<HTMLAttributes, 'src' | 'width' | 'height'>,
TransformOptions,
Pick<ImgHTMLAttributes, 'loading' | 'decoding'> {
2022-07-08 21:37:55 +00:00
src: string;
2022-09-01 21:24:07 +00:00
/** Defines an alternative text description of the image. Set to an empty string (alt="") if the image is not a key part of the content (it's decoration or a tracking pixel). */
alt: string;
2022-07-08 21:37:55 +00:00
sizes: HTMLImageElement['sizes'];
widths: number[];
aspectRatio: TransformOptions['aspectRatio'];
formats?: OutputFormat[];
2022-09-07 17:22:11 +00:00
background: TransformOptions['background'];
2022-07-08 21:37:55 +00:00
}
export type Props = LocalImageProps | RemoteImageProps;
2022-08-06 04:39:26 +00:00
const {
src,
alt,
sizes,
widths,
aspectRatio,
2022-09-09 20:13:59 +00:00
fit,
2022-09-07 17:22:11 +00:00
background,
2022-09-09 20:13:59 +00:00
position,
2022-08-06 04:39:26 +00:00
formats = ['avif', 'webp'],
loading = 'lazy',
decoding = 'async',
...attrs
} = Astro.props as Props;
2022-07-08 21:37:55 +00:00
2022-09-01 21:24:07 +00:00
if (alt === undefined || alt === null) {
warnForMissingAlt();
}
2022-09-09 20:13:59 +00:00
const { image, sources } = await getPicture({
src,
widths,
formats,
aspectRatio,
fit,
background,
position,
});
2022-09-22 21:01:38 +00:00
delete image.width;
delete image.height;
2022-07-08 21:37:55 +00:00
---
<picture {...attrs}>
2022-08-06 04:39:26 +00:00
{sources.map((attrs) => <source {...attrs} {sizes} />)}
2022-07-19 19:21:58 +00:00
<img {...image} {loading} {decoding} {alt} />
2022-07-08 21:37:55 +00:00
</picture>
<style>
img {
content-visibility: auto;
}
</style>