-
Notifications
You must be signed in to change notification settings - Fork 92
/
ProductCard.tsx
315 lines (292 loc) · 9.61 KB
/
ProductCard.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
import { isServer, TAttribute, TCromwellNotify, TProduct, TStoreListItem } from '@cromwell/core';
import {
getCStore,
getThumbnailSrc,
Link,
TCStoreOperationResult,
useAppPropsContext,
useCart,
useCurrency,
useForceUpdate,
useWishlist,
} from '@cromwell/core-frontend';
import clsx from 'clsx';
import React from 'react';
import { getNotifier, NotifierActionOptions } from '../../helpers/notifier';
import { useProductLink } from '../../helpers/useLinks';
import { useStoreAttributes } from '../../helpers/useStoreAttributes';
import { AddShoppingCartIcon, FavoriteActiveIcon, FavoriteHollowIcon, ShoppingCartIcon } from '../icons';
import { BaseButton, TBaseButtonProps } from '../shared/Button';
import { BaseRating, TBaseRatingProps } from '../shared/Rating';
import { BaseTooltip, TBaseTooltipProps } from '../shared/Tooltip';
import styles from './ProductCard.module.scss';
/** @internal */
const Empty = (props) => props?.children ?? null;
export type ProductCardProps = {
classes?: Partial<
Record<
| 'root'
| 'horizontal_variant'
| 'image'
| 'image_container'
| 'actions'
| 'action_button'
| 'title'
| 'price_block'
| 'description'
| 'rating',
string
>
>;
elements?: {
OtherActions?: React.ComponentType<{ cardProps: ProductCardProps }>;
Rating?: React.ComponentType<TBaseRatingProps>;
AddCartButton?: React.ComponentType<TBaseButtonProps>;
AddWishlistButton?: React.ComponentType<TBaseButtonProps>;
Tooltip?: React.ComponentType<TBaseTooltipProps>;
};
text?: {
addToCart?: string;
addToWishlist?: string;
inCart?: string;
inWishlist?: string;
openCart?: string;
reviews?: string;
clickToOpenCart?: string;
};
/** Product data. Required */
product: TProduct;
/**
* All available attributes in DB. If not passed will be fetched and cached automatically.
*/
attributes?: TAttribute[];
/**
* In `vertical` variant image at top and text at bottom (takes more vertical space).
* In `horizontal` variant image at left and text at right (takes more horizontal space).
*/
variant?: 'vertical' | 'horizontal';
/**
* Action button events
*/
onOpenCart?: () => void;
onOpenWishlist?: () => void;
onAddedToCart?: (item: TStoreListItem, result: TCStoreOperationResult) => void;
onFailedAddToCart?: (item: TStoreListItem, result: TCStoreOperationResult) => void;
/**
* Notifier tool. Will show notifications when user adds a product to the cart or
* wishlist. To disable notifications pass an empty object
*/
notifier?: TCromwellNotify<NotifierActionOptions>;
/**
* Notifier options
*/
notifierOptions?: NotifierActionOptions;
/**
* URL to a placeholder image to use if a product has no primary image set.
*/
noImagePlaceholderUrl?: string;
/**
* Custom link resolver onto product page.
*/
getProductLink?: (product: TProduct) => string | undefined;
/**
* Product link click (image or title). You can prevent navigation event.
*/
onProductLinkClick?: (event: React.MouseEvent<HTMLAnchorElement, MouseEvent>, link: string) => any;
};
/**
* Displays product cart with short product info. Used to display in product list
* of a product category
*/
export function ProductCard(props: ProductCardProps) {
const {
product,
onOpenCart,
notifier = getNotifier(),
notifierOptions = {},
elements = {},
classes,
text,
} = props ?? {};
const {
OtherActions = Empty,
Rating = BaseRating,
AddCartButton = BaseButton,
AddWishlistButton = BaseButton,
Tooltip = BaseTooltip,
} = elements;
const cstore = getCStore();
const pageContext = useAppPropsContext();
const attributes = useStoreAttributes(props.attributes);
const forceUpdate = useForceUpdate();
const productLink = useProductLink(product, props.getProductLink);
useCart();
useWishlist();
useCurrency();
const item: TStoreListItem = {
product: product ?? undefined,
pickedAttributes: {},
amount: 1,
};
const inCart = cstore.isInCart(item);
const inWishlist = cstore.isInWishlist({ product });
const handleAddToCart = () => {
if (inCart) {
onOpenCart?.();
} else {
const result = cstore.addToCart(item, attributes);
if (result.success) {
props?.onAddedToCart?.(item, result);
notifier?.success?.('Added! Click here to open cart', {
onClick: () => {
onOpenCart?.();
},
...notifierOptions,
});
} else {
props?.onFailedAddToCart?.(item, result);
}
if (result.code === 1) {
notifier?.warning?.('Product is already in your cart!', {
...notifierOptions,
});
}
if (result.missingAttributes?.length) {
props?.onFailedAddToCart?.(item, result);
notifier?.error?.(
`Please pick following attributes: ${result.missingAttributes
.map((attr) => attr?.title || attr.key)
.join(', ')}`,
{
...notifierOptions,
},
);
}
forceUpdate();
}
};
const handleAddToWishlist = () => {
if (inWishlist) {
const result = cstore.removeFromWishlist({ product });
if (result.success) {
notifier?.info?.('Removed', {
...notifierOptions,
});
}
} else {
const result = cstore.addToWishlist({ product });
if (result.success) {
notifier?.success?.('Added! Click here to open wishlist', {
onClick: () => {
props?.onOpenWishlist?.();
},
...notifierOptions,
});
}
if (result.code === 1) {
notifier?.warning?.('Product is already in your wishlist!', {
...notifierOptions,
});
}
}
forceUpdate();
};
let mainImage = product?.mainImage ?? product?.images?.[0] ?? props?.noImagePlaceholderUrl;
const origin = pageContext.routeInfo?.origin;
if (mainImage && mainImage.startsWith('/') && origin) {
mainImage = origin + mainImage;
}
const WishlistIcon = inWishlist ? FavoriteActiveIcon : FavoriteHollowIcon;
return (
<div
className={clsx(
styles.ProductCard,
classes?.root,
props?.variant === 'horizontal' && styles.horizontalVariant,
props?.variant === 'horizontal' && classes?.horizontal_variant,
)}
>
{mainImage !== undefined && mainImage !== null && (
<div className={clsx(styles.imageBlock, classes?.image_container)}>
<Link
href={productLink}
style={{ position: 'relative' }}
onClick={(e) => productLink && props.onProductLinkClick?.(e, productLink)}
>
<img
src={getThumbnailSrc({
src: mainImage,
width: 300,
height: 300,
})}
alt={product?.name || ''}
style={{
objectFit: 'cover',
}}
className={clsx(styles.image, classes?.image)}
/>
</Link>
</div>
)}
<div className={styles.caption}>
<div className={styles.productNameContainer}>
<Link
href={productLink}
onClick={(e) => productLink && props.onProductLinkClick?.(e, productLink)}
className={clsx(styles.productName, classes?.title)}
>
{product?.name}
</Link>
</div>
{product?.description && (
<div className={clsx(styles.description, classes?.description)}>
<div dangerouslySetInnerHTML={{ __html: product?.description }}></div>
<div className={styles.descriptionGradient}></div>
</div>
)}
<div className={styles.priceBlock}>
{product?.oldPrice !== undefined && product?.oldPrice !== null && (
<p className={styles.oldPrice}>{cstore.getPriceWithCurrency(product.oldPrice)}</p>
)}
<p className={styles.price}>{cstore.getPriceWithCurrency(product?.price)}</p>
</div>
<div className={clsx(styles.actions, classes?.actions)}>
<Tooltip title={inCart ? text?.openCart ?? 'Open cart' : text?.addToCart ?? 'Add to cart'}>
<AddCartButton
onClick={handleAddToCart}
aria-label={text?.addToCart ?? 'Add product to cart'}
className={clsx(styles.actionBtn, classes?.action_button)}
>
{inCart ? <ShoppingCartIcon /> : <AddShoppingCartIcon />}
</AddCartButton>
</Tooltip>
<Tooltip title={text?.addToWishlist ?? 'Add to wishlist'}>
<AddWishlistButton
onClick={handleAddToWishlist}
aria-label={text?.addToWishlist ?? 'Add product to wishlist'}
className={clsx(styles.actionBtn, classes?.action_button)}
>
{!isServer() && <WishlistIcon />}
</AddWishlistButton>
</Tooltip>
<OtherActions cardProps={props} />
</div>
<div className={clsx(styles.ratingBlock, classes?.rating)}>
<Rating name="read-only" value={product?.rating?.average} precision={0.5} readOnly />
{
!!(
product?.rating?.reviewsNumber !== undefined &&
props?.variant === 'horizontal' &&
product?.rating?.reviewsNumber && (
<p className={styles.ratingCaption}>
({product?.rating?.average ? product?.rating?.average.toFixed(2) : ''}){' '}
{product?.rating?.reviewsNumber} {text?.reviews ?? 'reviews'}
</p>
)
)
}
</div>
</div>
</div>
);
}