forked from input-output-hk/react-polymorph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumericInput.js
More file actions
475 lines (418 loc) · 15.3 KB
/
NumericInput.js
File metadata and controls
475 lines (418 loc) · 15.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
// @flow
import React, { Component } from 'react';
// $FlowFixMe
import type { ComponentType, SyntheticInputEvent, Element } from 'react';
// external libraries
import createRef from 'create-react-ref/lib/createRef';
import { flow } from 'lodash';
// internal components
import { withTheme } from './HOC/withTheme';
// internal utility functions
import { composeTheme, addThemeId, didThemePropsChange } from '../utils/themes';
// import constants
import { IDENTIFIERS } from '../themes/API';
type Props = {
autoFocus: boolean,
className: string,
context: {
theme: Object,
ROOT_THEME_API: Object
},
disabled: boolean,
enforceMax: boolean,
label: string | Element<any>,
enforceMin: boolean,
error: string,
onBlur: Function,
onChange: Function,
onFocus: Function,
maxAfterDot: number,
maxBeforeDot: number,
maxValue: number,
minValue: number,
readOnly: boolean,
placeholder: string,
setError: Function,
skin: ComponentType<any>,
theme: Object, // will take precedence over theme in context if passed
themeId: string,
themeOverrides: Object,
value: string
};
type State = {
composedTheme: Object,
caretPosition: number,
separatorsCount: number,
error: string,
oldValue: string
};
class NumericInputBase extends Component<Props, State> {
inputElement: Element<'input'>;
static defaultProps = {
disabled: false,
error: '',
enforceMax: false,
enforceMin: false,
readOnly: false,
theme: null,
themeId: IDENTIFIERS.INPUT,
themeOverrides: {},
value: ''
};
constructor(props: Props) {
super(props);
const { context, minValue, maxBeforeDot, maxAfterDot, themeId, theme, themeOverrides } = props;
const minValueIsNum = minValue && typeof minValue === 'number';
// if minValue is a number and user supplied maxBeforeDot and/or maxAfterDot
if (minValueIsNum && (maxBeforeDot || maxAfterDot)) {
// check combination of values for validity
this._validateLimitProps(minValue, maxBeforeDot, maxAfterDot);
}
// define ref
this.inputElement = createRef();
this.state = {
composedTheme: composeTheme(
addThemeId(theme || context.theme, themeId),
addThemeId(themeOverrides, themeId),
context.ROOT_THEME_API
),
caretPosition: 0,
separatorsCount: 0,
error: '',
oldValue: ''
};
}
componentDidMount() {
const { inputElement } = this;
// check for autoFocus prop
if (this.props.autoFocus) this.focus();
// Set last input caret position on updates
if (inputElement && inputElement.current) {
this.setState({ caretPosition: inputElement.current.selectionStart });
}
}
componentWillReceiveProps(nextProps: Props) {
didThemePropsChange(this.props, nextProps, this.setState.bind(this));
}
componentDidUpdate(prevProps: Props, prevState: State) {
const { inputElement } = this;
if (inputElement && inputElement.current !== document.activeElement) { return; }
// caret position calculation after separators injection
let caretPosition;
// prevent unnecessary changes on re-rendering
if (
this.state.oldValue !== prevState.oldValue ||
this.state.caretPosition !== prevState.caretPosition
) {
if (
this.state.separatorsCount !== prevState.separatorsCount &&
this.state.separatorsCount - prevState.separatorsCount <= 1 &&
this.state.separatorsCount - prevState.separatorsCount >= -1
) {
caretPosition =
this.state.caretPosition +
(this.state.separatorsCount - prevState.separatorsCount);
} else {
caretPosition = this.state.caretPosition;
}
caretPosition = caretPosition >= 0 ? caretPosition : 0;
if (inputElement && inputElement.current) {
inputElement.current.selectionEnd = caretPosition;
inputElement.current.selectionStart = caretPosition;
}
}
}
onChange = (event: SyntheticInputEvent<Element<'input'>>) => {
event.preventDefault();
const { onChange, disabled } = this.props;
if (disabled) { return; }
// it is crucial to remove whitespace from input value
// with String.trim()
const processedValue = this._processValue(
event.target.value.trim(),
event.target.selectionStart
);
// if the processed value is the same, then the user probably entered
// invalid input such as nonnumeric characters, do not call onChange
if (processedValue === this.state.oldValue) { return; }
if (onChange) { onChange(processedValue, event); }
};
focus = () => {
const { inputElement } = this;
if (!inputElement.current) return;
inputElement.current.focus();
}
_validateLimitProps(minValue: number, maxBeforeDot: number, maxAfterDot: number) {
const maxBeforeDotIsNum = maxBeforeDot && typeof maxBeforeDot === 'number';
const maxAfterDotIsNum = maxAfterDot && typeof maxAfterDot === 'number';
// if minValue is a float, it will split at the decimal
// trailing zeros are dropped with parseFloat
const minValParts = parseFloat(minValue).toString().split('.');
// if minValParts array has length of 2, it is a float
if (minValParts.length >= 2) {
const minValBeforeDot = minValParts[0];
const minValAfterDot = minValParts[1];
// if the number of integers in minValue is greater than maxBeforeDot
if (maxBeforeDotIsNum && (minValBeforeDot.length > maxBeforeDot)) {
// the combo is incompatible, throw error
const error = `
minValue: ${minValue} exceeds the limit of maxBeforeDot: ${maxBeforeDot}.
Adjust the values of these properties.
`;
throw new Error(error);
// if the number of decimal spaces in minValue is greater than maxBeforeDot
} else if (maxAfterDotIsNum && (minValAfterDot.length > maxAfterDot)) {
const error = `
minValue: ${minValue} exceeds the limit of maxAfterDot: ${maxAfterDot}.
Adjust the values of these properties.
`;
throw new Error(error);
}
}
}
_setError = (error: string) => {
const { setError } = this.props;
// checks for setError func from FormField component
// if this NumericInput instance is rendered within FormField's render prop,
// FormField's local state.error will also be set via props.setError
if (setError) setError(error);
// also set (this: NumericInput)'s state.error
this.setState({ error });
};
_processValue(value: string, position: number) {
return flow([
this._enforceNumericValue,
this._parseToParts,
this._enforceValueLimits,
this._separate
]).call(this, value, position);
}
_enforceNumericValue(value: string, position: number) {
const regex = /^[0-9.,]+$/;
const isValueRegular = regex.test(value);
let handledValue;
const lastValidValue = this.state.oldValue;
if (!isValueRegular && value !== '') {
// input contains invalid value
// e.g. 1,00AAbasdasd.asdasd123123
// - reject it and show last valid value
handledValue = lastValidValue || '0.000000';
position -= 1;
} else if (!this._isNumeric(value)) {
// input contains comma separated number
// e.g. 1,000,000.123456
// - make sure commas and caret are at correct position
const splitedValue = value.split('.');
if (splitedValue.length === 3) {
// input value contains more than one dot
const splitedOldValue = lastValidValue.split('.');
let beforeDot = splitedValue[0] + splitedValue[1];
if (splitedOldValue[0].length < beforeDot.length) {
// dot is in decimal part
position -= 1;
handledValue = beforeDot + '.' + splitedValue[2];
beforeDot = beforeDot.replace(/,/g, '');
// prevent replace dot if length before dot is greater then max before dot length
if (beforeDot.length > this.props.maxBeforeDot) {
handledValue = lastValidValue;
}
} else {
handledValue =
splitedValue[0] + '.' + splitedValue[1] + splitedValue[2];
// Second dot was entered after current one -> stay in same position (swallow dot)
if (position > beforeDot.length + 1) {
position -= 1;
}
}
} else if (
splitedValue.length === 2 &&
splitedValue[0] === '' &&
splitedValue[1] === ''
) {
// special case when dot is inserted in an empty input
// - return 0.|00000
handledValue = '0.000000';
position = 2; // position caret after the dot
} else if (value !== '') {
// special case when user selects part of an input value and hits ',' key
// - reject it and show last valid value
handledValue = lastValidValue;
}
}
const lastInsertedCharacter = value.substring(position - 1, position);
if (lastInsertedCharacter === ',') {
// prevent move caret position on hit ','
position -= 1;
}
return !this._isNumeric(value)
? { value: handledValue, position }
: { value, position };
}
_parseToParts(data: { value: string, position: number }) {
const value = data.value;
let position = data.position;
// show placeholder on select all and delete/backspace key action
if (!value) return;
let beforeDot;
let afterDot;
if (data.value.length > 1 && value.split('.').length < 2) {
// handle numbers deletion from both integer and decimal parts at once
beforeDot = value.substring(0, position) || '0';
afterDot = value.substring(position, value.length);
} else {
// split float number to integer and decimal part - regular way
const splitedValue = value.split('.');
beforeDot = splitedValue[0] ? splitedValue[0] : '0';
afterDot = splitedValue[1] ? splitedValue[1] : '000000';
}
// remove leading zero and update caret position
if (value.charAt(0) === '0' && parseInt(beforeDot.replace(/,/g, ''), 10) > 0) {
beforeDot = parseInt(beforeDot.replace(/,/g, ''), 10);
if (position !== 2) {
position = 0;
} else {
position = 1;
}
} else if (parseInt(beforeDot.replace(/,/g, ''), 10) === 0) {
beforeDot = parseInt(beforeDot.replace(/,/g, ''), 10);
}
return { value, position, parts: { beforeDot, afterDot } };
}
// enforces props.maxValue and props.minValue
_enforceValueLimits(data: {
value: string,
position: number,
parts: {
beforeDot: string,
afterDot: string
}
}) {
if (!data) return;
const { minValue, maxValue, enforceMax, enforceMin, maxAfterDot } = this.props;
const { position } = data;
// enforce props.maxBeforeDot and props.maxAfterDot
const valueWithDecimalRestrictions = this._enforceDecimalRestrictions(data);
// creates floating point number equal to valueWithDecimalRestrictions (string)
// will be used for value comparisons against props.maxValue and props.minValue if applicable
const valueWithoutSeparators = parseFloat(valueWithDecimalRestrictions.replace(/,/g, ''));
// if input value is greater than props.maxValue, throw error
if (maxValue && valueWithoutSeparators > maxValue) {
const formattedMaxVal = maxValue.toFixed(maxAfterDot || 6).toString();
this._setError(`Maximum amount is ${formattedMaxVal}`);
// if user passes enforceMax=true, restrict input value to props.maxValue
if (enforceMax) {
this.setState({ caretPosition: position });
return formattedMaxVal;
}
// if input value is below props.minValue, throw error
} else if (minValue && valueWithoutSeparators < minValue) {
const formattedMinVal = minValue.toFixed(maxAfterDot || 6).toString();
this._setError(`Minimum amount is ${formattedMinVal}`);
// if props.enforceMin=true, restrict input value to props.minValue
if (enforceMin) {
this.setState({ caretPosition: position });
return formattedMinVal;
}
// if input value has no errors, clear state.error
} else if (this.state.error !== '') {
this._setError('');
}
// update caret in state
this.setState({ caretPosition: position });
// input value w/ decimal restrictions is passed along
// to this._separate without value restrictions
return valueWithDecimalRestrictions;
}
// enforces props.maxBeforeDot and props.maxAfterDot
_enforceDecimalRestrictions(data: {
value: string,
position: number,
parts: {
beforeDot: string,
afterDot: string
}
}) {
const { maxBeforeDot, maxAfterDot } = this.props;
let { beforeDot } = data.parts;
let { afterDot } = data.parts;
// preventing numbers with more than maxBeforeDot units
// - return first maxBeforeDot numbers (with comma separators)
if (maxBeforeDot && beforeDot) {
// max number of commas depending on max number of characters before dot
const numberOfCommas =
maxBeforeDot % 3 > 0
? parseInt(maxBeforeDot / 3, 10)
: parseInt(maxBeforeDot / 3, 10) - 1;
const maxBeforeDotWithSeparator = maxBeforeDot + numberOfCommas;
if (beforeDot.length > maxBeforeDotWithSeparator) {
beforeDot = beforeDot.substring(0, maxBeforeDotWithSeparator);
}
}
// remove commas from decimal part
// (e.g. 123,23,2.002000 -> dot after 2.character reproduce 12.3,23,2)
afterDot = afterDot.replace(/,/g, '');
// preventing numbers with more than maxAfterDot units - return first maxAfterDot numbers
if (maxAfterDot && afterDot && afterDot.length > maxAfterDot) {
afterDot = afterDot.substring(0, maxAfterDot);
}
// if decimal number has less than maxAfterDot numbers add trailing zeros
let afterDotLength = afterDot ? afterDot.length : 0;
if (maxAfterDot && afterDotLength < maxAfterDot) {
for (afterDotLength; afterDotLength < maxAfterDot; afterDotLength++) {
afterDot += '0';
}
}
// return input value w/decimal restrictions as a string
const result = beforeDot + '.' + afterDot;
return result;
}
_separate(value: string) {
this.setState({ oldValue: value });
if (value) {
const splitedValue = value.split('.');
const separatedValue = splitedValue[0]
.replace(/,/g, '')
.split('')
.reverse()
.join('')
.replace(/(\d{3}\B)/g, '$1,')
.split('')
.reverse()
.join('');
const newSeparatorsCount = (separatedValue.match(/,/g) || []).length;
this.setState({ separatorsCount: newSeparatorsCount });
return separatedValue + '.' + splitedValue[1];
}
}
_isNumeric(value: string) {
const replacedValue = value.replace(/,/g, '');
// eslint-disable-next-line no-restricted-globals
return !isNaN(parseFloat(replacedValue)) && isFinite(replacedValue);
}
render() {
// destructuring props ensures only the "...rest" get passed down
const {
skin: InputSkin,
theme,
themeOverrides,
onChange,
error,
context,
maxValue,
minValue,
maxBeforeDot,
maxAfterDot,
...rest
} = this.props;
return (
<InputSkin
error={error || this.state.error}
inputRef={this.inputElement}
onChange={this.onChange}
theme={this.state.composedTheme}
{...rest}
/>
);
}
}
export const NumericInput = withTheme(NumericInputBase);