forked from mantinedev/mantine
/
NumberInput.tsx
453 lines (384 loc) · 12.3 KB
/
NumberInput.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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
import React, { useState, useEffect, useRef, forwardRef } from 'react';
import { useMergedRef, assignRef, useOs, clamp } from '@mantine/hooks';
import { DefaultProps, Selectors, useComponentDefaultProps } from '@mantine/styles';
import { TextInput } from '../TextInput';
import { InputStylesNames, InputWrapperStylesNames } from '../Input';
import { getInputMode } from './get-input-mode/get-input-mode';
import { Chevron } from './Chevron';
import useStyles, { CONTROL_SIZES } from './NumberInput.styles';
export type InnerNumberInputStylesNames = Selectors<typeof useStyles>;
export type NumberInputStylesNames =
| InputStylesNames
| InputWrapperStylesNames
| InnerNumberInputStylesNames;
export interface NumberInputHandlers {
increment(): void;
decrement(): void;
}
type Formatter = (value: string | undefined) => string;
type Parser = (value: string | undefined) => string | undefined;
export interface NumberInputProps
extends DefaultProps<NumberInputStylesNames>,
Omit<
React.ComponentPropsWithoutRef<typeof TextInput>,
'onChange' | 'value' | 'classNames' | 'styles' | 'type'
> {
/** onChange input handler for controlled variant, note that input event is not exposed. It will return undefined if the input is empty, otherwise it'll return a number */
onChange?(value: number | undefined): void;
/** Input value for controlled variant */
value?: number | undefined;
/** The decimal separator */
decimalSeparator?: string;
/** Maximum possible value */
max?: number;
/** Minimal possible value */
min?: number;
/** First value if no initial value was set and increment/decrement is triggered using controls or up/down arrows */
startValue?: number;
/** Number by which value will be incremented/decremented with controls and up/down arrows */
step?: number;
/** Delay before stepping the value. Can be a number of milliseconds or a function that receives the current step count and returns the delay in milliseconds. */
stepHoldInterval?: number | ((stepCount: number) => number);
/** Initial delay in milliseconds before stepping the value. */
stepHoldDelay?: number;
/** Removes increment/decrement controls */
hideControls?: boolean;
/** Amount of digits after the decimal point */
precision?: number;
/** Only works if a precision is given, removes the trailing zeros, false by default */
removeTrailingZeros?: boolean;
/** Default value for uncontrolled variant only */
defaultValue?: number | undefined;
/** Prevent value clamp on blur */
noClampOnBlur?: boolean;
/** Get increment/decrement handlers */
handlersRef?: React.ForwardedRef<NumberInputHandlers | undefined>;
/** Formats the number into the input */
formatter?: Formatter;
/** Parses the value from formatter, should be used with formatter at the same time */
parser?: Parser;
/** Input type, defaults to text */
type?: 'text' | 'number';
}
const defaultFormatter: Formatter = (value) => value || '';
const defaultParser: Parser = (num) => {
if (num === '-') {
return num;
}
let tempNum = num;
if (tempNum[0] === '.') {
tempNum = `0${num}`;
}
const parsedNum = parseFloat(tempNum);
if (Number.isNaN(parsedNum)) {
return undefined;
}
return num;
};
const CHEVRON_SIZES = {
xs: 10,
sm: 14,
md: 16,
lg: 18,
xl: 20,
};
const defaultProps: Partial<NumberInputProps> = {
step: 1,
hideControls: false,
size: 'sm',
precision: 0,
noClampOnBlur: false,
removeTrailingZeros: false,
formatter: defaultFormatter,
parser: defaultParser,
type: 'text',
};
export const NumberInput = forwardRef<HTMLInputElement, NumberInputProps>((props, ref) => {
const {
readOnly,
disabled,
value,
onChange,
decimalSeparator,
min,
max,
startValue,
step,
stepHoldInterval,
stepHoldDelay,
onBlur,
onFocus,
onKeyDown,
onKeyUp,
hideControls,
radius,
variant,
precision,
removeTrailingZeros,
defaultValue,
noClampOnBlur,
handlersRef,
classNames,
styles,
size,
rightSection,
rightSectionWidth,
formatter,
parser,
inputMode,
unstyled,
type,
...others
} = useComponentDefaultProps('NumberInput', defaultProps, props);
const { classes, cx, theme } = useStyles(
{ radius, size },
{ classNames, styles, unstyled, name: 'NumberInput' }
);
const parsePrecision = (val: number | undefined) => {
if (val === undefined) return undefined;
let result = val.toFixed(precision);
if (removeTrailingZeros && precision > 0) {
result = result.replace(new RegExp(`[0]{0,${precision}}$`), '');
if (result.endsWith('.') || result.endsWith(decimalSeparator)) {
result = result.slice(0, -1);
}
}
return result;
};
const [focused, setFocused] = useState(false);
const [_value, setValue] = useState(
typeof value === 'number' ? value : typeof defaultValue === 'number' ? defaultValue : undefined
);
const finalValue = typeof value === 'number' ? value : _value;
const [tempValue, setTempValue] = useState(
typeof finalValue === 'number' ? parsePrecision(finalValue) : ''
);
const inputRef = useRef<HTMLInputElement>();
const handleValueChange = (val: number | undefined) => {
if (val !== _value && !Number.isNaN(val)) {
typeof onChange === 'function' && onChange(val);
setValue(val);
}
};
const formatNum = (val: string | number = '') => {
let parsedStr = typeof val === 'number' ? String(val) : val;
if (decimalSeparator) {
parsedStr = parsedStr.replace(/\./g, decimalSeparator);
}
return formatter(parsedStr);
};
const parseNum = (val: string): string | undefined => {
let num = val;
if (decimalSeparator) {
num = num.replace(new RegExp(`\\${decimalSeparator}`, 'g'), '.');
}
return parser(num);
};
const _min = typeof min === 'number' ? min : -Infinity;
const _max = typeof max === 'number' ? max : Infinity;
const incrementRef = useRef<() => void>();
incrementRef.current = () => {
if (_value === undefined) {
handleValueChange(startValue ?? min ?? 0);
setTempValue(parsePrecision(startValue) ?? parsePrecision(min) ?? '0');
} else {
const result = parsePrecision(clamp(_value + step, _min, _max));
handleValueChange(parseFloat(result));
setTempValue(result);
}
};
const decrementRef = useRef<() => void>();
decrementRef.current = () => {
if (_value === undefined) {
handleValueChange(startValue ?? min ?? 0);
setTempValue(parsePrecision(startValue) ?? parsePrecision(min) ?? '0');
} else {
const result = parsePrecision(clamp(_value - step, _min, _max));
handleValueChange(parseFloat(result));
setTempValue(result);
}
};
assignRef(handlersRef, { increment: incrementRef.current, decrement: decrementRef.current });
useEffect(() => {
if (typeof value === 'number' && !focused) {
setValue(value);
setTempValue(parsePrecision(value));
}
if (defaultValue === undefined && value === undefined && !focused) {
setValue(value);
setTempValue('');
}
}, [value]);
const shouldUseStepInterval = stepHoldDelay !== undefined && stepHoldInterval !== undefined;
const onStepTimeoutRef = useRef<number>(null);
const stepCountRef = useRef<number>(0);
const onStepDone = () => {
if (onStepTimeoutRef.current) {
window.clearTimeout(onStepTimeoutRef.current);
}
onStepTimeoutRef.current = null;
stepCountRef.current = 0;
};
const onStepHandleChange = (isIncrement: boolean) => {
if (isIncrement) {
incrementRef.current();
} else {
decrementRef.current();
}
stepCountRef.current += 1;
};
const onStepLoop = (isIncrement: boolean) => {
onStepHandleChange(isIncrement);
if (shouldUseStepInterval) {
const interval =
typeof stepHoldInterval === 'number'
? stepHoldInterval
: stepHoldInterval(stepCountRef.current);
onStepTimeoutRef.current = window.setTimeout(() => onStepLoop(isIncrement), interval);
}
};
const onStep = (
event: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>,
isIncrement: boolean
) => {
event.preventDefault();
inputRef.current.focus();
onStepHandleChange(isIncrement);
if (shouldUseStepInterval) {
onStepTimeoutRef.current = window.setTimeout(() => onStepLoop(isIncrement), stepHoldDelay);
}
};
useEffect(() => {
onStepDone();
return onStepDone;
}, []);
const controls = (
<div className={classes.rightSection}>
<button
type="button"
tabIndex={-1}
aria-hidden
disabled={finalValue >= max}
className={cx(classes.control, classes.controlUp)}
onPointerDown={(event) => {
onStep(event, true);
}}
onPointerUp={onStepDone}
onPointerLeave={onStepDone}
>
<Chevron size={theme.fn.size({ size, sizes: CHEVRON_SIZES })} direction="up" />
</button>
<button
type="button"
tabIndex={-1}
aria-hidden
disabled={finalValue <= min}
className={cx(classes.control, classes.controlDown)}
onPointerDown={(event) => {
onStep(event, false);
}}
onPointerUp={onStepDone}
onPointerLeave={onStepDone}
>
<Chevron size={theme.fn.size({ size, sizes: CHEVRON_SIZES })} direction="down" />
</button>
</div>
);
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const evt = event.nativeEvent as InputEvent;
if (evt.isComposing) {
return;
}
const val = event.target.value;
const parsed = parseNum(val);
setTempValue(parsed);
if (val === '' || val === '-') {
handleValueChange(undefined);
} else {
val.trim() !== '' && !Number.isNaN(parsed) && handleValueChange(parseFloat(parsed));
}
};
const handleBlur = (event: React.FocusEvent<HTMLInputElement>) => {
if (event.target.value === '') {
setTempValue('');
handleValueChange(undefined);
} else {
let newNumber = event.target.value;
if (newNumber[0] === `${decimalSeparator}` || newNumber[0] === '.') {
newNumber = `0${newNumber}`;
}
const parsedVal = parseNum(newNumber);
const val = clamp(parseFloat(parsedVal), _min, _max);
if (!Number.isNaN(val)) {
if (!noClampOnBlur) {
setTempValue(parsePrecision(val));
handleValueChange(parseFloat(parsePrecision(val)));
}
} else {
setTempValue(parsePrecision(finalValue) ?? '');
}
}
setFocused(false);
typeof onBlur === 'function' && onBlur(event);
};
const handleFocus = (event: React.FocusEvent<HTMLInputElement>) => {
setFocused(true);
typeof onFocus === 'function' && onFocus(event);
};
const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
typeof onKeyDown === 'function' && onKeyDown(event);
if (
event.repeat &&
shouldUseStepInterval &&
(event.key === 'ArrowUp' || event.key === 'ArrowDown')
) {
event.preventDefault();
return;
}
if (!readOnly) {
if (event.key === 'ArrowUp') {
onStep(event, true);
} else if (event.key === 'ArrowDown') {
onStep(event, false);
}
}
};
const handleKeyUp = (event: React.KeyboardEvent<HTMLInputElement>) => {
typeof onKeyUp === 'function' && onKeyUp(event);
if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
onStepDone();
}
};
return (
<TextInput
{...others}
type={type}
variant={variant}
value={formatNum(tempValue)}
disabled={disabled}
readOnly={readOnly}
ref={useMergedRef(inputRef, ref)}
onChange={handleChange}
onBlur={handleBlur}
onFocus={handleFocus}
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
rightSection={
rightSection ||
(disabled || readOnly || hideControls || variant === 'unstyled' ? null : controls)
}
rightSectionWidth={rightSectionWidth || theme.fn.size({ size, sizes: CONTROL_SIZES }) + 1}
radius={radius}
max={max}
min={min}
step={step}
size={size}
styles={styles}
classNames={classNames}
inputMode={inputMode || getInputMode(step, precision, useOs())}
__staticSelector="NumberInput"
unstyled={unstyled}
/>
);
});
NumberInput.displayName = '@mantine/core/NumberInput';