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