Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Minicart product image size #48

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion components/minicart/CartItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import Image from "$live/std/ui/components/Image.tsx";

import QuantitySelector from "../ui/QuantitySelector.tsx";
import { useCart } from "../../sdk/cart/useCart.ts";
import resizeImage from "../../sdk/cart/resizeImage.ts";
import Button from "../ui/Button.tsx";

interface Props {
Expand Down Expand Up @@ -33,7 +34,7 @@ function CartItem({ index }: Props) {
<li class="flex gap-2 py-6">
<div class="overflow-hidden rounded-md border border-gray-200">
<Image
src={imageUrl}
src={resizeImage(imageUrl)}
alt={skuName}
width={100}
height={100}
Expand Down
39 changes: 39 additions & 0 deletions sdk/cart/resizeImage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* VTEX resizeImage function
*
* The item image returned in the orderForm is 55x55px by default, which results
* in a pixelated thumb in the cart.
*
* This resizeImage function should increase the image to 100px width and auto height.
*
* TODO: Make width value customizable.
*/

const baseUrlRegex = new RegExp(/.+ids\/(\d+)(?:-(\d+)-(\d+)|)\//);
const sizeRegex = new RegExp(/-(\d+)-(\d+)/);

const cleanImageUrl = (imageUrl: string) => {
let resizedImageUrl = imageUrl;
const result = baseUrlRegex.exec(imageUrl);
if (result && result.length > 0) {
if (
result.length === 4 &&
result[2] !== undefined &&
result[3] !== undefined
) {
resizedImageUrl = result[0].replace(sizeRegex, "");
} else {
resizedImageUrl = result[0];
}
}
return resizedImageUrl;
};

const changeImageUrlSize = (imageUrl: string) => {
const resizedImageUrl = imageUrl.slice(0, -1); // Remove last "/"
return `${resizedImageUrl}-100-auto`;
};

export default function resizeImage(imageUrl: string) {
return changeImageUrlSize(cleanImageUrl(imageUrl));
}