From fdb8e2dfa31012911485a4dfa6d58dfc04198248 Mon Sep 17 00:00:00 2001 From: Luis Sousa Date: Sat, 26 Aug 2023 00:30:04 -0300 Subject: [PATCH] fix: add function to get vtex product image in properly ratio --- components/product/ProductCard.tsx | 9 +++++++-- components/product/ProductDetails.tsx | 7 +++++-- sdk/getImageInCorrectRatio.ts | 11 +++++++++++ 3 files changed, 23 insertions(+), 4 deletions(-) create mode 100644 sdk/getImageInCorrectRatio.ts diff --git a/components/product/ProductCard.tsx b/components/product/ProductCard.tsx index 25928500..90f64288 100644 --- a/components/product/ProductCard.tsx +++ b/components/product/ProductCard.tsx @@ -7,6 +7,7 @@ import { useVariantPossibilities } from "$store/sdk/useVariantPossiblities.ts"; import type { Product } from "deco-sites/std/commerce/types.ts"; import { mapProductToAnalyticsItem } from "deco-sites/std/commerce/utils/productToAnalyticsItem.ts"; import Image from "deco-sites/std/components/Image.tsx"; +import { getImageInCorrectRatio } from "deco-sites/staging/sdk/getImageInCorrectRatio.ts"; export interface Layout { basics?: { @@ -155,7 +156,7 @@ function ProductCard({ product, preload, itemListName, layout }: Props) { class="grid grid-cols-1 grid-rows-1 w-full" > {front.alternateName} { const allImages = product.isVariantOf?.hasVariant.flatMap((p) => p.image) .reduce((acc, img) => { if (img?.url) { - acc[imageNameFromURL(img.url)] = img.url; + const url = getImageInCorrectRatio(img.url, WIDTH, HEIGHT); + acc[imageNameFromURL(img.url)] = url; } return acc; }, {} as Record) ?? {}; return images.map((img) => { const name = imageNameFromURL(img.url); + const url = getImageInCorrectRatio(img.url, WIDTH, HEIGHT); - return { ...img, url: allImages[name] ?? img.url }; + return { ...img, url: allImages[name] ?? url }; }); }; diff --git a/sdk/getImageInCorrectRatio.ts b/sdk/getImageInCorrectRatio.ts new file mode 100644 index 00000000..0c915164 --- /dev/null +++ b/sdk/getImageInCorrectRatio.ts @@ -0,0 +1,11 @@ +export const getImageInCorrectRatio = ( + url = "", + width: number, + height: number, +) => { + if (!url.includes("vteximg.com.br")) return url; + return url.replace( + /\/ids\/([0-9]*)\//, + `/ids/$1-${width}-${height}/`, + ); +};