Skip to content

Commit

Permalink
fix(helpers): correct srcset for images (#1191)
Browse files Browse the repository at this point in the history
* fix: prevent from using missing urls for srcset of an image

* chore: changeset

* chore: lint
  • Loading branch information
mkucmus authored Aug 5, 2024
1 parent 59d24c8 commit 2e4c887
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 6 deletions.
10 changes: 10 additions & 0 deletions .changeset/long-pianos-allow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
"@shopware-pwa/helpers-next": patch
---

Prevent from getting an incorrect srcset format when img url is not set.

before when there were no urls for 400w and 800w:
`src="image1.jpg 100w, 400w, 800w"`

now only the entry with an URL defined is returned
18 changes: 15 additions & 3 deletions packages/helpers/src/media/getSrcSetForMedia.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,31 @@ import { getSrcSetForMedia } from "./getSrcSetForMedia";
describe("getSrcSetForMedia", () => {
it("should return an empty string if media is undefined", () => {
const result = getSrcSetForMedia(undefined);
expect(result).toEqual("");
expect(result).toBeUndefined();
});

it("should return an empty string if media.thumbnails is undefined", () => {
const media = {};
const result = getSrcSetForMedia(media);
expect(result).toEqual("");
expect(result).toBeUndefined();
});

it("should return an empty string if media.thumbnails is an empty array", () => {
const media = { thumbnails: [] };
const result = getSrcSetForMedia(media);
expect(result).toEqual("");
expect(result).toBeUndefined();
});

it("should return the srcset only for media that contains a proper url defined", () => {
const media = {
thumbnails: [
{ width: 100, url: "image1.jpg" },
{ width: 200, url: "" },
{ width: 300, url: "" },
],
};
const result = getSrcSetForMedia(media);
expect(result).toEqual("image1.jpg 100w");
});

it("should return the correct srcset string if media.thumbnails is not empty", () => {
Expand Down
7 changes: 4 additions & 3 deletions packages/helpers/src/media/getSrcSetForMedia.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,15 @@ export function getSrcSetForMedia<
url: string;
}>;
},
>(media?: T): string {
>(media?: T): string | undefined {
if (!media?.thumbnails?.length) {
return "";
return;
}

return media.thumbnails
.map((thumbnail) => {
return `${thumbnail.url} ${thumbnail.width}w`;
return thumbnail.url ? `${thumbnail.url} ${thumbnail.width}w` : undefined;
})
.filter((value) => !!value)
.join(", ");
}

0 comments on commit 2e4c887

Please sign in to comment.