UNPKG

@procurifydev/react-number-format

Version:

React component to format number in an input or as a text.

2 lines (1 loc) 17.9 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).NumberFormat=t(e.React)}(this,function(e){"use strict";function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var f=t(e);function o(e,t,r){return t=a(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,i()?Reflect.construct(t,r||[],a(e).constructor):t.apply(e,r))}function n(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,(a=n.key,void 0,"symbol"==typeof(o=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0===r)return("string"===t?String:Number)(e);var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}(a,"string"))?o:o+""),n)}var a,o}function p(){return(p=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)!{}.hasOwnProperty.call(r,n)||(e[n]=r[n])}return e}).apply(null,arguments)}function a(e){return(a=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function i(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(i=function(){return!!e})()}function r(e,t){return(r=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e})(e,t)}function u(){}function s(){}s.resetWarningCache=u;var l,c=(function(e){e.exports=function(){function e(e,t,r,n,a,o){if("SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"!==o){var i=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw i.name="Invariant Violation",i}}function t(){return e}var r={array:e.isRequired=e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:s,resetWarningCache:u};return r.PropTypes=r}()}(l={exports:{}},l.exports),l.exports);function h(){}function m(e){return!!(e||"").match(/\d/)}function g(e){return e.replace(/[-[\]/{}()*+?.\\^$|]/g,"\\$&")}function N(e,t){var r=!(1<arguments.length&&void 0!==t)||t,n="-"===e[0],a=n&&r,o=(e=e.replace("-","")).split(".");return{beforeDecimal:o[0],afterDecimal:o[1]||"",hasNagation:n,addNegation:a}}function d(e,t,r){for(var n="",a=r?"0":"",o=0;o<=t-1;o++)n+=e[o]||a;return n}function v(e,t){if(e.value=e.value,null!==e){if(e.createTextRange){var r=e.createTextRange();return r.move("character",t),r.select(),!0}return e.selectionStart||0===e.selectionStart?(e.focus(),e.setSelectionRange(t,t),!0):(e.focus(),!1)}}function y(e,t,r){return Math.min(Math.max(e,t),r)}function b(e){return Math.max(e.selectionStart,e.selectionEnd)}var S={thousandSeparator:c.oneOfType([c.string,c.oneOf([!0])]),decimalSeparator:c.string,allowedDecimalSeparators:c.arrayOf(c.string),thousandsGroupStyle:c.oneOf(["thousand","lakh","wan"]),decimalScale:c.number,fixedDecimalScale:c.bool,minimumDecimalScale:c.number,forceValidateOnBlur:c.bool,displayType:c.oneOf(["input","text"]),prefix:c.string,suffix:c.string,format:c.oneOfType([c.string,c.func]),removeFormatting:c.func,mask:c.oneOfType([c.string,c.arrayOf(c.string)]),value:c.oneOfType([c.number,c.string]),defaultValue:c.oneOfType([c.number,c.string]),isNumericString:c.bool,customInput:c.elementType,allowNegative:c.bool,allowEmptyFormatting:c.bool,allowLeadingZeros:c.bool,allowTrailingZeros:c.bool,onValueChange:c.func,onKeyDown:c.func,onMouseUp:c.func,onChange:c.func,onFocus:c.func,onBlur:c.func,type:c.oneOf(["text","tel","password"]),isAllowed:c.func,renderText:c.func,getInputRef:c.oneOfType([c.func,c.shape({current:c.any})])},x={displayType:"input",decimalSeparator:".",thousandsGroupStyle:"thousand",fixedDecimalScale:!1,minimumDecimalScale:0,prefix:"",suffix:"",allowNegative:!0,allowEmptyFormatting:!1,allowLeadingZeros:!1,allowTrailingZeros:!0,isNumericString:!1,forceValidateOnBlur:!1,type:"text",onValueChange:h,onChange:h,onKeyDown:h,onMouseUp:h,onFocus:h,onBlur:h,isAllowed:function(){return!0}},w=function(){function a(e){var t;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,a),t=o(this,a,[e]);var r=e.defaultValue;t.validateProps();var n=t.formatValueProp(r);return t.state={value:n,numAsString:t.removeFormatting(n)},t.selectionBeforeInput={selectionStart:0,selectionEnd:0},t.onChange=t.onChange.bind(t),t.onKeyDown=t.onKeyDown.bind(t),t.onMouseUp=t.onMouseUp.bind(t),t.onFocus=t.onFocus.bind(t),t.onBlur=t.onBlur.bind(t),t}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&r(e,t)}(a,f["default"].Component),function(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}(a,[{key:"componentDidUpdate",value:function(e){this.updateValueIfRequired(e)}},{key:"componentWillUnmount",value:function(){clearTimeout(this.focusTimeout)}},{key:"updateValueIfRequired",value:function(e){var t=this.props,r=this.state,n=this.focusedElm,a=r.value,o=r.numAsString,i=void 0===o?"":o;if(e!==t){this.validateProps();var u=this.formatNumString(i),s=void 0===t.value?u:this.formatValueProp(),l=this.removeFormatting(s),c=parseFloat(l),f=parseFloat(i);(isNaN(c)&&isNaN(f)||c===f)&&u===a&&(null!==n||s===a)||this.updateValue({formattedValue:s,numAsString:l,input:n})}}},{key:"getFloatString",value:function(e){var t=0<arguments.length&&void 0!==e?e:"",r=this.props.decimalScale,n=this.getSeparators().decimalSeparator,a=this.getNumberRegex(!0),o="-"===t[0];o&&(t=t.replace("-","")),n&&0===r&&(t=t.split(n)[0]);var i=(t=(t.match(a)||[]).join("").replace(n,".")).indexOf(".");return-1!==i&&(t="".concat(t.substring(0,i),".").concat(t.substring(i+1,t.length).replace(new RegExp(g(n),"g"),""))),o&&(t="-"+t),t}},{key:"getNumberRegex",value:function(e,t){var r=this.props,n=r.format,a=r.decimalScale,o=this.getSeparators().decimalSeparator;return new RegExp("\\d"+(!o||0===a||t||n?"":"|"+g(o)),e?"g":void 0)}},{key:"getSeparators",value:function(){var e=this.props.decimalSeparator,t=this.props,r=t.thousandSeparator,n=t.allowedDecimalSeparators;return!0===r&&(r=","),{decimalSeparator:e,thousandSeparator:r,allowedDecimalSeparators:n=n||[e,"."]}}},{key:"getMaskAtIndex",value:function(e){var t=this.props.mask,r=void 0===t?" ":t;return"string"==typeof r?r:r[e]||" "}},{key:"getValueObject",value:function(e,t){var r=parseFloat(t);return{formattedValue:e,value:t,floatValue:isNaN(r)?void 0:r}}},{key:"validateProps",value:function(){var e=this.props.mask,t=this.getSeparators(),r=t.decimalSeparator,n=t.thousandSeparator;if(r===n)throw new Error("\n Decimal separator can't be same as thousand separator.\n thousandSeparator: ".concat(n,' (thousandSeparator = {true} is same as thousandSeparator = ",")\n decimalSeparator: ').concat(r," (default value for decimalSeparator is .)\n "));if(e&&("string"===e?e:e.toString()).match(/\d/g))throw new Error("\n Mask ".concat(e," should not contain numeric character;\n "))}},{key:"setPatchedCaretPosition",value:function(e,t,r){v(e,t),setTimeout(function(){e.value===r&&v(e,t)},0)}},{key:"correctCaretPosition",value:function(e,t,r){var n=this.props,a=n.prefix,o=n.suffix,i=n.format;if(""===e)return 0;if(t=y(t,0,e.length),!i){var u="-"===e[0];return y(t,a.length+(u?1:0),e.length-o.length)}if("function"==typeof i)return t;if("#"===i[t]&&m(e[t]))return t;if("#"===i[t-1]&&m(e[t-1]))return t;var s=i.indexOf("#");t=y(t,s,i.lastIndexOf("#")+1);for(var l=i.substring(t,i.length).indexOf("#"),c=t,f=t+(-1===l?0:l);s<c&&("#"!==i[c]||!m(e[c]));)c-=1;return!m(e[f])||"left"===r&&t!==s||t-c<f-t?m(e[c])?c+1:c:f}},{key:"getCaretPosition",value:function(e,t,r){var n,a,o=this.props.format,i=this.state.value,u=this.getNumberRegex(!0),s=(e.match(u)||[]).join(""),l=(t.match(u)||[]).join("");for(a=n=0;a<r;a++){var c=e[a]||"",f=t[n]||"";if((c.match(u)||c===f)&&("0"!==c||!f.match(u)||"0"===f||s.length===l.length)){for(;c!==t[n]&&n<t.length;)n++;n++}}return"string"!=typeof o||i||(n=t.length),n=this.correctCaretPosition(t,n)}},{key:"removePrefixAndSuffix",value:function(e){var t=this.props,r=t.format,n=t.prefix,a=t.suffix;if(!r&&e){var o="-"===e[0];o&&(e=e.substring(1,e.length));var i=(e=n&&0===e.indexOf(n)?e.substring(n.length,e.length):e).lastIndexOf(a);e=a&&-1!==i&&i===e.length-a.length?e.substring(0,i):e,o&&(e="-"+e)}return e}},{key:"removePatternFormatting",value:function(e){for(var t=this.props.format.split("#").filter(function(e){return""!==e}),r=0,n="",a=0,o=t.length;a<=o;a++){var i=t[a]||"",u=a===o?e.length:e.indexOf(i,r);if(-1===u){n=e;break}n+=e.substring(r,u),r=u+i.length}return(n.match(/\d/g)||[]).join("")}},{key:"removeFormatting",value:function(e){var t=this.props,r=t.format,n=t.removeFormatting;return e?e=r?"string"==typeof r?this.removePatternFormatting(e):"function"==typeof n?n(e):(e.match(/\d/g)||[]).join(""):(e=this.removePrefixAndSuffix(e),this.getFloatString(e)):e}},{key:"formatWithPattern",value:function(e){for(var t=this.props.format,r=0,n=t.split(""),a=0,o=t.length;a<o;a++)"#"===t[a]&&(n[a]=e[r]||this.getMaskAtIndex(r),r+=1);return n.join("")}},{key:"formatAsNumber",value:function(e){var t=this.props,r=t.decimalScale,n=t.fixedDecimalScale,a=t.prefix,o=t.suffix,i=t.allowNegative,u=t.thousandsGroupStyle,s=this.getSeparators(),l=s.thousandSeparator,c=s.decimalSeparator,f=-1!==e.indexOf(".")||r&&n,p=N(e,i),h=p.beforeDecimal,m=p.afterDecimal,g=p.addNegation;return void 0!==r&&(m=d(m,r,n)),l&&(h=function(e,t,r){var n=function(e){switch(e){case"lakh":return/(\d+?)(?=(\d\d)+(\d)(?!\d))(\.\d+)?/g;case"wan":return/(\d)(?=(\d{4})+(?!\d))/g;case"thousand":default:return/(\d)(?=(\d{3})+(?!\d))/g}}(r),a=e.search(/[1-9]/);return a=-1===a?e.length:a,e.substring(0,a)+e.substring(a,e.length).replace(n,"$1"+t)}(h,l,u)),a&&(h=a+h),o&&(m+=o),g&&(h="-"+h),e=h+(f&&c||"")+m}},{key:"formatNumString",value:function(e){var t=0<arguments.length&&void 0!==e?e:"",r=this.props,n=r.format,a=r.allowEmptyFormatting,o=t;return o=""!==t||a?"-"!==t||n?"string"==typeof n?this.formatWithPattern(o):"function"==typeof n?n(o):this.formatAsNumber(o):"-":""}},{key:"formatValueProp",value:function(e){var t=this.props,r=t.format,n=t.decimalScale,a=t.fixedDecimalScale,o=t.allowEmptyFormatting,i=this.props,u=i.value,s=void 0===u?e:u,l=i.isNumericString,c=!s&&0!==s;return c&&o&&(s=""),c&&!o?"":("number"==typeof s&&(s=s.toString(),l=!0),"Infinity"===s&&l&&(s=""),l&&!r&&"number"==typeof n&&(s=function(e,t,r){if(-1!==["","-"].indexOf(e))return e;var n=-1!==e.indexOf(".")&&t,a=N(e),o=a.beforeDecimal,i=a.afterDecimal,u=a.hasNagation,s=parseFloat("0.".concat(i||"0")).toFixed(t).split("."),l=o.split("").reverse().reduce(function(e,t,r){return e.length>r?(Number(e[0])+Number(t)).toString()+e.substring(1,e.length):t+e},s[0]),c=d(s[1]||"",Math.min(t,i.length),r),f=n?".":"";return"".concat(u?"-":"").concat(l).concat(f).concat(c)}(s,n,a)),l?this.formatNumString(s):this.formatInput(s))}},{key:"formatNegation",value:function(e){var t=0<arguments.length&&void 0!==e?e:"",r=this.props.allowNegative,n=new RegExp("(-)"),a=new RegExp("(-)(.)*(-)"),o=n.test(t),i=a.test(t);return t=t.replace(/-/g,""),o&&!i&&r&&(t="-"+t),t}},{key:"formatInput",value:function(e){var t=0<arguments.length&&void 0!==e?e:"";return this.props.format||(t=this.removePrefixAndSuffix(t),t=this.formatNegation(t)),t=this.removeFormatting(t),this.formatNumString(t)}},{key:"isCharacterAFormat",value:function(e,t){var r=this.props,n=r.format,a=r.prefix,o=r.suffix,i=r.decimalScale,u=r.fixedDecimalScale,s=this.getSeparators().decimalSeparator;return"string"==typeof n&&"#"!==n[e]||!(n||!(e<a.length||e>=t.length-o.length||i&&u&&t[e]===s))}},{key:"checkIfFormatGotDeleted",value:function(e,t,r){for(var n=e;n<t;n++)if(this.isCharacterAFormat(n,r))return!0;return!1}},{key:"correctInputValue",value:function(e,t,r){var n=this.props,a=n.format,o=n.allowNegative,i=n.prefix,u=n.suffix,s=n.decimalScale,l=this.getSeparators(),c=l.allowedDecimalSeparators,f=l.decimalSeparator,p=this.state.numAsString||"",h=this.selectionBeforeInput,m=h.selectionStart,g=h.selectionEnd,d=function(e,t){for(var r=0,n=0,a=e.length,o=t.length;e[r]===t[r]&&r<a;)r++;for(;e[a-1-n]===t[o-1-n]&&r<o-n&&r<a-n;)n++;return{start:r,end:a-n}}(t,r),v=d.start,y=d.end;if(!a&&v===y&&-1!==c.indexOf(r[m])){var b=0===s?"":f;return r.substr(0,m)+b+r.substr(m+1,r.length)}var S=a?0:i.length,x=t.length-(a?0:u.length);if(r.length>t.length||!r.length||v===y||0===m&&g===t.length||m===S&&g===x)return r;if(this.checkIfFormatGotDeleted(v,y,t)&&(r=t),!a){var w=this.removeFormatting(r),O=N(w,o),P=O.beforeDecimal,k=O.afterDecimal,T=O.addNegation,D=e<r.indexOf(f)+1;if(w.length<p.length&&D&&""===P&&!parseFloat(k))return T?"-":""}return r}},{key:"updateValue",value:function(e){var t=e.formattedValue,r=e.input,n=e.setCaretPosition,a=void 0===n||n,o=e.numAsString,i=e.caretPos,u=this.props.onValueChange,s=this.state.value;if(r)if(a){if(!i){var l=e.inputValue||r.value,c=b(r);r.value=t,i=this.getCaretPosition(l,t,c)}this.setPatchedCaretPosition(r,i,t)}else r.value=t;void 0===o&&(o=this.removeFormatting(t)),t!==s&&(this.setState({value:t,numAsString:o}),u(this.getValueObject(t,o)))}},{key:"onChange",value:function(e){var t=e.target,r=t.value,n=this.state,a=this.props,o=a.isAllowed,i=n.value||"",u=b(t);r=this.correctInputValue(u,i,r);var s=this.formatInput(r)||"",l=this.removeFormatting(s);o(this.getValueObject(s,l))||(s=i),this.updateValue({formattedValue:s,numAsString:l,inputValue:r,input:t}),a.onChange(e)}},{key:"onBlur",value:function(e){var t=this.props,r=this.state,n=t.format,a=t.onBlur,o=t.minimumDecimalScale,i=t.allowLeadingZeros,u=t.allowTrailingZeros,s=t.forceValidateOnBlur,l=r.numAsString,c=r.value;if(this.focusedElm=null,clearTimeout(this.focusTimeout),!n||s){isNaN(parseFloat(l))&&(l=""),i||(l=function(e){if(!e)return e;var t="-"===e[0];t&&(e=e.substring(1,e.length));var r=e.split("."),n=r[0].replace(/^0+/,"")||"0",a=r[1]||"";return"".concat(t?"-":"").concat(n).concat(a?".".concat(a):"")}(l)),u||(l=function(e){if(!e)return e;var t="-"===e[0];t&&(e=e.substring(1,e.length));var r=e.split("."),n=r[0]||"0",a=r[1]?r[1].replace(/0+$/,""):"";return"".concat(t?"-":"").concat(n).concat(a?".".concat(a):"")}(l)),0<o&&(l=function(e,t){if(!e||t<0)return e;var r="-"===e[0];r&&(e=e.substring(1,e.length));var n=e.split("."),a=n[0]||"0",o="";return o=n[1]?n[1].length<t?n[1].concat(new Array(t-n[1].length).fill("0").join("")):n[1]:new Array(t).fill("0").join(""),"".concat(r?"-":"").concat(a).concat(o?".".concat(o):"")}(l,o));var f=this.formatNumString(l);if(f!==c)return this.updateValue({formattedValue:f,numAsString:l,input:e.target,setCaretPosition:!1}),void a(e)}a(e)}},{key:"onKeyDown",value:function(e){var t,r=e.target,n=e.key,a=r.selectionStart,o=r.selectionEnd,i=r.value,u=void 0===i?"":i,s=this.props,l=s.decimalScale,c=s.fixedDecimalScale,f=s.prefix,p=s.suffix,h=s.format,m=s.onKeyDown,g=void 0!==l&&c,d=this.getNumberRegex(!1,g),v=new RegExp("-"),y="string"==typeof h;if(this.selectionBeforeInput={selectionStart:a,selectionEnd:o},"ArrowLeft"===n||"Backspace"===n?t=a-1:"ArrowRight"===n?t=a+1:"Delete"===n&&(t=a),void 0!==t&&a===o){var b=t,S=y?h.indexOf("#"):f.length,x=y?h.lastIndexOf("#")+1:u.length-p.length;if("ArrowLeft"===n||"ArrowRight"===n){var w="ArrowLeft"===n?"left":"right";b=this.correctCaretPosition(u,t,w)}else if("Delete"!==n||d.test(u[t])||v.test(u[t])){if("Backspace"===n&&!d.test(u[t]))if(a<=S+1&&"-"===u[0]&&void 0===h){var O=u.substring(1);this.updateValue({formattedValue:O,caretPos:b,input:r})}else if(!v.test(u[t])){for(;!d.test(u[b-1])&&S<b;)b--;b=this.correctCaretPosition(u,b,"left")}}else for(;!d.test(u[b])&&b<x;)b++;(b!==t||t<S||x<t)&&(e.preventDefault(),this.setPatchedCaretPosition(r,b,u)),e.isUnitTestRun&&this.setPatchedCaretPosition(r,b,u),m(e)}else m(e)}},{key:"onMouseUp",value:function(e){var t=e.target,r=t.selectionStart,n=t.selectionEnd,a=t.value,o=void 0===a?"":a;if(r===n){var i=this.correctCaretPosition(o,r);i!==r&&this.setPatchedCaretPosition(t,i,o)}this.props.onMouseUp(e)}},{key:"onFocus",value:function(i){var u=this;i.persist(),this.focusedElm=i.target,this.focusTimeout=setTimeout(function(){var e=i.target,t=e.selectionStart,r=e.selectionEnd,n=e.value,a=void 0===n?"":n,o=u.correctCaretPosition(a,t);o===t||0===t&&r===a.length||u.setPatchedCaretPosition(e,o,a),u.props.onFocus(i)},0)}},{key:"render",value:function(){var e=this.props,t=e.type,r=e.displayType,n=e.customInput,a=e.renderText,o=e.getInputRef,i=e.format,u=this.state.value,s=function(t,r){var n={};return Object.keys(t).forEach(function(e){r[e]||(n[e]=t[e])}),n}(this.props,S),l=p({inputMode:function(e){return e||!(navigator.platform&&/iPhone|iPod/.test(navigator.platform))}(i)?"numeric":void 0},s,{type:t,value:u,onChange:this.onChange,onKeyDown:this.onKeyDown,onMouseUp:this.onMouseUp,onFocus:this.onFocus,onBlur:this.onBlur});if("text"===r)return a?a(u)||null:f.default.createElement("span",p({},s,{ref:o}),u);if(n){var c=n;return f.default.createElement(c,p({},l,{ref:o}))}return f.default.createElement("input",p({},l,{ref:o}))}}])}();return w.propTypes=S,w.defaultProps=x,w});