-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathProductItem.tsx
433 lines (397 loc) · 14.6 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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
/*
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,
SwatchValues
} 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 ImageHover from '../ImageHover';
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: string[],
quantity: number
) => Promise<void | undefined>;
}
const SWATCH_COLORS = 'Colors';
const SWATCH_COLORS_TEAM = 'Colors / Team';
const SWATCH_COLORS_TEAM_NAME = 'Colors / Team name';
const SWATCH_SIZE = 'Size';
export const ProductItem: FunctionComponent<ProductProps> = ({
item,
currencySymbol,
currencyRate,
setRoute,
refineProduct,
setCartUpdated,
setItemAdded,
setError,
addToCart,
}: ProductProps) => {
const { product, productView } = item;
const [selectedSwatch, setSelectedSwatch] = useState('');
const [imagesFromRefinedProduct, setImagesFromRefinedProduct] = useState<
ProductViewMedia[] | null
>();
const [refinedProduct, setRefinedProduct] = useState<RefinedProduct>();
const [isHovering, setIsHovering] = useState(false);
const [showSizes, setShowSizes] = useState(false);
const { addToCartGraphQL, refreshCart } = useCart();
const { viewType } = useProducts();
const {
config: { optimizeImages, imageBaseWidth, listview },
} = useStore();
const { screenSize } = useSensor();
const handleMouseOver = () => {
setIsHovering(true);
};
const handleMouseOut = () => {
setIsHovering(false);
setShowSizes(false);
};
const handleSelection = async (optionIds: string[], sku: string) => {
const data = await refineProduct(optionIds, sku);
setSelectedSwatch(optionIds[0]);
setImagesFromRefinedProduct(data.refineProduct.images);
setRefinedProduct(data);
};
/** TEMP FIX to show image of the first variant per product */
const loadProductImagesFromRefinedProduct = async (optionIds: string[], sku: string) => {
const data = await refineProduct(optionIds, sku);
setImagesFromRefinedProduct(data.refineProduct?.images);
};
if (!productView.images?.length && !imagesFromRefinedProduct){
const optionId = productView.options?.[0]?.values?.[0]?.id || '';
loadProductImagesFromRefinedProduct([optionId], productView.sku);
}
/** END TEMP FIX to show image of the first variant per product */
const isSelected = (id: string) => {
const selected = selectedSwatch ? selectedSwatch === id : false;
return selected;
};
const productImageArray = imagesFromRefinedProduct
? getProductImageURLs(imagesFromRefinedProduct ?? [], 2)
: getProductImageURLs(
productView.images ?? [],
2,
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 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.adobeDataLayer.push((dl: any) => {
dl.push({
event: 'search-product-click',
eventInfo: {
...dl.getState(),
sku: product?.sku,
searchUnitId: SEARCH_UNIT_ID,
},
});
});
};
const productUrl = setRoute
? setRoute({ sku: productView?.sku, urlKey: productView?.urlKey })
: product?.canonical_url;
const updateCart = async (selectedVariants: string[] = []) => {
setError(false);
if (addToCart) {
//Custom add to cart function passed in
await addToCart(productView.sku, selectedVariants, 1);
} else {
// Add to cart using GraphQL & Luma extension
const response = await addToCartGraphQL(productView.sku, selectedVariants);
if (
response?.errors ||
response?.data?.addProductsToCart?.user_errors.length > 0
) {
setError(true);
return;
}
setItemAdded(product.name);
refreshCart && refreshCart();
setCartUpdated(true);
}
}
const handleAddToCart = async (evt: any) => {
evt.preventDefault();
evt.stopPropagation();
const hasSizeOptions = productView?.options?.some((swatches) => swatches.title === SWATCH_SIZE);
if ((!listview || viewType !== 'listview') && hasSizeOptions) {
setShowSizes(true);
return;
}
const selectedVariants = selectedSwatch ? [selectedSwatch] : [];
updateCart(selectedVariants);
};
const handleSizeSelection = async (optionIds: string[]) => {
setShowSizes(false);
let selectedVariants = selectedSwatch ? [selectedSwatch] : [];
if (optionIds) {
selectedVariants = [...selectedVariants, ...optionIds];
}
updateCart(selectedVariants);
};
if (listview && viewType === 'listview') {
return (
<>
<div className="grid-container">
<div
className={`product-image ds-sdk-product-item__image relative overflow-hidden}`}
>
<a
href={productUrl as string}
onClick={onProductClick}
className="!text-brand-700 hover:no-underline hover:text-brand-700"
>
{/* Image */}
{productImageArray.length ? (
<ImageHover
images={
optimizedImageArray.length
? optimizedImageArray
: productImageArray
}
// productName={product.name}
/>
) : (
<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 p-2">
{/* Product name */}
<a
href={productUrl as string}
onClick={onProductClick}
className="!text-brand-700 hover:no-underline hover:text-brand-700"
>
<div className="ds-sdk-product-item__product-name mt-xs text-sm text-brand-700">
{product.name !== null && htmlStringDecode(product.name)}
</div>
<div className="ds-sdk-product-item__product-sku mt-xs text-sm text-brand-700">
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-brand-700 pb-6">
{productView?.options?.map(
(swatches) => {
// swatches.id === 'color' && (
return swatches.title === SWATCH_COLORS && (
<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-brand-700 hover:no-underline hover:text-brand-700"
>
<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-brand-700 mt-xs">
<a
href={productUrl as string}
onClick={onProductClick}
className="!text-brand-700 hover:no-underline hover:text-brand-700"
>
{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 w-full justify-between h-full"
style={{
'border-color': '#D5D5D5',
}}
onMouseEnter={handleMouseOver}
onMouseLeave={handleMouseOut}
>
<a
href={productUrl as string}
onClick={onProductClick}
className="!text-brand-700 hover:no-underline hover:text-brand-700"
>
<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 h-[445px] overflow-hidden">
{productImageArray.length ? (
<ImageHover
images={
optimizedImageArray.length
? optimizedImageArray
: productImageArray
}
// productName={product.name}
/>
) : (
<NoImage
className={`max-h-[45rem] w-full object-cover object-center lg:w-full`}
/>
)}
<div className="add-to-cart-overlay absolute left-0 right-0 bottom-0 p-xsmall h-[56px]">
{!screenSize.desktop && !showSizes && <AddToCartButton onClick={handleAddToCart} />}
{isHovering && screenSize.desktop && !showSizes && (
<AddToCartButton onClick={handleAddToCart} />
)}
{showSizes && productView?.options?.map((swatches) => {
if (swatches.title === SWATCH_SIZE) {
const swatchItems: SwatchValues[] = (swatches.values ?? []).map((swatch) => ({
...swatch,
type: 'SIZE',
}));
return (
<SwatchButtonGroup
key={product?.sku}
isSelected={isSelected}
swatches={swatchItems}
showMore={onProductClick}
productUrl={productUrl as string}
onClick={handleSizeSelection}
sku={product?.sku}
maxSwatches={swatchItems.length}
/>
);
}
})}
</div>
</div>
<div className="flex flex-col px-xsmall py-small gap-2">
{productView?.options && productView.options?.length > 0 && (
<div className="ds-sdk-product-item__product-swatch flex flex-row text-sm text-brand-700">
{productView?.options?.map(
(swatches) => {
if ([SWATCH_COLORS, SWATCH_COLORS_TEAM, SWATCH_COLORS_TEAM_NAME].includes(swatches.title || '')) {
return (
<SwatchButtonGroup
key={product?.sku}
isSelected={isSelected}
swatches={swatches.values ?? []}
showMore={onProductClick}
productUrl={productUrl as string}
onClick={handleSelection}
sku={product?.sku}
/>
);
}
}
)}
</div>
)}
<div className="ds-sdk-product-item__product-name font-medium text-lg">
{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>
</div>
</a>
</div>
);
};
export default ProductItem;