Skip to content

Commit

Permalink
fix(image): handle storyblok links without dimensions
Browse files Browse the repository at this point in the history
  • Loading branch information
BJvdA committed Oct 27, 2021
1 parent b484b88 commit 191f08b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
11 changes: 11 additions & 0 deletions src/image/__tests__/getImageProps.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });

Expand Down
10 changes: 5 additions & 5 deletions src/image/getImageProps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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,
Expand Down

1 comment on commit 191f08b

@vercel
Copy link

@vercel vercel bot commented on 191f08b Oct 27, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.