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
/
index.tsx
242 lines (225 loc) · 6.08 KB
/
index.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
/**
* External dependencies
*/
import { __, sprintf } from '@wordpress/i18n';
import { speak } from '@wordpress/a11y';
import classNames from 'classnames';
import { useCallback, useLayoutEffect } from '@wordpress/element';
import { DOWN, UP } from '@wordpress/keycodes';
import { useDebouncedCallback } from 'use-debounce';
/**
* Internal dependencies
*/
import './style.scss';
export interface QuantitySelectorProps {
/**
* Component wrapper classname
*
* @default 'wc-block-components-quantity-selector'
*/
className?: string;
/**
* Current quantity
*/
quantity?: number;
/**
* Minimum quantity
*/
minimum?: number;
/**
* Maximum quantity
*/
maximum: number;
/**
* Input step attribute.
*/
step?: number;
/**
* Event handler triggered when the quantity is changed
*/
onChange: ( newQuantity: number ) => void;
/**
* Name of the item the quantity selector refers to
*
* Used for a11y purposes
*/
itemName?: string;
/**
* Whether the component should be interactable or not
*/
disabled: boolean;
}
const QuantitySelector = ( {
className,
quantity = 1,
minimum = 1,
maximum,
onChange = () => void 0,
step = 1,
itemName = '',
disabled,
}: QuantitySelectorProps ): JSX.Element => {
const classes = classNames(
'wc-block-components-quantity-selector',
className
);
const hasMaximum = typeof maximum !== 'undefined';
const canDecrease = quantity - step >= minimum;
const canIncrease = ! hasMaximum || quantity + step <= maximum;
/**
* The goal of this function is to normalize what was inserted,
* but after the customer has stopped typing.
*/
const normalizeQuantity = useCallback(
( initialValue: number ) => {
// We copy the starting value.
let value = initialValue;
// We check if we have a maximum value, and select the lowest between what was inserted and the maximum.
if ( hasMaximum ) {
value = Math.min(
value,
// the maximum possible value in step increments.
Math.floor( maximum / step ) * step
);
}
// Select the biggest between what's inserted, the the minimum value in steps.
value = Math.max( value, Math.ceil( minimum / step ) * step );
// We round off the value to our steps.
value = Math.floor( value / step ) * step;
// Only commit if the value has changed
if ( value !== initialValue ) {
onChange( value );
}
},
[ hasMaximum, maximum, minimum, onChange, step ]
);
/*
* It's important to wait before normalizing or we end up with
* a frustrating experience, for example, if the minimum is 2 and
* the customer is trying to type "10", premature normalizing would
* always kick in at "1" and turn that into 2.
*/
const debouncedNormalizeQuantity = useDebouncedCallback(
normalizeQuantity,
// This value is deliberately smaller than what's in useStoreCartItemQuantity so we don't end up with two requests.
300
);
/**
* Normalize qty on mount before render.
*/
useLayoutEffect( () => {
normalizeQuantity( quantity );
}, [ quantity, normalizeQuantity ] );
/**
* Handles keyboard up and down keys to change quantity value.
*
* @param {Object} event event data.
*/
const quantityInputOnKeyDown = useCallback(
( event ) => {
const isArrowDown =
typeof event.key !== undefined
? event.key === 'ArrowDown'
: event.keyCode === DOWN;
const isArrowUp =
typeof event.key !== undefined
? event.key === 'ArrowUp'
: event.keyCode === UP;
if ( isArrowDown && canDecrease ) {
event.preventDefault();
onChange( quantity - step );
}
if ( isArrowUp && canIncrease ) {
event.preventDefault();
onChange( quantity + step );
}
},
[ quantity, onChange, canIncrease, canDecrease, step ]
);
return (
<div className={ classes }>
<input
className="wc-block-components-quantity-selector__input"
disabled={ disabled }
type="number"
step={ step }
min={ minimum }
max={ maximum }
value={ quantity }
onKeyDown={ quantityInputOnKeyDown }
onChange={ ( event ) => {
// Inputs values are strings, we parse them here.
let value = parseInt( event.target.value, 10 );
// parseInt would throw NaN for anything not a number,
// so we revert value to the quantity value.
value = isNaN( value ) ? quantity : value;
if ( value !== quantity ) {
// we commit this value immediately.
onChange( value );
// but once the customer has stopped typing, we make sure his value is respecting the bounds (maximum value, minimum value, step value), and commit the normalized value.
debouncedNormalizeQuantity( value );
}
} }
aria-label={ sprintf(
/* translators: %s refers to the item name in the cart. */
__(
'Quantity of %s in your cart.',
'woo-gutenberg-products-block'
),
itemName
) }
/>
<button
aria-label={ __(
'Reduce quantity',
'woo-gutenberg-products-block'
) }
className="wc-block-components-quantity-selector__button wc-block-components-quantity-selector__button--minus"
disabled={ disabled || ! canDecrease }
onClick={ () => {
const newQuantity = quantity - step;
onChange( newQuantity );
speak(
sprintf(
/* translators: %s refers to the item name in the cart. */
__(
'Quantity reduced to %s.',
'woo-gutenberg-products-block'
),
newQuantity
)
);
normalizeQuantity( newQuantity );
} }
>
-
</button>
<button
aria-label={ __(
'Increase quantity',
'woo-gutenberg-products-block'
) }
disabled={ disabled || ! canIncrease }
className="wc-block-components-quantity-selector__button wc-block-components-quantity-selector__button--plus"
onClick={ () => {
const newQuantity = quantity + step;
onChange( newQuantity );
speak(
sprintf(
/* translators: %s refers to the item name in the cart. */
__(
'Quantity increased to %s.',
'woo-gutenberg-products-block'
),
newQuantity
)
);
normalizeQuantity( newQuantity );
} }
>
+
</button>
</div>
);
};
export default QuantitySelector;