@depup/react-number-format 5.4.4-depup.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1453 @@
1
+ /**
2
+ * react-number-format - 5.4.4
3
+ * Author : Sudhanshu Yadav
4
+ * Copyright (c) 2016, 2025 to Sudhanshu Yadav, released under the MIT license.
5
+ * https://github.com/s-yadav/react-number-format
6
+ */
7
+
8
+ (function (global, factory) {
9
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
10
+ typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
11
+ (global = global || self, factory(global.NumberFormat = {}, global.React));
12
+ }(this, (function (exports, React) { 'use strict';
13
+
14
+ var React__default = 'default' in React ? React['default'] : React;
15
+
16
+ /******************************************************************************
17
+ Copyright (c) Microsoft Corporation.
18
+
19
+ Permission to use, copy, modify, and/or distribute this software for any
20
+ purpose with or without fee is hereby granted.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
23
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
24
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
25
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
26
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
27
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
28
+ PERFORMANCE OF THIS SOFTWARE.
29
+ ***************************************************************************** */
30
+
31
+ function __rest(s, e) {
32
+ var t = {};
33
+ for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
34
+ { t[p] = s[p]; } }
35
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
36
+ { for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
37
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
38
+ { t[p[i]] = s[p[i]]; }
39
+ } }
40
+ return t;
41
+ }
42
+
43
+ var SourceType;
44
+ (function (SourceType) {
45
+ SourceType["event"] = "event";
46
+ SourceType["props"] = "prop";
47
+ })(SourceType || (SourceType = {}));
48
+
49
+ // basic noop function
50
+ function noop() { }
51
+ function memoizeOnce(cb) {
52
+ var lastArgs;
53
+ var lastValue = undefined;
54
+ return function () {
55
+ var args = [], len = arguments.length;
56
+ while ( len-- ) args[ len ] = arguments[ len ];
57
+
58
+ if (lastArgs &&
59
+ args.length === lastArgs.length &&
60
+ args.every(function (value, index) { return value === lastArgs[index]; })) {
61
+ return lastValue;
62
+ }
63
+ lastArgs = args;
64
+ lastValue = cb.apply(void 0, args);
65
+ return lastValue;
66
+ };
67
+ }
68
+ function charIsNumber(char) {
69
+ return !!(char || '').match(/\d/);
70
+ }
71
+ function isNil(val) {
72
+ return val === null || val === undefined;
73
+ }
74
+ function isNanValue(val) {
75
+ return typeof val === 'number' && isNaN(val);
76
+ }
77
+ function isNotValidValue(val) {
78
+ return isNil(val) || isNanValue(val) || (typeof val === 'number' && !isFinite(val));
79
+ }
80
+ function escapeRegExp(str) {
81
+ return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
82
+ }
83
+ function getThousandsGroupRegex(thousandsGroupStyle) {
84
+ switch (thousandsGroupStyle) {
85
+ case 'lakh':
86
+ return /(\d+?)(?=(\d\d)+(\d)(?!\d))(\.\d+)?/g;
87
+ case 'wan':
88
+ return /(\d)(?=(\d{4})+(?!\d))/g;
89
+ case 'thousand':
90
+ default:
91
+ return /(\d)(?=(\d{3})+(?!\d))/g;
92
+ }
93
+ }
94
+ function applyThousandSeparator(str, thousandSeparator, thousandsGroupStyle) {
95
+ var thousandsGroupRegex = getThousandsGroupRegex(thousandsGroupStyle);
96
+ var index = str.search(/[1-9]/);
97
+ index = index === -1 ? str.length : index;
98
+ return (str.substring(0, index) +
99
+ str.substring(index, str.length).replace(thousandsGroupRegex, '$1' + thousandSeparator));
100
+ }
101
+ function usePersistentCallback(cb) {
102
+ var callbackRef = React.useRef(cb);
103
+ // keep the callback ref upto date
104
+ callbackRef.current = cb;
105
+ /**
106
+ * initialize a persistent callback which never changes
107
+ * through out the component lifecycle
108
+ */
109
+ var persistentCbRef = React.useRef(function () {
110
+ var args = [], len = arguments.length;
111
+ while ( len-- ) args[ len ] = arguments[ len ];
112
+
113
+ return callbackRef.current.apply(callbackRef, args);
114
+ });
115
+ return persistentCbRef.current;
116
+ }
117
+ //spilt a float number into different parts beforeDecimal, afterDecimal, and negation
118
+ function splitDecimal(numStr, allowNegative) {
119
+ if ( allowNegative === void 0 ) allowNegative = true;
120
+
121
+ var hasNegation = numStr[0] === '-';
122
+ var addNegation = hasNegation && allowNegative;
123
+ numStr = numStr.replace('-', '');
124
+ var parts = numStr.split('.');
125
+ var beforeDecimal = parts[0];
126
+ var afterDecimal = parts[1] || '';
127
+ return {
128
+ beforeDecimal: beforeDecimal,
129
+ afterDecimal: afterDecimal,
130
+ hasNegation: hasNegation,
131
+ addNegation: addNegation,
132
+ };
133
+ }
134
+ function fixLeadingZero(numStr) {
135
+ if (!numStr)
136
+ { return numStr; }
137
+ var isNegative = numStr[0] === '-';
138
+ if (isNegative)
139
+ { numStr = numStr.substring(1, numStr.length); }
140
+ var parts = numStr.split('.');
141
+ var beforeDecimal = parts[0].replace(/^0+/, '') || '0';
142
+ var afterDecimal = parts[1] || '';
143
+ return ("" + (isNegative ? '-' : '') + beforeDecimal + (afterDecimal ? ("." + afterDecimal) : ''));
144
+ }
145
+ /**
146
+ * limit decimal numbers to given scale
147
+ * Not used .fixedTo because that will break with big numbers
148
+ */
149
+ function limitToScale(numStr, scale, fixedDecimalScale) {
150
+ var str = '';
151
+ var filler = fixedDecimalScale ? '0' : '';
152
+ for (var i = 0; i <= scale - 1; i++) {
153
+ str += numStr[i] || filler;
154
+ }
155
+ return str;
156
+ }
157
+ function repeat(str, count) {
158
+ return Array(count + 1).join(str);
159
+ }
160
+ function toNumericString(num) {
161
+ var _num = num + ''; // typecast number to string
162
+ // store the sign and remove it from the number.
163
+ var sign = _num[0] === '-' ? '-' : '';
164
+ if (sign)
165
+ { _num = _num.substring(1); }
166
+ // split the number into cofficient and exponent
167
+ var ref = _num.split(/[eE]/g);
168
+ var coefficient = ref[0];
169
+ var exponent = ref[1];
170
+ // covert exponent to number;
171
+ exponent = Number(exponent);
172
+ // if there is no exponent part or its 0, return the coffiecient with sign
173
+ if (!exponent)
174
+ { return sign + coefficient; }
175
+ coefficient = coefficient.replace('.', '');
176
+ /**
177
+ * for scientific notation the current decimal index will be after first number (index 0)
178
+ * So effective decimal index will always be 1 + exponent value
179
+ */
180
+ var decimalIndex = 1 + exponent;
181
+ var coffiecientLn = coefficient.length;
182
+ if (decimalIndex < 0) {
183
+ // if decimal index is less then 0 add preceding 0s
184
+ // add 1 as join will have
185
+ coefficient = '0.' + repeat('0', Math.abs(decimalIndex)) + coefficient;
186
+ }
187
+ else if (decimalIndex >= coffiecientLn) {
188
+ // if decimal index is less then 0 add leading 0s
189
+ coefficient = coefficient + repeat('0', decimalIndex - coffiecientLn);
190
+ }
191
+ else {
192
+ // else add decimal point at proper index
193
+ coefficient =
194
+ (coefficient.substring(0, decimalIndex) || '0') + '.' + coefficient.substring(decimalIndex);
195
+ }
196
+ return sign + coefficient;
197
+ }
198
+ /**
199
+ * This method is required to round prop value to given scale.
200
+ * Not used .round or .fixedTo because that will break with big numbers
201
+ */
202
+ function roundToPrecision(numStr, scale, fixedDecimalScale) {
203
+ //if number is empty don't do anything return empty string
204
+ if (['', '-'].indexOf(numStr) !== -1)
205
+ { return numStr; }
206
+ var shouldHaveDecimalSeparator = (numStr.indexOf('.') !== -1 || fixedDecimalScale) && scale;
207
+ var ref = splitDecimal(numStr);
208
+ var beforeDecimal = ref.beforeDecimal;
209
+ var afterDecimal = ref.afterDecimal;
210
+ var hasNegation = ref.hasNegation;
211
+ var floatValue = parseFloat(("0." + (afterDecimal || '0')));
212
+ var floatValueStr = afterDecimal.length <= scale ? ("0." + afterDecimal) : floatValue.toFixed(scale);
213
+ var roundedDecimalParts = floatValueStr.split('.');
214
+ var intPart = beforeDecimal;
215
+ // if we have cary over from rounding decimal part, add that on before decimal
216
+ if (beforeDecimal && Number(roundedDecimalParts[0])) {
217
+ intPart = beforeDecimal
218
+ .split('')
219
+ .reverse()
220
+ .reduce(function (roundedStr, current, idx) {
221
+ if (roundedStr.length > idx) {
222
+ return ((Number(roundedStr[0]) + Number(current)).toString() +
223
+ roundedStr.substring(1, roundedStr.length));
224
+ }
225
+ return current + roundedStr;
226
+ }, roundedDecimalParts[0]);
227
+ }
228
+ var decimalPart = limitToScale(roundedDecimalParts[1] || '', scale, fixedDecimalScale);
229
+ var negation = hasNegation ? '-' : '';
230
+ var decimalSeparator = shouldHaveDecimalSeparator ? '.' : '';
231
+ return ("" + negation + intPart + decimalSeparator + decimalPart);
232
+ }
233
+ /** set the caret positon in an input field **/
234
+ function setCaretPosition(el, caretPos) {
235
+ el.value = el.value;
236
+ // ^ this is used to not only get 'focus', but
237
+ // to make sure we don't have it everything -selected-
238
+ // (it causes an issue in chrome, and having it doesn't hurt any other browser)
239
+ if (el !== null) {
240
+ /* @ts-ignore */
241
+ if (el.createTextRange) {
242
+ /* @ts-ignore */
243
+ var range = el.createTextRange();
244
+ range.move('character', caretPos);
245
+ range.select();
246
+ return true;
247
+ }
248
+ // (el.selectionStart === 0 added for Firefox bug)
249
+ if (el.selectionStart || el.selectionStart === 0) {
250
+ el.focus();
251
+ el.setSelectionRange(caretPos, caretPos);
252
+ return true;
253
+ }
254
+ // fail city, fortunately this never happens (as far as I've tested) :)
255
+ el.focus();
256
+ return false;
257
+ }
258
+ }
259
+ /**
260
+ * TODO: remove dependency of findChangeRange, findChangedRangeFromCaretPositions is better way to find what is changed
261
+ * currently this is mostly required by test and isCharacterSame util
262
+ * Given previous value and newValue it returns the index
263
+ * start - end to which values have changed.
264
+ * This function makes assumption about only consecutive
265
+ * characters are changed which is correct assumption for caret input.
266
+ */
267
+ var findChangeRange = memoizeOnce(function (prevValue, newValue) {
268
+ var i = 0, j = 0;
269
+ var prevLength = prevValue.length;
270
+ var newLength = newValue.length;
271
+ while (prevValue[i] === newValue[i] && i < prevLength)
272
+ { i++; }
273
+ //check what has been changed from last
274
+ while (prevValue[prevLength - 1 - j] === newValue[newLength - 1 - j] &&
275
+ newLength - j > i &&
276
+ prevLength - j > i) {
277
+ j++;
278
+ }
279
+ return {
280
+ from: { start: i, end: prevLength - j },
281
+ to: { start: i, end: newLength - j },
282
+ };
283
+ });
284
+ var findChangedRangeFromCaretPositions = function (lastCaretPositions, currentCaretPosition) {
285
+ var startPosition = Math.min(lastCaretPositions.selectionStart, currentCaretPosition);
286
+ return {
287
+ from: { start: startPosition, end: lastCaretPositions.selectionEnd },
288
+ to: { start: startPosition, end: currentCaretPosition },
289
+ };
290
+ };
291
+ /*
292
+ Returns a number whose value is limited to the given range
293
+ */
294
+ function clamp(num, min, max) {
295
+ return Math.min(Math.max(num, min), max);
296
+ }
297
+ function geInputCaretPosition(el) {
298
+ /*Max of selectionStart and selectionEnd is taken for the patch of pixel and other mobile device caret bug*/
299
+ return Math.max(el.selectionStart, el.selectionEnd);
300
+ }
301
+ function addInputMode() {
302
+ return (typeof navigator !== 'undefined' &&
303
+ !(navigator.platform && /iPhone|iPod/.test(navigator.platform)));
304
+ }
305
+ function getDefaultChangeMeta(value) {
306
+ return {
307
+ from: {
308
+ start: 0,
309
+ end: 0,
310
+ },
311
+ to: {
312
+ start: 0,
313
+ end: value.length,
314
+ },
315
+ lastValue: '',
316
+ };
317
+ }
318
+ function getMaskAtIndex(mask, index) {
319
+ if ( mask === void 0 ) mask = ' ';
320
+
321
+ if (typeof mask === 'string') {
322
+ return mask;
323
+ }
324
+ return mask[index] || ' ';
325
+ }
326
+ function defaultIsCharacterSame(ref) {
327
+ var currentValue = ref.currentValue;
328
+ var formattedValue = ref.formattedValue;
329
+ var currentValueIndex = ref.currentValueIndex;
330
+ var formattedValueIndex = ref.formattedValueIndex;
331
+
332
+ return currentValue[currentValueIndex] === formattedValue[formattedValueIndex];
333
+ }
334
+ function getCaretPosition(newFormattedValue, lastFormattedValue, curValue, curCaretPos, boundary, isValidInputCharacter,
335
+ /**
336
+ * format function can change the character, the caret engine relies on mapping old value and new value
337
+ * In such case if character is changed, parent can tell which chars are equivalent
338
+ * Some example, all allowedDecimalCharacters are updated to decimalCharacters, 2nd case if user is coverting
339
+ * number to different numeric system.
340
+ */
341
+ isCharacterSame) {
342
+ if ( isCharacterSame === void 0 ) isCharacterSame = defaultIsCharacterSame;
343
+
344
+ /**
345
+ * if something got inserted on empty value, add the formatted character before the current value,
346
+ * This is to avoid the case where typed character is present on format characters
347
+ */
348
+ var firstAllowedPosition = boundary.findIndex(function (b) { return b; });
349
+ var prefixFormat = newFormattedValue.slice(0, firstAllowedPosition);
350
+ if (!lastFormattedValue && !curValue.startsWith(prefixFormat)) {
351
+ lastFormattedValue = prefixFormat;
352
+ curValue = prefixFormat + curValue;
353
+ curCaretPos = curCaretPos + prefixFormat.length;
354
+ }
355
+ var curValLn = curValue.length;
356
+ var formattedValueLn = newFormattedValue.length;
357
+ // create index map
358
+ var addedIndexMap = {};
359
+ var indexMap = new Array(curValLn);
360
+ for (var i = 0; i < curValLn; i++) {
361
+ indexMap[i] = -1;
362
+ for (var j = 0, jLn = formattedValueLn; j < jLn; j++) {
363
+ var isCharSame = isCharacterSame({
364
+ currentValue: curValue,
365
+ lastValue: lastFormattedValue,
366
+ formattedValue: newFormattedValue,
367
+ currentValueIndex: i,
368
+ formattedValueIndex: j,
369
+ });
370
+ if (isCharSame && addedIndexMap[j] !== true) {
371
+ indexMap[i] = j;
372
+ addedIndexMap[j] = true;
373
+ break;
374
+ }
375
+ }
376
+ }
377
+ /**
378
+ * For current caret position find closest characters (left and right side)
379
+ * which are properly mapped to formatted value.
380
+ * The idea is that the new caret position will exist always in the boundary of
381
+ * that mapped index
382
+ */
383
+ var pos = curCaretPos;
384
+ while (pos < curValLn && (indexMap[pos] === -1 || !isValidInputCharacter(curValue[pos]))) {
385
+ pos++;
386
+ }
387
+ // if the caret position is on last keep the endIndex as last for formatted value
388
+ var endIndex = pos === curValLn || indexMap[pos] === -1 ? formattedValueLn : indexMap[pos];
389
+ pos = curCaretPos - 1;
390
+ while (pos > 0 && indexMap[pos] === -1)
391
+ { pos--; }
392
+ var startIndex = pos === -1 || indexMap[pos] === -1 ? 0 : indexMap[pos] + 1;
393
+ /**
394
+ * case where a char is added on suffix and removed from middle, example 2sq345 becoming $2,345 sq
395
+ * there is still a mapping but the order of start index and end index is changed
396
+ */
397
+ if (startIndex > endIndex)
398
+ { return endIndex; }
399
+ /**
400
+ * given the current caret position if it closer to startIndex
401
+ * keep the new caret position on start index or keep it closer to endIndex
402
+ */
403
+ return curCaretPos - startIndex < endIndex - curCaretPos ? startIndex : endIndex;
404
+ }
405
+ /* This keeps the caret within typing area so people can't type in between prefix or suffix or format characters */
406
+ function getCaretPosInBoundary(value, caretPos, boundary, direction) {
407
+ var valLn = value.length;
408
+ // clamp caret position to [0, value.length]
409
+ caretPos = clamp(caretPos, 0, valLn);
410
+ if (direction === 'left') {
411
+ while (caretPos >= 0 && !boundary[caretPos])
412
+ { caretPos--; }
413
+ // if we don't find any suitable caret position on left, set it on first allowed position
414
+ if (caretPos === -1)
415
+ { caretPos = boundary.indexOf(true); }
416
+ }
417
+ else {
418
+ while (caretPos <= valLn && !boundary[caretPos])
419
+ { caretPos++; }
420
+ // if we don't find any suitable caret position on right, set it on last allowed position
421
+ if (caretPos > valLn)
422
+ { caretPos = boundary.lastIndexOf(true); }
423
+ }
424
+ // if we still don't find caret position, set it at the end of value
425
+ if (caretPos === -1)
426
+ { caretPos = valLn; }
427
+ return caretPos;
428
+ }
429
+ function caretUnknownFormatBoundary(formattedValue) {
430
+ var boundaryAry = Array.from({ length: formattedValue.length + 1 }).map(function () { return true; });
431
+ for (var i = 0, ln = boundaryAry.length; i < ln; i++) {
432
+ // consider caret to be in boundary if it is before or after numeric value
433
+ boundaryAry[i] = Boolean(charIsNumber(formattedValue[i]) || charIsNumber(formattedValue[i - 1]));
434
+ }
435
+ return boundaryAry;
436
+ }
437
+ function useInternalValues(value, defaultValue, valueIsNumericString, format, removeFormatting, onValueChange) {
438
+ if ( onValueChange === void 0 ) onValueChange = noop;
439
+
440
+ var getValues = usePersistentCallback(function (value, valueIsNumericString) {
441
+ var formattedValue, numAsString;
442
+ if (isNotValidValue(value)) {
443
+ numAsString = '';
444
+ formattedValue = '';
445
+ }
446
+ else if (typeof value === 'number' || valueIsNumericString) {
447
+ numAsString = typeof value === 'number' ? toNumericString(value) : value;
448
+ formattedValue = format(numAsString);
449
+ }
450
+ else {
451
+ numAsString = removeFormatting(value, undefined);
452
+ formattedValue = format(numAsString);
453
+ }
454
+ return { formattedValue: formattedValue, numAsString: numAsString };
455
+ });
456
+ var ref = React.useState(function () {
457
+ return getValues(isNil(value) ? defaultValue : value, valueIsNumericString);
458
+ });
459
+ var values = ref[0];
460
+ var setValues = ref[1];
461
+ var _onValueChange = function (newValues, sourceInfo) {
462
+ if (newValues.formattedValue !== values.formattedValue) {
463
+ setValues({
464
+ formattedValue: newValues.formattedValue,
465
+ numAsString: newValues.value,
466
+ });
467
+ }
468
+ // call parent on value change if only if formatted value is changed
469
+ onValueChange(newValues, sourceInfo);
470
+ };
471
+ // if value is switch from controlled to uncontrolled, use the internal state's value to format with new props
472
+ var _value = value;
473
+ var _valueIsNumericString = valueIsNumericString;
474
+ if (isNil(value)) {
475
+ _value = values.numAsString;
476
+ _valueIsNumericString = true;
477
+ }
478
+ var newValues = getValues(_value, _valueIsNumericString);
479
+ React.useMemo(function () {
480
+ setValues(newValues);
481
+ }, [newValues.formattedValue]);
482
+ return [values, _onValueChange];
483
+ }
484
+
485
+ function defaultRemoveFormatting(value) {
486
+ return value.replace(/[^0-9]/g, '');
487
+ }
488
+ function defaultFormat(value) {
489
+ return value;
490
+ }
491
+ function NumberFormatBase(props) {
492
+ var type = props.type; if ( type === void 0 ) type = 'text';
493
+ var displayType = props.displayType; if ( displayType === void 0 ) displayType = 'input';
494
+ var customInput = props.customInput;
495
+ var renderText = props.renderText;
496
+ var getInputRef = props.getInputRef;
497
+ var format = props.format; if ( format === void 0 ) format = defaultFormat;
498
+ var removeFormatting = props.removeFormatting; if ( removeFormatting === void 0 ) removeFormatting = defaultRemoveFormatting;
499
+ var defaultValue = props.defaultValue;
500
+ var valueIsNumericString = props.valueIsNumericString;
501
+ var onValueChange = props.onValueChange;
502
+ var isAllowed = props.isAllowed;
503
+ var onChange = props.onChange; if ( onChange === void 0 ) onChange = noop;
504
+ var onKeyDown = props.onKeyDown; if ( onKeyDown === void 0 ) onKeyDown = noop;
505
+ var onMouseUp = props.onMouseUp; if ( onMouseUp === void 0 ) onMouseUp = noop;
506
+ var onFocus = props.onFocus; if ( onFocus === void 0 ) onFocus = noop;
507
+ var onBlur = props.onBlur; if ( onBlur === void 0 ) onBlur = noop;
508
+ var propValue = props.value;
509
+ var getCaretBoundary = props.getCaretBoundary; if ( getCaretBoundary === void 0 ) getCaretBoundary = caretUnknownFormatBoundary;
510
+ var isValidInputCharacter = props.isValidInputCharacter; if ( isValidInputCharacter === void 0 ) isValidInputCharacter = charIsNumber;
511
+ var isCharacterSame = props.isCharacterSame;
512
+ var otherProps = __rest(props, ["type", "displayType", "customInput", "renderText", "getInputRef", "format", "removeFormatting", "defaultValue", "valueIsNumericString", "onValueChange", "isAllowed", "onChange", "onKeyDown", "onMouseUp", "onFocus", "onBlur", "value", "getCaretBoundary", "isValidInputCharacter", "isCharacterSame"]);
513
+ var ref = useInternalValues(propValue, defaultValue, Boolean(valueIsNumericString), format, removeFormatting, onValueChange);
514
+ var ref_0 = ref[0];
515
+ var formattedValue = ref_0.formattedValue;
516
+ var numAsString = ref_0.numAsString;
517
+ var onFormattedValueChange = ref[1];
518
+ var caretPositionBeforeChange = React.useRef();
519
+ var lastUpdatedValue = React.useRef({ formattedValue: formattedValue, numAsString: numAsString });
520
+ var _onValueChange = function (values, source) {
521
+ lastUpdatedValue.current = { formattedValue: values.formattedValue, numAsString: values.value };
522
+ onFormattedValueChange(values, source);
523
+ };
524
+ var ref$1 = React.useState(false);
525
+ var mounted = ref$1[0];
526
+ var setMounted = ref$1[1];
527
+ var focusedElm = React.useRef(null);
528
+ var timeout = React.useRef({
529
+ setCaretTimeout: null,
530
+ focusTimeout: null,
531
+ });
532
+ React.useEffect(function () {
533
+ setMounted(true);
534
+ return function () {
535
+ clearTimeout(timeout.current.setCaretTimeout);
536
+ clearTimeout(timeout.current.focusTimeout);
537
+ };
538
+ }, []);
539
+ var _format = format;
540
+ var getValueObject = function (formattedValue, numAsString) {
541
+ var floatValue = parseFloat(numAsString);
542
+ return {
543
+ formattedValue: formattedValue,
544
+ value: numAsString,
545
+ floatValue: isNaN(floatValue) ? undefined : floatValue,
546
+ };
547
+ };
548
+ var setPatchedCaretPosition = function (el, caretPos, currentValue) {
549
+ // don't reset the caret position when the whole input content is selected
550
+ if (el.selectionStart === 0 && el.selectionEnd === el.value.length)
551
+ { return; }
552
+ /* setting caret position within timeout of 0ms is required for mobile chrome,
553
+ otherwise browser resets the caret position after we set it
554
+ We are also setting it without timeout so that in normal browser we don't see the flickering */
555
+ setCaretPosition(el, caretPos);
556
+ timeout.current.setCaretTimeout = setTimeout(function () {
557
+ if (el.value === currentValue && el.selectionStart !== caretPos) {
558
+ setCaretPosition(el, caretPos);
559
+ }
560
+ }, 0);
561
+ };
562
+ /* This keeps the caret within typing area so people can't type in between prefix or suffix */
563
+ var correctCaretPosition = function (value, caretPos, direction) {
564
+ return getCaretPosInBoundary(value, caretPos, getCaretBoundary(value), direction);
565
+ };
566
+ var getNewCaretPosition = function (inputValue, newFormattedValue, caretPos) {
567
+ var caretBoundary = getCaretBoundary(newFormattedValue);
568
+ var updatedCaretPos = getCaretPosition(newFormattedValue, formattedValue, inputValue, caretPos, caretBoundary, isValidInputCharacter, isCharacterSame);
569
+ //correct caret position if its outside of editable area
570
+ updatedCaretPos = getCaretPosInBoundary(newFormattedValue, updatedCaretPos, caretBoundary);
571
+ return updatedCaretPos;
572
+ };
573
+ var updateValueAndCaretPosition = function (params) {
574
+ var newFormattedValue = params.formattedValue; if ( newFormattedValue === void 0 ) newFormattedValue = '';
575
+ var input = params.input;
576
+ var source = params.source;
577
+ var event = params.event;
578
+ var numAsString = params.numAsString;
579
+ var caretPos;
580
+ if (input) {
581
+ var inputValue = params.inputValue || input.value;
582
+ var currentCaretPosition = geInputCaretPosition(input);
583
+ /**
584
+ * set the value imperatively, this is required for IE fix
585
+ * This is also required as if new caret position is beyond the previous value.
586
+ * Caret position will not be set correctly
587
+ */
588
+ input.value = newFormattedValue;
589
+ //get the caret position
590
+ caretPos = getNewCaretPosition(inputValue, newFormattedValue, currentCaretPosition);
591
+ //set caret position imperatively
592
+ if (caretPos !== undefined) {
593
+ setPatchedCaretPosition(input, caretPos, newFormattedValue);
594
+ }
595
+ }
596
+ if (newFormattedValue !== formattedValue) {
597
+ // trigger onValueChange synchronously, so parent is updated along with the number format. Fix for #277, #287
598
+ _onValueChange(getValueObject(newFormattedValue, numAsString), { event: event, source: source });
599
+ }
600
+ };
601
+ /**
602
+ * if the formatted value is not synced to parent, or if the formatted value is different from last synced value sync it
603
+ * if the formatting props is removed, in which case last formatted value will be different from the numeric string value
604
+ * in such case we need to inform the parent.
605
+ */
606
+ React.useEffect(function () {
607
+ var ref = lastUpdatedValue.current;
608
+ var lastFormattedValue = ref.formattedValue;
609
+ var lastNumAsString = ref.numAsString;
610
+ if (formattedValue !== lastFormattedValue || numAsString !== lastNumAsString) {
611
+ _onValueChange(getValueObject(formattedValue, numAsString), {
612
+ event: undefined,
613
+ source: SourceType.props,
614
+ });
615
+ }
616
+ }, [formattedValue, numAsString]);
617
+ // also if formatted value is changed from the props, we need to update the caret position
618
+ // keep the last caret position if element is focused
619
+ var currentCaretPosition = focusedElm.current
620
+ ? geInputCaretPosition(focusedElm.current)
621
+ : undefined;
622
+ // needed to prevent warning with useLayoutEffect on server
623
+ var useIsomorphicLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
624
+ useIsomorphicLayoutEffect(function () {
625
+ var input = focusedElm.current;
626
+ if (formattedValue !== lastUpdatedValue.current.formattedValue && input) {
627
+ var caretPos = getNewCaretPosition(lastUpdatedValue.current.formattedValue, formattedValue, currentCaretPosition);
628
+ /**
629
+ * set the value imperatively, as we set the caret position as well imperatively.
630
+ * This is to keep value and caret position in sync
631
+ */
632
+ input.value = formattedValue;
633
+ setPatchedCaretPosition(input, caretPos, formattedValue);
634
+ }
635
+ }, [formattedValue]);
636
+ var formatInputValue = function (inputValue, event, source) {
637
+ var input = event.target;
638
+ var changeRange = caretPositionBeforeChange.current
639
+ ? findChangedRangeFromCaretPositions(caretPositionBeforeChange.current, input.selectionEnd)
640
+ : findChangeRange(formattedValue, inputValue);
641
+ var changeMeta = Object.assign(Object.assign({}, changeRange), { lastValue: formattedValue });
642
+ var _numAsString = removeFormatting(inputValue, changeMeta);
643
+ var _formattedValue = _format(_numAsString);
644
+ // formatting can remove some of the number chars, so we need to fine number string again
645
+ _numAsString = removeFormatting(_formattedValue, undefined);
646
+ if (isAllowed && !isAllowed(getValueObject(_formattedValue, _numAsString))) {
647
+ //reset the caret position
648
+ var input$1 = event.target;
649
+ var currentCaretPosition = geInputCaretPosition(input$1);
650
+ var caretPos = getNewCaretPosition(inputValue, formattedValue, currentCaretPosition);
651
+ input$1.value = formattedValue;
652
+ setPatchedCaretPosition(input$1, caretPos, formattedValue);
653
+ return false;
654
+ }
655
+ updateValueAndCaretPosition({
656
+ formattedValue: _formattedValue,
657
+ numAsString: _numAsString,
658
+ inputValue: inputValue,
659
+ event: event,
660
+ source: source,
661
+ input: event.target,
662
+ });
663
+ return true;
664
+ };
665
+ var setCaretPositionInfoBeforeChange = function (el, endOffset) {
666
+ if ( endOffset === void 0 ) endOffset = 0;
667
+
668
+ var selectionStart = el.selectionStart;
669
+ var selectionEnd = el.selectionEnd;
670
+ caretPositionBeforeChange.current = { selectionStart: selectionStart, selectionEnd: selectionEnd + endOffset };
671
+ };
672
+ var _onChange = function (e) {
673
+ var el = e.target;
674
+ var inputValue = el.value;
675
+ var changed = formatInputValue(inputValue, e, SourceType.event);
676
+ if (changed)
677
+ { onChange(e); }
678
+ // reset the position, as we have already handled the caret position
679
+ caretPositionBeforeChange.current = undefined;
680
+ };
681
+ var _onKeyDown = function (e) {
682
+ var el = e.target;
683
+ var key = e.key;
684
+ var selectionStart = el.selectionStart;
685
+ var selectionEnd = el.selectionEnd;
686
+ var value = el.value; if ( value === void 0 ) value = '';
687
+ var expectedCaretPosition;
688
+ //Handle backspace and delete against non numerical/decimal characters or arrow keys
689
+ if (key === 'ArrowLeft' || key === 'Backspace') {
690
+ expectedCaretPosition = Math.max(selectionStart - 1, 0);
691
+ }
692
+ else if (key === 'ArrowRight') {
693
+ expectedCaretPosition = Math.min(selectionStart + 1, value.length);
694
+ }
695
+ else if (key === 'Delete') {
696
+ expectedCaretPosition = selectionStart;
697
+ }
698
+ // if key is delete and text is not selected keep the end offset to 1, as it deletes one character
699
+ // this is required as selection is not changed on delete case, which changes the change range calculation
700
+ var endOffset = 0;
701
+ if (key === 'Delete' && selectionStart === selectionEnd) {
702
+ endOffset = 1;
703
+ }
704
+ var isArrowKey = key === 'ArrowLeft' || key === 'ArrowRight';
705
+ //if expectedCaretPosition is not set it means we don't want to Handle keyDown
706
+ // also if multiple characters are selected don't handle
707
+ if (expectedCaretPosition === undefined || (selectionStart !== selectionEnd && !isArrowKey)) {
708
+ onKeyDown(e);
709
+ // keep information of what was the caret position before keyDown
710
+ // set it after onKeyDown, in case parent updates the position manually
711
+ setCaretPositionInfoBeforeChange(el, endOffset);
712
+ return;
713
+ }
714
+ var newCaretPosition = expectedCaretPosition;
715
+ if (isArrowKey) {
716
+ var direction = key === 'ArrowLeft' ? 'left' : 'right';
717
+ newCaretPosition = correctCaretPosition(value, expectedCaretPosition, direction);
718
+ // arrow left or right only moves the caret, so no need to handle the event, if we are handling it manually
719
+ if (newCaretPosition !== expectedCaretPosition) {
720
+ e.preventDefault();
721
+ }
722
+ }
723
+ else if (key === 'Delete' && !isValidInputCharacter(value[expectedCaretPosition])) {
724
+ // in case of delete go to closest caret boundary on the right side
725
+ newCaretPosition = correctCaretPosition(value, expectedCaretPosition, 'right');
726
+ }
727
+ else if (key === 'Backspace' && !isValidInputCharacter(value[expectedCaretPosition])) {
728
+ // in case of backspace go to closest caret boundary on the left side
729
+ newCaretPosition = correctCaretPosition(value, expectedCaretPosition, 'left');
730
+ }
731
+ if (newCaretPosition !== expectedCaretPosition) {
732
+ setPatchedCaretPosition(el, newCaretPosition, value);
733
+ }
734
+ onKeyDown(e);
735
+ setCaretPositionInfoBeforeChange(el, endOffset);
736
+ };
737
+ /** required to handle the caret position when click anywhere within the input **/
738
+ var _onMouseUp = function (e) {
739
+ var el = e.target;
740
+ /**
741
+ * NOTE: we have to give default value for value as in case when custom input is provided
742
+ * value can come as undefined when nothing is provided on value prop.
743
+ */
744
+ var correctCaretPositionIfRequired = function () {
745
+ var selectionStart = el.selectionStart;
746
+ var selectionEnd = el.selectionEnd;
747
+ var value = el.value; if ( value === void 0 ) value = '';
748
+ if (selectionStart === selectionEnd) {
749
+ var caretPosition = correctCaretPosition(value, selectionStart);
750
+ if (caretPosition !== selectionStart) {
751
+ setPatchedCaretPosition(el, caretPosition, value);
752
+ }
753
+ }
754
+ };
755
+ correctCaretPositionIfRequired();
756
+ // try to correct after selection has updated by browser
757
+ // this case is required when user clicks on some position while a text is selected on input
758
+ requestAnimationFrame(function () {
759
+ correctCaretPositionIfRequired();
760
+ });
761
+ onMouseUp(e);
762
+ setCaretPositionInfoBeforeChange(el);
763
+ };
764
+ var _onFocus = function (e) {
765
+ // Workaround Chrome and Safari bug https://bugs.chromium.org/p/chromium/issues/detail?id=779328
766
+ // (onFocus event target selectionStart is always 0 before setTimeout)
767
+ if (e.persist)
768
+ { e.persist(); }
769
+ var el = e.target;
770
+ var currentTarget = e.currentTarget;
771
+ focusedElm.current = el;
772
+ timeout.current.focusTimeout = setTimeout(function () {
773
+ var selectionStart = el.selectionStart;
774
+ var selectionEnd = el.selectionEnd;
775
+ var value = el.value; if ( value === void 0 ) value = '';
776
+ var caretPosition = correctCaretPosition(value, selectionStart);
777
+ //setPatchedCaretPosition only when everything is not selected on focus (while tabbing into the field)
778
+ if (caretPosition !== selectionStart &&
779
+ !(selectionStart === 0 && selectionEnd === value.length)) {
780
+ setPatchedCaretPosition(el, caretPosition, value);
781
+ }
782
+ onFocus(Object.assign(Object.assign({}, e), { currentTarget: currentTarget }));
783
+ }, 0);
784
+ };
785
+ var _onBlur = function (e) {
786
+ focusedElm.current = null;
787
+ clearTimeout(timeout.current.focusTimeout);
788
+ clearTimeout(timeout.current.setCaretTimeout);
789
+ onBlur(e);
790
+ };
791
+ // add input mode on element based on format prop and device once the component is mounted
792
+ var inputMode = mounted && addInputMode() ? 'numeric' : undefined;
793
+ var inputProps = Object.assign({ inputMode: inputMode }, otherProps, {
794
+ type: type,
795
+ value: formattedValue,
796
+ onChange: _onChange,
797
+ onKeyDown: _onKeyDown,
798
+ onMouseUp: _onMouseUp,
799
+ onFocus: _onFocus,
800
+ onBlur: _onBlur,
801
+ });
802
+ if (displayType === 'text') {
803
+ return renderText ? (React__default.createElement(React__default.Fragment, null, renderText(formattedValue, otherProps) || null)) : (React__default.createElement("span", Object.assign({}, otherProps, { ref: getInputRef }), formattedValue));
804
+ }
805
+ else if (customInput) {
806
+ var CustomInput = customInput;
807
+ /* @ts-ignore */
808
+ return React__default.createElement(CustomInput, Object.assign({}, inputProps, { ref: getInputRef }));
809
+ }
810
+ return React__default.createElement("input", Object.assign({}, inputProps, { ref: getInputRef }));
811
+ }
812
+
813
+ function format(numStr, props) {
814
+ var decimalScale = props.decimalScale;
815
+ var fixedDecimalScale = props.fixedDecimalScale;
816
+ var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';
817
+ var suffix = props.suffix; if ( suffix === void 0 ) suffix = '';
818
+ var allowNegative = props.allowNegative;
819
+ var thousandsGroupStyle = props.thousandsGroupStyle; if ( thousandsGroupStyle === void 0 ) thousandsGroupStyle = 'thousand';
820
+ // don't apply formatting on empty string or '-'
821
+ if (numStr === '' || numStr === '-') {
822
+ return numStr;
823
+ }
824
+ var ref = getSeparators(props);
825
+ var thousandSeparator = ref.thousandSeparator;
826
+ var decimalSeparator = ref.decimalSeparator;
827
+ /**
828
+ * Keep the decimal separator
829
+ * when decimalScale is not defined or non zero and the numStr has decimal in it
830
+ * Or if decimalScale is > 0 and fixeDecimalScale is true (even if numStr has no decimal)
831
+ */
832
+ var hasDecimalSeparator = (decimalScale !== 0 && numStr.indexOf('.') !== -1) || (decimalScale && fixedDecimalScale);
833
+ var ref$1 = splitDecimal(numStr, allowNegative);
834
+ var beforeDecimal = ref$1.beforeDecimal;
835
+ var afterDecimal = ref$1.afterDecimal;
836
+ var addNegation = ref$1.addNegation; // eslint-disable-line prefer-const
837
+ //apply decimal precision if its defined
838
+ if (decimalScale !== undefined) {
839
+ afterDecimal = limitToScale(afterDecimal, decimalScale, !!fixedDecimalScale);
840
+ }
841
+ if (thousandSeparator) {
842
+ beforeDecimal = applyThousandSeparator(beforeDecimal, thousandSeparator, thousandsGroupStyle);
843
+ }
844
+ //add prefix and suffix when there is a number present
845
+ if (prefix)
846
+ { beforeDecimal = prefix + beforeDecimal; }
847
+ if (suffix)
848
+ { afterDecimal = afterDecimal + suffix; }
849
+ //restore negation sign
850
+ if (addNegation)
851
+ { beforeDecimal = '-' + beforeDecimal; }
852
+ numStr = beforeDecimal + ((hasDecimalSeparator && decimalSeparator) || '') + afterDecimal;
853
+ return numStr;
854
+ }
855
+ function getSeparators(props) {
856
+ var decimalSeparator = props.decimalSeparator; if ( decimalSeparator === void 0 ) decimalSeparator = '.';
857
+ var thousandSeparator = props.thousandSeparator;
858
+ var allowedDecimalSeparators = props.allowedDecimalSeparators;
859
+ if (thousandSeparator === true) {
860
+ thousandSeparator = ',';
861
+ }
862
+ if (!allowedDecimalSeparators) {
863
+ allowedDecimalSeparators = [decimalSeparator, '.'];
864
+ }
865
+ return {
866
+ decimalSeparator: decimalSeparator,
867
+ thousandSeparator: thousandSeparator,
868
+ allowedDecimalSeparators: allowedDecimalSeparators,
869
+ };
870
+ }
871
+ function handleNegation(value, allowNegative) {
872
+ if ( value === void 0 ) value = '';
873
+
874
+ var negationRegex = new RegExp('(-)');
875
+ var doubleNegationRegex = new RegExp('(-)(.)*(-)');
876
+ // Check number has '-' value
877
+ var hasNegation = negationRegex.test(value);
878
+ // Check number has 2 or more '-' values
879
+ var removeNegation = doubleNegationRegex.test(value);
880
+ //remove negation
881
+ value = value.replace(/-/g, '');
882
+ if (hasNegation && !removeNegation && allowNegative) {
883
+ value = '-' + value;
884
+ }
885
+ return value;
886
+ }
887
+ function getNumberRegex(decimalSeparator, global) {
888
+ return new RegExp(("(^-)|[0-9]|" + (escapeRegExp(decimalSeparator))), global ? 'g' : undefined);
889
+ }
890
+ function isNumericString(val, prefix, suffix) {
891
+ // for empty value we can always treat it as numeric string
892
+ if (val === '')
893
+ { return true; }
894
+ return (!(prefix === null || prefix === void 0 ? void 0 : prefix.match(/\d/)) && !(suffix === null || suffix === void 0 ? void 0 : suffix.match(/\d/)) && typeof val === 'string' && !isNaN(Number(val)));
895
+ }
896
+ function removeFormatting(value, changeMeta, props) {
897
+ var assign;
898
+
899
+ if ( changeMeta === void 0 ) changeMeta = getDefaultChangeMeta(value);
900
+ var allowNegative = props.allowNegative;
901
+ var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';
902
+ var suffix = props.suffix; if ( suffix === void 0 ) suffix = '';
903
+ var decimalScale = props.decimalScale;
904
+ var from = changeMeta.from;
905
+ var to = changeMeta.to;
906
+ var start = to.start;
907
+ var end = to.end;
908
+ var ref = getSeparators(props);
909
+ var allowedDecimalSeparators = ref.allowedDecimalSeparators;
910
+ var decimalSeparator = ref.decimalSeparator;
911
+ var isBeforeDecimalSeparator = value[end] === decimalSeparator;
912
+ /**
913
+ * If only a number is added on empty input which matches with the prefix or suffix,
914
+ * then don't remove it, just return the same
915
+ */
916
+ if (charIsNumber(value) &&
917
+ (value === prefix || value === suffix) &&
918
+ changeMeta.lastValue === '') {
919
+ return value;
920
+ }
921
+ /** Check for any allowed decimal separator is added in the numeric format and replace it with decimal separator */
922
+ if (end - start === 1 && allowedDecimalSeparators.indexOf(value[start]) !== -1) {
923
+ var separator = decimalScale === 0 ? '' : decimalSeparator;
924
+ value = value.substring(0, start) + separator + value.substring(start + 1, value.length);
925
+ }
926
+ var stripNegation = function (value, start, end) {
927
+ /**
928
+ * if prefix starts with - we don't allow negative number to avoid confusion
929
+ * if suffix starts with - and the value length is same as suffix length, then the - sign is from the suffix
930
+ * In other cases, if the value starts with - then it is a negation
931
+ */
932
+ var hasNegation = false;
933
+ var hasDoubleNegation = false;
934
+ if (prefix.startsWith('-')) {
935
+ hasNegation = false;
936
+ }
937
+ else if (value.startsWith('--')) {
938
+ hasNegation = false;
939
+ hasDoubleNegation = true;
940
+ }
941
+ else if (suffix.startsWith('-') && value.length === suffix.length) {
942
+ hasNegation = false;
943
+ }
944
+ else if (value[0] === '-') {
945
+ hasNegation = true;
946
+ }
947
+ var charsToRemove = hasNegation ? 1 : 0;
948
+ if (hasDoubleNegation)
949
+ { charsToRemove = 2; }
950
+ // remove negation/double negation from start to simplify prefix logic as negation comes before prefix
951
+ if (charsToRemove) {
952
+ value = value.substring(charsToRemove);
953
+ // account for the removal of the negation for start and end index
954
+ start -= charsToRemove;
955
+ end -= charsToRemove;
956
+ }
957
+ return { value: value, start: start, end: end, hasNegation: hasNegation };
958
+ };
959
+ var toMetadata = stripNegation(value, start, end);
960
+ var hasNegation = toMetadata.hasNegation;
961
+ ((assign = toMetadata, value = assign.value, start = assign.start, end = assign.end));
962
+ var ref$1 = stripNegation(changeMeta.lastValue, from.start, from.end);
963
+ var fromStart = ref$1.start;
964
+ var fromEnd = ref$1.end;
965
+ var lastValue = ref$1.value;
966
+ // if only prefix and suffix part is updated reset the value to last value
967
+ // if the changed range is from suffix in the updated value, and the the suffix starts with the same characters, allow the change
968
+ var updatedSuffixPart = value.substring(start, end);
969
+ if (value.length &&
970
+ lastValue.length &&
971
+ (fromStart > lastValue.length - suffix.length || fromEnd < prefix.length) &&
972
+ !(updatedSuffixPart && suffix.startsWith(updatedSuffixPart))) {
973
+ value = lastValue;
974
+ }
975
+ /**
976
+ * remove prefix
977
+ * Remove whole prefix part if its present on the value
978
+ * If the prefix is partially deleted (in which case change start index will be less the prefix length)
979
+ * Remove only partial part of prefix.
980
+ */
981
+ var startIndex = 0;
982
+ if (value.startsWith(prefix))
983
+ { startIndex += prefix.length; }
984
+ else if (start < prefix.length)
985
+ { startIndex = start; }
986
+ value = value.substring(startIndex);
987
+ // account for deleted prefix for end
988
+ end -= startIndex;
989
+ /**
990
+ * Remove suffix
991
+ * Remove whole suffix part if its present on the value
992
+ * If the suffix is partially deleted (in which case change end index will be greater than the suffixStartIndex)
993
+ * remove the partial part of suffix
994
+ */
995
+ var endIndex = value.length;
996
+ var suffixStartIndex = value.length - suffix.length;
997
+ if (value.endsWith(suffix))
998
+ { endIndex = suffixStartIndex; }
999
+ // if the suffix is removed from the end
1000
+ else if (end > suffixStartIndex)
1001
+ { endIndex = end; }
1002
+ // if the suffix is removed from start
1003
+ else if (end > value.length - suffix.length)
1004
+ { endIndex = end; }
1005
+ value = value.substring(0, endIndex);
1006
+ // add the negation back and handle for double negation
1007
+ value = handleNegation(hasNegation ? ("-" + value) : value, allowNegative);
1008
+ // remove non numeric characters
1009
+ value = (value.match(getNumberRegex(decimalSeparator, true)) || []).join('');
1010
+ // replace the decimalSeparator with ., and only keep the first separator, ignore following ones
1011
+ var firstIndex = value.indexOf(decimalSeparator);
1012
+ value = value.replace(new RegExp(escapeRegExp(decimalSeparator), 'g'), function (match, index) {
1013
+ return index === firstIndex ? '.' : '';
1014
+ });
1015
+ //check if beforeDecimal got deleted and there is nothing after decimal,
1016
+ //clear all numbers in such case while keeping the - sign
1017
+ var ref$2 = splitDecimal(value, allowNegative);
1018
+ var beforeDecimal = ref$2.beforeDecimal;
1019
+ var afterDecimal = ref$2.afterDecimal;
1020
+ var addNegation = ref$2.addNegation; // eslint-disable-line prefer-const
1021
+ //clear only if something got deleted before decimal (cursor is before decimal)
1022
+ if (to.end - to.start < from.end - from.start &&
1023
+ beforeDecimal === '' &&
1024
+ isBeforeDecimalSeparator &&
1025
+ !parseFloat(afterDecimal)) {
1026
+ value = addNegation ? '-' : '';
1027
+ }
1028
+ return value;
1029
+ }
1030
+ function getCaretBoundary(formattedValue, props) {
1031
+ var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';
1032
+ var suffix = props.suffix; if ( suffix === void 0 ) suffix = '';
1033
+ var boundaryAry = Array.from({ length: formattedValue.length + 1 }).map(function () { return true; });
1034
+ var hasNegation = formattedValue[0] === '-';
1035
+ // fill for prefix and negation
1036
+ boundaryAry.fill(false, 0, prefix.length + (hasNegation ? 1 : 0));
1037
+ // fill for suffix
1038
+ var valLn = formattedValue.length;
1039
+ boundaryAry.fill(false, valLn - suffix.length + 1, valLn + 1);
1040
+ return boundaryAry;
1041
+ }
1042
+ function validateAndUpdateProps(props) {
1043
+ var ref = getSeparators(props);
1044
+ var thousandSeparator = ref.thousandSeparator;
1045
+ var decimalSeparator = ref.decimalSeparator;
1046
+ // eslint-disable-next-line prefer-const
1047
+ var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';
1048
+ var allowNegative = props.allowNegative; if ( allowNegative === void 0 ) allowNegative = true;
1049
+ if (thousandSeparator === decimalSeparator) {
1050
+ throw new Error(("\n Decimal separator can't be same as thousand separator.\n thousandSeparator: " + thousandSeparator + " (thousandSeparator = {true} is same as thousandSeparator = \",\")\n decimalSeparator: " + decimalSeparator + " (default value for decimalSeparator is .)\n "));
1051
+ }
1052
+ if (prefix.startsWith('-') && allowNegative) {
1053
+ // TODO: throw error in next major version
1054
+ console.error(("\n Prefix can't start with '-' when allowNegative is true.\n prefix: " + prefix + "\n allowNegative: " + allowNegative + "\n "));
1055
+ allowNegative = false;
1056
+ }
1057
+ return Object.assign(Object.assign({}, props), { allowNegative: allowNegative });
1058
+ }
1059
+ function useNumericFormat(props) {
1060
+ // validate props
1061
+ props = validateAndUpdateProps(props);
1062
+ var _decimalSeparator = props.decimalSeparator;
1063
+ var _allowedDecimalSeparators = props.allowedDecimalSeparators;
1064
+ var thousandsGroupStyle = props.thousandsGroupStyle;
1065
+ var suffix = props.suffix;
1066
+ var allowNegative = props.allowNegative;
1067
+ var allowLeadingZeros = props.allowLeadingZeros;
1068
+ var onKeyDown = props.onKeyDown; if ( onKeyDown === void 0 ) onKeyDown = noop;
1069
+ var onBlur = props.onBlur; if ( onBlur === void 0 ) onBlur = noop;
1070
+ var thousandSeparator = props.thousandSeparator;
1071
+ var decimalScale = props.decimalScale;
1072
+ var fixedDecimalScale = props.fixedDecimalScale;
1073
+ var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';
1074
+ var defaultValue = props.defaultValue;
1075
+ var value = props.value;
1076
+ var valueIsNumericString = props.valueIsNumericString;
1077
+ var onValueChange = props.onValueChange;
1078
+ var restProps = __rest(props, ["decimalSeparator", "allowedDecimalSeparators", "thousandsGroupStyle", "suffix", "allowNegative", "allowLeadingZeros", "onKeyDown", "onBlur", "thousandSeparator", "decimalScale", "fixedDecimalScale", "prefix", "defaultValue", "value", "valueIsNumericString", "onValueChange"]);
1079
+ // get derived decimalSeparator and allowedDecimalSeparators
1080
+ var ref = getSeparators(props);
1081
+ var decimalSeparator = ref.decimalSeparator;
1082
+ var allowedDecimalSeparators = ref.allowedDecimalSeparators;
1083
+ var _format = function (numStr) { return format(numStr, props); };
1084
+ var _removeFormatting = function (inputValue, changeMeta) { return removeFormatting(inputValue, changeMeta, props); };
1085
+ var _value = isNil(value) ? defaultValue : value;
1086
+ // try to figure out isValueNumericString based on format prop and value
1087
+ var _valueIsNumericString = valueIsNumericString !== null && valueIsNumericString !== void 0 ? valueIsNumericString : isNumericString(_value, prefix, suffix);
1088
+ if (!isNil(value)) {
1089
+ _valueIsNumericString = _valueIsNumericString || typeof value === 'number';
1090
+ }
1091
+ else if (!isNil(defaultValue)) {
1092
+ _valueIsNumericString = _valueIsNumericString || typeof defaultValue === 'number';
1093
+ }
1094
+ var roundIncomingValueToPrecision = function (value) {
1095
+ if (isNotValidValue(value))
1096
+ { return value; }
1097
+ if (typeof value === 'number') {
1098
+ value = toNumericString(value);
1099
+ }
1100
+ /**
1101
+ * only round numeric or float string values coming through props,
1102
+ * we don't need to do it for onChange events, as we want to prevent typing there
1103
+ */
1104
+ if (_valueIsNumericString && typeof decimalScale === 'number') {
1105
+ return roundToPrecision(value, decimalScale, Boolean(fixedDecimalScale));
1106
+ }
1107
+ return value;
1108
+ };
1109
+ var ref$1 = useInternalValues(roundIncomingValueToPrecision(value), roundIncomingValueToPrecision(defaultValue), Boolean(_valueIsNumericString), _format, _removeFormatting, onValueChange);
1110
+ var ref$1_0 = ref$1[0];
1111
+ var numAsString = ref$1_0.numAsString;
1112
+ var formattedValue = ref$1_0.formattedValue;
1113
+ var _onValueChange = ref$1[1];
1114
+ var _onKeyDown = function (e) {
1115
+ var el = e.target;
1116
+ var key = e.key;
1117
+ var selectionStart = el.selectionStart;
1118
+ var selectionEnd = el.selectionEnd;
1119
+ var value = el.value; if ( value === void 0 ) value = '';
1120
+ // if user tries to delete partial prefix then ignore it
1121
+ if ((key === 'Backspace' || key === 'Delete') && selectionEnd < prefix.length) {
1122
+ e.preventDefault();
1123
+ return;
1124
+ }
1125
+ // if multiple characters are selected and user hits backspace, no need to handle anything manually
1126
+ if (selectionStart !== selectionEnd) {
1127
+ onKeyDown(e);
1128
+ return;
1129
+ }
1130
+ // if user hits backspace, while the cursor is before prefix, and the input has negation, remove the negation
1131
+ if (key === 'Backspace' &&
1132
+ value[0] === '-' &&
1133
+ selectionStart === prefix.length + 1 &&
1134
+ allowNegative) {
1135
+ // bring the cursor to after negation
1136
+ setCaretPosition(el, 1);
1137
+ }
1138
+ // don't allow user to delete decimal separator when decimalScale and fixedDecimalScale is set
1139
+ if (decimalScale && fixedDecimalScale) {
1140
+ if (key === 'Backspace' && value[selectionStart - 1] === decimalSeparator) {
1141
+ setCaretPosition(el, selectionStart - 1);
1142
+ e.preventDefault();
1143
+ }
1144
+ else if (key === 'Delete' && value[selectionStart] === decimalSeparator) {
1145
+ e.preventDefault();
1146
+ }
1147
+ }
1148
+ // if user presses the allowed decimal separator before the separator, move the cursor after the separator
1149
+ if ((allowedDecimalSeparators === null || allowedDecimalSeparators === void 0 ? void 0 : allowedDecimalSeparators.includes(key)) && value[selectionStart] === decimalSeparator) {
1150
+ setCaretPosition(el, selectionStart + 1);
1151
+ }
1152
+ var _thousandSeparator = thousandSeparator === true ? ',' : thousandSeparator;
1153
+ // move cursor when delete or backspace is pressed before/after thousand separator
1154
+ if (key === 'Backspace' && value[selectionStart - 1] === _thousandSeparator) {
1155
+ setCaretPosition(el, selectionStart - 1);
1156
+ }
1157
+ if (key === 'Delete' && value[selectionStart] === _thousandSeparator) {
1158
+ setCaretPosition(el, selectionStart + 1);
1159
+ }
1160
+ onKeyDown(e);
1161
+ };
1162
+ var _onBlur = function (e) {
1163
+ var _value = numAsString;
1164
+ // if there no no numeric value, clear the input
1165
+ if (!_value.match(/\d/g)) {
1166
+ _value = '';
1167
+ }
1168
+ // clear leading 0s
1169
+ if (!allowLeadingZeros) {
1170
+ _value = fixLeadingZero(_value);
1171
+ }
1172
+ // apply fixedDecimalScale on blur event
1173
+ if (fixedDecimalScale && decimalScale) {
1174
+ _value = roundToPrecision(_value, decimalScale, fixedDecimalScale);
1175
+ }
1176
+ if (_value !== numAsString) {
1177
+ var formattedValue = format(_value, props);
1178
+ _onValueChange({
1179
+ formattedValue: formattedValue,
1180
+ value: _value,
1181
+ floatValue: parseFloat(_value),
1182
+ }, {
1183
+ event: e,
1184
+ source: SourceType.event,
1185
+ });
1186
+ }
1187
+ onBlur(e);
1188
+ };
1189
+ var isValidInputCharacter = function (inputChar) {
1190
+ if (inputChar === decimalSeparator)
1191
+ { return true; }
1192
+ return charIsNumber(inputChar);
1193
+ };
1194
+ var isCharacterSame = function (ref) {
1195
+ var currentValue = ref.currentValue;
1196
+ var lastValue = ref.lastValue;
1197
+ var formattedValue = ref.formattedValue;
1198
+ var currentValueIndex = ref.currentValueIndex;
1199
+ var formattedValueIndex = ref.formattedValueIndex;
1200
+
1201
+ var curChar = currentValue[currentValueIndex];
1202
+ var newChar = formattedValue[formattedValueIndex];
1203
+ /**
1204
+ * NOTE: as thousand separator and allowedDecimalSeparators can be same, we need to check on
1205
+ * typed range if we have typed any character from allowedDecimalSeparators, in that case we
1206
+ * consider different characters like , and . same within the range of updated value.
1207
+ */
1208
+ var typedRange = findChangeRange(lastValue, currentValue);
1209
+ var to = typedRange.to;
1210
+ // handle corner case where if we user types a decimal separator with fixedDecimalScale
1211
+ // and pass back float value the cursor jumps. #851
1212
+ var getDecimalSeparatorIndex = function (value) {
1213
+ return _removeFormatting(value).indexOf('.') + prefix.length;
1214
+ };
1215
+ if (value === 0 &&
1216
+ fixedDecimalScale &&
1217
+ decimalScale &&
1218
+ currentValue[to.start] === decimalSeparator &&
1219
+ getDecimalSeparatorIndex(currentValue) < currentValueIndex &&
1220
+ getDecimalSeparatorIndex(formattedValue) > formattedValueIndex) {
1221
+ return false;
1222
+ }
1223
+ if (currentValueIndex >= to.start &&
1224
+ currentValueIndex < to.end &&
1225
+ allowedDecimalSeparators &&
1226
+ allowedDecimalSeparators.includes(curChar) &&
1227
+ newChar === decimalSeparator) {
1228
+ return true;
1229
+ }
1230
+ return curChar === newChar;
1231
+ };
1232
+ return Object.assign(Object.assign({}, restProps), { value: formattedValue, valueIsNumericString: false, isValidInputCharacter: isValidInputCharacter,
1233
+ isCharacterSame: isCharacterSame, onValueChange: _onValueChange, format: _format, removeFormatting: _removeFormatting, getCaretBoundary: function (formattedValue) { return getCaretBoundary(formattedValue, props); }, onKeyDown: _onKeyDown, onBlur: _onBlur });
1234
+ }
1235
+ function NumericFormat(props) {
1236
+ var numericFormatProps = useNumericFormat(props);
1237
+ return React__default.createElement(NumberFormatBase, Object.assign({}, numericFormatProps));
1238
+ }
1239
+
1240
+ function format$1(numStr, props) {
1241
+ var format = props.format;
1242
+ var allowEmptyFormatting = props.allowEmptyFormatting;
1243
+ var mask = props.mask;
1244
+ var patternChar = props.patternChar; if ( patternChar === void 0 ) patternChar = '#';
1245
+ if (numStr === '' && !allowEmptyFormatting)
1246
+ { return ''; }
1247
+ var hashCount = 0;
1248
+ var formattedNumberAry = format.split('');
1249
+ for (var i = 0, ln = format.length; i < ln; i++) {
1250
+ if (format[i] === patternChar) {
1251
+ formattedNumberAry[i] = numStr[hashCount] || getMaskAtIndex(mask, hashCount);
1252
+ hashCount += 1;
1253
+ }
1254
+ }
1255
+ return formattedNumberAry.join('');
1256
+ }
1257
+ function removeFormatting$1(value, changeMeta, props) {
1258
+ if ( changeMeta === void 0 ) changeMeta = getDefaultChangeMeta(value);
1259
+
1260
+ var format = props.format;
1261
+ var patternChar = props.patternChar; if ( patternChar === void 0 ) patternChar = '#';
1262
+ var from = changeMeta.from;
1263
+ var to = changeMeta.to;
1264
+ var lastValue = changeMeta.lastValue; if ( lastValue === void 0 ) lastValue = '';
1265
+ var isNumericSlot = function (caretPos) { return format[caretPos] === patternChar; };
1266
+ var removeFormatChar = function (string, startIndex) {
1267
+ var str = '';
1268
+ for (var i = 0; i < string.length; i++) {
1269
+ if (isNumericSlot(startIndex + i) && charIsNumber(string[i])) {
1270
+ str += string[i];
1271
+ }
1272
+ }
1273
+ return str;
1274
+ };
1275
+ var extractNumbers = function (str) { return str.replace(/[^0-9]/g, ''); };
1276
+ // if format doesn't have any number, remove all the non numeric characters
1277
+ if (!format.match(/\d/)) {
1278
+ return extractNumbers(value);
1279
+ }
1280
+ /**
1281
+ * if user paste the whole formatted text in an empty input or doing select all and paste, check if matches to the pattern
1282
+ * and remove the format characters, if there is a mismatch on the pattern, do plane number extract
1283
+ */
1284
+ if ((lastValue === '' || from.end - from.start === lastValue.length) &&
1285
+ value.length === format.length) {
1286
+ var str = '';
1287
+ for (var i = 0; i < value.length; i++) {
1288
+ if (isNumericSlot(i)) {
1289
+ if (charIsNumber(value[i])) {
1290
+ str += value[i];
1291
+ }
1292
+ }
1293
+ else if (value[i] !== format[i]) {
1294
+ // if there is a mismatch on the pattern, do plane number extract
1295
+ return extractNumbers(value);
1296
+ }
1297
+ }
1298
+ return str;
1299
+ }
1300
+ /**
1301
+ * For partial change,
1302
+ * where ever there is a change on the input, we can break the number in three parts
1303
+ * 1st: left part which is unchanged
1304
+ * 2nd: middle part which is changed
1305
+ * 3rd: right part which is unchanged
1306
+ *
1307
+ * The first and third section will be same as last value, only the middle part will change
1308
+ * We can consider on the change part all the new characters are non format characters.
1309
+ * And on the first and last section it can have partial format characters.
1310
+ *
1311
+ * We pick first and last section from the lastValue (as that has 1-1 mapping with format)
1312
+ * and middle one from the update value.
1313
+ */
1314
+ var firstSection = lastValue.substring(0, from.start);
1315
+ var middleSection = value.substring(to.start, to.end);
1316
+ var lastSection = lastValue.substring(from.end);
1317
+ return ("" + (removeFormatChar(firstSection, 0)) + (extractNumbers(middleSection)) + (removeFormatChar(lastSection, from.end)));
1318
+ }
1319
+ function getCaretBoundary$1(formattedValue, props) {
1320
+ var format = props.format;
1321
+ var mask = props.mask;
1322
+ var patternChar = props.patternChar; if ( patternChar === void 0 ) patternChar = '#';
1323
+ var boundaryAry = Array.from({ length: formattedValue.length + 1 }).map(function () { return true; });
1324
+ var hashCount = 0;
1325
+ var firstEmptySlot = -1;
1326
+ var maskAndIndexMap = {};
1327
+ format.split('').forEach(function (char, index) {
1328
+ var maskAtIndex = undefined;
1329
+ if (char === patternChar) {
1330
+ hashCount++;
1331
+ maskAtIndex = getMaskAtIndex(mask, hashCount - 1);
1332
+ if (firstEmptySlot === -1 && formattedValue[index] === maskAtIndex) {
1333
+ firstEmptySlot = index;
1334
+ }
1335
+ }
1336
+ maskAndIndexMap[index] = maskAtIndex;
1337
+ });
1338
+ var isPosAllowed = function (pos) {
1339
+ // the position is allowed if the position is not masked and valid number area
1340
+ return format[pos] === patternChar && formattedValue[pos] !== maskAndIndexMap[pos];
1341
+ };
1342
+ for (var i = 0, ln = boundaryAry.length; i < ln; i++) {
1343
+ // consider caret to be in boundary if it is before or after numeric value
1344
+ // Note: on pattern based format its denoted by patternCharacter
1345
+ // we should also allow user to put cursor on first empty slot
1346
+ boundaryAry[i] = i === firstEmptySlot || isPosAllowed(i) || isPosAllowed(i - 1);
1347
+ }
1348
+ // the first patternChar position is always allowed
1349
+ boundaryAry[format.indexOf(patternChar)] = true;
1350
+ return boundaryAry;
1351
+ }
1352
+ function validateProps(props) {
1353
+ var mask = props.mask;
1354
+ if (mask) {
1355
+ var maskAsStr = mask === 'string' ? mask : mask.toString();
1356
+ if (maskAsStr.match(/\d/g)) {
1357
+ throw new Error(("Mask " + mask + " should not contain numeric character;"));
1358
+ }
1359
+ }
1360
+ }
1361
+ function isNumericString$1(val, format) {
1362
+ //we can treat empty string as numeric string
1363
+ if (val === '')
1364
+ { return true; }
1365
+ return !(format === null || format === void 0 ? void 0 : format.match(/\d/)) && typeof val === 'string' && (!!val.match(/^\d+$/) || val === '');
1366
+ }
1367
+ function usePatternFormat(props) {
1368
+ var mask = props.mask;
1369
+ var allowEmptyFormatting = props.allowEmptyFormatting;
1370
+ var formatProp = props.format;
1371
+ var inputMode = props.inputMode; if ( inputMode === void 0 ) inputMode = 'numeric';
1372
+ var onKeyDown = props.onKeyDown; if ( onKeyDown === void 0 ) onKeyDown = noop;
1373
+ var patternChar = props.patternChar; if ( patternChar === void 0 ) patternChar = '#';
1374
+ var value = props.value;
1375
+ var defaultValue = props.defaultValue;
1376
+ var valueIsNumericString = props.valueIsNumericString;
1377
+ var restProps = __rest(props, ["mask", "allowEmptyFormatting", "format", "inputMode", "onKeyDown", "patternChar", "value", "defaultValue", "valueIsNumericString"]);
1378
+ // validate props
1379
+ validateProps(props);
1380
+ var _getCaretBoundary = function (formattedValue) {
1381
+ return getCaretBoundary$1(formattedValue, props);
1382
+ };
1383
+ var _onKeyDown = function (e) {
1384
+ var key = e.key;
1385
+ var el = e.target;
1386
+ var selectionStart = el.selectionStart;
1387
+ var selectionEnd = el.selectionEnd;
1388
+ var value = el.value;
1389
+ // if multiple characters are selected and user hits backspace, no need to handle anything manually
1390
+ if (selectionStart !== selectionEnd) {
1391
+ onKeyDown(e);
1392
+ return;
1393
+ }
1394
+ // bring the cursor to closest numeric section
1395
+ var caretPos = selectionStart;
1396
+ // if backspace is pressed after the format characters, bring it to numeric section
1397
+ // if delete is pressed before the format characters, bring it to numeric section
1398
+ if (key === 'Backspace' || key === 'Delete') {
1399
+ var direction = 'right';
1400
+ if (key === 'Backspace') {
1401
+ while (caretPos > 0 && formatProp[caretPos - 1] !== patternChar) {
1402
+ caretPos--;
1403
+ }
1404
+ direction = 'left';
1405
+ }
1406
+ else {
1407
+ var formatLn = formatProp.length;
1408
+ while (caretPos < formatLn && formatProp[caretPos] !== patternChar) {
1409
+ caretPos++;
1410
+ }
1411
+ direction = 'right';
1412
+ }
1413
+ caretPos = getCaretPosInBoundary(value, caretPos, _getCaretBoundary(value), direction);
1414
+ }
1415
+ else if (formatProp[caretPos] !== patternChar &&
1416
+ key !== 'ArrowLeft' &&
1417
+ key !== 'ArrowRight') {
1418
+ // if user is typing on format character position, bring user to next allowed caret position
1419
+ caretPos = getCaretPosInBoundary(value, caretPos + 1, _getCaretBoundary(value), 'right');
1420
+ }
1421
+ // if we changing caret position, set the caret position
1422
+ if (caretPos !== selectionStart) {
1423
+ setCaretPosition(el, caretPos);
1424
+ }
1425
+ onKeyDown(e);
1426
+ };
1427
+ // try to figure out isValueNumericString based on format prop and value
1428
+ var _value = isNil(value) ? defaultValue : value;
1429
+ var isValueNumericString = valueIsNumericString !== null && valueIsNumericString !== void 0 ? valueIsNumericString : isNumericString$1(_value, formatProp);
1430
+ var _props = Object.assign(Object.assign({}, props), { valueIsNumericString: isValueNumericString });
1431
+ return Object.assign(Object.assign({}, restProps), { value: value,
1432
+ defaultValue: defaultValue, valueIsNumericString: isValueNumericString, inputMode: inputMode, format: function (numStr) { return format$1(numStr, _props); }, removeFormatting: function (inputValue, changeMeta) { return removeFormatting$1(inputValue, changeMeta, _props); }, getCaretBoundary: _getCaretBoundary, onKeyDown: _onKeyDown });
1433
+ }
1434
+ function PatternFormat(props) {
1435
+ var patternFormatProps = usePatternFormat(props);
1436
+ return React__default.createElement(NumberFormatBase, Object.assign({}, patternFormatProps));
1437
+ }
1438
+
1439
+ exports.NumberFormatBase = NumberFormatBase;
1440
+ exports.NumericFormat = NumericFormat;
1441
+ exports.PatternFormat = PatternFormat;
1442
+ exports.getNumericCaretBoundary = getCaretBoundary;
1443
+ exports.getPatternCaretBoundary = getCaretBoundary$1;
1444
+ exports.numericFormatter = format;
1445
+ exports.patternFormatter = format$1;
1446
+ exports.removeNumericFormat = removeFormatting;
1447
+ exports.removePatternFormat = removeFormatting$1;
1448
+ exports.useNumericFormat = useNumericFormat;
1449
+ exports.usePatternFormat = usePatternFormat;
1450
+
1451
+ Object.defineProperty(exports, '__esModule', { value: true });
1452
+
1453
+ })));