ivt
Version:
Ivt Components Library
1 lines • 125 kB
Source Map (JSON)
{"version":3,"file":"react-number-format.es-DSc45Db0.mjs","sources":["../../node_modules/react-number-format/dist/react-number-format.es.js"],"sourcesContent":["/**\n * react-number-format - 5.4.4\n * Author : Sudhanshu Yadav\n * Copyright (c) 2016, 2025 to Sudhanshu Yadav, released under the MIT license.\n * https://github.com/s-yadav/react-number-format\n */\n\nimport React, { useState, useMemo, useRef, useEffect, useLayoutEffect } from 'react';\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n { t[p] = s[p]; } }\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n { for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n { t[p[i]] = s[p[i]]; }\r\n } }\r\n return t;\r\n}\n\nvar SourceType;\n(function (SourceType) {\n SourceType[\"event\"] = \"event\";\n SourceType[\"props\"] = \"prop\";\n})(SourceType || (SourceType = {}));\n\n// basic noop function\nfunction noop() { }\nfunction memoizeOnce(cb) {\n var lastArgs;\n var lastValue = undefined;\n return function () {\n var args = [], len = arguments.length;\n while ( len-- ) args[ len ] = arguments[ len ];\n\n if (lastArgs &&\n args.length === lastArgs.length &&\n args.every(function (value, index) { return value === lastArgs[index]; })) {\n return lastValue;\n }\n lastArgs = args;\n lastValue = cb.apply(void 0, args);\n return lastValue;\n };\n}\nfunction charIsNumber(char) {\n return !!(char || '').match(/\\d/);\n}\nfunction isNil(val) {\n return val === null || val === undefined;\n}\nfunction isNanValue(val) {\n return typeof val === 'number' && isNaN(val);\n}\nfunction isNotValidValue(val) {\n return isNil(val) || isNanValue(val) || (typeof val === 'number' && !isFinite(val));\n}\nfunction escapeRegExp(str) {\n return str.replace(/[-[\\]/{}()*+?.\\\\^$|]/g, '\\\\$&');\n}\nfunction getThousandsGroupRegex(thousandsGroupStyle) {\n switch (thousandsGroupStyle) {\n case 'lakh':\n return /(\\d+?)(?=(\\d\\d)+(\\d)(?!\\d))(\\.\\d+)?/g;\n case 'wan':\n return /(\\d)(?=(\\d{4})+(?!\\d))/g;\n case 'thousand':\n default:\n return /(\\d)(?=(\\d{3})+(?!\\d))/g;\n }\n}\nfunction applyThousandSeparator(str, thousandSeparator, thousandsGroupStyle) {\n var thousandsGroupRegex = getThousandsGroupRegex(thousandsGroupStyle);\n var index = str.search(/[1-9]/);\n index = index === -1 ? str.length : index;\n return (str.substring(0, index) +\n str.substring(index, str.length).replace(thousandsGroupRegex, '$1' + thousandSeparator));\n}\nfunction usePersistentCallback(cb) {\n var callbackRef = useRef(cb);\n // keep the callback ref upto date\n callbackRef.current = cb;\n /**\n * initialize a persistent callback which never changes\n * through out the component lifecycle\n */\n var persistentCbRef = useRef(function () {\n var args = [], len = arguments.length;\n while ( len-- ) args[ len ] = arguments[ len ];\n\n return callbackRef.current.apply(callbackRef, args);\n });\n return persistentCbRef.current;\n}\n//spilt a float number into different parts beforeDecimal, afterDecimal, and negation\nfunction splitDecimal(numStr, allowNegative) {\n if ( allowNegative === void 0 ) allowNegative = true;\n\n var hasNegation = numStr[0] === '-';\n var addNegation = hasNegation && allowNegative;\n numStr = numStr.replace('-', '');\n var parts = numStr.split('.');\n var beforeDecimal = parts[0];\n var afterDecimal = parts[1] || '';\n return {\n beforeDecimal: beforeDecimal,\n afterDecimal: afterDecimal,\n hasNegation: hasNegation,\n addNegation: addNegation,\n };\n}\nfunction fixLeadingZero(numStr) {\n if (!numStr)\n { return numStr; }\n var isNegative = numStr[0] === '-';\n if (isNegative)\n { numStr = numStr.substring(1, numStr.length); }\n var parts = numStr.split('.');\n var beforeDecimal = parts[0].replace(/^0+/, '') || '0';\n var afterDecimal = parts[1] || '';\n return (\"\" + (isNegative ? '-' : '') + beforeDecimal + (afterDecimal ? (\".\" + afterDecimal) : ''));\n}\n/**\n * limit decimal numbers to given scale\n * Not used .fixedTo because that will break with big numbers\n */\nfunction limitToScale(numStr, scale, fixedDecimalScale) {\n var str = '';\n var filler = fixedDecimalScale ? '0' : '';\n for (var i = 0; i <= scale - 1; i++) {\n str += numStr[i] || filler;\n }\n return str;\n}\nfunction repeat(str, count) {\n return Array(count + 1).join(str);\n}\nfunction toNumericString(num) {\n var _num = num + ''; // typecast number to string\n // store the sign and remove it from the number.\n var sign = _num[0] === '-' ? '-' : '';\n if (sign)\n { _num = _num.substring(1); }\n // split the number into cofficient and exponent\n var ref = _num.split(/[eE]/g);\n var coefficient = ref[0];\n var exponent = ref[1];\n // covert exponent to number;\n exponent = Number(exponent);\n // if there is no exponent part or its 0, return the coffiecient with sign\n if (!exponent)\n { return sign + coefficient; }\n coefficient = coefficient.replace('.', '');\n /**\n * for scientific notation the current decimal index will be after first number (index 0)\n * So effective decimal index will always be 1 + exponent value\n */\n var decimalIndex = 1 + exponent;\n var coffiecientLn = coefficient.length;\n if (decimalIndex < 0) {\n // if decimal index is less then 0 add preceding 0s\n // add 1 as join will have\n coefficient = '0.' + repeat('0', Math.abs(decimalIndex)) + coefficient;\n }\n else if (decimalIndex >= coffiecientLn) {\n // if decimal index is less then 0 add leading 0s\n coefficient = coefficient + repeat('0', decimalIndex - coffiecientLn);\n }\n else {\n // else add decimal point at proper index\n coefficient =\n (coefficient.substring(0, decimalIndex) || '0') + '.' + coefficient.substring(decimalIndex);\n }\n return sign + coefficient;\n}\n/**\n * This method is required to round prop value to given scale.\n * Not used .round or .fixedTo because that will break with big numbers\n */\nfunction roundToPrecision(numStr, scale, fixedDecimalScale) {\n //if number is empty don't do anything return empty string\n if (['', '-'].indexOf(numStr) !== -1)\n { return numStr; }\n var shouldHaveDecimalSeparator = (numStr.indexOf('.') !== -1 || fixedDecimalScale) && scale;\n var ref = splitDecimal(numStr);\n var beforeDecimal = ref.beforeDecimal;\n var afterDecimal = ref.afterDecimal;\n var hasNegation = ref.hasNegation;\n var floatValue = parseFloat((\"0.\" + (afterDecimal || '0')));\n var floatValueStr = afterDecimal.length <= scale ? (\"0.\" + afterDecimal) : floatValue.toFixed(scale);\n var roundedDecimalParts = floatValueStr.split('.');\n var intPart = beforeDecimal;\n // if we have cary over from rounding decimal part, add that on before decimal\n if (beforeDecimal && Number(roundedDecimalParts[0])) {\n intPart = beforeDecimal\n .split('')\n .reverse()\n .reduce(function (roundedStr, current, idx) {\n if (roundedStr.length > idx) {\n return ((Number(roundedStr[0]) + Number(current)).toString() +\n roundedStr.substring(1, roundedStr.length));\n }\n return current + roundedStr;\n }, roundedDecimalParts[0]);\n }\n var decimalPart = limitToScale(roundedDecimalParts[1] || '', scale, fixedDecimalScale);\n var negation = hasNegation ? '-' : '';\n var decimalSeparator = shouldHaveDecimalSeparator ? '.' : '';\n return (\"\" + negation + intPart + decimalSeparator + decimalPart);\n}\n/** set the caret positon in an input field **/\nfunction setCaretPosition(el, caretPos) {\n el.value = el.value;\n // ^ this is used to not only get 'focus', but\n // to make sure we don't have it everything -selected-\n // (it causes an issue in chrome, and having it doesn't hurt any other browser)\n if (el !== null) {\n /* @ts-ignore */\n if (el.createTextRange) {\n /* @ts-ignore */\n var range = el.createTextRange();\n range.move('character', caretPos);\n range.select();\n return true;\n }\n // (el.selectionStart === 0 added for Firefox bug)\n if (el.selectionStart || el.selectionStart === 0) {\n el.focus();\n el.setSelectionRange(caretPos, caretPos);\n return true;\n }\n // fail city, fortunately this never happens (as far as I've tested) :)\n el.focus();\n return false;\n }\n}\n/**\n * TODO: remove dependency of findChangeRange, findChangedRangeFromCaretPositions is better way to find what is changed\n * currently this is mostly required by test and isCharacterSame util\n * Given previous value and newValue it returns the index\n * start - end to which values have changed.\n * This function makes assumption about only consecutive\n * characters are changed which is correct assumption for caret input.\n */\nvar findChangeRange = memoizeOnce(function (prevValue, newValue) {\n var i = 0, j = 0;\n var prevLength = prevValue.length;\n var newLength = newValue.length;\n while (prevValue[i] === newValue[i] && i < prevLength)\n { i++; }\n //check what has been changed from last\n while (prevValue[prevLength - 1 - j] === newValue[newLength - 1 - j] &&\n newLength - j > i &&\n prevLength - j > i) {\n j++;\n }\n return {\n from: { start: i, end: prevLength - j },\n to: { start: i, end: newLength - j },\n };\n});\nvar findChangedRangeFromCaretPositions = function (lastCaretPositions, currentCaretPosition) {\n var startPosition = Math.min(lastCaretPositions.selectionStart, currentCaretPosition);\n return {\n from: { start: startPosition, end: lastCaretPositions.selectionEnd },\n to: { start: startPosition, end: currentCaretPosition },\n };\n};\n/*\n Returns a number whose value is limited to the given range\n*/\nfunction clamp(num, min, max) {\n return Math.min(Math.max(num, min), max);\n}\nfunction geInputCaretPosition(el) {\n /*Max of selectionStart and selectionEnd is taken for the patch of pixel and other mobile device caret bug*/\n return Math.max(el.selectionStart, el.selectionEnd);\n}\nfunction addInputMode() {\n return (typeof navigator !== 'undefined' &&\n !(navigator.platform && /iPhone|iPod/.test(navigator.platform)));\n}\nfunction getDefaultChangeMeta(value) {\n return {\n from: {\n start: 0,\n end: 0,\n },\n to: {\n start: 0,\n end: value.length,\n },\n lastValue: '',\n };\n}\nfunction getMaskAtIndex(mask, index) {\n if ( mask === void 0 ) mask = ' ';\n\n if (typeof mask === 'string') {\n return mask;\n }\n return mask[index] || ' ';\n}\nfunction defaultIsCharacterSame(ref) {\n var currentValue = ref.currentValue;\n var formattedValue = ref.formattedValue;\n var currentValueIndex = ref.currentValueIndex;\n var formattedValueIndex = ref.formattedValueIndex;\n\n return currentValue[currentValueIndex] === formattedValue[formattedValueIndex];\n}\nfunction getCaretPosition(newFormattedValue, lastFormattedValue, curValue, curCaretPos, boundary, isValidInputCharacter, \n/**\n * format function can change the character, the caret engine relies on mapping old value and new value\n * In such case if character is changed, parent can tell which chars are equivalent\n * Some example, all allowedDecimalCharacters are updated to decimalCharacters, 2nd case if user is coverting\n * number to different numeric system.\n */\nisCharacterSame) {\n if ( isCharacterSame === void 0 ) isCharacterSame = defaultIsCharacterSame;\n\n /**\n * if something got inserted on empty value, add the formatted character before the current value,\n * This is to avoid the case where typed character is present on format characters\n */\n var firstAllowedPosition = boundary.findIndex(function (b) { return b; });\n var prefixFormat = newFormattedValue.slice(0, firstAllowedPosition);\n if (!lastFormattedValue && !curValue.startsWith(prefixFormat)) {\n lastFormattedValue = prefixFormat;\n curValue = prefixFormat + curValue;\n curCaretPos = curCaretPos + prefixFormat.length;\n }\n var curValLn = curValue.length;\n var formattedValueLn = newFormattedValue.length;\n // create index map\n var addedIndexMap = {};\n var indexMap = new Array(curValLn);\n for (var i = 0; i < curValLn; i++) {\n indexMap[i] = -1;\n for (var j = 0, jLn = formattedValueLn; j < jLn; j++) {\n var isCharSame = isCharacterSame({\n currentValue: curValue,\n lastValue: lastFormattedValue,\n formattedValue: newFormattedValue,\n currentValueIndex: i,\n formattedValueIndex: j,\n });\n if (isCharSame && addedIndexMap[j] !== true) {\n indexMap[i] = j;\n addedIndexMap[j] = true;\n break;\n }\n }\n }\n /**\n * For current caret position find closest characters (left and right side)\n * which are properly mapped to formatted value.\n * The idea is that the new caret position will exist always in the boundary of\n * that mapped index\n */\n var pos = curCaretPos;\n while (pos < curValLn && (indexMap[pos] === -1 || !isValidInputCharacter(curValue[pos]))) {\n pos++;\n }\n // if the caret position is on last keep the endIndex as last for formatted value\n var endIndex = pos === curValLn || indexMap[pos] === -1 ? formattedValueLn : indexMap[pos];\n pos = curCaretPos - 1;\n while (pos > 0 && indexMap[pos] === -1)\n { pos--; }\n var startIndex = pos === -1 || indexMap[pos] === -1 ? 0 : indexMap[pos] + 1;\n /**\n * case where a char is added on suffix and removed from middle, example 2sq345 becoming $2,345 sq\n * there is still a mapping but the order of start index and end index is changed\n */\n if (startIndex > endIndex)\n { return endIndex; }\n /**\n * given the current caret position if it closer to startIndex\n * keep the new caret position on start index or keep it closer to endIndex\n */\n return curCaretPos - startIndex < endIndex - curCaretPos ? startIndex : endIndex;\n}\n/* This keeps the caret within typing area so people can't type in between prefix or suffix or format characters */\nfunction getCaretPosInBoundary(value, caretPos, boundary, direction) {\n var valLn = value.length;\n // clamp caret position to [0, value.length]\n caretPos = clamp(caretPos, 0, valLn);\n if (direction === 'left') {\n while (caretPos >= 0 && !boundary[caretPos])\n { caretPos--; }\n // if we don't find any suitable caret position on left, set it on first allowed position\n if (caretPos === -1)\n { caretPos = boundary.indexOf(true); }\n }\n else {\n while (caretPos <= valLn && !boundary[caretPos])\n { caretPos++; }\n // if we don't find any suitable caret position on right, set it on last allowed position\n if (caretPos > valLn)\n { caretPos = boundary.lastIndexOf(true); }\n }\n // if we still don't find caret position, set it at the end of value\n if (caretPos === -1)\n { caretPos = valLn; }\n return caretPos;\n}\nfunction caretUnknownFormatBoundary(formattedValue) {\n var boundaryAry = Array.from({ length: formattedValue.length + 1 }).map(function () { return true; });\n for (var i = 0, ln = boundaryAry.length; i < ln; i++) {\n // consider caret to be in boundary if it is before or after numeric value\n boundaryAry[i] = Boolean(charIsNumber(formattedValue[i]) || charIsNumber(formattedValue[i - 1]));\n }\n return boundaryAry;\n}\nfunction useInternalValues(value, defaultValue, valueIsNumericString, format, removeFormatting, onValueChange) {\n if ( onValueChange === void 0 ) onValueChange = noop;\n\n var getValues = usePersistentCallback(function (value, valueIsNumericString) {\n var formattedValue, numAsString;\n if (isNotValidValue(value)) {\n numAsString = '';\n formattedValue = '';\n }\n else if (typeof value === 'number' || valueIsNumericString) {\n numAsString = typeof value === 'number' ? toNumericString(value) : value;\n formattedValue = format(numAsString);\n }\n else {\n numAsString = removeFormatting(value, undefined);\n formattedValue = format(numAsString);\n }\n return { formattedValue: formattedValue, numAsString: numAsString };\n });\n var ref = useState(function () {\n return getValues(isNil(value) ? defaultValue : value, valueIsNumericString);\n });\n var values = ref[0];\n var setValues = ref[1];\n var _onValueChange = function (newValues, sourceInfo) {\n if (newValues.formattedValue !== values.formattedValue) {\n setValues({\n formattedValue: newValues.formattedValue,\n numAsString: newValues.value,\n });\n }\n // call parent on value change if only if formatted value is changed\n onValueChange(newValues, sourceInfo);\n };\n // if value is switch from controlled to uncontrolled, use the internal state's value to format with new props\n var _value = value;\n var _valueIsNumericString = valueIsNumericString;\n if (isNil(value)) {\n _value = values.numAsString;\n _valueIsNumericString = true;\n }\n var newValues = getValues(_value, _valueIsNumericString);\n useMemo(function () {\n setValues(newValues);\n }, [newValues.formattedValue]);\n return [values, _onValueChange];\n}\n\nfunction defaultRemoveFormatting(value) {\n return value.replace(/[^0-9]/g, '');\n}\nfunction defaultFormat(value) {\n return value;\n}\nfunction NumberFormatBase(props) {\n var type = props.type; if ( type === void 0 ) type = 'text';\n var displayType = props.displayType; if ( displayType === void 0 ) displayType = 'input';\n var customInput = props.customInput;\n var renderText = props.renderText;\n var getInputRef = props.getInputRef;\n var format = props.format; if ( format === void 0 ) format = defaultFormat;\n var removeFormatting = props.removeFormatting; if ( removeFormatting === void 0 ) removeFormatting = defaultRemoveFormatting;\n var defaultValue = props.defaultValue;\n var valueIsNumericString = props.valueIsNumericString;\n var onValueChange = props.onValueChange;\n var isAllowed = props.isAllowed;\n var onChange = props.onChange; if ( onChange === void 0 ) onChange = noop;\n var onKeyDown = props.onKeyDown; if ( onKeyDown === void 0 ) onKeyDown = noop;\n var onMouseUp = props.onMouseUp; if ( onMouseUp === void 0 ) onMouseUp = noop;\n var onFocus = props.onFocus; if ( onFocus === void 0 ) onFocus = noop;\n var onBlur = props.onBlur; if ( onBlur === void 0 ) onBlur = noop;\n var propValue = props.value;\n var getCaretBoundary = props.getCaretBoundary; if ( getCaretBoundary === void 0 ) getCaretBoundary = caretUnknownFormatBoundary;\n var isValidInputCharacter = props.isValidInputCharacter; if ( isValidInputCharacter === void 0 ) isValidInputCharacter = charIsNumber;\n var isCharacterSame = props.isCharacterSame;\n var otherProps = __rest(props, [\"type\", \"displayType\", \"customInput\", \"renderText\", \"getInputRef\", \"format\", \"removeFormatting\", \"defaultValue\", \"valueIsNumericString\", \"onValueChange\", \"isAllowed\", \"onChange\", \"onKeyDown\", \"onMouseUp\", \"onFocus\", \"onBlur\", \"value\", \"getCaretBoundary\", \"isValidInputCharacter\", \"isCharacterSame\"]);\n var ref = useInternalValues(propValue, defaultValue, Boolean(valueIsNumericString), format, removeFormatting, onValueChange);\n var ref_0 = ref[0];\n var formattedValue = ref_0.formattedValue;\n var numAsString = ref_0.numAsString;\n var onFormattedValueChange = ref[1];\n var caretPositionBeforeChange = useRef();\n var lastUpdatedValue = useRef({ formattedValue: formattedValue, numAsString: numAsString });\n var _onValueChange = function (values, source) {\n lastUpdatedValue.current = { formattedValue: values.formattedValue, numAsString: values.value };\n onFormattedValueChange(values, source);\n };\n var ref$1 = useState(false);\n var mounted = ref$1[0];\n var setMounted = ref$1[1];\n var focusedElm = useRef(null);\n var timeout = useRef({\n setCaretTimeout: null,\n focusTimeout: null,\n });\n useEffect(function () {\n setMounted(true);\n return function () {\n clearTimeout(timeout.current.setCaretTimeout);\n clearTimeout(timeout.current.focusTimeout);\n };\n }, []);\n var _format = format;\n var getValueObject = function (formattedValue, numAsString) {\n var floatValue = parseFloat(numAsString);\n return {\n formattedValue: formattedValue,\n value: numAsString,\n floatValue: isNaN(floatValue) ? undefined : floatValue,\n };\n };\n var setPatchedCaretPosition = function (el, caretPos, currentValue) {\n // don't reset the caret position when the whole input content is selected\n if (el.selectionStart === 0 && el.selectionEnd === el.value.length)\n { return; }\n /* setting caret position within timeout of 0ms is required for mobile chrome,\n otherwise browser resets the caret position after we set it\n We are also setting it without timeout so that in normal browser we don't see the flickering */\n setCaretPosition(el, caretPos);\n timeout.current.setCaretTimeout = setTimeout(function () {\n if (el.value === currentValue && el.selectionStart !== caretPos) {\n setCaretPosition(el, caretPos);\n }\n }, 0);\n };\n /* This keeps the caret within typing area so people can't type in between prefix or suffix */\n var correctCaretPosition = function (value, caretPos, direction) {\n return getCaretPosInBoundary(value, caretPos, getCaretBoundary(value), direction);\n };\n var getNewCaretPosition = function (inputValue, newFormattedValue, caretPos) {\n var caretBoundary = getCaretBoundary(newFormattedValue);\n var updatedCaretPos = getCaretPosition(newFormattedValue, formattedValue, inputValue, caretPos, caretBoundary, isValidInputCharacter, isCharacterSame);\n //correct caret position if its outside of editable area\n updatedCaretPos = getCaretPosInBoundary(newFormattedValue, updatedCaretPos, caretBoundary);\n return updatedCaretPos;\n };\n var updateValueAndCaretPosition = function (params) {\n var newFormattedValue = params.formattedValue; if ( newFormattedValue === void 0 ) newFormattedValue = '';\n var input = params.input;\n var source = params.source;\n var event = params.event;\n var numAsString = params.numAsString;\n var caretPos;\n if (input) {\n var inputValue = params.inputValue || input.value;\n var currentCaretPosition = geInputCaretPosition(input);\n /**\n * set the value imperatively, this is required for IE fix\n * This is also required as if new caret position is beyond the previous value.\n * Caret position will not be set correctly\n */\n input.value = newFormattedValue;\n //get the caret position\n caretPos = getNewCaretPosition(inputValue, newFormattedValue, currentCaretPosition);\n //set caret position imperatively\n if (caretPos !== undefined) {\n setPatchedCaretPosition(input, caretPos, newFormattedValue);\n }\n }\n if (newFormattedValue !== formattedValue) {\n // trigger onValueChange synchronously, so parent is updated along with the number format. Fix for #277, #287\n _onValueChange(getValueObject(newFormattedValue, numAsString), { event: event, source: source });\n }\n };\n /**\n * if the formatted value is not synced to parent, or if the formatted value is different from last synced value sync it\n * if the formatting props is removed, in which case last formatted value will be different from the numeric string value\n * in such case we need to inform the parent.\n */\n useEffect(function () {\n var ref = lastUpdatedValue.current;\n var lastFormattedValue = ref.formattedValue;\n var lastNumAsString = ref.numAsString;\n if (formattedValue !== lastFormattedValue || numAsString !== lastNumAsString) {\n _onValueChange(getValueObject(formattedValue, numAsString), {\n event: undefined,\n source: SourceType.props,\n });\n }\n }, [formattedValue, numAsString]);\n // also if formatted value is changed from the props, we need to update the caret position\n // keep the last caret position if element is focused\n var currentCaretPosition = focusedElm.current\n ? geInputCaretPosition(focusedElm.current)\n : undefined;\n // needed to prevent warning with useLayoutEffect on server\n var useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;\n useIsomorphicLayoutEffect(function () {\n var input = focusedElm.current;\n if (formattedValue !== lastUpdatedValue.current.formattedValue && input) {\n var caretPos = getNewCaretPosition(lastUpdatedValue.current.formattedValue, formattedValue, currentCaretPosition);\n /**\n * set the value imperatively, as we set the caret position as well imperatively.\n * This is to keep value and caret position in sync\n */\n input.value = formattedValue;\n setPatchedCaretPosition(input, caretPos, formattedValue);\n }\n }, [formattedValue]);\n var formatInputValue = function (inputValue, event, source) {\n var input = event.target;\n var changeRange = caretPositionBeforeChange.current\n ? findChangedRangeFromCaretPositions(caretPositionBeforeChange.current, input.selectionEnd)\n : findChangeRange(formattedValue, inputValue);\n var changeMeta = Object.assign(Object.assign({}, changeRange), { lastValue: formattedValue });\n var _numAsString = removeFormatting(inputValue, changeMeta);\n var _formattedValue = _format(_numAsString);\n // formatting can remove some of the number chars, so we need to fine number string again\n _numAsString = removeFormatting(_formattedValue, undefined);\n if (isAllowed && !isAllowed(getValueObject(_formattedValue, _numAsString))) {\n //reset the caret position\n var input$1 = event.target;\n var currentCaretPosition = geInputCaretPosition(input$1);\n var caretPos = getNewCaretPosition(inputValue, formattedValue, currentCaretPosition);\n input$1.value = formattedValue;\n setPatchedCaretPosition(input$1, caretPos, formattedValue);\n return false;\n }\n updateValueAndCaretPosition({\n formattedValue: _formattedValue,\n numAsString: _numAsString,\n inputValue: inputValue,\n event: event,\n source: source,\n input: event.target,\n });\n return true;\n };\n var setCaretPositionInfoBeforeChange = function (el, endOffset) {\n if ( endOffset === void 0 ) endOffset = 0;\n\n var selectionStart = el.selectionStart;\n var selectionEnd = el.selectionEnd;\n caretPositionBeforeChange.current = { selectionStart: selectionStart, selectionEnd: selectionEnd + endOffset };\n };\n var _onChange = function (e) {\n var el = e.target;\n var inputValue = el.value;\n var changed = formatInputValue(inputValue, e, SourceType.event);\n if (changed)\n { onChange(e); }\n // reset the position, as we have already handled the caret position\n caretPositionBeforeChange.current = undefined;\n };\n var _onKeyDown = function (e) {\n var el = e.target;\n var key = e.key;\n var selectionStart = el.selectionStart;\n var selectionEnd = el.selectionEnd;\n var value = el.value; if ( value === void 0 ) value = '';\n var expectedCaretPosition;\n //Handle backspace and delete against non numerical/decimal characters or arrow keys\n if (key === 'ArrowLeft' || key === 'Backspace') {\n expectedCaretPosition = Math.max(selectionStart - 1, 0);\n }\n else if (key === 'ArrowRight') {\n expectedCaretPosition = Math.min(selectionStart + 1, value.length);\n }\n else if (key === 'Delete') {\n expectedCaretPosition = selectionStart;\n }\n // if key is delete and text is not selected keep the end offset to 1, as it deletes one character\n // this is required as selection is not changed on delete case, which changes the change range calculation\n var endOffset = 0;\n if (key === 'Delete' && selectionStart === selectionEnd) {\n endOffset = 1;\n }\n var isArrowKey = key === 'ArrowLeft' || key === 'ArrowRight';\n //if expectedCaretPosition is not set it means we don't want to Handle keyDown\n // also if multiple characters are selected don't handle\n if (expectedCaretPosition === undefined || (selectionStart !== selectionEnd && !isArrowKey)) {\n onKeyDown(e);\n // keep information of what was the caret position before keyDown\n // set it after onKeyDown, in case parent updates the position manually\n setCaretPositionInfoBeforeChange(el, endOffset);\n return;\n }\n var newCaretPosition = expectedCaretPosition;\n if (isArrowKey) {\n var direction = key === 'ArrowLeft' ? 'left' : 'right';\n newCaretPosition = correctCaretPosition(value, expectedCaretPosition, direction);\n // arrow left or right only moves the caret, so no need to handle the event, if we are handling it manually\n if (newCaretPosition !== expectedCaretPosition) {\n e.preventDefault();\n }\n }\n else if (key === 'Delete' && !isValidInputCharacter(value[expectedCaretPosition])) {\n // in case of delete go to closest caret boundary on the right side\n newCaretPosition = correctCaretPosition(value, expectedCaretPosition, 'right');\n }\n else if (key === 'Backspace' && !isValidInputCharacter(value[expectedCaretPosition])) {\n // in case of backspace go to closest caret boundary on the left side\n newCaretPosition = correctCaretPosition(value, expectedCaretPosition, 'left');\n }\n if (newCaretPosition !== expectedCaretPosition) {\n setPatchedCaretPosition(el, newCaretPosition, value);\n }\n onKeyDown(e);\n setCaretPositionInfoBeforeChange(el, endOffset);\n };\n /** required to handle the caret position when click anywhere within the input **/\n var _onMouseUp = function (e) {\n var el = e.target;\n /**\n * NOTE: we have to give default value for value as in case when custom input is provided\n * value can come as undefined when nothing is provided on value prop.\n */\n var correctCaretPositionIfRequired = function () {\n var selectionStart = el.selectionStart;\n var selectionEnd = el.selectionEnd;\n var value = el.value; if ( value === void 0 ) value = '';\n if (selectionStart === selectionEnd) {\n var caretPosition = correctCaretPosition(value, selectionStart);\n if (caretPosition !== selectionStart) {\n setPatchedCaretPosition(el, caretPosition, value);\n }\n }\n };\n correctCaretPositionIfRequired();\n // try to correct after selection has updated by browser\n // this case is required when user clicks on some position while a text is selected on input\n requestAnimationFrame(function () {\n correctCaretPositionIfRequired();\n });\n onMouseUp(e);\n setCaretPositionInfoBeforeChange(el);\n };\n var _onFocus = function (e) {\n // Workaround Chrome and Safari bug https://bugs.chromium.org/p/chromium/issues/detail?id=779328\n // (onFocus event target selectionStart is always 0 before setTimeout)\n if (e.persist)\n { e.persist(); }\n var el = e.target;\n var currentTarget = e.currentTarget;\n focusedElm.current = el;\n timeout.current.focusTimeout = setTimeout(function () {\n var selectionStart = el.selectionStart;\n var selectionEnd = el.selectionEnd;\n var value = el.value; if ( value === void 0 ) value = '';\n var caretPosition = correctCaretPosition(value, selectionStart);\n //setPatchedCaretPosition only when everything is not selected on focus (while tabbing into the field)\n if (caretPosition !== selectionStart &&\n !(selectionStart === 0 && selectionEnd === value.length)) {\n setPatchedCaretPosition(el, caretPosition, value);\n }\n onFocus(Object.assign(Object.assign({}, e), { currentTarget: currentTarget }));\n }, 0);\n };\n var _onBlur = function (e) {\n focusedElm.current = null;\n clearTimeout(timeout.current.focusTimeout);\n clearTimeout(timeout.current.setCaretTimeout);\n onBlur(e);\n };\n // add input mode on element based on format prop and device once the component is mounted\n var inputMode = mounted && addInputMode() ? 'numeric' : undefined;\n var inputProps = Object.assign({ inputMode: inputMode }, otherProps, {\n type: type,\n value: formattedValue,\n onChange: _onChange,\n onKeyDown: _onKeyDown,\n onMouseUp: _onMouseUp,\n onFocus: _onFocus,\n onBlur: _onBlur,\n });\n if (displayType === 'text') {\n return renderText ? (React.createElement(React.Fragment, null, renderText(formattedValue, otherProps) || null)) : (React.createElement(\"span\", Object.assign({}, otherProps, { ref: getInputRef }), formattedValue));\n }\n else if (customInput) {\n var CustomInput = customInput;\n /* @ts-ignore */\n return React.createElement(CustomInput, Object.assign({}, inputProps, { ref: getInputRef }));\n }\n return React.createElement(\"input\", Object.assign({}, inputProps, { ref: getInputRef }));\n}\n\nfunction format(numStr, props) {\n var decimalScale = props.decimalScale;\n var fixedDecimalScale = props.fixedDecimalScale;\n var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';\n var suffix = props.suffix; if ( suffix === void 0 ) suffix = '';\n var allowNegative = props.allowNegative;\n var thousandsGroupStyle = props.thousandsGroupStyle; if ( thousandsGroupStyle === void 0 ) thousandsGroupStyle = 'thousand';\n // don't apply formatting on empty string or '-'\n if (numStr === '' || numStr === '-') {\n return numStr;\n }\n var ref = getSeparators(props);\n var thousandSeparator = ref.thousandSeparator;\n var decimalSeparator = ref.decimalSeparator;\n /**\n * Keep the decimal separator\n * when decimalScale is not defined or non zero and the numStr has decimal in it\n * Or if decimalScale is > 0 and fixeDecimalScale is true (even if numStr has no decimal)\n */\n var hasDecimalSeparator = (decimalScale !== 0 && numStr.indexOf('.') !== -1) || (decimalScale && fixedDecimalScale);\n var ref$1 = splitDecimal(numStr, allowNegative);\n var beforeDecimal = ref$1.beforeDecimal;\n var afterDecimal = ref$1.afterDecimal;\n var addNegation = ref$1.addNegation; // eslint-disable-line prefer-const\n //apply decimal precision if its defined\n if (decimalScale !== undefined) {\n afterDecimal = limitToScale(afterDecimal, decimalScale, !!fixedDecimalScale);\n }\n if (thousandSeparator) {\n beforeDecimal = applyThousandSeparator(beforeDecimal, thousandSeparator, thousandsGroupStyle);\n }\n //add prefix and suffix when there is a number present\n if (prefix)\n { beforeDecimal = prefix + beforeDecimal; }\n if (suffix)\n { afterDecimal = afterDecimal + suffix; }\n //restore negation sign\n if (addNegation)\n { beforeDecimal = '-' + beforeDecimal; }\n numStr = beforeDecimal + ((hasDecimalSeparator && decimalSeparator) || '') + afterDecimal;\n return numStr;\n}\nfunction getSeparators(props) {\n var decimalSeparator = props.decimalSeparator; if ( decimalSeparator === void 0 ) decimalSeparator = '.';\n var thousandSeparator = props.thousandSeparator;\n var allowedDecimalSeparators = props.allowedDecimalSeparators;\n if (thousandSeparator === true) {\n thousandSeparator = ',';\n }\n if (!allowedDecimalSeparators) {\n allowedDecimalSeparators = [decimalSeparator, '.'];\n }\n return {\n decimalSeparator: decimalSeparator,\n thousandSeparator: thousandSeparator,\n allowedDecimalSeparators: allowedDecimalSeparators,\n };\n}\nfunction handleNegation(value, allowNegative) {\n if ( value === void 0 ) value = '';\n\n var negationRegex = new RegExp('(-)');\n var doubleNegationRegex = new RegExp('(-)(.)*(-)');\n // Check number has '-' value\n var hasNegation = negationRegex.test(value);\n // Check number has 2 or more '-' values\n var removeNegation = doubleNegationRegex.test(value);\n //remove negation\n value = value.replace(/-/g, '');\n if (hasNegation && !removeNegation && allowNegative) {\n value = '-' + value;\n }\n return value;\n}\nfunction getNumberRegex(decimalSeparator, global) {\n return new RegExp((\"(^-)|[0-9]|\" + (escapeRegExp(decimalSeparator))), global ? 'g' : undefined);\n}\nfunction isNumericString(val, prefix, suffix) {\n // for empty value we can always treat it as numeric string\n if (val === '')\n { return true; }\n 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)));\n}\nfunction removeFormatting(value, changeMeta, props) {\n var assign;\n\n if ( changeMeta === void 0 ) changeMeta = getDefaultChangeMeta(value);\n var allowNegative = props.allowNegative;\n var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';\n var suffix = props.suffix; if ( suffix === void 0 ) suffix = '';\n var decimalScale = props.decimalScale;\n var from = changeMeta.from;\n var to = changeMeta.to;\n var start = to.start;\n var end = to.end;\n var ref = getSeparators(props);\n var allowedDecimalSeparators = ref.allowedDecimalSeparators;\n var decimalSeparator = ref.decimalSeparator;\n var isBeforeDecimalSeparator = value[end] === decimalSeparator;\n /**\n * If only a number is added on empty input which matches with the prefix or suffix,\n * then don't remove it, just return the same\n */\n if (charIsNumber(value) &&\n (value === prefix || value === suffix) &&\n changeMeta.lastValue === '') {\n return value;\n }\n /** Check for any allowed decimal separator is added in the numeric format and replace it with decimal separator */\n if (end - start === 1 && allowedDecimalSeparators.indexOf(value[start]) !== -1) {\n var separator = decimalScale === 0 ? '' : decimalSeparator;\n value = value.substring(0, start) + separator + value.substring(start + 1, value.length);\n }\n var stripNegation = function (value, start, end) {\n /**\n * if prefix starts with - we don't allow negative number to avoid confusion\n * if suffix starts with - and the value length is same as suffix length, then the - sign is from the suffix\n * In other cases, if the value starts with - then it is a negation\n */\n var hasNegation = false;\n var hasDoubleNegation = false;\n if (prefix.startsWith('-')) {\n hasNegation = false;\n }\n else if (value.startsWith('--')) {\n hasNegation = false;\n hasDoubleNegation = true;\n }\n else if (suffix.startsWith('-') && value.length === suffix.length) {\n hasNegation = false;\n }\n else if (value[0] === '-') {\n hasNegation = true;\n }\n var charsToRemove = hasNegation ? 1 : 0;\n if (hasDoubleNegation)\n { charsToRemove = 2; }\n // remove negation/double negation from start to simplify prefix logic as negation comes before prefix\n if (charsToRemove) {\n value = value.substring(charsToRemove);\n // account for the removal of the negation for start and end index\n start -= charsToRemove;\n end -= charsToRemove;\n }\n return { value: value, start: start, end: end, hasNegation: hasNegation };\n };\n var toMetadata = stripNegation(value, start, end);\n var hasNegation = toMetadata.hasNegation;\n ((assign = toMetadata, value = assign.value, start = assign.start, end = assign.end));\n var ref$1 = stripNegation(changeMeta.lastValue, from.start, from.end);\n var fromStart = ref$1.start;\n var fromEnd = ref$1.end;\n var lastValue = ref$1.value;\n // if only prefix and suffix part is updated reset the value to last value\n // if the changed range is from suffix in the updated value, and the the suffix starts with the same characters, allow the change\n var updatedSuffixPart = value.substring(start, end);\n if (value.length &&\n lastValue.length &&\n (fromStart > lastValue.length - suffix.length || fromEnd < prefix.length) &&\n !(updatedSuffixPart && suffix.startsWith(updatedSuffixPart))) {\n value = lastValue;\n }\n /**\n * remove prefix\n * Remove whole prefix part if its present on the value\n * If the prefix is partially deleted (in which case change start index will be less the prefix length)\n * Remove only partial part of prefix.\n */\n var startIndex = 0;\n if (value.startsWith(prefix))\n { startIndex += prefix.length; }\n else if (start < prefix.length)\n { startIndex = start; }\n value = value.substring(startIndex);\n // account for deleted prefix for end\n end -= startIndex;\n /**\n * Remove suffix\n * Remove whole suffix part if its present on the value\n * If the suffix is partially deleted (in which case change end index will be greater than the suffixStartIndex)\n * remove the partial part of suffix\n */\n var endIndex = value.length;\n var suffixStartIndex = value.length - suffix.length;\n if (value.endsWith(suffix))\n { endIndex = suffixStartIndex; }\n // if the suffix is removed from the end\n else if (end > suffixStartIndex)\n { endIndex = end; }\n // if the suffix is removed from start\n else if (end > value.length - suffix.length)\n { endIndex = end; }\n value = value.substring(0, endIndex);\n // add the negation back and handle for double negation\n value = handleNegation(hasNegation ? (\"-\" + value) : value, allowNegative);\n // remove non numeric characters\n value = (value.match(getNumberRegex(decimalSeparator, true)) || []).join('');\n // replace the decimalSeparator with ., and only keep the first separator, ignore following ones\n var firstIndex = value.indexOf(decimalSeparator);\n value = value.replace(new RegExp(escapeRegExp(decimalSeparator), 'g'), function (match, index) {\n return index === firstIndex ? '.' : '';\n });\n //check if beforeDecimal got deleted and there is nothing after decimal,\n //clear all numbers in such case while keeping the - sign\n var ref$2 = splitDecimal(value, allowNegative);\n var beforeDecimal = ref$2.beforeDecimal;\n var afterDecimal = ref$2.afterDecimal;\n var addNegation = ref$2.addNegation; // eslint-disable-line prefer-const\n //clear only if something got deleted before decimal (cursor is before decimal)\n if (to.end - to.start < from.end - from.start &&\n beforeDecimal === '' &&\n isBeforeDecimalSeparator &&\n !parseFloat(afterDecimal)) {\n value = addNegation ? '-' : '';\n }\n return value;\n}\nfunction getCaretBoundary(formattedValue, props) {\n var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';\n var suffix = props.suffix; if ( suffix === void 0 ) suffix = '';\n var boundaryAry = Array.from({ length: formattedValue.length + 1 }).map(function () { return true; });\n var hasNegation = formattedValue[0] === '-';\n // fill for prefix and negation\n boundaryAry.fill(false, 0, prefix.length + (hasNegation ? 1 : 0));\n // fill for suffix\n var valLn = formattedValue.length;\n boundaryAry.fill(false, valLn - suffix.length + 1, valLn + 1);\n return boundaryAry;\n}\nfunction validateAndUpdateProps(props) {\n var ref = getSeparators(props);\n var thousandSeparator = ref.thousandSeparator;\n var decimalSeparator = ref.decimalSeparator;\n // eslint-disable-next-line prefer-const\n var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';\n var allowNegative = props.allowNegative; if ( allowNegative === void 0 ) allowNegative = true;\n if (thousandSeparator === decimalSeparator) {\n 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 \"));\n }\n if (prefix.startsWith('-') && allowNegative) {\n // TODO: throw error in next major version\n console.error((\"\\n Prefix can't start with '-' when allowNegative is true.\\n prefix: \" + prefix + \"\\n allowNegative: \" + allowNegative + \"\\n \"));\n allowNegative = false;\n }\n return Object.assign(Object.assign({}, props), { allowNegative: allowNegative });\n}\nfunction useNumericFormat(props) {\n // validate props\n props = validateAndUpdateProps(props);\n var _decimalSeparator = props.decimalSeparator;\n var _allowedDecimalSeparators = props.allowedDecimalSeparators;\n var thousandsGroupStyle = props.thousandsGroupStyle;\n var suffix = props.suffix;\n var allowNegative = props.allowNegative;\n var allowLeadingZeros = props.allowLeadingZeros;\n var onKeyDown = props.onKeyDown; if ( onKeyDown === void 0 ) onKeyDown = noop;\n var onBlur = props.onBlur; if ( onBlur === void 0 ) onBlur = noop;\n var thousandSeparator = props.thousandSeparator;\n var decimalScale = props.decimalScale;\n var fixedDecimalScale = props.fixedDecimalScale;\n var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';\n var defaultValue = props.defaultValue;\n var value = props.value;\n var valueIsNumericString = props.valueIsNumericString;\n var onValueChange = props.onValueChange;\n var restProps = __rest(props, [\"decimalSeparator\", \"allowedDecimalSeparators\", \"thousandsGroupStyle\", \"suffix\", \"allowNegative\", \"allowLeadingZeros\", \"onKeyDown\", \"onBlur\", \"thousandSeparator\", \"decimalScale\", \"fixedDecimalScale\", \"prefix\", \"defaultValue\", \"value\", \"valueIsNumericString\", \"onValueChange\"]);\n // get derived decimalSeparator and allowedDecimalSeparators\n var ref = getSeparators(props);\n var decimalSeparator = ref.decimalSeparator;\n var allowedDecimalSeparators = ref.