react-number-format
Advanced tools
Comparing version 3.0.0-alpha to 3.0.0-alpha2
/*! | ||
* react-number-format - 3.0.0-alpha | ||
* react-number-format - 3.0.0-alpha2 | ||
* Author : Sudhanshu Yadav | ||
@@ -522,2 +522,3 @@ * Copyright (c) 2016,2017 to Sudhanshu Yadav - ignitersworld.com , released under the MIT license. | ||
var hasNagation = numStr[0] === '-'; | ||
var addNegation = hasNagation && allowNegative; | ||
numStr = numStr.replace('-', ''); | ||
@@ -531,2 +532,7 @@ | ||
//if beforeDecimal is empty and after decimal is 0 clear the input while keeping the negation sign | ||
if (beforeDecimal === '' && !parseFloat(afterDecimal)) { | ||
return addNegation ? '-' : ''; | ||
} | ||
//remove leading zeros from number before decimal | ||
@@ -547,3 +553,3 @@ beforeDecimal = (0, _utils.removeLeadingZero)(beforeDecimal); | ||
//restore negation sign | ||
if (hasNagation && allowNegative) beforeDecimal = '-' + beforeDecimal; | ||
if (addNegation) beforeDecimal = '-' + beforeDecimal; | ||
@@ -658,10 +664,18 @@ numStr = beforeDecimal + (hasDecimalSeparator && decimalSeparator || '') + afterDecimal; | ||
prefix = _props8.prefix, | ||
suffix = _props8.suffix; | ||
suffix = _props8.suffix, | ||
decimalPrecision = _props8.decimalPrecision; | ||
var _getSeparators5 = this.getSeparators(), | ||
decimalSeparator = _getSeparators5.decimalSeparator; | ||
//check within format pattern | ||
if (typeof format === 'string' && format[caretPos] !== '#') return true; | ||
//check in number format | ||
if (!format && (caretPos < prefix.length || caretPos >= value.length - suffix.length)) return true; | ||
if (!format && (caretPos < prefix.length || caretPos >= value.length - suffix.length || decimalPrecision && value[caretPos] === decimalSeparator)) { | ||
return true; | ||
} | ||
return false; | ||
@@ -672,3 +686,2 @@ } | ||
value: function checkIfFormatGotDeleted(start, end, value) { | ||
for (var i = start; i < end; i++) { | ||
@@ -688,3 +701,2 @@ if (this.isCharacterAFormat(i, value)) return true; | ||
value: function correctInputValue(caretPos, lastValue, value) { | ||
//don't do anyhting if something got added, or if value is empty string (when whole input is cleared) | ||
@@ -691,0 +703,0 @@ if (value.length >= lastValue.length || !value.length) { |
/*! | ||
* react-number-format - 3.0.0-alpha | ||
* react-number-format - 3.0.0-alpha2 | ||
* Author : Sudhanshu Yadav | ||
* Copyright (c) 2016,2017 to Sudhanshu Yadav - ignitersworld.com , released under the MIT license. | ||
*/ | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):"object"==typeof exports?exports.NumberFormat=t(require("react")):e.NumberFormat=t(e.React)}(this,function(e){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){e.exports=r(1)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=function(){function e(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,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),f=r(2),l=n(f),c=r(7),p=n(c),h=r(8),d={thousandSeparator:l.default.oneOfType([l.default.string,l.default.oneOf([!0])]),decimalSeparator:l.default.string,decimalPrecision:l.default.number,displayType:l.default.oneOf(["input","text"]),prefix:l.default.string,suffix:l.default.string,format:l.default.oneOfType([l.default.string,l.default.func]),removeFormatting:l.default.func,mask:l.default.oneOfType([l.default.string,l.default.arrayOf(l.default.string)]),value:l.default.oneOfType([l.default.number,l.default.string]),isNumericString:l.default.bool,customInput:l.default.func,allowNegative:l.default.bool,onKeyDown:l.default.func,onMouseUp:l.default.func,onChange:l.default.func,onFocus:l.default.func,type:l.default.oneOf(["text","tel"]),isAllowed:l.default.func,renderText:l.default.func},g={displayType:"input",decimalSeparator:".",prefix:"",suffix:"",allowNegative:!0,isNumericString:!1,type:"text",onChange:h.noop,onKeyDown:h.noop,onMouseUp:h.noop,onFocus:h.noop,isAllowed:h.returnTrue},m=function(e){function t(e){o(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));r.validateProps();var n=r.formatValueProp();return r.state={value:n,numAsString:r.removeFormatting(n)},r.onChange=r.onChange.bind(r),r.onKeyDown=r.onKeyDown.bind(r),r.onMouseUp=r.onMouseUp.bind(r),r.onFocus=r.onFocus.bind(r),r}return i(t,e),s(t,[{key:"componentDidUpdate",value:function(e){this.updateValueIfRequired(e)}},{key:"updateValueIfRequired",value:function(e){var t=this.props,r=this.state;if(e!==t){this.validateProps();var n=r.value,o=r.numAsString||"",a=void 0===t.value?this.formatNumString(o).formattedValue:this.formatValueProp();a!==n&&this.setState({value:a,numAsString:this.removeFormatting(a)})}}},{key:"getFloatString",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=this.getSeparators(),r=t.decimalSeparator,n=this.getNumberRegex(!0),o="-"===e[0];o&&(e=e.replace("-","")),e=(e.match(n)||[]).join("").replace(r,".");var a=e.indexOf(".");return a!==-1&&(e=e.substring(0,a)+"."+e.substring(a+1,e.length).replace(new RegExp((0,h.escapeRegExp)(r),"g"),"")),o&&(e="-"+e),e}},{key:"getNumberRegex",value:function(e,t){var r=this.props,n=r.format,o=r.decimalPrecision,a=this.getSeparators(),i=a.decimalSeparator;return new RegExp("\\d"+(!i||0===o||t||n?"":"|"+(0,h.escapeRegExp)(i)),e?"g":void 0)}},{key:"getSeparators",value:function(){var e=this.props.decimalSeparator,t=this.props.thousandSeparator;return t===!0&&(t=","),{decimalSeparator:e,thousandSeparator:t}}},{key:"getMaskAtIndex",value:function(e){var t=this.props.mask,r=void 0===t?" ":t;return"string"==typeof r?r:r[e]||" "}},{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\n thousandSeparator: "+n+' (thousandSeparator = {true} is same as thousandSeparator = ",")\n decimalSeparator: '+r+" (default value for decimalSeparator is .)\n ");if(e){var o="string"===e?e:e.toString();if(o.match(/\d/g))throw new Error("\n Mask "+e+" should not contain numeric character;\n ")}}},{key:"setPatchedCaretPosition",value:function(e,t,r){(0,h.setCaretPosition)(e,t),setTimeout(function(){e.value===r&&(0,h.setCaretPosition)(e,t)},0)}},{key:"correctCaretPosition",value:function(e,t,r){var n=this.props,o=n.prefix,a=n.suffix,i=n.format;if(!i){var u="-"===e[0];return Math.min(Math.max(t,o.length+(u?1:0)),e.length-a.length)}if("function"==typeof i)return t;if("#"===i[t]&&(0,h.charIsNumber)(e[t]))return t;if("#"===i[t-1]&&(0,h.charIsNumber)(e[t-1]))return t;var s=i.indexOf("#"),f=i.lastIndexOf("#");t=Math.min(Math.max(t,s),f+1);for(var l=i.substring(t,i.length).indexOf("#"),c=t,p=t+(l===-1?0:l);c>s&&("#"!==i[c]||!(0,h.charIsNumber)(e[c]));)c-=1;var d=!(0,h.charIsNumber)(e[p])||"left"===r&&t!==s||t-c<p-t;return d?c+1:p}},{key:"getCaretPosition",value:function(e,t,r){var n=this.props.format,o=this.state.value,a=this.getNumberRegex(!0),i=(e.match(a)||[]).join(""),u=(t.match(a)||[]).join(""),s=void 0,f=void 0;for(s=0,f=0;f<r;f++){var l=e[f],c=t[s]||"";if((l.match(a)||l===c)&&("0"!==l||!c.match(a)||"0"===c||i.length===u.length)){for(;l!==t[s]&&s<t.length;)s++;s++}}return"string"!=typeof n||o||(s=t.length),s=this.correctCaretPosition(t,s)}},{key:"removePrefixAndSuffix",value:function(e){var t=this.props,r=t.format,n=t.prefix,o=t.suffix;if(!r&&e){var a="-"===e[0];a&&(e=e.substring(1,e.length)),e=n&&0===e.indexOf(n)?e.substring(n.length,e.length):e;var i=e.lastIndexOf(o);e=o&&i!==-1&&i===e.length-o.length?e.substring(0,i):e,a&&(e="-"+e)}return e}},{key:"removePatternFormatting",value:function(e){for(var t=this.props.format,r=t.split("#").filter(function(e){return""!==e}),n=0,o="",a=0,i=r.length;a<=i;a++){var u=r[a]||"",s=a===i?e.length:e.indexOf(u,n);if(s===-1){o=e;break}o+=e.substring(n,s),n=s+u.length}return(o.match(/\d/g)||[]).join("")}},{key:"removeFormatting",value:function e(t){var r=this.props,n=r.format,e=r.removeFormatting;return t?(n?t="string"==typeof n?this.removePatternFormatting(t):"function"==typeof e?e(t):(t.match(/\d/g)||[]).join(""):(t=this.removePrefixAndSuffix(t),t=this.getFloatString(t)),t):t}},{key:"formatWithPattern",value:function(e){for(var t=this.props.format,r=0,n=t.split(""),o=0,a=t.length;o<a;o++)"#"===t[o]&&(n[o]=e[r]||this.getMaskAtIndex(r),r+=1);return n.join("")}},{key:"formatAsNumber",value:function(e){var t=this.props,r=t.decimalPrecision,n=t.allowNegative,o=t.prefix,a=t.suffix,i=this.getSeparators(),u=i.thousandSeparator,s=i.decimalSeparator,f="-"===e[0];e=e.replace("-","");var l=e.indexOf(".")!==-1||r,c=e.split("."),p=c[0],d=c[1]||"";return p=(0,h.removeLeadingZero)(p),void 0!==r&&(d=(0,h.limitToPrecision)(d,r)),u&&(p=p.replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1"+u)),o&&(p=o+p),a&&(d+=a),f&&n&&(p="-"+p),e=p+(l&&s||"")+d}},{key:"formatNumString",value:function(e){var t=this.props.format,r=e;return""===e?r="":"-"!==e||t?r="string"==typeof t?this.formatWithPattern(r):"function"==typeof t?t(r):this.formatAsNumber(r):(r="-",e=""),{value:e,formattedValue:r}}},{key:"formatValueProp",value:function(){var e=this.props,t=e.format,r=e.decimalPrecision,n=this.props,o=n.value,a=n.isNumericString;if(void 0===o)return"";"number"==typeof o&&(o=o.toString(),a=!0),a&&!t&&"number"==typeof r&&(o=(0,h.roundToPrecision)(o,r));var i=a?this.formatNumString(o):this.formatInput(o);return i.formattedValue}},{key:"formatNegation",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=this.props.allowNegative,r=new RegExp("(-)"),n=new RegExp("(-)(.)*(-)"),o=r.test(e),a=n.test(e);return e=e.replace(/-/g,""),o&&!a&&t&&(e="-"+e),e}},{key:"formatInput",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=this.props.format;return t||(e=this.formatNegation(e)),e=this.removeFormatting(e),this.formatNumString(e)}},{key:"isCharacterAFormat",value:function(e,t){var r=this.props,n=r.format,o=r.prefix,a=r.suffix;return"string"==typeof n&&"#"!==n[e]||!n&&(e<o.length||e>=t.length-a.length)}},{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){if(r.length>=t.length||!r.length)return r;var n=e,o=(0,h.splitString)(t,e),a=(0,h.splitString)(r,e),i=o[1].lastIndexOf(a[1]),u=i!==-1?o[1].substring(0,i):"",s=n+u.length;return this.checkIfFormatGotDeleted(n,s,t)&&(r=t),r}},{key:"onChange",value:function(e){e.persist();var t=e.target,r=t.value,n=this.state,o=this.props,a=o.isAllowed,i=n.value||"",u=Math.max(t.selectionStart,t.selectionEnd);r=this.correctInputValue(u,i,r);var s=this.formatInput(r),f=s.formattedValue,l=void 0===f?"":f,c=s.value,p={formattedValue:l,value:c,floatValue:parseFloat(c)};a(p)||(l=i),t.value=l;var h=this.getCaretPosition(r,l,u);return this.setPatchedCaretPosition(t,h,l),l!==i&&this.setState({value:l,numAsString:this.removeFormatting(l)},function(){o.onChange(e,p)}),c}},{key:"onKeyDown",value:function e(t){var r=t.target,n=t.key,o=r.selectionEnd,a=r.value,i=r.selectionStart,u=void 0,s=this.props,f=s.decimalPrecision,l=s.prefix,c=s.suffix,p=s.format,e=s.onKeyDown,h=this.getNumberRegex(!1,void 0!==f),d=new RegExp("-"),g="string"==typeof p;if("ArrowLeft"===n||"Backspace"===n?u=i-1:"ArrowRight"===n?u=i+1:"Delete"===n&&(u=i),void 0===u||i!==o)return void e(t);var m=u,v=g?p.indexOf("#"):l.length,y=g?p.lastIndexOf("#")+1:a.length-c.length;if("ArrowLeft"===n||"ArrowRight"===n){var x="ArrowLeft"===n?"left":"right";m=this.correctCaretPosition(a,u,x)}else if("Delete"!==n||h.test(a[u])||d.test(a[u])){if("Backspace"===n&&!h.test(a[u])&&!d.test(a[u])){for(;!h.test(a[m-1])&&m>v;)m--;m=this.correctCaretPosition(a,m,"left")}}else for(;!h.test(a[m])&&m<y;)m++;(m!==u||u<v||u>y)&&(t.preventDefault(),this.setPatchedCaretPosition(r,m,a)),t.isUnitTestRun&&this.setPatchedCaretPosition(r,m,a),this.props.onKeyDown(t)}},{key:"onMouseUp",value:function(e){var t=e.target,r=t.selectionStart,n=t.selectionEnd,o=t.value;if(r===n){var a=this.correctCaretPosition(o,r);a!==r&&this.setPatchedCaretPosition(t,a,o)}this.props.onMouseUp(e)}},{key:"onFocus",value:function(e){var t=e.target,r=t.selectionStart,n=t.value,o=this.correctCaretPosition(n,r);o!==r&&this.setPatchedCaretPosition(t,o,n),this.props.onFocus(e)}},{key:"render",value:function(){var e=this.props,t=e.type,r=e.displayType,n=e.customInput,o=e.renderText,a=this.state.value,i=(0,h.omit)(this.props,d),s=u({},i,{type:t,value:a,onChange:this.onChange,onKeyDown:this.onKeyDown,onMouseUp:this.onMouseUp,onFocus:this.onFocus});if("text"===r)return o?o(a)||null:p.default.createElement("span",i,a);if(n){var f=n;return p.default.createElement(f,s)}return p.default.createElement("input",s)}}]),t}(p.default.Component);m.propTypes=d,m.defaultProps=g,e.exports=m},function(e,t,r){e.exports=r(3)()},function(e,t,r){"use strict";var n=r(4),o=r(5),a=r(6);e.exports=function(){function e(e,t,r,n,i,u){u!==a&&o(!1,"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")}function t(){return e}e.isRequired=e;var r={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t};return r.checkPropTypes=n,r.PropTypes=r,r}},function(e,t){"use strict";function r(e){return function(){return e}}var n=function(){};n.thatReturns=r,n.thatReturnsFalse=r(!1),n.thatReturnsTrue=r(!0),n.thatReturnsNull=r(null),n.thatReturnsThis=function(){return this},n.thatReturnsArgument=function(e){return e},e.exports=n},function(e,t,r){"use strict";function n(e,t,r,n,a,i,u,s){if(o(t),!e){var f;if(void 0===t)f=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[r,n,a,i,u,s],c=0;f=new Error(t.replace(/%s/g,function(){return l[c++]})),f.name="Invariant Violation"}throw f.framesToPop=1,f}}var o=function(e){};e.exports=n},function(e,t){"use strict";var r="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";e.exports=r},function(t,r){t.exports=e},function(e,t){"use strict";function r(){}function n(){return!0}function o(e){return!!(e||"").match(/\d/)}function a(e){return e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}function i(e){return e.replace(/^0+/,"")||"0"}function u(e,t){return[e.substring(0,t),e.substring(t)]}function s(e,t){for(var r="",n=0;n<=t-1;n++)r+=e[n]||"0";return r}function f(e,t){var r=e.split("."),n=parseFloat("0."+(r[1]||"0")).toFixed(t).split("."),o=r[0].split("").reverse().reduce(function(e,t,r){return e.length>r?(Number(e[0])+Number(t)).toString()+e.substring(1,e.length):t+e},n[0]),a=n[1];return o+(a?"."+a:"")}function l(e,t){var r={};return Object.keys(e).forEach(function(n){t[n]||(r[n]=e[n])}),r}function c(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)}}Object.defineProperty(t,"__esModule",{value:!0}),t.noop=r,t.returnTrue=n,t.charIsNumber=o,t.escapeRegExp=a,t.removeLeadingZero=i,t.splitString=u,t.limitToPrecision=s,t.roundToPrecision=f,t.omit=l,t.setCaretPosition=c}])}); | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):"object"==typeof exports?exports.NumberFormat=t(require("react")):e.NumberFormat=t(e.React)}(this,function(e){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){e.exports=r(1)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=function(){function e(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,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),f=r(2),l=n(f),c=r(7),p=n(c),h=r(8),d={thousandSeparator:l.default.oneOfType([l.default.string,l.default.oneOf([!0])]),decimalSeparator:l.default.string,decimalPrecision:l.default.number,displayType:l.default.oneOf(["input","text"]),prefix:l.default.string,suffix:l.default.string,format:l.default.oneOfType([l.default.string,l.default.func]),removeFormatting:l.default.func,mask:l.default.oneOfType([l.default.string,l.default.arrayOf(l.default.string)]),value:l.default.oneOfType([l.default.number,l.default.string]),isNumericString:l.default.bool,customInput:l.default.func,allowNegative:l.default.bool,onKeyDown:l.default.func,onMouseUp:l.default.func,onChange:l.default.func,onFocus:l.default.func,type:l.default.oneOf(["text","tel"]),isAllowed:l.default.func,renderText:l.default.func},m={displayType:"input",decimalSeparator:".",prefix:"",suffix:"",allowNegative:!0,isNumericString:!1,type:"text",onChange:h.noop,onKeyDown:h.noop,onMouseUp:h.noop,onFocus:h.noop,isAllowed:h.returnTrue},g=function(e){function t(e){o(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));r.validateProps();var n=r.formatValueProp();return r.state={value:n,numAsString:r.removeFormatting(n)},r.onChange=r.onChange.bind(r),r.onKeyDown=r.onKeyDown.bind(r),r.onMouseUp=r.onMouseUp.bind(r),r.onFocus=r.onFocus.bind(r),r}return i(t,e),s(t,[{key:"componentDidUpdate",value:function(e){this.updateValueIfRequired(e)}},{key:"updateValueIfRequired",value:function(e){var t=this.props,r=this.state;if(e!==t){this.validateProps();var n=r.value,o=r.numAsString||"",a=void 0===t.value?this.formatNumString(o).formattedValue:this.formatValueProp();a!==n&&this.setState({value:a,numAsString:this.removeFormatting(a)})}}},{key:"getFloatString",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=this.getSeparators(),r=t.decimalSeparator,n=this.getNumberRegex(!0),o="-"===e[0];o&&(e=e.replace("-","")),e=(e.match(n)||[]).join("").replace(r,".");var a=e.indexOf(".");return a!==-1&&(e=e.substring(0,a)+"."+e.substring(a+1,e.length).replace(new RegExp((0,h.escapeRegExp)(r),"g"),"")),o&&(e="-"+e),e}},{key:"getNumberRegex",value:function(e,t){var r=this.props,n=r.format,o=r.decimalPrecision,a=this.getSeparators(),i=a.decimalSeparator;return new RegExp("\\d"+(!i||0===o||t||n?"":"|"+(0,h.escapeRegExp)(i)),e?"g":void 0)}},{key:"getSeparators",value:function(){var e=this.props.decimalSeparator,t=this.props.thousandSeparator;return t===!0&&(t=","),{decimalSeparator:e,thousandSeparator:t}}},{key:"getMaskAtIndex",value:function(e){var t=this.props.mask,r=void 0===t?" ":t;return"string"==typeof r?r:r[e]||" "}},{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\n thousandSeparator: "+n+' (thousandSeparator = {true} is same as thousandSeparator = ",")\n decimalSeparator: '+r+" (default value for decimalSeparator is .)\n ");if(e){var o="string"===e?e:e.toString();if(o.match(/\d/g))throw new Error("\n Mask "+e+" should not contain numeric character;\n ")}}},{key:"setPatchedCaretPosition",value:function(e,t,r){(0,h.setCaretPosition)(e,t),setTimeout(function(){e.value===r&&(0,h.setCaretPosition)(e,t)},0)}},{key:"correctCaretPosition",value:function(e,t,r){var n=this.props,o=n.prefix,a=n.suffix,i=n.format;if(!i){var u="-"===e[0];return Math.min(Math.max(t,o.length+(u?1:0)),e.length-a.length)}if("function"==typeof i)return t;if("#"===i[t]&&(0,h.charIsNumber)(e[t]))return t;if("#"===i[t-1]&&(0,h.charIsNumber)(e[t-1]))return t;var s=i.indexOf("#"),f=i.lastIndexOf("#");t=Math.min(Math.max(t,s),f+1);for(var l=i.substring(t,i.length).indexOf("#"),c=t,p=t+(l===-1?0:l);c>s&&("#"!==i[c]||!(0,h.charIsNumber)(e[c]));)c-=1;var d=!(0,h.charIsNumber)(e[p])||"left"===r&&t!==s||t-c<p-t;return d?c+1:p}},{key:"getCaretPosition",value:function(e,t,r){var n=this.props.format,o=this.state.value,a=this.getNumberRegex(!0),i=(e.match(a)||[]).join(""),u=(t.match(a)||[]).join(""),s=void 0,f=void 0;for(s=0,f=0;f<r;f++){var l=e[f],c=t[s]||"";if((l.match(a)||l===c)&&("0"!==l||!c.match(a)||"0"===c||i.length===u.length)){for(;l!==t[s]&&s<t.length;)s++;s++}}return"string"!=typeof n||o||(s=t.length),s=this.correctCaretPosition(t,s)}},{key:"removePrefixAndSuffix",value:function(e){var t=this.props,r=t.format,n=t.prefix,o=t.suffix;if(!r&&e){var a="-"===e[0];a&&(e=e.substring(1,e.length)),e=n&&0===e.indexOf(n)?e.substring(n.length,e.length):e;var i=e.lastIndexOf(o);e=o&&i!==-1&&i===e.length-o.length?e.substring(0,i):e,a&&(e="-"+e)}return e}},{key:"removePatternFormatting",value:function(e){for(var t=this.props.format,r=t.split("#").filter(function(e){return""!==e}),n=0,o="",a=0,i=r.length;a<=i;a++){var u=r[a]||"",s=a===i?e.length:e.indexOf(u,n);if(s===-1){o=e;break}o+=e.substring(n,s),n=s+u.length}return(o.match(/\d/g)||[]).join("")}},{key:"removeFormatting",value:function e(t){var r=this.props,n=r.format,e=r.removeFormatting;return t?(n?t="string"==typeof n?this.removePatternFormatting(t):"function"==typeof e?e(t):(t.match(/\d/g)||[]).join(""):(t=this.removePrefixAndSuffix(t),t=this.getFloatString(t)),t):t}},{key:"formatWithPattern",value:function(e){for(var t=this.props.format,r=0,n=t.split(""),o=0,a=t.length;o<a;o++)"#"===t[o]&&(n[o]=e[r]||this.getMaskAtIndex(r),r+=1);return n.join("")}},{key:"formatAsNumber",value:function(e){var t=this.props,r=t.decimalPrecision,n=t.allowNegative,o=t.prefix,a=t.suffix,i=this.getSeparators(),u=i.thousandSeparator,s=i.decimalSeparator,f="-"===e[0],l=f&&n;e=e.replace("-","");var c=e.indexOf(".")!==-1||r,p=e.split("."),d=p[0],m=p[1]||"";return""!==d||parseFloat(m)?(d=(0,h.removeLeadingZero)(d),void 0!==r&&(m=(0,h.limitToPrecision)(m,r)),u&&(d=d.replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1"+u)),o&&(d=o+d),a&&(m+=a),l&&(d="-"+d),e=d+(c&&s||"")+m):l?"-":""}},{key:"formatNumString",value:function(e){var t=this.props.format,r=e;return""===e?r="":"-"!==e||t?r="string"==typeof t?this.formatWithPattern(r):"function"==typeof t?t(r):this.formatAsNumber(r):(r="-",e=""),{value:e,formattedValue:r}}},{key:"formatValueProp",value:function(){var e=this.props,t=e.format,r=e.decimalPrecision,n=this.props,o=n.value,a=n.isNumericString;if(void 0===o)return"";"number"==typeof o&&(o=o.toString(),a=!0),a&&!t&&"number"==typeof r&&(o=(0,h.roundToPrecision)(o,r));var i=a?this.formatNumString(o):this.formatInput(o);return i.formattedValue}},{key:"formatNegation",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=this.props.allowNegative,r=new RegExp("(-)"),n=new RegExp("(-)(.)*(-)"),o=r.test(e),a=n.test(e);return e=e.replace(/-/g,""),o&&!a&&t&&(e="-"+e),e}},{key:"formatInput",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=this.props.format;return t||(e=this.formatNegation(e)),e=this.removeFormatting(e),this.formatNumString(e)}},{key:"isCharacterAFormat",value:function(e,t){var r=this.props,n=r.format,o=r.prefix,a=r.suffix,i=r.decimalPrecision,u=this.getSeparators(),s=u.decimalSeparator;return"string"==typeof n&&"#"!==n[e]||!(n||!(e<o.length||e>=t.length-a.length||i&&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){if(r.length>=t.length||!r.length)return r;var n=e,o=(0,h.splitString)(t,e),a=(0,h.splitString)(r,e),i=o[1].lastIndexOf(a[1]),u=i!==-1?o[1].substring(0,i):"",s=n+u.length;return this.checkIfFormatGotDeleted(n,s,t)&&(r=t),r}},{key:"onChange",value:function(e){e.persist();var t=e.target,r=t.value,n=this.state,o=this.props,a=o.isAllowed,i=n.value||"",u=Math.max(t.selectionStart,t.selectionEnd);r=this.correctInputValue(u,i,r);var s=this.formatInput(r),f=s.formattedValue,l=void 0===f?"":f,c=s.value,p={formattedValue:l,value:c,floatValue:parseFloat(c)};a(p)||(l=i),t.value=l;var h=this.getCaretPosition(r,l,u);return this.setPatchedCaretPosition(t,h,l),l!==i&&this.setState({value:l,numAsString:this.removeFormatting(l)},function(){o.onChange(e,p)}),c}},{key:"onKeyDown",value:function e(t){var r=t.target,n=t.key,o=r.selectionEnd,a=r.value,i=r.selectionStart,u=void 0,s=this.props,f=s.decimalPrecision,l=s.prefix,c=s.suffix,p=s.format,e=s.onKeyDown,h=this.getNumberRegex(!1,void 0!==f),d=new RegExp("-"),m="string"==typeof p;if("ArrowLeft"===n||"Backspace"===n?u=i-1:"ArrowRight"===n?u=i+1:"Delete"===n&&(u=i),void 0===u||i!==o)return void e(t);var g=u,v=m?p.indexOf("#"):l.length,y=m?p.lastIndexOf("#")+1:a.length-c.length;if("ArrowLeft"===n||"ArrowRight"===n){var x="ArrowLeft"===n?"left":"right";g=this.correctCaretPosition(a,u,x)}else if("Delete"!==n||h.test(a[u])||d.test(a[u])){if("Backspace"===n&&!h.test(a[u])&&!d.test(a[u])){for(;!h.test(a[g-1])&&g>v;)g--;g=this.correctCaretPosition(a,g,"left")}}else for(;!h.test(a[g])&&g<y;)g++;(g!==u||u<v||u>y)&&(t.preventDefault(),this.setPatchedCaretPosition(r,g,a)),t.isUnitTestRun&&this.setPatchedCaretPosition(r,g,a),this.props.onKeyDown(t)}},{key:"onMouseUp",value:function(e){var t=e.target,r=t.selectionStart,n=t.selectionEnd,o=t.value;if(r===n){var a=this.correctCaretPosition(o,r);a!==r&&this.setPatchedCaretPosition(t,a,o)}this.props.onMouseUp(e)}},{key:"onFocus",value:function(e){var t=e.target,r=t.selectionStart,n=t.value,o=this.correctCaretPosition(n,r);o!==r&&this.setPatchedCaretPosition(t,o,n),this.props.onFocus(e)}},{key:"render",value:function(){var e=this.props,t=e.type,r=e.displayType,n=e.customInput,o=e.renderText,a=this.state.value,i=(0,h.omit)(this.props,d),s=u({},i,{type:t,value:a,onChange:this.onChange,onKeyDown:this.onKeyDown,onMouseUp:this.onMouseUp,onFocus:this.onFocus});if("text"===r)return o?o(a)||null:p.default.createElement("span",i,a);if(n){var f=n;return p.default.createElement(f,s)}return p.default.createElement("input",s)}}]),t}(p.default.Component);g.propTypes=d,g.defaultProps=m,e.exports=g},function(e,t,r){e.exports=r(3)()},function(e,t,r){"use strict";var n=r(4),o=r(5),a=r(6);e.exports=function(){function e(e,t,r,n,i,u){u!==a&&o(!1,"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")}function t(){return e}e.isRequired=e;var r={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t};return r.checkPropTypes=n,r.PropTypes=r,r}},function(e,t){"use strict";function r(e){return function(){return e}}var n=function(){};n.thatReturns=r,n.thatReturnsFalse=r(!1),n.thatReturnsTrue=r(!0),n.thatReturnsNull=r(null),n.thatReturnsThis=function(){return this},n.thatReturnsArgument=function(e){return e},e.exports=n},function(e,t,r){"use strict";function n(e,t,r,n,a,i,u,s){if(o(t),!e){var f;if(void 0===t)f=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[r,n,a,i,u,s],c=0;f=new Error(t.replace(/%s/g,function(){return l[c++]})),f.name="Invariant Violation"}throw f.framesToPop=1,f}}var o=function(e){};e.exports=n},function(e,t){"use strict";var r="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";e.exports=r},function(t,r){t.exports=e},function(e,t){"use strict";function r(){}function n(){return!0}function o(e){return!!(e||"").match(/\d/)}function a(e){return e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}function i(e){return e.replace(/^0+/,"")||"0"}function u(e,t){return[e.substring(0,t),e.substring(t)]}function s(e,t){for(var r="",n=0;n<=t-1;n++)r+=e[n]||"0";return r}function f(e,t){var r=e.split("."),n=parseFloat("0."+(r[1]||"0")).toFixed(t).split("."),o=r[0].split("").reverse().reduce(function(e,t,r){return e.length>r?(Number(e[0])+Number(t)).toString()+e.substring(1,e.length):t+e},n[0]),a=n[1];return o+(a?"."+a:"")}function l(e,t){var r={};return Object.keys(e).forEach(function(n){t[n]||(r[n]=e[n])}),r}function c(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)}}Object.defineProperty(t,"__esModule",{value:!0}),t.noop=r,t.returnTrue=n,t.charIsNumber=o,t.escapeRegExp=a,t.removeLeadingZero=i,t.splitString=u,t.limitToPrecision=s,t.roundToPrecision=f,t.omit=l,t.setCaretPosition=c}])}); |
@@ -49,3 +49,2 @@ import React from 'react'; | ||
prefix="$" | ||
decimalPrecision={3} | ||
onChange={(e) => this.setState({test: e.target.value})} | ||
@@ -52,0 +51,0 @@ /> |
@@ -454,2 +454,3 @@ 'use strict'; | ||
var hasNagation = numStr[0] === '-'; | ||
var addNegation = hasNagation && allowNegative; | ||
numStr = numStr.replace('-', ''); | ||
@@ -463,2 +464,7 @@ | ||
//if beforeDecimal is empty and after decimal is 0 clear the input while keeping the negation sign | ||
if (beforeDecimal === '' && !parseFloat(afterDecimal)) { | ||
return addNegation ? '-' : ''; | ||
} | ||
//remove leading zeros from number before decimal | ||
@@ -479,3 +485,3 @@ beforeDecimal = (0, _utils.removeLeadingZero)(beforeDecimal); | ||
//restore negation sign | ||
if (hasNagation && allowNegative) beforeDecimal = '-' + beforeDecimal; | ||
if (addNegation) beforeDecimal = '-' + beforeDecimal; | ||
@@ -590,10 +596,18 @@ numStr = beforeDecimal + (hasDecimalSeparator && decimalSeparator || '') + afterDecimal; | ||
prefix = _props8.prefix, | ||
suffix = _props8.suffix; | ||
suffix = _props8.suffix, | ||
decimalPrecision = _props8.decimalPrecision; | ||
var _getSeparators5 = this.getSeparators(), | ||
decimalSeparator = _getSeparators5.decimalSeparator; | ||
//check within format pattern | ||
if (typeof format === 'string' && format[caretPos] !== '#') return true; | ||
//check in number format | ||
if (!format && (caretPos < prefix.length || caretPos >= value.length - suffix.length)) return true; | ||
if (!format && (caretPos < prefix.length || caretPos >= value.length - suffix.length || decimalPrecision && value[caretPos] === decimalSeparator)) { | ||
return true; | ||
} | ||
return false; | ||
@@ -604,3 +618,2 @@ } | ||
value: function checkIfFormatGotDeleted(start, end, value) { | ||
for (var i = start; i < end; i++) { | ||
@@ -620,3 +633,2 @@ if (this.isCharacterAFormat(i, value)) return true; | ||
value: function correctInputValue(caretPos, lastValue, value) { | ||
//don't do anyhting if something got added, or if value is empty string (when whole input is cleared) | ||
@@ -838,2 +850,2 @@ if (value.length >= lastValue.length || !value.length) { | ||
module.exports = NumberFormat; | ||
module.exports = NumberFormat; |
{ | ||
"name": "react-number-format", | ||
"description": "React component to format number in an input or as a text.", | ||
"version": "3.0.0-alpha", | ||
"version": "3.0.0-alpha2", | ||
"main": "lib/number_format.js", | ||
@@ -28,3 +28,3 @@ "author": "Sudhanshu Yadav", | ||
"bundle": "cross-env NODE_ENV=production npm run compile && cross-env NODE_ENV=production webpack --config webpack.bundle.config.js && cross-env NODE_ENV=production karma start", | ||
"compile": "cross-env NODE_ENV=production babel src/number_format.js --out-file lib/number_format.js", | ||
"compile": "cross-env NODE_ENV=production babel src --out-dir lib", | ||
"test": "cross-env NODE_ENV=test karma start" | ||
@@ -31,0 +31,0 @@ }, |
@@ -39,2 +39,3 @@ # react-number-format | ||
| renderText | (formattedValue) => React Element | null | A renderText method useful if you want to render formattedValue in different element other than span. | | ||
**Other than this it accepts all the props which can be given to a input or span based on displayType you selected.** | ||
@@ -188,3 +189,3 @@ | ||
- Fixed caret position issues. | ||
- Lot of bugs and stability fixes ([See release notes](https://github.com/s-yadav/react-number-format/releases)) | ||
- Lot of bugs and stability fixes ([See v3 tracker](https://github.com/s-yadav/react-number-format/issues/99)) | ||
@@ -191,0 +192,0 @@ ### v2.0.0 |
@@ -396,2 +396,3 @@ //@flow | ||
const hasNagation = numStr[0] === '-'; | ||
const addNegation = hasNagation && allowNegative; | ||
numStr = numStr.replace('-', ''); | ||
@@ -405,2 +406,7 @@ | ||
//if beforeDecimal is empty and after decimal is 0 clear the input while keeping the negation sign | ||
if (beforeDecimal === '' && !parseFloat(afterDecimal)) { | ||
return addNegation ? '-' : ''; | ||
} | ||
//remove leading zeros from number before decimal | ||
@@ -421,3 +427,3 @@ beforeDecimal = removeLeadingZero(beforeDecimal); | ||
//restore negation sign | ||
if (hasNagation && allowNegative) beforeDecimal = '-' + beforeDecimal; | ||
if (addNegation) beforeDecimal = '-' + beforeDecimal; | ||
@@ -513,3 +519,4 @@ numStr = beforeDecimal + (hasDecimalSeparator && decimalSeparator || '') + afterDecimal; | ||
isCharacterAFormat(caretPos: number, value: string) { | ||
const {format, prefix, suffix} = this.props; | ||
const {format, prefix, suffix, decimalPrecision} = this.props; | ||
const {decimalSeparator} = this.getSeparators(); | ||
@@ -520,7 +527,13 @@ //check within format pattern | ||
//check in number format | ||
if (!format && (caretPos < prefix.length || caretPos >= value.length - suffix.length)) return true; | ||
if (!format && (caretPos < prefix.length | ||
|| caretPos >= value.length - suffix.length | ||
|| (decimalPrecision && value[caretPos] === decimalSeparator)) | ||
) { | ||
return true; | ||
} | ||
return false; | ||
} | ||
checkIfFormatGotDeleted(start: number, end: number, value: string) { | ||
for (let i = start; i < end; i++) { | ||
@@ -537,3 +550,2 @@ if (this.isCharacterAFormat(i, value)) return true; | ||
correctInputValue(caretPos: number, lastValue: string, value: string) { | ||
//don't do anyhting if something got added, or if value is empty string (when whole input is cleared) | ||
@@ -540,0 +552,0 @@ if (value.length >= lastValue.length || !value.length) { |
@@ -183,2 +183,3 @@ import React from 'react'; | ||
//case 4th - no decimal should round with 4 zeros | ||
input.simulate('change', getCustomEvent('')); | ||
input.simulate('change', getCustomEvent('4111')); | ||
@@ -265,2 +266,19 @@ expect(wrapper.state().value).toEqual('4111.0000'); | ||
it('should allow deleting all numbers when decimalPrecision is defined', () => { | ||
const wrapper = shallow(<NumberFormat prefix="$" decimalPrecision={3} value="$1.000"/>); | ||
simulateKeyInput(wrapper.find('input'), 'Backspace', 2); | ||
expect(wrapper.state().value).toEqual('') | ||
}) | ||
it('should not allow to remove decimalSeparator if decimalPrecision is defined', () => { | ||
const wrapper = shallow(<NumberFormat prefix="$" thousandSeparator={true} decimalPrecision={3} value="$1,234.000"/>); | ||
simulateKeyInput(wrapper.find('input'), 'Backspace', 7); | ||
expect(wrapper.state().value).toEqual('$1,234.000'); | ||
wrapper.setProps({decimalPrecision: undefined}) | ||
wrapper.update(); | ||
simulateKeyInput(wrapper.find('input'), 'Backspace', 7); | ||
expect(wrapper.state().value).toEqual('$1,234,000'); | ||
}); | ||
it('should not round by default', () => { | ||
@@ -267,0 +285,0 @@ const wrapper = shallow(<NumberFormat/>); |
@@ -7,3 +7,3 @@ module.exports = { | ||
}, | ||
devtool: "cheap-eval-source-map", | ||
devtool: "eval-source-map", | ||
debug: true, | ||
@@ -10,0 +10,0 @@ output: { |
341153
31
3788
213