-
-
Notifications
You must be signed in to change notification settings - Fork 185
Expand file tree
/
Copy pathInputNumber.tsx
More file actions
737 lines (625 loc) · 21.3 KB
/
InputNumber.tsx
File metadata and controls
737 lines (625 loc) · 21.3 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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
import getMiniDecimal, {
DecimalClass,
getNumberPrecision,
num2str,
toFixed,
validateNumber,
ValueType,
} from '@rc-component/mini-decimal';
import { useLayoutUpdateEffect } from '@rc-component/util/lib/hooks/useLayoutEffect';
import proxyObject from '@rc-component/util/lib/proxyObject';
import { clsx } from 'clsx';
import * as React from 'react';
import useCursor from './hooks/useCursor';
import StepHandler from './StepHandler';
import { getDecupleSteps } from './utils/numberUtil';
import { useEvent } from '@rc-component/util';
import { triggerFocus, type InputFocusOptions } from '@rc-component/util/lib/Dom/focus';
import useFrame from './hooks/useFrame';
export type { ValueType };
export interface InputNumberRef extends HTMLInputElement {
focus: (options?: InputFocusOptions) => void;
blur: () => void;
nativeElement: HTMLElement;
}
/**
* We support `stringMode` which need handle correct type when user call in onChange
* format max or min value
* 1. if isInvalid return null
* 2. if precision is undefined, return decimal
* 3. format with precision
* I. if max > 0, round down with precision. Example: max= 3.5, precision=0 afterFormat: 3
* II. if max < 0, round up with precision. Example: max= -3.5, precision=0 afterFormat: -4
* III. if min > 0, round up with precision. Example: min= 3.5, precision=0 afterFormat: 4
* IV. if min < 0, round down with precision. Example: max= -3.5, precision=0 afterFormat: -3
*/
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;
};
type SemanticName = 'root' | 'actions' | 'input' | 'action' | 'prefix' | 'suffix';
export interface InputNumberProps<T extends ValueType = ValueType>
extends Omit<
React.InputHTMLAttributes<HTMLInputElement>,
| 'value'
| 'defaultValue'
| 'onInput'
| 'onChange'
| 'prefix'
| 'suffix'
| 'onMouseDown'
| 'onClick'
| 'onMouseUp'
| 'onMouseLeave'
| 'onMouseMove'
| 'onMouseEnter'
| 'onMouseOut'
>,
Pick<
React.HTMLAttributes<HTMLDivElement>,
| 'onMouseDown'
| 'onClick'
| 'onMouseUp'
| 'onMouseLeave'
| 'onMouseMove'
| 'onMouseEnter'
| 'onMouseOut'
> {
disabled?: boolean;
readOnly?: boolean;
/** value will show as string */
stringMode?: boolean;
mode?: 'input' | 'spinner';
defaultValue?: T;
value?: T | null;
prefixCls?: string;
className?: string;
style?: React.CSSProperties;
min?: T;
max?: T;
step?: ValueType;
tabIndex?: number;
controls?: boolean;
prefix?: React.ReactNode;
suffix?: React.ReactNode;
classNames?: Partial<Record<SemanticName, string>>;
styles?: Partial<Record<SemanticName, React.CSSProperties>>;
// Customize handler node
upHandler?: React.ReactNode;
downHandler?: React.ReactNode;
keyboard?: boolean;
changeOnWheel?: boolean;
/** Parse display value to validate number */
parser?: (displayValue: string | undefined) => T;
/** Transform `value` to display value show in input */
formatter?: (value: T | undefined, info: { userTyping: boolean; input: string }) => 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 | null) => void;
onPressEnter?: React.KeyboardEventHandler<HTMLInputElement>;
onStep?: (
value: T,
info: { offset: ValueType; type: 'up' | 'down'; emitter: 'handler' | 'keyboard' | 'wheel' },
) => void;
/**
* Trigger change onBlur event.
* If disabled, user must press enter or click handler to confirm the value update
*/
changeOnBlur?: boolean;
}
const InputNumber = React.forwardRef<InputNumberRef, InputNumberProps>((props, ref) => {
const {
mode = 'input',
prefixCls = 'rc-input-number',
className,
style,
classNames,
styles,
min,
max,
step = 1,
defaultValue,
value,
disabled,
readOnly,
upHandler,
downHandler,
keyboard,
changeOnWheel = false,
controls = true,
prefix,
suffix,
stringMode,
parser,
formatter,
precision,
decimalSeparator,
onChange,
onInput,
onPressEnter,
onStep,
// Mouse Events
onMouseDown,
onClick,
onMouseUp,
onMouseLeave,
onMouseMove,
onMouseEnter,
onMouseOut,
changeOnBlur = true,
...restProps
} = props;
const [focus, setFocus] = React.useState(false);
const userTypingRef = React.useRef(false);
const compositionRef = React.useRef(false);
const shiftKeyRef = React.useRef(false);
// ============================= Refs =============================
const rootRef = React.useRef<HTMLDivElement>(null);
const inputRef = React.useRef<HTMLInputElement>(null);
React.useImperativeHandle(ref, () =>
proxyObject(inputRef.current, {
focus: (option?: InputFocusOptions) => {
triggerFocus(inputRef.current, option);
},
blur: () => {
inputRef.current?.blur();
},
nativeElement: rootRef.current,
}),
);
// ============================ Value =============================
// Real value control
const [decimalValue, setDecimalValue] = React.useState<DecimalClass>(() =>
getMiniDecimal(value ?? defaultValue),
);
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.
*
* 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 (userTyping) {
return undefined;
}
if (precision >= 0) {
return precision;
}
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 inputValueRef = React.useRef<string | number>('');
const mergedFormatter = React.useCallback(
(number: string, userTyping: boolean) => {
if (formatter) {
return formatter(number, { userTyping, input: String(inputValueRef.current) });
}
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 updates 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);
});
inputValueRef.current = inputValue;
// Should always be string
function setInputValue(newValue: DecimalClass, userTyping: boolean) {
setInternalInputValue(
mergedFormatter(
// Invalidate number is sometime passed by external control, we should let it go
// Otherwise is controlled by internal interactive logic which check by userTyping
// You can ref 'show limited value when input is not focused' test for more info.
newValue.isInvalidate() ? newValue.toString(false) : newValue.toString(!userTyping),
userTyping,
),
);
}
// >>> Max & Min limit
const maxDecimal = React.useMemo(() => getDecimalIfValidate(max), [max, precision]);
const minDecimal = React.useMemo(() => getDecimalIfValidate(min), [min, precision]);
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;
let isRangeValidate = isInRange(updateValue) || updateValue.isEmpty();
// Skip align value when trigger value is empty.
// We just trigger onChange(null)
// This should not block user typing
if (!updateValue.isEmpty() && !userTyping) {
// Revert value in range if needed
updateValue = getRangeValue(updateValue) || updateValue;
isRangeValidate = true;
}
if (!readOnly && !disabled && isRangeValidate) {
const numStr = updateValue.toString();
const mergedPrecision = getPrecision(numStr, userTyping);
if (mergedPrecision >= 0) {
updateValue = getMiniDecimal(toFixed(numStr, '.', mergedPrecision));
// When to fixed. The value may out of min & max range.
// 4 in [0, 3.8] => 3.8 => 4 (toFixed)
if (!isInRange(updateValue)) {
updateValue = getMiniDecimal(toFixed(numStr, '.', mergedPrecision, true));
}
}
// 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 ==========================
const onNextPromise = useFrame();
// >>> Collect input value
const collectInputValue = (inputStr: string) => {
recordCursor();
// Update inputValue in case input can not parse as number
// Refresh ref value immediately since it may used by formatter
inputValueRef.current = inputStr;
setInternalInputValue(inputStr);
// Parse number
if (!compositionRef.current) {
const finalValue = mergedParser(inputStr);
const finalDecimal = getMiniDecimal(finalValue);
if (!finalDecimal.isNaN()) {
triggerValueUpdate(finalDecimal, true);
}
}
// Trigger onInput later to let user customize value if they want to handle something after onChange
onInput?.(inputStr);
// optimize for chinese input experience
// https://github.com/ant-design/ant-design/issues/8196
onNextPromise(() => {
let nextInputStr = inputStr;
if (!parser) {
nextInputStr = inputStr.replace(/。/g, '.');
}
if (nextInputStr !== inputStr) {
collectInputValue(nextInputStr);
}
});
};
// >>> Composition
const onCompositionStart = () => {
compositionRef.current = true;
};
const onCompositionEnd = () => {
compositionRef.current = false;
collectInputValue(inputRef.current.value);
};
// >>> Input
const onInternalInput: React.ChangeEventHandler<HTMLInputElement> = (e) => {
collectInputValue(e.target.value);
};
// ============================= Step =============================
const onInternalStep = useEvent((up: boolean, emitter: 'handler' | 'keyboard' | 'wheel') => {
// Ignore step since out of range
if ((up && upDisabled) || (!up && downDisabled)) {
return;
}
// Clear typing status since it may be caused by up & down key.
// We should sync with input value.
userTypingRef.current = false;
let stepDecimal = getMiniDecimal(shiftKeyRef.current ? getDecupleSteps(step) : step);
if (!up) {
stepDecimal = stepDecimal.negate();
}
const target = (decimalValue || getMiniDecimal(0)).add(stepDecimal.toString());
const updatedValue = triggerValueUpdate(target, false);
onStep?.(getDecimalValue(stringMode, updatedValue), {
offset: shiftKeyRef.current ? getDecupleSteps(step) : step,
type: up ? 'up' : 'down',
emitter,
});
inputRef.current?.focus();
});
// ============================ Flush =============================
/**
* Flush current input content to trigger value change & re-formatter input if needed.
* This will always flush input value for update.
* If it's invalidate, will fallback to last validate value.
*/
const flushInputValue = (userTyping: boolean) => {
const parsedValue = getMiniDecimal(mergedParser(inputValue));
let formatValue: DecimalClass;
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, userTyping);
} else {
formatValue = triggerValueUpdate(decimalValue, userTyping);
}
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);
}
};
// Solve the issue of the event triggering sequence when entering numbers in chinese input (Safari)
const onBeforeInput = () => {
userTypingRef.current = true;
};
const onKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (event) => {
const { key, shiftKey } = event;
userTypingRef.current = true;
shiftKeyRef.current = shiftKey;
if (key === 'Enter') {
if (!compositionRef.current) {
userTypingRef.current = false;
}
flushInputValue(false);
onPressEnter?.(event);
}
if (keyboard === false) {
return;
}
// Do step
if (!compositionRef.current && ['Up', 'ArrowUp', 'Down', 'ArrowDown'].includes(key)) {
onInternalStep(key === 'Up' || key === 'ArrowUp', 'keyboard');
event.preventDefault();
}
};
const onKeyUp = () => {
userTypingRef.current = false;
shiftKeyRef.current = false;
};
React.useEffect(() => {
if (changeOnWheel && focus) {
const onWheel = (event) => {
// moving mouse wheel rises wheel event with deltaY < 0
// scroll value grows from top to bottom, as screen Y coordinate
onInternalStep(event.deltaY < 0, 'wheel');
event.preventDefault();
};
const input = inputRef.current;
if (input) {
// React onWheel is passive and we can't preventDefault() in it.
// That's why we should subscribe with DOM listener
// https://stackoverflow.com/questions/63663025/react-onwheel-handler-cant-preventdefault-because-its-a-passive-event-listenev
input.addEventListener('wheel', onWheel, { passive: false });
return () => input.removeEventListener('wheel', onWheel);
}
}
});
// >>> Focus & Blur
const onBlur = () => {
if (changeOnBlur) {
flushInputValue(false);
}
setFocus(false);
userTypingRef.current = false;
};
// >>> Mouse events
const onInternalMouseDown: React.MouseEventHandler<HTMLDivElement> = (event) => {
if (event.target !== inputRef.current) {
inputRef.current.focus();
}
onMouseDown?.(event);
};
// ========================== Controlled ==========================
// Input by precision & formatter
useLayoutUpdateEffect(() => {
if (!decimalValue.isInvalidate()) {
setInputValue(decimalValue, false);
}
}, [precision, formatter]);
// Input by value
useLayoutUpdateEffect(() => {
const newValue = getMiniDecimal(value);
setDecimalValue(newValue);
const currentParsedValue = getMiniDecimal(mergedParser(inputValue));
// 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.equals(currentParsedValue) || !userTypingRef.current || formatter) {
// Update value as effect
setInputValue(newValue, userTypingRef.current);
}
}, [value]);
// ============================ Cursor ============================
useLayoutUpdateEffect(() => {
if (formatter) {
restoreCursor();
}
}, [inputValue]);
// ============================ Render ============================
// >>>>>> Handler
const sharedHandlerProps = {
prefixCls,
onStep: onInternalStep,
className: classNames?.action,
style: styles?.action,
};
const upNode = (
<StepHandler {...sharedHandlerProps} action="up" disabled={upDisabled}>
{upHandler}
</StepHandler>
);
const downNode = (
<StepHandler {...sharedHandlerProps} action="down" disabled={downDisabled}>
{downHandler}
</StepHandler>
);
// >>>>>> Render
return (
<div
ref={rootRef}
className={clsx(prefixCls, `${prefixCls}-mode-${mode}`, className, classNames?.root, {
[`${prefixCls}-focused`]: focus,
[`${prefixCls}-disabled`]: disabled,
[`${prefixCls}-readonly`]: readOnly,
[`${prefixCls}-not-a-number`]: decimalValue.isNaN(),
[`${prefixCls}-out-of-range`]: !decimalValue.isInvalidate() && !isInRange(decimalValue),
})}
style={{ ...styles?.root, ...style }}
onMouseDown={onInternalMouseDown}
onMouseUp={onMouseUp}
onMouseLeave={onMouseLeave}
onMouseMove={onMouseMove}
onMouseEnter={onMouseEnter}
onMouseOut={onMouseOut}
onClick={onClick}
onFocus={() => {
setFocus(true);
}}
onBlur={onBlur}
onKeyDown={onKeyDown}
onKeyUp={onKeyUp}
onCompositionStart={onCompositionStart}
onCompositionEnd={onCompositionEnd}
onBeforeInput={onBeforeInput}
>
{mode === 'spinner' && controls && downNode}
{prefix !== undefined && (
<div className={clsx(`${prefixCls}-prefix`, classNames?.prefix)} style={styles?.prefix}>
{prefix}
</div>
)}
<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}
ref={inputRef}
className={clsx(`${prefixCls}-input`, classNames?.input)}
style={styles?.input}
value={inputValue}
onChange={onInternalInput}
disabled={disabled}
readOnly={readOnly}
{...restProps}
/>
{suffix !== undefined && (
<div className={clsx(`${prefixCls}-suffix`, classNames?.suffix)} style={styles?.suffix}>
{suffix}
</div>
)}
{mode === 'spinner' && controls && upNode}
{mode === 'input' && controls && (
<div className={clsx(`${prefixCls}-actions`, classNames?.actions)} style={styles?.actions}>
{upNode}
{downNode}
</div>
)}
</div>
);
}) as (<T extends ValueType = ValueType>(
props: React.PropsWithChildren<InputNumberProps<T>> & {
ref?: React.Ref<HTMLInputElement>;
},
) => React.ReactElement) & { displayName?: string };
if (process.env.NODE_ENV !== 'production') {
InputNumber.displayName = 'InputNumber';
}
export default InputNumber;