-
-
Notifications
You must be signed in to change notification settings - Fork 186
Expand file tree
/
Copy pathInputNumber.tsx
More file actions
524 lines (437 loc) · 15.4 KB
/
InputNumber.tsx
File metadata and controls
524 lines (437 loc) · 15.4 KB
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
import * as React from 'react';
import classNames from 'classnames';
import KeyCode from 'rc-util/lib/KeyCode';
import { composeRef } from 'rc-util/lib/ref';
import getMiniDecimal, { DecimalClass, toFixed, ValueType } from './utils/MiniDecimal';
import StepHandler from './StepHandler';
import { getNumberPrecision, num2str, validateNumber } from './utils/numberUtil';
import useCursor from './hooks/useCursor';
import useUpdateEffect from './hooks/useUpdateEffect';
/**
* We support `stringMode` which need handle correct type when user call in onChange
*/
const getDecimalValue = (stringMode: boolean, decimalValue: DecimalClass) => {
if (stringMode || decimalValue.isEmpty()) {
return decimalValue.toString();
}
return decimalValue.toNumber();
};
const getDecimalIfValidate = (value: ValueType) => {
const decimal = getMiniDecimal(value);
return decimal.isInvalidate() ? null : decimal;
};
export interface InputNumberProps<T extends ValueType = ValueType>
extends Omit<
React.InputHTMLAttributes<HTMLInputElement>,
'value' | 'defaultValue' | 'onInput' | 'onChange'
> {
/** value will show as string */
stringMode?: boolean;
defaultValue?: T;
value?: T;
prefixCls?: string;
className?: string;
style?: React.CSSProperties;
min?: T;
max?: T;
step?: ValueType;
tabIndex?: number;
// Customize handler node
upHandler?: React.ReactNode;
downHandler?: React.ReactNode;
keyboard?: boolean;
/** Parse display value to validate number */
parser?: (displayValue: string | undefined) => T;
/** Transform `value` to display value show in input */
formatter?: (value: T | undefined) => string;
/** Syntactic sugar of `formatter`. Config precision of display. */
precision?: number;
/** Syntactic sugar of `formatter`. Config decimal separator of display. */
decimalSeparator?: string;
onInput?: (text: string) => void;
onChange?: (value: T) => void;
onPressEnter?: React.KeyboardEventHandler<HTMLInputElement>;
onStep?: (value: T, info: { offset: ValueType; type: 'up' | 'down' }) => void;
// focusOnUpDown: boolean;
// useTouch: boolean;
// size?: ISize;
}
const InputNumber = React.forwardRef(
(props: InputNumberProps, ref: React.Ref<HTMLInputElement>) => {
const {
prefixCls = 'rc-input-number',
className,
style,
min,
max,
step = 1,
defaultValue,
value,
disabled,
readOnly,
upHandler,
downHandler,
keyboard,
stringMode,
parser,
formatter,
precision,
decimalSeparator,
onChange,
onInput,
onPressEnter,
onStep,
...inputProps
} = props;
const inputClassName = `${prefixCls}-input`;
const inputRef = React.useRef<HTMLInputElement>(null);
const [focus, setFocus] = React.useState(false);
const userTypingRef = React.useRef(false);
const compositionRef = React.useRef(false);
// ============================ Value =============================
// Real value control
const [decimalValue, setDecimalValue] = React.useState<DecimalClass>(() =>
getMiniDecimal(defaultValue ?? value),
);
function setUncontrolledDecimalValue(newDecimal: DecimalClass) {
if (value === undefined) {
setDecimalValue(newDecimal);
}
}
// ====================== Parser & Formatter ======================
/**
* `precision` is used for formatter & onChange.
* It will auto generate by `value` & `step`.
* But it will not block user typing when auto generated.
*
* Note: Auto generate `precision` is used for legacy logic.
* We should remove this since we already support high precision with BigInt.
*
* @param number Provide which number should calculate precision
* @param userTyping Change by user typing
*/
const getPrecision = React.useCallback(
(numStr: string, userTyping: boolean) => {
if (precision >= 0) {
return precision;
}
if (userTyping) {
return undefined;
}
return Math.max(getNumberPrecision(numStr), getNumberPrecision(step));
},
[precision, step],
);
// >>> Parser
const mergedParser = React.useCallback(
(num: string | number) => {
const numStr = String(num);
if (parser) {
return parser(numStr);
}
let parsedStr = numStr;
if (decimalSeparator) {
parsedStr = parsedStr.replace(decimalSeparator, '.');
}
// [Legacy] We still support auto convert `$ 123,456` to `123456`
return parsedStr.replace(/[^\w.-]+/g, '');
},
[parser, decimalSeparator],
);
// >>> Formatter
const mergedFormatter = React.useCallback(
(number: string, userTyping: boolean) => {
if (formatter) {
return formatter(number);
}
let str = typeof number === 'number' ? num2str(number) : number;
// User typing will not auto format with precision directly
if (!userTyping) {
const mergedPrecision = getPrecision(str, userTyping);
if (validateNumber(str) && (decimalSeparator || mergedPrecision >= 0)) {
// Separator
const separatorStr = decimalSeparator || '.';
str = toFixed(str, separatorStr, mergedPrecision);
}
}
return str;
},
[formatter, getPrecision, decimalSeparator],
);
// ========================== InputValue ==========================
/**
* Input text value control
*
* User can not update input content directly. It update with follow rules by priority:
* 1. controlled `value` changed
* * [SPECIAL] Typing like `1.` should not immediately convert to `1`
* 2. User typing with format (not precision)
* 3. Blur or Enter trigger revalidate
*/
const [inputValue, setInternalInputValue] = React.useState<string | number>(() => {
const initValue = defaultValue ?? value;
if (decimalValue.isInvalidate() && ['string', 'number'].includes(typeof initValue)) {
return Number.isNaN(initValue) ? '' : initValue;
}
return mergedFormatter(decimalValue.toString(), false);
});
// Should always be string
function setInputValue(newValue: DecimalClass, userTyping: boolean) {
setInternalInputValue(mergedFormatter(newValue.toString(false), userTyping));
}
// >>> Max & Min limit
const maxDecimal = React.useMemo(() => getDecimalIfValidate(max), [max]);
const minDecimal = React.useMemo(() => getDecimalIfValidate(min), [min]);
const upDisabled = React.useMemo(() => {
if (!maxDecimal || !decimalValue || decimalValue.isInvalidate()) {
return false;
}
return maxDecimal.lessEquals(decimalValue);
}, [maxDecimal, decimalValue]);
const downDisabled = React.useMemo(() => {
if (!minDecimal || !decimalValue || decimalValue.isInvalidate()) {
return false;
}
return decimalValue.lessEquals(minDecimal);
}, [minDecimal, decimalValue]);
// Cursor controller
const [recordCursor, restoreCursor] = useCursor(inputRef.current, focus);
// ============================= Data =============================
/**
* Find target value closet within range.
* e.g. [11, 28]:
* 3 => 11
* 23 => 23
* 99 => 28
*/
const getRangeValue = (target: DecimalClass) => {
// target > max
if (maxDecimal && !target.lessEquals(maxDecimal)) {
return maxDecimal;
}
// target < min
if (minDecimal && !minDecimal.lessEquals(target)) {
return minDecimal;
}
return null;
};
/**
* Check value is in [min, max] range
*/
const isInRange = (target: DecimalClass) => !getRangeValue(target);
/**
* Trigger `onChange` if value validated and not equals of origin.
* Return the value that re-align in range.
*/
const triggerValueUpdate = (newValue: DecimalClass, userTyping: boolean): DecimalClass => {
let updateValue = newValue;
// Skip align value when trigger value is empty.
// We just trigger onChange(null)
if (!updateValue.isEmpty()) {
// Revert value in range if needed
updateValue = getRangeValue(updateValue) || updateValue;
}
if (!readOnly && !disabled) {
const numStr = updateValue.toString();
const mergedPrecision = getPrecision(numStr, userTyping);
if (mergedPrecision >= 0) {
updateValue = getMiniDecimal(toFixed(numStr, '.', mergedPrecision));
}
// Trigger event
if (!updateValue.equals(decimalValue)) {
setUncontrolledDecimalValue(updateValue);
onChange?.(updateValue.isEmpty() ? null : getDecimalValue(stringMode, updateValue));
// Reformat input if value is not controlled
if (value === undefined) {
setInputValue(updateValue, userTyping);
}
}
return updateValue;
}
return decimalValue;
};
// ========================== User Input ==========================
// >>> Collect input value
const collectInputValue = (inputStr: string) => {
recordCursor();
// Update inputValue incase input can not parse as number
setInternalInputValue(inputStr);
if (inputStr === '') triggerValueUpdate(getMiniDecimal(mergedParser(inputStr)), true);
// Parse number
if (!compositionRef.current) {
const finalValue = mergedParser(inputStr);
const finalDecimal = getMiniDecimal(finalValue);
if (!finalDecimal.isInvalidate()) {
triggerValueUpdate(finalDecimal, true);
}
}
};
// >>> Composition
const onCompositionStart = () => {
compositionRef.current = true;
};
const onCompositionEnd = () => {
compositionRef.current = false;
collectInputValue(inputRef.current.value);
};
// >>> Input
const onInternalInput: React.ChangeEventHandler<HTMLInputElement> = (e) => {
let inputStr = e.target.value;
// optimize for chinese input experience
// https://github.com/ant-design/ant-design/issues/8196
if (!parser) {
inputStr = inputStr.replace(/。/g, '.');
}
collectInputValue(inputStr);
// Trigger onInput later to let user customize value if they want do handle something after onChange
onInput?.(inputStr);
};
// ============================= Step =============================
const onInternalStep = (up: boolean) => {
// Ignore step since out of range
if ((up && upDisabled) || (!up && downDisabled)) {
return;
}
// Clear typing status since it may caused by up & down key.
// We should sync with input value.
userTypingRef.current = false;
let stepDecimal = getMiniDecimal(step);
if (!up) {
stepDecimal = stepDecimal.negate();
}
const target = (decimalValue || getMiniDecimal(0)).add(stepDecimal.toString());
const updatedValue = triggerValueUpdate(target, false);
onStep?.(getDecimalValue(stringMode, updatedValue), {
offset: step,
type: up ? 'up' : 'down',
});
inputRef.current?.focus();
};
// ============================ Flush =============================
/**
* Flush current input content to trigger value change & re-formatter input if needed
*/
const flushInputValue = () => {
const parsedValue = getMiniDecimal(mergedParser(inputValue));
let formatValue: DecimalClass = parsedValue;
if (!parsedValue.isNaN()) {
// Only validate value or empty value can be re-fill to inputValue
// Reassign the formatValue within ranged of trigger control
formatValue = triggerValueUpdate(parsedValue, true);
} else {
formatValue = decimalValue;
}
if (value !== undefined) {
// Reset back with controlled value first
setInputValue(decimalValue, false);
} else if (!formatValue.isNaN()) {
// Reset input back since no validate value
setInputValue(formatValue, false);
}
};
const onKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (event) => {
const { which } = event;
userTypingRef.current = true;
if (which === KeyCode.ENTER) {
if(!compositionRef.current) {
userTypingRef.current = false;
}
flushInputValue();
onPressEnter?.(event);
}
if (keyboard === false) {
return;
}
// Do step
if (!compositionRef.current && [KeyCode.UP, KeyCode.DOWN].includes(which)) {
onInternalStep(KeyCode.UP === which);
event.preventDefault();
}
};
const onKeyUp = () => {
userTypingRef.current = false;
};
// >>> Focus & Blur
const onBlur = () => {
flushInputValue();
setFocus(false);
};
// ========================== Controlled ==========================
// Input by precision
useUpdateEffect(() => {
if (!decimalValue.isInvalidate()) {
setInputValue(decimalValue, false);
}
}, [precision]);
// Input by value
useUpdateEffect(() => {
const newValue = getMiniDecimal(value);
setDecimalValue(newValue);
// When user typing from `1.2` to `1.`, we should not convert to `1` immediately.
// But let it go if user set `formatter`
if (newValue.isNaN() || !userTypingRef.current || formatter) {
// Update value as effect
setInputValue(newValue, false);
}
}, [value]);
// ============================ Cursor ============================
useUpdateEffect(() => {
if (formatter) {
restoreCursor();
}
}, [inputValue]);
// ============================ Render ============================
return (
<div
className={classNames(prefixCls, className, {
[`${prefixCls}-focused`]: focus,
[`${prefixCls}-disabled`]: disabled,
[`${prefixCls}-readonly`]: readOnly,
[`${prefixCls}-not-a-number`]: decimalValue.isNaN(),
[`${prefixCls}-out-of-range`]: !decimalValue.isInvalidate() && !isInRange(decimalValue),
})}
style={style}
onFocus={() => {
setFocus(true);
}}
onBlur={onBlur}
onKeyDown={onKeyDown}
onKeyUp={onKeyUp}
onCompositionStart={onCompositionStart}
onCompositionEnd={onCompositionEnd}
>
<StepHandler
prefixCls={prefixCls}
upNode={upHandler}
downNode={downHandler}
upDisabled={upDisabled}
downDisabled={downDisabled}
onStep={onInternalStep}
/>
<div className={`${inputClassName}-wrap`}>
<input
autoComplete="off"
role="spinbutton"
aria-valuemin={min as any}
aria-valuemax={max as any}
aria-valuenow={decimalValue.isInvalidate() ? null : (decimalValue.toString() as any)}
step={step}
{...inputProps}
ref={composeRef(inputRef, ref)}
className={inputClassName}
value={inputValue}
onChange={onInternalInput}
disabled={disabled}
readOnly={readOnly}
/>
</div>
</div>
);
},
) as (<T extends ValueType = ValueType>(
props: React.PropsWithChildren<InputNumberProps<T>> & {
ref?: React.Ref<HTMLInputElement>;
},
) => React.ReactElement) & { displayName?: string };
InputNumber.displayName = 'InputNumber';
export default InputNumber;