From b10ea2b549de61cf568c721ad299a6d60fbe0f03 Mon Sep 17 00:00:00 2001 From: prototypa Date: Thu, 11 Apr 2024 23:25:18 -0400 Subject: [PATCH] Update image optimization to remote astro asset loading --- src/components/common/Image.astro | 23 ++++++++++++++++------- src/utils/images-optimization.ts | 10 +++++++--- 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/src/components/common/Image.astro b/src/components/common/Image.astro index a0f7ddf..52fc1cd 100644 --- a/src/components/common/Image.astro +++ b/src/components/common/Image.astro @@ -4,15 +4,16 @@ import { getImagesOptimized, astroAsseetsOptimizer, unpicOptimizer, + isUnpicCompatible, type ImageProps, - type AttributesProps + type AttributesProps, } from '~/utils/images-optimization'; type Props = ImageProps; type ImageType = { src: string; attributes: AttributesProps; -} +}; const props = Astro.props; @@ -40,13 +41,21 @@ const _image = await findImage(props.src); let image: ImageType | undefined = undefined; -if (_image !== null && typeof _image === 'object') { - image = await getImagesOptimized(_image, props, astroAsseetsOptimizer); -} else if (typeof _image === 'string' && (_image.startsWith('http://') || _image.startsWith('https://'))) { +if ( + typeof _image === 'string' && + (_image.startsWith('http://') || _image.startsWith('https://')) && + isUnpicCompatible(_image) +) { image = await getImagesOptimized(_image, props, unpicOptimizer); } else if (_image) { - image = await getImagesOptimized(_image, props); + image = await getImagesOptimized(_image, props, astroAsseetsOptimizer); } --- -{!image ? : } +{ + !image ? ( + + ) : ( + + ) +} diff --git a/src/utils/images-optimization.ts b/src/utils/images-optimization.ts index d735fc4..5c4662c 100644 --- a/src/utils/images-optimization.ts +++ b/src/utils/images-optimization.ts @@ -210,14 +210,14 @@ const getBreakpoints = ({ }; /* ** */ -export const astroAsseetsOptimizer: ImagesOptimizer = async (image, breakpoints) => { - if (!image || typeof image === 'string') { +export const astroAsseetsOptimizer: ImagesOptimizer = async (image, breakpoints, width, height) => { + if (!image) { return []; } return Promise.all( breakpoints.map(async (w: number) => { - const url = (await getImage({ src: image, width: w })).src; + const url = (await getImage({ src: image, width: w, inferSize: true })).src; return { src: url, width: w, @@ -226,6 +226,10 @@ export const astroAsseetsOptimizer: ImagesOptimizer = async (image, breakpoints) ); }; +export const isUnpicCompatible = (image: string) => { + return typeof parseUrl(image) !== 'undefined'; +}; + /* ** */ export const unpicOptimizer: ImagesOptimizer = async (image, breakpoints, width, height) => { if (!image || typeof image !== 'string') {