-
Notifications
You must be signed in to change notification settings - Fork 34
/
ProductItem.tsx
380 lines (354 loc) · 12.7 KB
/
ProductItem.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/*
Copyright 2024 Adobe
All Rights Reserved.
NOTICE: Adobe permits you to use, modify, and distribute this file in
accordance with the terms of the Adobe license agreement accompanying
it.
*/
import { FunctionComponent } from 'preact';
import { useState } from 'preact/hooks';
import '../ProductItem/ProductItem.css';
import { useCart, useProducts, useSensor, useStore } from '../../context';
import NoImage from '../../icons/NoImage.svg';
import {
Product,
ProductViewMedia,
RedirectRouteFunc,
RefinedProduct,
} from '../../types/interface';
import { SEARCH_UNIT_ID } from '../../utils/constants';
import {
generateOptimizedImages,
getProductImageURLs,
} from '../../utils/getProductImage';
import { htmlStringDecode } from '../../utils/htmlStringDecode';
import { AddToCartButton } from '../AddToCartButton';
import { ImageCarousel } from '../ImageCarousel';
import { SwatchButtonGroup } from '../SwatchButtonGroup';
import ProductPrice from './ProductPrice';
export interface ProductProps {
item: Product;
currencySymbol: string;
currencyRate?: string;
setRoute?: RedirectRouteFunc | undefined;
refineProduct: (optionIds: string[], sku: string) => any;
setCartUpdated: (cartUpdated: boolean) => void;
setItemAdded: (itemAdded: string) => void;
setError: (error: boolean) => void;
addToCart?: (
sku: string,
options: [],
quantity: number
) => Promise<void | undefined>;
}
export const ProductItem: FunctionComponent<ProductProps> = ({
item,
currencySymbol,
currencyRate,
setRoute,
refineProduct,
setCartUpdated,
setItemAdded,
setError,
addToCart,
}: ProductProps) => {
const { product, productView } = item;
const [carouselIndex, setCarouselIndex] = useState(0);
const [selectedSwatch, setSelectedSwatch] = useState('');
const [imagesFromRefinedProduct, setImagesFromRefinedProduct] = useState<
ProductViewMedia[] | null
>();
const [refinedProduct, setRefinedProduct] = useState<RefinedProduct>();
const [isHovering, setIsHovering] = useState(false);
const { addToCartGraphQL, refreshCart } = useCart();
const { viewType } = useProducts();
const {
config: { optimizeImages, imageBaseWidth, imageCarousel, listview },
} = useStore();
const { screenSize } = useSensor();
const handleMouseOver = () => {
setIsHovering(true);
};
const handleMouseOut = () => {
setIsHovering(false);
};
const handleSelection = async (optionIds: string[], sku: string) => {
const data = await refineProduct(optionIds, sku);
setSelectedSwatch(optionIds[0]);
setImagesFromRefinedProduct(data.refineProduct.images);
setRefinedProduct(data);
setCarouselIndex(0);
};
const isSelected = (id: string) => {
const selected = selectedSwatch ? selectedSwatch === id : false;
return selected;
};
const productImageArray = imagesFromRefinedProduct
? getProductImageURLs(imagesFromRefinedProduct ?? [], imageCarousel ? 3 : 1)
: getProductImageURLs(
productView.images ?? [],
imageCarousel ? 3 : 1, // number of images to display in carousel
product.image?.url ?? undefined
);
let optimizedImageArray: { src: string; srcset: any }[] = [];
if (optimizeImages) {
optimizedImageArray = generateOptimizedImages(
productImageArray,
imageBaseWidth ?? 200
);
}
// will have to figure out discount logic for amount_off and percent_off still
const discount: boolean = refinedProduct
? refinedProduct.refineProduct?.priceRange?.minimum?.regular?.amount
?.value >
refinedProduct.refineProduct?.priceRange?.minimum?.final?.amount?.value
: product?.price_range?.minimum_price?.regular_price?.value >
product?.price_range?.minimum_price?.final_price?.value ||
productView?.price?.regular?.amount?.value >
productView?.price?.final?.amount?.value;
const isSimple = product?.__typename === 'SimpleProduct';
const isComplexProductView = productView?.__typename === 'ComplexProductView';
const isBundle = product?.__typename === 'BundleProduct';
const isGrouped = product?.__typename === 'GroupedProduct';
const isGiftCard = product?.__typename === 'GiftCardProduct';
const isConfigurable = product?.__typename === 'ConfigurableProduct';
const onProductClick = () => {
window.magentoStorefrontEvents?.publish.searchProductClick(
SEARCH_UNIT_ID,
product?.sku
);
};
const productUrl = setRoute
? setRoute({ sku: productView?.sku, urlKey: productView?.urlKey })
: product?.canonical_url;
const handleAddToCart = async () => {
setError(false);
if (isSimple) {
if (addToCart) {
//Custom add to cart function passed in
await addToCart(productView.sku, [], 1);
} else {
// Add to cart using GraphQL & Luma extension
const response = await addToCartGraphQL(productView.sku);
if (
response?.errors ||
response?.data?.addProductsToCart?.user_errors.length > 0
) {
setError(true);
return;
}
setItemAdded(product.name);
refreshCart && refreshCart();
setCartUpdated(true);
}
} else if (productUrl) {
window.open(productUrl, '_self');
}
};
if (listview && viewType === 'listview') {
return (
<>
<div className="grid-container">
<div
className={`product-image ds-sdk-product-item__image relative rounded-md overflow-hidden}`}
>
<a
href={productUrl as string}
onClick={onProductClick}
className="!text-primary hover:no-underline hover:text-primary"
>
{/* Image */}
{productImageArray.length ? (
<ImageCarousel
images={
optimizedImageArray.length
? optimizedImageArray
: productImageArray
}
productName={product.name}
carouselIndex={carouselIndex}
setCarouselIndex={setCarouselIndex}
/>
) : (
<NoImage
className={`max-h-[250px] max-w-[200px] pr-5 m-auto object-cover object-center lg:w-full`}
/>
)}
</a>
</div>
<div className="product-details">
<div className="flex flex-col w-1/3">
{/* Product name */}
<a
href={productUrl as string}
onClick={onProductClick}
className="!text-primary hover:no-underline hover:text-primary"
>
<div className="ds-sdk-product-item__product-name mt-xs text-sm text-primary">
{product.name !== null && htmlStringDecode(product.name)}
</div>
<div className="ds-sdk-product-item__product-sku mt-xs text-sm text-primary">
SKU:
{product.sku !== null && htmlStringDecode(product.sku)}
</div>
</a>
{/* Swatch */}
<div className="ds-sdk-product-item__product-swatch flex flex-row mt-sm text-sm text-primary pb-6">
{productView?.options?.map(
(swatches) =>
swatches.id === 'color' && (
<SwatchButtonGroup
key={productView?.sku}
isSelected={isSelected}
swatches={swatches.values ?? []}
showMore={onProductClick}
productUrl={productUrl as string}
onClick={handleSelection}
sku={productView?.sku}
/>
)
)}
</div>
</div>
</div>
<div className="product-price">
<a
href={productUrl as string}
onClick={onProductClick}
className="!text-primary hover:no-underline hover:text-primary"
>
<ProductPrice
item={refinedProduct ?? item}
isBundle={isBundle}
isGrouped={isGrouped}
isGiftCard={isGiftCard}
isConfigurable={isConfigurable}
isComplexProductView={isComplexProductView}
discount={discount}
currencySymbol={currencySymbol}
currencyRate={currencyRate}
/>
</a>
</div>
<div className="product-description text-sm text-primary mt-xs">
<a
href={productUrl as string}
onClick={onProductClick}
className="!text-primary hover:no-underline hover:text-primary"
>
{product.short_description?.html ? (
<>
<span
dangerouslySetInnerHTML={{
__html: product.short_description.html,
}}
/>
</>
) : (
<span />
)}
</a>
</div>
{/* TO BE ADDED LATER */}
<div className="product-ratings" />
<div className="product-add-to-cart">
<div className="pb-4 h-[38px] w-96">
<AddToCartButton onClick={handleAddToCart} />
</div>
</div>
</div>
</>
);
}
return (
<div
className="ds-sdk-product-item group relative flex flex-col max-w-sm justify-between h-full hover:border-[1.5px] border-solid hover:shadow-lg border-offset-2 p-2"
style={{
'border-color': '#D5D5D5',
}}
onMouseEnter={handleMouseOver}
onMouseLeave={handleMouseOut}
>
<a
href={productUrl as string}
onClick={onProductClick}
className="!text-primary hover:no-underline hover:text-primary"
>
<div className="ds-sdk-product-item__main relative flex flex-col justify-between h-full">
<div className="ds-sdk-product-item__image relative w-full h-full rounded-md overflow-hidden">
{productImageArray.length ? (
<ImageCarousel
images={
optimizedImageArray.length
? optimizedImageArray
: productImageArray
}
productName={product.name}
carouselIndex={carouselIndex}
setCarouselIndex={setCarouselIndex}
/>
) : (
<NoImage
className={`max-h-[45rem] w-full object-cover object-center lg:w-full`}
/>
)}
</div>
<div className="flex flex-row">
<div className="flex flex-col">
<div className="ds-sdk-product-item__product-name mt-md text-sm text-primary">
{product.name !== null && htmlStringDecode(product.name)}
</div>
<ProductPrice
item={refinedProduct ?? item}
isBundle={isBundle}
isGrouped={isGrouped}
isGiftCard={isGiftCard}
isConfigurable={isConfigurable}
isComplexProductView={isComplexProductView}
discount={discount}
currencySymbol={currencySymbol}
currencyRate={currencyRate}
/>
</div>
{/*
//TODO: Wishlist button to be added later
{flags.addToWishlist && widgetConfig.addToWishlist.enabled && (
// TODO: Remove flag during phase 3 MSRCH-4278
<div className="ds-sdk-wishlist ml-auto mt-md">
<WishlistButton
productSku={item.product.sku}
type={widgetConfig.addToWishlist.placement}
/>
</div>
)} */}
</div>
</div>
</a>
{productView?.options && productView.options?.length > 0 && (
<div className="ds-sdk-product-item__product-swatch flex flex-row mt-sm text-sm text-primary">
{productView?.options?.map(
(swatches) =>
swatches.id == 'color' && (
<SwatchButtonGroup
key={product?.sku}
isSelected={isSelected}
swatches={swatches.values ?? []}
showMore={onProductClick}
productUrl={productUrl as string}
onClick={handleSelection}
sku={product?.sku}
/>
)
)}
</div>
)}
<div className="pb-4 mt-sm">
{screenSize.mobile && <AddToCartButton onClick={handleAddToCart} />}
{isHovering && screenSize.desktop && (
<AddToCartButton onClick={handleAddToCart} />
)}
</div>
</div>
);
};
export default ProductItem;