astro/packages/integrations/image/components/Picture.astro

56 lines
1.3 KiB
Text
Raw Normal View History

---
import { getPicture } from '../dist/index.js';
import type { ImgHTMLAttributes, HTMLAttributes } from './index.js';
import type { ImageMetadata, OutputFormat, TransformOptions } from '../dist/index.js';
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'> {
src: ImageMetadata | Promise<{ default: ImageMetadata }>;
alt?: string;
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'> {
src: string;
alt?: string;
sizes: HTMLImageElement['sizes'];
widths: number[];
aspectRatio: TransformOptions['aspectRatio'];
formats?: OutputFormat[];
}
export type Props = LocalImageProps | RemoteImageProps;
2022-08-06 04:39:26 +00:00
const {
src,
alt,
sizes,
widths,
aspectRatio,
formats = ['avif', 'webp'],
loading = 'lazy',
decoding = 'async',
...attrs
} = Astro.props as Props;
const { image, sources } = await getPicture({ src, widths, formats, aspectRatio });
---
<picture {...attrs}>
2022-08-06 04:39:26 +00:00
{sources.map((attrs) => <source {...attrs} {sizes} />)}
<img {...image} {loading} {decoding} {alt} />
</picture>
<style>
img {
content-visibility: auto;
}
</style>