react-number-format-datagrid-stable-version
Version:
React component to format number in an input or as a text.
2 lines (1 loc) • 15.3 kB
JavaScript
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("react")):"function"==typeof define&&define.amd?define(["react"],e):(t=t||self).NumberFormat=e(t.React)}(this,function(h){"use strict";function t(){}function f(t){return!!(t||"").match(/\d/)}function c(t){return null==t}function s(t){return t.replace(/[-[\]/{}()*+?.\\^$|]/g,"\\$&")}function j(t,e){void 0===e&&(e=!0);var r="-"===t[0],o=r&&e,n=(t=t.replace("-","")).split(".");return{beforeDecimal:n[0],afterDecimal:n[1]||"",hasNagation:r,addNegation:o}}function d(t,e,r){for(var o="",n=r?"0":"",a=0;a<=e-1;a++)o+=t[a]||n;return o}function p(t,e){return Array(e+1).join(t)}function n(t,e){if(t.value=t.value,null!==t){if(t.createTextRange){var r=t.createTextRange();return r.move("character",e),r.select(),!0}return t.selectionStart||0===t.selectionStart?(t.focus(),t.setSelectionRange(e,e),!0):(t.focus(),!1)}}function m(t,e,r){return Math.min(Math.max(t,e),r)}function g(t){return Math.max(t.selectionStart,t.selectionEnd)}var e={displayType:"input",decimalSeparator:".",thousandsGroupStyle:"thousand",fixedDecimalScale:!1,prefix:"",suffix:"",allowNegative:!0,allowEmptyFormatting:!1,allowLeadingZeros:!1,isNumericString:!1,type:"text",onValueChange:t,onChange:t,onKeyDown:t,onMouseUp:t,onFocus:t,onBlur:t,isAllowed:function(){return!0}},r=function(o){function t(t){o.call(this,t);var e=t.defaultValue;this.validateProps();var r=this.formatValueProp(e);this.state={value:r,numAsString:this.removeFormatting(r),mounted:!1},this.selectionBeforeInput={selectionStart:0,selectionEnd:0},this.onChange=this.onChange.bind(this),this.onKeyDown=this.onKeyDown.bind(this),this.onMouseUp=this.onMouseUp.bind(this),this.onFocus=this.onFocus.bind(this),this.onBlur=this.onBlur.bind(this)}return o&&(t.__proto__=o),((t.prototype=Object.create(o&&o.prototype)).constructor=t).prototype.componentDidMount=function(){this.setState({mounted:!0})},t.prototype.componentDidUpdate=function(t){this.updateValueIfRequired(t)},t.prototype.componentWillUnmount=function(){clearTimeout(this.focusTimeout),clearTimeout(this.caretPositionTimeout)},t.prototype.updateValueIfRequired=function(t){var e=this.props,r=this.state,o=this.focusedElm,n=r.value,a=r.numAsString;if(void 0===a&&(a=""),t!==e){this.validateProps();var i=this.formatNumString(a),s=c(e.value)?i:this.formatValueProp(),u=this.removeFormatting(s),l=parseFloat(u),p=parseFloat(a);(isNaN(l)&&isNaN(p)||l===p)&&i===n&&(null!==o||s===n)||this.updateValue({formattedValue:s,numAsString:u,input:o,source:"prop",event:null})}},t.prototype.getFloatString=function(t){void 0===t&&(t="");var e=this.props.decimalScale,r=this.getSeparators().decimalSeparator,o=this.getNumberRegex(!0),n="-"===t[0];n&&(t=t.replace("-","")),r&&0===e&&(t=t.split(r)[0]);var a=(t=(t.match(o)||[]).join("").replace(r,".")).indexOf(".");return-1!==a&&(t=t.substring(0,a)+"."+t.substring(a+1,t.length).replace(new RegExp(s(r),"g"),"")),n&&(t="-"+t),t},t.prototype.getNumberRegex=function(t,e){var r=this.props,o=r.format,n=r.decimalScale,a=r.customNumerals,i=this.getSeparators().decimalSeparator;return new RegExp("[0-9"+(a?a.join(""):"")+"]"+(!i||0===n||e||o?"":"|"+s(i)),t?"g":void 0)},t.prototype.getSeparators=function(){var t=this.props.decimalSeparator,e=this.props,r=e.thousandSeparator,o=e.allowedDecimalSeparators;return!0===r&&(r=","),{decimalSeparator:t,thousandSeparator:r,allowedDecimalSeparators:o=o||[t,"."]}},t.prototype.getMaskAtIndex=function(t){var e=this.props.mask;return void 0===e&&(e=" "),"string"==typeof e?e:e[t]||" "},t.prototype.getValueObject=function(t,e){var r=parseFloat(e);return{formattedValue:t,value:e,floatValue:isNaN(r)?void 0:r}},t.prototype.validateProps=function(){var t=this.props.mask,e=this.getSeparators(),r=e.decimalSeparator,o=e.thousandSeparator;if(r===o)throw new Error("\n Decimal separator can't be same as thousand separator.\n thousandSeparator: "+o+' (thousandSeparator = {true} is same as thousandSeparator = ",")\n decimalSeparator: '+r+" (default value for decimalSeparator is .)\n ");if(t&&("string"===t?t:t.toString()).match(/\d/g))throw new Error("\n Mask "+t+" should not contain numeric character;\n ")},t.prototype.setPatchedCaretPosition=function(t,e,r){n(t,e),this.caretPositionTimeout=setTimeout(function(){t.value===r&&n(t,e)},0)},t.prototype.correctCaretPosition=function(t,e,r){var o=this.props,n=o.prefix,a=o.suffix,i=o.format;if(""===t)return 0;if(e=m(e,0,t.length),!i){var s="-"===t[0];return m(e,n.length+(s?1:0),t.length-a.length)}if("function"==typeof i)return e;if("#"===i[e]&&f(t[e]))return e;if("#"===i[e-1]&&f(t[e-1]))return e;var u=i.indexOf("#");e=m(e,u,i.lastIndexOf("#")+1);for(var l=i.substring(e,i.length).indexOf("#"),p=e,c=e+(-1===l?0:l);u<p&&("#"!==i[p]||!f(t[p]));)p-=1;return!f(t[c])||"left"===r&&e!==u||e-p<c-e?f(t[p])?p+1:p:c},t.prototype.getCaretPosition=function(t,e,r){var o,n,a=this.props.format,i=this.state.value,s=this.getNumberRegex(!0),u=(t.match(s)||[]).join(""),l=(e.match(s)||[]).join("");for(n=o=0;n<r;n++){var p=t[n]||"",c=e[o]||"";if((p.match(s)||p===c)&&("0"!==p||!c.match(s)||"0"===c||u.length===l.length)){for(;p!==e[o]&&o<e.length;)o++;o++}}return"string"!=typeof a||i||(o=e.length),o=this.correctCaretPosition(e,o)},t.prototype.removePrefixAndSuffix=function(t){var e=this.props,r=e.format,o=e.prefix,n=e.suffix;if(!r&&t){var a="-"===t[0];a&&(t=t.substring(1,t.length));var i=(t=o&&0===t.indexOf(o)?t.substring(o.length,t.length):t).lastIndexOf(n);t=n&&-1!==i&&i===t.length-n.length?t.substring(0,i):t,a&&(t="-"+t)}return t},t.prototype.removePatternFormatting=function(t){for(var e=this.props.format.split("#").filter(function(t){return""!==t}),r=0,o="",n=0,a=e.length;n<=a;n++){var i=e[n]||"",s=n===a?t.length:t.indexOf(i,r);if(-1===s){o=t;break}o+=t.substring(r,s),r=s+i.length}return(o.match(this.getNumberRegex(!0))||[]).join("")},t.prototype.removeFormatting=function(t){var e=this.props,r=e.format,o=e.removeFormatting;return t?t=r?"string"==typeof r?this.removePatternFormatting(t):"function"==typeof o?o(t):(t.match(this.getNumberRegex(!0))||[]).join(""):(t=this.removePrefixAndSuffix(t),this.getFloatString(t)):t},t.prototype.formatWithPattern=function(t){for(var e=this.props.format,r=0,o=e.split(""),n=0,a=e.length;n<a;n++)"#"===e[n]&&(o[n]=t[r]||this.getMaskAtIndex(r),r+=1);return o.join("")},t.prototype.formatAsNumber=function(t){var e=this.props,r=e.decimalScale,o=e.fixedDecimalScale,n=e.prefix,a=e.suffix,i=e.allowNegative,s=e.thousandsGroupStyle,u=this.getSeparators(),l=u.thousandSeparator,p=u.decimalSeparator,c=-1!==t.indexOf(".")||r&&o,f=j(t,i),h=f.beforeDecimal,m=f.afterDecimal,g=f.addNegation;return void 0!==r&&(m=d(m,r,o)),l&&(h=function(t,e,r){var o=function(t){switch(t){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),n=t.search(/[1-9]/);return n=-1===n?t.length:n,t.substring(0,n)+t.substring(n,t.length).replace(o,"$1"+e)}(h,l,s)),n&&(h=n+h),a&&(m+=a),g&&(h="-"+h),t=h+(c&&p||"")+m},t.prototype.formatNumString=function(t){void 0===t&&(t="");var e=this.props,r=e.format,o=e.allowEmptyFormatting,n=e.customNumerals,a=t;if(n&&10===n.length){var i=new RegExp("["+n.join("")+"]","g");a=t.replace(i,function(t){return n.indexOf(t).toString()})}return a=""!==t||o?"-"!==t||r?"string"==typeof r?this.formatWithPattern(a):"function"==typeof r?r(a):this.formatAsNumber(a):"-":""},t.prototype.formatValueProp=function(t){var e=this.props,r=e.format,o=e.decimalScale,n=e.fixedDecimalScale,a=e.allowEmptyFormatting,i=this.props,s=i.value,u=i.isNumericString,l=!(s=c(s)?t:s)&&0!==s;return l&&a&&(s=""),l&&!a?"":("number"==typeof s&&(s=function(t){var e="-"===(t+="")[0]?"-":"";e&&(t=t.substring(1));var r=t.split(/[eE]/g),o=r[0],n=r[1];if(!(n=Number(n)))return e+o;var a=1+n,i=(o=o.replace(".","")).length;return a<0?o="0."+p("0",Math.abs(a))+o:i<=a?o+=p("0",a-i):o=(o.substring(0,a)||"0")+"."+o.substring(a),e+o}(s),u=!0),"Infinity"===s&&u&&(s=""),u&&!r&&"number"==typeof o&&(s=function(t,e,r){if(-1!==["","-"].indexOf(t))return t;var o=-1!==t.indexOf(".")&&e,n=j(t),a=n.beforeDecimal,i=n.afterDecimal,s=n.hasNagation,u=parseFloat("0."+(i||"0")),l=(i.length<=e?"0."+i:u.toFixed(e)).split(".");return(s?"-":"")+a.split("").reverse().reduce(function(t,e,r){return t.length>r?(Number(t[0])+Number(e)).toString()+t.substring(1,t.length):e+t},l[0])+(o?".":"")+d(l[1]||"",Math.min(e,i.length),r)}(s,o,n)),u?this.formatNumString(s):this.formatInput(s))},t.prototype.formatNegation=function(t){void 0===t&&(t="");var e=this.props.allowNegative,r=new RegExp("(-)"),o=new RegExp("(-)(.)*(-)"),n=r.test(t),a=o.test(t);return t=t.replace(/-/g,""),n&&!a&&e&&(t="-"+t),t},t.prototype.formatInput=function(t){return void 0===t&&(t=""),this.props.format||(t=this.removePrefixAndSuffix(t),t=this.formatNegation(t)),t=this.removeFormatting(t),this.formatNumString(t)},t.prototype.isCharacterAFormat=function(t,e){var r=this.props,o=r.format,n=r.prefix,a=r.suffix,i=r.decimalScale,s=r.fixedDecimalScale,u=this.getSeparators().decimalSeparator;return"string"==typeof o&&"#"!==o[t]||!(o||!(t<n.length||t>=e.length-a.length||i&&s&&e[t]===u))},t.prototype.correctInputValue=function(t,r,e){var o=this,n=this.props,a=n.format,i=n.allowNegative,s=n.prefix,u=n.suffix,l=n.decimalScale,p=this.getSeparators(),c=p.allowedDecimalSeparators,f=p.decimalSeparator,h=this.state.numAsString||"",m=this.selectionBeforeInput,g=m.selectionStart,d=m.selectionEnd,v=function(t,e){for(var r=0,o=0,n=t.length,a=e.length;t[r]===e[r]&&r<n;)r++;for(;t[n-1-o]===e[a-1-o]&&r<a-o&&r<n-o;)o++;return{start:r,end:n-o}}(r,e),S=v.start,y=v.end;if(!a&&S===y&&-1!==c.indexOf(e[g])){var x=0===l?"":f;return e.substr(0,g)+x+e.substr(g+1,e.length)}var b=a?0:s.length,w=r.length-(a?0:u.length);if(e.length>r.length||!e.length||S===y||0===g&&d===r.length||0===S&&y===r.length||g===b&&d===w)return e;var N=r.substr(S,y-S);if(!![].concat(N).find(function(t,e){return o.isCharacterAFormat(e+S,r)})){var P=r.substr(S),F={},D=[];[].concat(P).forEach(function(t,e){o.isCharacterAFormat(e+S,r)?F[e]=t:e>N.length-1&&D.push(t)}),Object.keys(F).forEach(function(t){D.length>t?D.splice(t,0,F[t]):D.push(F[t])}),e=r.substr(0,S)+D.join("")}if(!a){var C=this.removeFormatting(e),V=j(C,i),A=V.beforeDecimal,E=V.afterDecimal,O=V.addNegation,R=t<e.indexOf(f)+1;if(C.length<h.length&&R&&""===A&&!parseFloat(E))return O?"-":""}return e},t.prototype.updateValue=function(t){var e=t.formattedValue,r=t.input,o=t.setCaretPosition;void 0===o&&(o=!0);var n=t.source,a=t.event,i=t.numAsString,s=t.caretPos,u=this.props.onValueChange,l=this.state.value;if(r){if(void 0===s&&o){var p=t.inputValue||r.value,c=g(r);r.value=e,s=this.getCaretPosition(p,e,c)}r.value=e,o&&this.setPatchedCaretPosition(r,s,e)}void 0===i&&(i=this.removeFormatting(e)),e!==l&&(this.setState({value:e,numAsString:i}),u(this.getValueObject(e,i),{event:a,source:n}))},t.prototype.onChange=function(t){var e=t.target,r=e.value,o=this.state,n=this.props,a=n.isAllowed,i=o.value||"",s=g(e);r=this.correctInputValue(s,i,r);var u=this.formatInput(r)||"",l=this.removeFormatting(u),p=a(this.getValueObject(u,l));p||(u=i),this.updateValue({formattedValue:u,numAsString:l,inputValue:r,input:e,event:t,source:"event"}),p&&n.onChange(t)},t.prototype.onBlur=function(t){var e=this.props,r=this.state,o=e.format,n=e.onBlur,a=e.allowLeadingZeros,i=r.numAsString,s=r.value;if(this.focusedElm=null,clearTimeout(this.focusTimeout),clearTimeout(this.caretPositionTimeout),!o){isNaN(parseFloat(i))&&(i=""),a||(i=function(t){if(!t)return t;var e="-"===t[0];e&&(t=t.substring(1,t.length));var r=t.split("."),o=r[0].replace(/^0+/,"")||"0",n=r[1]||"";return(e?"-":"")+o+(n?"."+n:"")}(i));var u=this.formatNumString(i);if(u!==s)return this.updateValue({formattedValue:u,numAsString:i,input:t.target,setCaretPosition:!1,event:t,source:"event"}),void n(t)}n(t)},t.prototype.onKeyDown=function(t){var e,r=t.target,o=t.key,n=r.selectionStart,a=r.selectionEnd,i=r.value;void 0===i&&(i="");var s=this.props,u=s.decimalScale,l=s.fixedDecimalScale,p=s.prefix,c=s.suffix,f=s.format,h=s.onKeyDown,m=void 0!==u&&l,g=this.getNumberRegex(!1,m),d=new RegExp("-"),v="string"==typeof f;if(this.selectionBeforeInput={selectionStart:n,selectionEnd:a},"ArrowLeft"===o||"Backspace"===o?e=n-1:"ArrowRight"===o?e=n+1:"Delete"===o&&(e=n),void 0!==e&&n===a){var S=e,y=v?f.indexOf("#"):p.length,x=v?f.lastIndexOf("#")+1:i.length-c.length;if("ArrowLeft"===o||"ArrowRight"===o){var b="ArrowLeft"===o?"left":"right";S=this.correctCaretPosition(i,e,b)}else if("Delete"!==o||g.test(i[e])||d.test(i[e])){if("Backspace"===o&&!g.test(i[e]))if(n<=y+1&&"-"===i[0]&&void 0===f){var w=i.substring(1);this.updateValue({formattedValue:w,caretPos:S,input:r,event:t,source:"event"})}else if(!d.test(i[e])){for(;!g.test(i[S-1])&&y<S;)S--;S=this.correctCaretPosition(i,S,"left")}}else for(;!g.test(i[S])&&S<x;)S++;(S!==e||e<y||x<e)&&(t.preventDefault(),this.setPatchedCaretPosition(r,S,i)),t.isUnitTestRun&&this.setPatchedCaretPosition(r,S,i),h(t)}else h(t)},t.prototype.onMouseUp=function(t){var e=t.target,r=e.selectionStart,o=e.selectionEnd,n=e.value;if(void 0===n&&(n=""),r===o){var a=this.correctCaretPosition(n,r);a!==r&&this.setPatchedCaretPosition(e,a,n)}this.props.onMouseUp(t)},t.prototype.onFocus=function(a){var i=this;a.persist(),this.focusedElm=a.target,this.focusTimeout=setTimeout(function(){var t=a.target,e=t.selectionStart,r=t.selectionEnd,o=t.value;void 0===o&&(o="");var n=i.correctCaretPosition(o,e);n===e||0===e&&r===o.length||i.setPatchedCaretPosition(t,n,o),i.props.onFocus(a)},0)},t.prototype.render=function(){var t=this.props,e=t.type,r=t.displayType,o=t.customInput,n=t.renderText,a=t.getInputRef,i=t.format,s=(t.thousandSeparator,t.decimalSeparator,t.allowedDecimalSeparators,t.thousandsGroupStyle,t.decimalScale,t.fixedDecimalScale,t.prefix,t.suffix,t.removeFormatting,t.mask,t.defaultValue,t.isNumericString,t.allowNegative,t.allowEmptyFormatting,t.allowLeadingZeros,t.onValueChange,t.isAllowed,t.customNumerals,t.onChange,t.onKeyDown,t.onMouseUp,t.onFocus,t.onBlur,t.value,function(t,e){var r={};for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&-1===e.indexOf(o)&&(r[o]=t[o]);return r}(t,["type","displayType","customInput","renderText","getInputRef","format","thousandSeparator","decimalSeparator","allowedDecimalSeparators","thousandsGroupStyle","decimalScale","fixedDecimalScale","prefix","suffix","removeFormatting","mask","defaultValue","isNumericString","allowNegative","allowEmptyFormatting","allowLeadingZeros","onValueChange","isAllowed","customNumerals","onChange","onKeyDown","onMouseUp","onFocus","onBlur","value"])),u=this.state,l=u.value,p=u.mounted&&function(t){return t||"undefined"!=typeof navigator&&!(navigator.platform&&/iPhone|iPod/.test(navigator.platform))}(i)?"numeric":void 0,c=Object.assign({inputMode:p},s,{type:e,value:l,onChange:this.onChange,onKeyDown:this.onKeyDown,onMouseUp:this.onMouseUp,onFocus:this.onFocus,onBlur:this.onBlur});if("text"===r)return n?n(l,s)||null:h.createElement("span",Object.assign({},s,{ref:a}),l);if(o){var f=o;return h.createElement(f,Object.assign({},c,{ref:a}))}return h.createElement("input",Object.assign({},c,{ref:a}))},t}((h=h&&h.hasOwnProperty("default")?h.default:h).Component);return r.defaultProps=e,r});