This repository has been archived by the owner on Feb 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 219
/
cart-line-item-row.tsx
359 lines (340 loc) · 9.56 KB
/
cart-line-item-row.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
/**
* External dependencies
*/
import classnames from 'classnames';
import { __, sprintf } from '@wordpress/i18n';
import { speak } from '@wordpress/a11y';
import QuantitySelector from '@woocommerce/base-components/quantity-selector';
import ProductPrice from '@woocommerce/base-components/product-price';
import ProductName from '@woocommerce/base-components/product-name';
import {
useStoreCartItemQuantity,
useStoreEvents,
useStoreCart,
} from '@woocommerce/base-context/hooks';
import {
ProductBackorderBadge,
ProductImage,
ProductLowStockBadge,
ProductMetadata,
ProductSaleBadge,
} from '@woocommerce/base-components/cart-checkout';
import {
getCurrencyFromPriceResponse,
Currency,
} from '@woocommerce/price-format';
import {
__experimentalApplyCheckoutFilter,
mustContain,
} from '@woocommerce/blocks-checkout';
import Dinero from 'dinero.js';
import { forwardRef, useMemo } from '@wordpress/element';
import type { CartItem } from '@woocommerce/type-defs/cart';
import { objectHasProp } from '@woocommerce/types';
import { getSetting } from '@woocommerce/settings';
/**
* Convert a Dinero object with precision to store currency minor unit.
*
* @param {Dinero} priceObject Price object to convert.
* @param {Object} currency Currency data.
* @return {number} Amount with new minor unit precision.
*/
const getAmountFromRawPrice = (
priceObject: Dinero.Dinero,
currency: Currency
) => {
return priceObject.convertPrecision( currency.minorUnit ).getAmount();
};
const productPriceValidation = ( value ) => mustContain( value, '<price/>' );
interface CartLineItemRowProps {
lineItem: CartItem | Record< string, never >;
onRemove?: () => void;
tabIndex?: number;
}
/**
* Cart line item table row component.
*/
const CartLineItemRow = forwardRef< HTMLTableRowElement, CartLineItemRowProps >(
(
{ lineItem, onRemove = () => void null, tabIndex = null },
ref
): JSX.Element => {
const {
name: initialName = '',
catalog_visibility: catalogVisibility = 'visible',
short_description: shortDescription = '',
description: fullDescription = '',
low_stock_remaining: lowStockRemaining = null,
show_backorder_badge: showBackorderBadge = false,
quantity_limits: quantityLimits = {
minimum: 1,
maximum: 99,
multiple_of: 1,
editable: true,
},
sold_individually: soldIndividually = false,
permalink = '',
images = [],
variation = [],
item_data: itemData = [],
prices = {
currency_code: 'USD',
currency_minor_unit: 2,
currency_symbol: '$',
currency_prefix: '$',
currency_suffix: '',
currency_decimal_separator: '.',
currency_thousand_separator: ',',
price: '0',
regular_price: '0',
sale_price: '0',
price_range: null,
raw_prices: {
precision: 6,
price: '0',
regular_price: '0',
sale_price: '0',
},
},
totals = {
currency_code: 'USD',
currency_minor_unit: 2,
currency_symbol: '$',
currency_prefix: '$',
currency_suffix: '',
currency_decimal_separator: '.',
currency_thousand_separator: ',',
line_subtotal: '0',
line_subtotal_tax: '0',
},
extensions,
} = lineItem;
const { quantity, setItemQuantity, removeItem, isPendingDelete } =
useStoreCartItemQuantity( lineItem );
const { dispatchStoreEvent } = useStoreEvents();
// Prepare props to pass to the __experimentalApplyCheckoutFilter filter.
// We need to pluck out receiveCart.
// eslint-disable-next-line no-unused-vars
const { receiveCart, ...cart } = useStoreCart();
const arg = useMemo(
() => ( {
context: 'cart',
cartItem: lineItem,
cart,
} ),
[ lineItem, cart ]
);
const priceCurrency = getCurrencyFromPriceResponse( prices );
const name = __experimentalApplyCheckoutFilter( {
filterName: 'itemName',
defaultValue: initialName,
extensions,
arg,
} );
const regularAmountSingle = Dinero( {
amount: parseInt( prices.raw_prices.regular_price, 10 ),
precision: prices.raw_prices.precision,
} );
const purchaseAmountSingle = Dinero( {
amount: parseInt( prices.raw_prices.price, 10 ),
precision: prices.raw_prices.precision,
} );
const saleAmountSingle =
regularAmountSingle.subtract( purchaseAmountSingle );
const saleAmount = saleAmountSingle.multiply( quantity );
const totalsCurrency = getCurrencyFromPriceResponse( totals );
let lineSubtotal = parseInt( totals.line_subtotal, 10 );
if ( getSetting( 'displayCartPricesIncludingTax', false ) ) {
lineSubtotal += parseInt( totals.line_subtotal_tax, 10 );
}
const subtotalPrice = Dinero( {
amount: lineSubtotal,
precision: totalsCurrency.minorUnit,
} );
const firstImage = images.length ? images[ 0 ] : {};
const isProductHiddenFromCatalog =
catalogVisibility === 'hidden' || catalogVisibility === 'search';
const cartItemClassNameFilter = __experimentalApplyCheckoutFilter( {
filterName: 'cartItemClass',
defaultValue: '',
extensions,
arg,
} );
// Allow extensions to filter how the price is displayed. Ie: prepending or appending some values.
const productPriceFormat = __experimentalApplyCheckoutFilter( {
filterName: 'cartItemPrice',
defaultValue: '<price/>',
extensions,
arg,
validation: productPriceValidation,
} );
const subtotalPriceFormat = __experimentalApplyCheckoutFilter( {
filterName: 'subtotalPriceFormat',
defaultValue: '<price/>',
extensions,
arg,
validation: productPriceValidation,
} );
const saleBadgePriceFormat = __experimentalApplyCheckoutFilter( {
filterName: 'saleBadgePriceFormat',
defaultValue: '<price/>',
extensions,
arg,
validation: productPriceValidation,
} );
return (
<tr
className={ classnames(
'wc-block-cart-items__row',
cartItemClassNameFilter,
{
'is-disabled': isPendingDelete,
}
) }
ref={ ref }
tabIndex={ tabIndex }
>
{ /* If the image has no alt text, this link is unnecessary and can be hidden. */ }
<td
className="wc-block-cart-item__image"
aria-hidden={
! objectHasProp( firstImage, 'alt' ) || ! firstImage.alt
}
>
{ /* We don't need to make it focusable, because product name has the same link. */ }
{ isProductHiddenFromCatalog ? (
<ProductImage
image={ firstImage }
fallbackAlt={ name }
/>
) : (
<a href={ permalink } tabIndex={ -1 }>
<ProductImage
image={ firstImage }
fallbackAlt={ name }
/>
</a>
) }
</td>
<td className="wc-block-cart-item__product">
<div className="wc-block-cart-item__wrap">
<ProductName
disabled={
isPendingDelete || isProductHiddenFromCatalog
}
name={ name }
permalink={ permalink }
/>
{ showBackorderBadge ? (
<ProductBackorderBadge />
) : (
!! lowStockRemaining && (
<ProductLowStockBadge
lowStockRemaining={ lowStockRemaining }
/>
)
) }
<div className="wc-block-cart-item__prices">
<ProductPrice
currency={ priceCurrency }
regularPrice={ getAmountFromRawPrice(
regularAmountSingle,
priceCurrency
) }
price={ getAmountFromRawPrice(
purchaseAmountSingle,
priceCurrency
) }
format={ subtotalPriceFormat }
/>
</div>
<ProductSaleBadge
currency={ priceCurrency }
saleAmount={ getAmountFromRawPrice(
saleAmountSingle,
priceCurrency
) }
format={ saleBadgePriceFormat }
/>
<ProductMetadata
shortDescription={ shortDescription }
fullDescription={ fullDescription }
itemData={ itemData }
variation={ variation }
/>
<div className="wc-block-cart-item__quantity">
{ ! soldIndividually &&
!! quantityLimits.editable && (
<QuantitySelector
disabled={ isPendingDelete }
quantity={ quantity }
minimum={ quantityLimits.minimum }
maximum={ quantityLimits.maximum }
step={ quantityLimits.multiple_of }
onChange={ ( newQuantity ) => {
setItemQuantity( newQuantity );
dispatchStoreEvent(
'cart-set-item-quantity',
{
product: lineItem,
quantity: newQuantity,
}
);
} }
itemName={ name }
/>
) }
<button
className="wc-block-cart-item__remove-link"
onClick={ () => {
onRemove();
removeItem();
dispatchStoreEvent( 'cart-remove-item', {
product: lineItem,
quantity,
} );
speak(
sprintf(
/* translators: %s refers to the item name in the cart. */
__(
'%s has been removed from your cart.',
'woo-gutenberg-products-block'
),
name
)
);
} }
disabled={ isPendingDelete }
>
{ __(
'Remove item',
'woo-gutenberg-products-block'
) }
</button>
</div>
</div>
</td>
<td className="wc-block-cart-item__total">
<div className="wc-block-cart-item__total-price-and-sale-badge-wrapper">
<ProductPrice
currency={ totalsCurrency }
format={ productPriceFormat }
price={ subtotalPrice.getAmount() }
/>
{ quantity > 1 && (
<ProductSaleBadge
currency={ priceCurrency }
saleAmount={ getAmountFromRawPrice(
saleAmount,
priceCurrency
) }
format={ saleBadgePriceFormat }
/>
) }
</div>
</td>
</tr>
);
}
);
export default CartLineItemRow;