-
Notifications
You must be signed in to change notification settings - Fork 416
/
Copy pathnumber_format_base.tsx
396 lines (336 loc) · 12.4 KB
/
number_format_base.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
import React, { useEffect, useState, useRef } from 'react';
import {
FormatInputValueFunction,
NumberFormatBaseProps,
InputAttributes,
SourceType,
Timeout,
} from './types';
import {
addInputMode,
findChangeRange,
geInputCaretPosition,
setCaretPosition,
getCaretPosition,
charIsNumber,
useInternalValues,
noop,
caretUnknownFormatBoundary,
getCaretPosInBoundary,
} from './utils';
function defaultRemoveFormatting(value: string) {
return value.replace(/[^0-9]/g, '');
}
function defaultFormat(value: string) {
return value;
}
export default function NumberFormatBase<BaseType = InputAttributes>(
props: NumberFormatBaseProps<BaseType>,
): React.ReactElement {
const {
type = 'text',
displayType = 'input',
customInput,
renderText,
getInputRef,
format = defaultFormat,
removeFormatting = defaultRemoveFormatting,
defaultValue,
valueIsNumericString,
onValueChange,
isAllowed,
onChange = noop,
onKeyDown = noop,
onMouseUp = noop,
onFocus = noop,
onBlur = noop,
value: propValue,
getCaretBoundary = caretUnknownFormatBoundary,
isValidInputCharacter = charIsNumber,
...otherProps
} = props;
const [{ formattedValue, numAsString }, onFormattedValueChange] = useInternalValues(
propValue,
defaultValue,
Boolean(valueIsNumericString),
format as FormatInputValueFunction,
removeFormatting,
onValueChange,
);
const lastUpdatedValue = useRef<string>();
const _onValueChange: NumberFormatBaseProps['onValueChange'] = (values, source) => {
lastUpdatedValue.current = values.formattedValue;
onFormattedValueChange(values, source);
};
// check if there is any change in the value due to props change
useEffect(() => {
const newFormattedValue = (format as FormatInputValueFunction)(numAsString);
// if the formatted value is not synced to parent, or if the formatted value is different
if (lastUpdatedValue.current === undefined || newFormattedValue !== lastUpdatedValue.current) {
const input = focusedElm.current;
updateValue({
formattedValue: newFormattedValue,
numAsString: numAsString,
input,
setCaretPosition: true,
source: SourceType.props,
event: undefined,
});
}
});
const [mounted, setMounted] = useState(false);
const focusedElm = useRef<HTMLInputElement | null>(null);
const timeout = useRef<{
setCaretTimeout: Timeout | null;
focusTimeout: Timeout | null;
}>({
setCaretTimeout: null,
focusTimeout: null,
});
useEffect(() => {
setMounted(true);
return () => {
clearTimeout(timeout.current.setCaretTimeout as unknown as Timeout);
clearTimeout(timeout.current.focusTimeout as unknown as Timeout);
};
}, []);
const _format = format as FormatInputValueFunction;
const getValueObject = (formattedValue: string, numAsString: string) => {
const floatValue = parseFloat(numAsString);
return {
formattedValue,
value: numAsString,
floatValue: isNaN(floatValue) ? undefined : floatValue,
};
};
const setPatchedCaretPosition = (
el: HTMLInputElement,
caretPos: number,
currentValue: string,
) => {
/* setting caret position within timeout of 0ms is required for mobile chrome,
otherwise browser resets the caret position after we set it
We are also setting it without timeout so that in normal browser we don't see the flickering */
setCaretPosition(el, caretPos);
timeout.current.setCaretTimeout = setTimeout(() => {
if (el.value === currentValue) setCaretPosition(el, caretPos);
}, 0);
};
/* This keeps the caret within typing area so people can't type in between prefix or suffix */
const correctCaretPosition = (value: string, caretPos: number, direction?: string) => {
return getCaretPosInBoundary(value, caretPos, getCaretBoundary(value), direction);
};
const getNewCaretPosition = (inputValue: string, newFormattedValue: string, caretPos: number) => {
const caretBoundary = getCaretBoundary(newFormattedValue);
let updatedCaretPos = getCaretPosition(
newFormattedValue,
formattedValue,
inputValue,
caretPos,
caretBoundary,
isValidInputCharacter,
);
//correct caret position if its outside of editable area
updatedCaretPos = getCaretPosInBoundary(newFormattedValue, updatedCaretPos, caretBoundary);
return updatedCaretPos;
};
const updateValue = (params: {
formattedValue?: string;
numAsString: string;
inputValue?: string;
input?: HTMLInputElement | null;
event?:
| React.ChangeEvent<HTMLInputElement>
| React.FocusEvent<HTMLInputElement>
| React.KeyboardEvent<HTMLInputElement>;
source: SourceType;
caretPos?: number;
setCaretPosition?: Boolean;
}) => {
const {
formattedValue: newFormattedValue = '',
input,
setCaretPosition = true,
source,
event,
numAsString,
} = params;
let { caretPos } = params;
if (input) {
//calculate caret position if not defined
if (caretPos === undefined && setCaretPosition) {
const inputValue = params.inputValue || input.value;
const currentCaretPosition = geInputCaretPosition(input);
/**
* set the value imperatively, this is required for IE fix
* This is also required as if new caret position is beyond the previous value.
* Caret position will not be set correctly
*/
input.value = newFormattedValue;
//get the caret position
caretPos = getNewCaretPosition(inputValue, newFormattedValue, currentCaretPosition);
}
/**
* set the value imperatively, as we set the caret position as well imperatively.
* This is to keep value and caret position in sync
*/
input.value = newFormattedValue;
//set caret position, and value imperatively when element is provided
if (setCaretPosition && caretPos !== undefined) {
//set caret position
setPatchedCaretPosition(input, caretPos, newFormattedValue);
}
}
if (newFormattedValue !== formattedValue) {
// trigger onValueChange synchronously, so parent is updated along with the number format. Fix for #277, #287
_onValueChange(getValueObject(newFormattedValue, numAsString), { event, source });
}
};
const formatInputValue = (
inputValue: string,
event:
| React.ChangeEvent<HTMLInputElement>
| React.FocusEvent<HTMLInputElement>
| React.KeyboardEvent<HTMLInputElement>,
source: SourceType,
) => {
const changeRange = findChangeRange(formattedValue, inputValue);
const changeMeta = {
...changeRange,
lastValue: formattedValue,
};
const _numAsString = removeFormatting(inputValue, changeMeta);
const _formattedValue = _format(_numAsString);
if (isAllowed && !isAllowed(getValueObject(_formattedValue, _numAsString))) {
//reset the caret position
const input = event.target as HTMLInputElement;
const currentCaretPosition = geInputCaretPosition(input);
const caretPos = getNewCaretPosition(inputValue, formattedValue, currentCaretPosition);
setPatchedCaretPosition(input, caretPos, formattedValue);
return false;
}
updateValue({
formattedValue: _formattedValue,
numAsString: _numAsString,
inputValue,
event,
source,
setCaretPosition: true,
input: event.target as HTMLInputElement,
});
return true;
};
const _onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const el = e.target;
const inputValue = el.value;
const changed = formatInputValue(inputValue, e, SourceType.event);
if (changed) onChange(e);
};
const _onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
const el = e.target as HTMLInputElement;
const { key } = e;
const { selectionStart, selectionEnd, value = '' } = el;
let expectedCaretPosition;
//Handle backspace and delete against non numerical/decimal characters or arrow keys
if (key === 'ArrowLeft' || key === 'Backspace') {
expectedCaretPosition = Math.max((selectionStart as number) - 1, 0);
} else if (key === 'ArrowRight') {
expectedCaretPosition = Math.min((selectionStart as number) + 1, value.length);
} else if (key === 'Delete') {
expectedCaretPosition = selectionStart;
}
//if expectedCaretPosition is not set it means we don't want to Handle keyDown
// also if multiple characters are selected don't handle
if (expectedCaretPosition === undefined || selectionStart !== selectionEnd) {
onKeyDown(e);
return;
}
let newCaretPosition = expectedCaretPosition;
if (key === 'ArrowLeft' || key === 'ArrowRight') {
const direction = key === 'ArrowLeft' ? 'left' : 'right';
newCaretPosition = correctCaretPosition(value, expectedCaretPosition, direction);
} else if (key === 'Delete' && !isValidInputCharacter(value[expectedCaretPosition])) {
// in case of delete go to closest caret boundary on the right side
newCaretPosition = correctCaretPosition(value, expectedCaretPosition, 'right');
} else if (key === 'Backspace' && !isValidInputCharacter(value[expectedCaretPosition])) {
// in case of backspace go to closest caret boundary on the left side
newCaretPosition = correctCaretPosition(value, expectedCaretPosition, 'left');
}
if (newCaretPosition !== expectedCaretPosition) {
setPatchedCaretPosition(el, newCaretPosition, value);
}
/* NOTE: this is just required for unit test as we need to get the newCaretPosition,
Remove this when you find different solution */
/* @ts-ignore */
if (e.isUnitTestRun) {
setPatchedCaretPosition(el, newCaretPosition, value);
}
onKeyDown(e);
};
/** required to handle the caret position when click anywhere within the input **/
const _onMouseUp = (e: React.MouseEvent<HTMLInputElement>) => {
const el = e.target as HTMLInputElement;
/**
* NOTE: we have to give default value for value as in case when custom input is provided
* value can come as undefined when nothing is provided on value prop.
*/
const { selectionStart, selectionEnd, value = '' } = el;
if (selectionStart === selectionEnd) {
const caretPosition = correctCaretPosition(value, selectionStart as number);
if (caretPosition !== selectionStart) {
setPatchedCaretPosition(el, caretPosition, value);
}
}
onMouseUp(e);
};
const _onFocus = (e: React.FocusEvent<HTMLInputElement>) => {
// Workaround Chrome and Safari bug https://bugs.chromium.org/p/chromium/issues/detail?id=779328
// (onFocus event target selectionStart is always 0 before setTimeout)
if (e.persist) e.persist();
const el = e.target;
focusedElm.current = el;
timeout.current.focusTimeout = setTimeout(() => {
const { selectionStart, selectionEnd, value = '' } = el;
const caretPosition = correctCaretPosition(value, selectionStart as number);
//setPatchedCaretPosition only when everything is not selected on focus (while tabbing into the field)
if (
caretPosition !== selectionStart &&
!(selectionStart === 0 && selectionEnd === value.length)
) {
setPatchedCaretPosition(el, caretPosition, value);
}
onFocus(e);
}, 0);
};
const _onBlur = (e: React.FocusEvent<HTMLInputElement>) => {
focusedElm.current = null;
clearTimeout(timeout.current.focusTimeout as unknown as Timeout);
clearTimeout(timeout.current.setCaretTimeout as unknown as Timeout);
onBlur(e);
};
// add input mode on element based on format prop and device once the component is mounted
const inputMode: InputAttributes['inputMode'] = mounted && addInputMode() ? 'numeric' : undefined;
const inputProps = Object.assign({ inputMode }, otherProps, {
type,
value: formattedValue,
onChange: _onChange,
onKeyDown: _onKeyDown,
onMouseUp: _onMouseUp,
onFocus: _onFocus,
onBlur: _onBlur,
});
if (displayType === 'text') {
return renderText ? (
<>{renderText(formattedValue, otherProps) || null}</>
) : (
<span {...otherProps} ref={getInputRef}>
{formattedValue}
</span>
);
} else if (customInput) {
const CustomInput = customInput;
/* @ts-ignore */
return <CustomInput {...inputProps} ref={getInputRef} />;
}
return <input {...inputProps} ref={getInputRef} />;
}