From 191f08bdca3f222bb8a476f280e3061c126c4dc1 Mon Sep 17 00:00:00 2001 From: Bart van den Aardweg Date: Wed, 27 Oct 2021 10:57:07 +0200 Subject: [PATCH] fix(image): handle storyblok links without dimensions --- src/image/__tests__/getImageProps.test.ts | 11 +++++++++++ src/image/getImageProps.ts | 10 +++++----- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/image/__tests__/getImageProps.test.ts b/src/image/__tests__/getImageProps.test.ts index 610b845..f52bd60 100644 --- a/src/image/__tests__/getImageProps.test.ts +++ b/src/image/__tests__/getImageProps.test.ts @@ -34,6 +34,17 @@ describe('[image] getImageProps', () => { expect(props.height).toBe(2192); }); + it('should optimize props for fluid', async () => { + const props = getImageProps( + 'https://a.storyblok.com/f/39898/e4ec08624e/demo-image.jpeg', + { fluid: 1080 }, + ); + + expect(props.src).toBeDefined(); + expect(props.sizes).toBeDefined(); + expect(props.srcSet).toMatch(/(.*\dw.*){5}/gim); + }); + it('should not put fluid sizes that are larger than original', async () => { const props = getImageProps(storyblokImage, { fluid: 5000 }); diff --git a/src/image/getImageProps.ts b/src/image/getImageProps.ts index dc38137..1e5d006 100644 --- a/src/image/getImageProps.ts +++ b/src/image/getImageProps.ts @@ -44,8 +44,8 @@ export const getImageProps = ( const filters = options?.focus ? `/filters:focal(${options.focus})` : ''; const dimensions = path.match(/\/(\d*)x(\d*)\//); - const originalWidth = parseInt(dimensions?.[1]); - const originalHeight = parseInt(dimensions?.[2]); + const originalWidth = parseInt(dimensions?.[1]) || undefined; + const originalHeight = parseInt(dimensions?.[2]) || undefined; if (options) { if (options.fixed) { @@ -75,16 +75,16 @@ export const getImageProps = ( : options.fluid; const fluidHeight = Array.isArray(options.fluid) ? options.fluid[1] : 0; - for (let i = 0; i <= widths.length; i += 1) { + for (let i = 0; i < widths.length; i += 1) { const currentWidth = Math.round(widths[i] * fluidWidth); - if (widths[i] * fluidWidth <= originalWidth) { + if (!originalWidth || widths[i] * fluidWidth <= originalWidth) { srcSets.push( `${imageService}/${currentWidth}x${Math.round( widths[i] * fluidHeight, )}${smart}${filters}${path} ${currentWidth}w`, ); - } else if (widths[i] <= 1) { + } else if (originalWidth && widths[i] <= 1) { srcSets.push( `${imageService}/${currentWidth}x${Math.round( widths[i] * fluidHeight,