formsy-react
Advanced tools
Comparing version 2.3.0 to 2.3.1
@@ -161,14 +161,13 @@ 'use strict'; | ||
} | ||
function throttle(callback, interval) { | ||
var enableCall = true; | ||
function debounce(callback, timeout) { | ||
var _this = this; | ||
var timer; | ||
return function () { | ||
if (!enableCall) return; | ||
enableCall = false; | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
callback.apply(this, args); | ||
setTimeout(function () { | ||
return enableCall = true; | ||
}, interval); | ||
clearTimeout(timer); | ||
timer = setTimeout(function () { | ||
callback.apply(_this, args); | ||
}, timeout); | ||
}; | ||
@@ -724,4 +723,3 @@ } | ||
} | ||
// Will be triggered immediately & every one frame rate | ||
_this.throttledValidateForm(); | ||
_this.debouncedValidateForm(); | ||
}; | ||
@@ -731,7 +729,6 @@ // Method put on each input component to unregister | ||
_this.detachFromForm = function (component) { | ||
var componentPos = _this.inputs.indexOf(component); | ||
if (componentPos !== -1) { | ||
_this.inputs = _this.inputs.slice(0, componentPos).concat(_this.inputs.slice(componentPos + 1)); | ||
} | ||
_this.validateForm(); | ||
_this.inputs = _this.inputs.filter(function (input) { | ||
return input !== component; | ||
}); | ||
_this.debouncedValidateForm(); | ||
}; | ||
@@ -817,3 +814,3 @@ // Checks if the values have changed from their initial value | ||
// We need a callback as we are validating all inputs again. This will | ||
// run when the last component has set its state | ||
// run when the last input has set its state | ||
var onValidationComplete = function onValidationComplete() { | ||
@@ -829,16 +826,13 @@ var allIsValid = _this.inputs.every(function (component) { | ||
}; | ||
// Run validation again in case affected by other inputs. The | ||
// last component validated will run the onValidationComplete callback | ||
_this.inputs.forEach(function (component, index) { | ||
var validationState = _this.runValidation(component); | ||
var isFinalInput = index === _this.inputs.length - 1; | ||
var callback = isFinalInput ? onValidationComplete : null; | ||
component.setState(validationState, callback); | ||
}); | ||
// If there are no inputs, set state where form is ready to trigger | ||
// change event. New inputs might be added later | ||
if (!_this.inputs.length) { | ||
_this.setState({ | ||
canChange: true | ||
}, onValidationComplete); | ||
if (_this.inputs.length === 0) { | ||
onValidationComplete(); | ||
} else { | ||
// Run validation again in case affected by other inputs. The | ||
// last component validated will run the onValidationComplete callback | ||
_this.inputs.forEach(function (component, index) { | ||
var validationState = _this.runValidation(component); | ||
var isLastInput = index === _this.inputs.length - 1; | ||
var callback = isLastInput ? onValidationComplete : null; | ||
component.setState(validationState, callback); | ||
}); | ||
} | ||
@@ -861,3 +855,3 @@ }; | ||
_this.emptyArray = []; | ||
_this.throttledValidateForm = throttle(_this.validateForm, ONE_RENDER_FRAME); | ||
_this.debouncedValidateForm = debounce(_this.validateForm, ONE_RENDER_FRAME); | ||
return _this; | ||
@@ -864,0 +858,0 @@ } |
@@ -1,2 +0,2 @@ | ||
"use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t.default:t}Object.defineProperty(exports,"__esModule",{value:!0});var e=require("lodash"),n=t(require("prop-types")),r=t(require("react"));function i(){return(i=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t}).apply(this,arguments)}function o(t,e){var n,r;t.prototype=Object.create(e.prototype),t.prototype.constructor=t,n=t,r=e,(Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(n,r)}function a(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function u(t){return Array.isArray(t)}function s(t){return e.isPlainObject(t)}function l(t){return t instanceof Date}function d(t){return null!==t&&"function"==typeof t}function c(t){return"string"==typeof t}function f(t){return t instanceof RegExp}function p(t){return""===t}function m(t){return null==t}function v(t){return void 0===t}function h(){}function V(t){return s(t)?i({},t):u(t)?[].concat(t):t}function g(t,e){return typeof t==typeof e&&(u(t)&&u(e)?t.length===e.length&&t.every((function(t,n){return g(t,e[n])})):d(t)&&d(e)||l(t)&&l(e)?t.toString()===e.toString():s(t)&&s(e)?Object.keys(t).length===Object.keys(e).length&&Object.keys(t).every((function(n){return g(t[n],e[n])})):f(t)&&f(e)?t.toString()===e.toString():t===e)}function b(t,e,n,r){var i={errors:[],failed:[],success:[]};return Object.keys(n).forEach((function(o){var a=n[o],u=r[o],s=function(t){c(t)?(i.errors.push(t),i.failed.push(o)):t?i.success.push(o):i.failed.push(o)};if(u&&d(a))throw new Error("Formsy does not allow you to override default validations: "+o);if(!u&&!d(a))throw new Error("Formsy does not have the validation rule: "+o);return d(a)?s(a(e,t)):s(u(e,t,a))})),i}function y(t){return!m(t)}function E(t){return c(t)?p(t):!function(t){return void 0===t}(t)&&v(t)}function F(t){return c(t)?p(t):m(t)}function S(t,e,n){return!y(e)||E(e)||n.test(""+e)}var w=/^[A-Z]+$/i,O=/^[0-9A-Z]+$/i,I=/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i,q=/^(?:[-+]?(?:\d+))?(?:\.\d*)?(?:[eE][+-]?(?:\d+))?$/,x=/^(?:[-+]?(?:0|[1-9]\d*))$/,R=/^[-+]?(?:\d*[.])?\d+$/,j=/^[\sA-ZÀ-ÖØ-öø-ÿ]+$/i,C=/^(?:\w+:)?\/\/([^\s.]+\.\S{2}|localhost[:?\d]*)\S*$/i,D=/^[A-Z\s]+$/i,P={equals:function(t,e,n){return!y(e)||E(e)||e===n},equalsField:function(t,e,n){return e===t[n]},isAlpha:function(t,e){return S(0,e,w)},isAlphanumeric:function(t,e){return S(0,e,O)},isDefaultRequiredValue:function(t,e){return F(e)},isEmail:function(t,e){return S(0,e,I)},isEmptyString:function(t,e){return E(e)},isExisty:function(t,e){return y(e)},isFalse:function(t,e){return!1===e},isFloat:function(t,e){return S(0,e,q)},isInt:function(t,e){return S(0,e,x)},isLength:function(t,e,n){return!y(e)||E(e)||e.length===n},isNumeric:function(t,e){return function(t){return"number"==typeof t}(e)||S(0,e,R)},isSpecialWords:function(t,e){return S(0,e,j)},isTrue:function(t,e){return!0===e},isUndefined:function(t,e){return v(e)},isUrl:function(t,e){return S(0,e,C)},isWords:function(t,e){return S(0,e,D)},matchRegexp:S,maxLength:function(t,e,n){return!y(e)||e.length<=n},minLength:function(t,e,n){return!y(e)||E(e)||e.length>=n}},M=function(){throw new Error("Could not find Formsy Context Provider. Did you use withFormsy outside <Formsy />?")},A=r.createContext({attachToForm:M,detachFromForm:M,isFormDisabled:!0,isValidValue:M,validate:M,runValidation:M}),T=function(t){return c(t)?t.split(/,(?![^{[]*[}\]])/g).reduce((function(t,e){var n=e.split(":"),r=n.shift();if((n=n.map((function(t){try{return JSON.parse(t)}catch(e){return t}}))).length>1)throw new Error("Formsy does not support multiple args on string validations. Use object format of validations instead.");var o=i({},t);return o[r]=!n.length||n[0],o}),{}):t||{}},N={innerRef:n.func,name:n.string.isRequired,required:n.oneOfType([n.bool,n.object,n.string]),validations:n.oneOfType([n.object,n.string]),value:n.any},k=["children","mapping","onChange","onInvalid","onInvalidSubmit","onReset","onSubmit","onValid","onValidSubmit","preventDefaultSubmit","preventExternalInvalidation","validationErrors","disabled","formElement"],$=function(t){function n(n){var r,o,a;return(r=t.call(this,n)||this).prevInputNames=null,r.componentDidMount=function(){r.prevInputNames=r.inputs.map((function(t){return t.props.name})),r.validateForm()},r.componentDidUpdate=function(t){var e=r.props,n=e.validationErrors,o=e.disabled;n&&s(n)&&Object.keys(n).length>0&&r.setInputValidationErrors(n);var a=r.inputs.map((function(t){return t.props.name}));r.prevInputNames&&!g(r.prevInputNames,a)&&(r.prevInputNames=a,r.validateForm()),o!==t.disabled&&r.setState((function(t){return i({},t,{contextValue:i({},t.contextValue,{isFormDisabled:o})})}))},r.getCurrentValues=function(){return r.inputs.reduce((function(t,e){return t[e.props.name]=V(e.state.value),t}),{})},r.getModel=function(){var t=r.getCurrentValues();return r.mapModel(t)},r.getPristineValues=function(){return r.inputs.reduce((function(t,e){var n=e.props;return t[n.name]=V(n.value),t}),{})},r.setFormPristine=function(t){r.setState({formSubmitted:!t}),r.inputs.forEach((function(e){e.setState({formSubmitted:!t,isPristine:t})}))},r.setInputValidationErrors=function(t){var e=r.props.preventExternalInvalidation,n=r.state.isValid;r.inputs.forEach((function(e){var n=e.props.name;e.setState({isValid:!(n in t),validationError:c(t[n])?[t[n]]:t[n]})})),!e&&n&&r.setFormValidState(!1)},r.setFormValidState=function(t){var e=r.props,n=e.onValid,i=e.onInvalid;r.setState({isValid:t}),t?n():i()},r.isValidValue=function(t,e){return r.runValidation(t,e).isValid},r.isFormDisabled=function(){return r.props.disabled},r.mapModel=function(t){var n=r.props.mapping;if(n)return n(t);var i={};return Object.keys(t).forEach((function(n){e.set(i,n,t[n])})),i},r.reset=function(t){r.setFormPristine(!0),r.resetModel(t)},r.resetInternal=function(t){var e=r.props.onReset;t.preventDefault(),r.reset(),e&&e()},r.resetModel=function(t){r.inputs.forEach((function(n){var r=n.props.name;t&&e.has(t,r)?n.setValue(e.get(t,r)):n.resetValue()})),r.validateForm()},r.runValidation=function(t,e){void 0===e&&(e=t.state.value);var n=r.props.validationErrors,i=t.props,o=i.validationError,a=i.validationErrors,u=i.name,s=r.getCurrentValues(),l=b(e,s,t.validations,P),d=b(e,s,t.requiredValidations,P),f=!!Object.keys(t.requiredValidations).length&&!!d.success.length,p=!(l.failed.length||n&&n[t.props.name]);return{isRequired:f,isValid:!f&&p,validationError:function(){if(p&&!f)return r.emptyArray;if(l.errors.length)return l.errors;if(n&&n[u])return c(n[u])?[n[u]]:n[u];if(f){var t=a[d.success[0]]||o;return t?[t]:null}return l.failed.length?l.failed.map((function(t){return a[t]?a[t]:o})).filter((function(t,e,n){return n.indexOf(t)===e})):void 0}()}},r.attachToForm=function(t){-1===r.inputs.indexOf(t)&&r.inputs.push(t),r.state.canChange&&(0,r.props.onChange)(r.getModel(),r.isChanged()),r.throttledValidateForm()},r.detachFromForm=function(t){var e=r.inputs.indexOf(t);-1!==e&&(r.inputs=r.inputs.slice(0,e).concat(r.inputs.slice(e+1))),r.validateForm()},r.isChanged=function(){return!g(r.getPristineValues(),r.getCurrentValues())},r.submit=function(t){var e=r.props,n=e.onSubmit,i=e.onValidSubmit,o=e.onInvalidSubmit,a=r.state.isValid;e.preventDefaultSubmit&&t&&t.preventDefault&&t.preventDefault(),r.setFormPristine(!1);var u=r.getModel();n(u,r.resetModel,r.updateInputsWithError,t),a?i(u,r.resetModel,r.updateInputsWithError,t):o(u,r.resetModel,r.updateInputsWithError,t)},r.updateInputsWithError=function(t,e){var n=r.props.preventExternalInvalidation,i=r.state.isValid;Object.entries(t).forEach((function(e){var i=e[0],o=e[1],a=r.inputs.find((function(t){return t.props.name===i}));if(!a)throw new Error("You are trying to update an input that does not exist. Verify errors object with input names. "+JSON.stringify(t));a.setState({isValid:n,validationError:c(o)?[o]:o})})),e&&i&&r.setFormValidState(!1)},r.updateInputsWithValue=function(t,n){r.inputs.forEach((function(r){var i=r.props.name;t&&e.has(t,i)&&r.setValue(e.get(t,i),n)}))},r.validate=function(t){r.state.canChange&&(0,r.props.onChange)(r.getModel(),r.isChanged());var e=r.runValidation(t);t.setState(e,r.validateForm)},r.validateForm=function(){var t=function(){var t=r.inputs.every((function(t){return t.state.isValid}));r.setFormValidState(t),r.setState({canChange:!0})};r.inputs.forEach((function(e,n){var i=r.runValidation(e);e.setState(i,n===r.inputs.length-1?t:null)})),r.inputs.length||r.setState({canChange:!0},t)},r.state={canChange:!1,isSubmitting:!1,isValid:!0,contextValue:{attachToForm:r.attachToForm,detachFromForm:r.detachFromForm,isFormDisabled:n.disabled,isValidValue:r.isValidValue,validate:r.validate,runValidation:r.runValidation}},r.inputs=[],r.emptyArray=[],r.throttledValidateForm=(o=r.validateForm,a=!0,function(){if(a){a=!1;for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];o.apply(this,e),setTimeout((function(){return a=!0}),66)}}),r}return o(n,t),n.prototype.render=function(){var t=this.props,e=t.children,n=t.disabled,o=t.formElement,a=function(t,e){if(null==t)return{};var n,r,i={},o=Object.keys(t);for(r=0;r<o.length;r++)e.indexOf(n=o[r])>=0||(i[n]=t[n]);return i}(t,k);return r.createElement(A.Provider,{value:this.state.contextValue},r.createElement(o,i({onReset:this.resetInternal,onSubmit:this.submit},a,{disabled:n}),e))},n}(r.Component);$.displayName="Formsy",$.propTypes={disabled:n.bool,mapping:n.func,formElement:n.oneOfType([n.string,n.object,n.func]),onChange:n.func,onInvalid:n.func,onInvalidSubmit:n.func,onReset:n.func,onSubmit:n.func,onValid:n.func,onValidSubmit:n.func,preventDefaultSubmit:n.bool,preventExternalInvalidation:n.bool,validationErrors:n.object},$.defaultProps={disabled:!1,mapping:null,onChange:h,onInvalid:h,onInvalidSubmit:h,onReset:h,onSubmit:h,onValid:h,onValidSubmit:h,preventDefaultSubmit:!0,preventExternalInvalidation:!1,validationErrors:{},formElement:"form"},exports.addValidationRule=function(t,e){P[t]=e},exports.default=$,exports.propTypes=N,exports.validationRules=P,exports.withFormsy=function(t){var e,n=function(e){function n(t){var n;(n=e.call(this,t)||this).getErrorMessage=function(){var t=n.getErrorMessages();return t.length?t[0]:null},n.getErrorMessages=function(){var t=n.state.validationError;return(!n.isValid()||n.showRequired())&&t||[]},n.getValue=function(){return n.state.value},n.setValidations=function(t,e){n.validations=T(t)||{},n.requiredValidations=!0===e?{isDefaultRequiredValue:e}:T(e)},n.setValue=function(t,e){void 0===e&&(e=!0);var r=n.props.validate;e?n.setState({value:t,isPristine:!1},(function(){r(a(n))})):n.setState({value:t})},n.hasValue=function(){return F(n.state.value)},n.isFormDisabled=function(){return n.props.isFormDisabled},n.isFormSubmitted=function(){return n.state.formSubmitted},n.isPristine=function(){return n.state.isPristine},n.isRequired=function(){return!!n.props.required},n.isValid=function(){return n.state.isValid},n.isValidValue=function(t){return n.props.isValidValue(a(n),t)},n.resetValue=function(){var t=n.props.validate;n.setState({value:n.state.pristineValue,isPristine:!0},(function(){t(a(n))}))},n.showError=function(){return!n.showRequired()&&!n.isValid()},n.showRequired=function(){return n.state.isRequired};var r=t.runValidation,o=t.validations,u=t.required;return n.state={value:t.value},n.setValidations(o,u),n.state=i({formSubmitted:!1,isPristine:!0,pristineValue:t.value,value:t.value},r(a(n),t.value)),n}o(n,e);var u=n.prototype;return u.componentDidMount=function(){var t=this.props,e=t.attachToForm;if(!t.name)throw new Error("Form Input requires a name property when used");e(this)},u.shouldComponentUpdate=function(t,e){var n=this.state,r=function(t,e){return Object.keys(t).some((function(n){return t[n]!==e[n]}))},i=r(this.props,t),o=r(n,e);return i||o},u.componentDidUpdate=function(t){var e=this.props,n=e.value,r=e.validations,i=e.required,o=e.validate;g(n,t.value)||this.setValue(n),g(r,t.validations)&&g(i,t.required)||(this.setValidations(r,i),o(this))},u.componentWillUnmount=function(){(0,this.props.detachFromForm)(this)},u.render=function(){var e=this.props.innerRef,n=i({},this.props,{errorMessage:this.getErrorMessage(),errorMessages:this.getErrorMessages(),hasValue:this.hasValue(),isFormDisabled:this.isFormDisabled(),isFormSubmitted:this.isFormSubmitted(),isPristine:this.isPristine(),isRequired:this.isRequired(),isValid:this.isValid(),isValidValue:this.isValidValue,resetValue:this.resetValue,setValidations:this.setValidations,setValue:this.setValue,showError:this.showError(),showRequired:this.showRequired(),value:this.getValue()});return e&&(n.ref=e),r.createElement(t,n)},n}(r.Component);return n.displayName="Formsy("+((e=t).displayName||e.name||(c(e)?e:"Component"))+")",n.propTypes=N,n.defaultProps={innerRef:null,required:!1,validationError:"",validationErrors:{},validations:null,value:t.defaultValue},function(t){return r.createElement(A.Consumer,null,(function(e){return r.createElement(n,i({},t,e))}))}}; | ||
"use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t.default:t}Object.defineProperty(exports,"__esModule",{value:!0});var e=require("lodash"),n=t(require("prop-types")),r=t(require("react"));function i(){return(i=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t}).apply(this,arguments)}function o(t,e){var n,r;t.prototype=Object.create(e.prototype),t.prototype.constructor=t,n=t,r=e,(Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(n,r)}function a(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function u(t){return Array.isArray(t)}function s(t){return e.isPlainObject(t)}function l(t){return t instanceof Date}function d(t){return null!==t&&"function"==typeof t}function c(t){return"string"==typeof t}function f(t){return t instanceof RegExp}function p(t){return""===t}function m(t){return null==t}function v(t){return void 0===t}function h(){}function V(t){return s(t)?i({},t):u(t)?[].concat(t):t}function g(t,e){return typeof t==typeof e&&(u(t)&&u(e)?t.length===e.length&&t.every((function(t,n){return g(t,e[n])})):d(t)&&d(e)||l(t)&&l(e)?t.toString()===e.toString():s(t)&&s(e)?Object.keys(t).length===Object.keys(e).length&&Object.keys(t).every((function(n){return g(t[n],e[n])})):f(t)&&f(e)?t.toString()===e.toString():t===e)}function b(t,e,n,r){var i={errors:[],failed:[],success:[]};return Object.keys(n).forEach((function(o){var a=n[o],u=r[o],s=function(t){c(t)?(i.errors.push(t),i.failed.push(o)):t?i.success.push(o):i.failed.push(o)};if(u&&d(a))throw new Error("Formsy does not allow you to override default validations: "+o);if(!u&&!d(a))throw new Error("Formsy does not have the validation rule: "+o);return d(a)?s(a(e,t)):s(u(e,t,a))})),i}function y(t){return!m(t)}function E(t){return c(t)?p(t):!function(t){return void 0===t}(t)&&v(t)}function F(t){return c(t)?p(t):m(t)}function S(t,e,n){return!y(e)||E(e)||n.test(""+e)}var w=/^[A-Z]+$/i,I=/^[0-9A-Z]+$/i,O=/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i,q=/^(?:[-+]?(?:\d+))?(?:\.\d*)?(?:[eE][+-]?(?:\d+))?$/,R=/^(?:[-+]?(?:0|[1-9]\d*))$/,j=/^[-+]?(?:\d*[.])?\d+$/,x=/^[\sA-ZÀ-ÖØ-öø-ÿ]+$/i,C=/^(?:\w+:)?\/\/([^\s.]+\.\S{2}|localhost[:?\d]*)\S*$/i,D=/^[A-Z\s]+$/i,P={equals:function(t,e,n){return!y(e)||E(e)||e===n},equalsField:function(t,e,n){return e===t[n]},isAlpha:function(t,e){return S(0,e,w)},isAlphanumeric:function(t,e){return S(0,e,I)},isDefaultRequiredValue:function(t,e){return F(e)},isEmail:function(t,e){return S(0,e,O)},isEmptyString:function(t,e){return E(e)},isExisty:function(t,e){return y(e)},isFalse:function(t,e){return!1===e},isFloat:function(t,e){return S(0,e,q)},isInt:function(t,e){return S(0,e,R)},isLength:function(t,e,n){return!y(e)||E(e)||e.length===n},isNumeric:function(t,e){return function(t){return"number"==typeof t}(e)||S(0,e,j)},isSpecialWords:function(t,e){return S(0,e,x)},isTrue:function(t,e){return!0===e},isUndefined:function(t,e){return v(e)},isUrl:function(t,e){return S(0,e,C)},isWords:function(t,e){return S(0,e,D)},matchRegexp:S,maxLength:function(t,e,n){return!y(e)||e.length<=n},minLength:function(t,e,n){return!y(e)||E(e)||e.length>=n}},M=function(){throw new Error("Could not find Formsy Context Provider. Did you use withFormsy outside <Formsy />?")},T=r.createContext({attachToForm:M,detachFromForm:M,isFormDisabled:!0,isValidValue:M,validate:M,runValidation:M}),A=function(t){return c(t)?t.split(/,(?![^{[]*[}\]])/g).reduce((function(t,e){var n=e.split(":"),r=n.shift();if((n=n.map((function(t){try{return JSON.parse(t)}catch(e){return t}}))).length>1)throw new Error("Formsy does not support multiple args on string validations. Use object format of validations instead.");var o=i({},t);return o[r]=!n.length||n[0],o}),{}):t||{}},N={innerRef:n.func,name:n.string.isRequired,required:n.oneOfType([n.bool,n.object,n.string]),validations:n.oneOfType([n.object,n.string]),value:n.any},k=["children","mapping","onChange","onInvalid","onInvalidSubmit","onReset","onSubmit","onValid","onValidSubmit","preventDefaultSubmit","preventExternalInvalidation","validationErrors","disabled","formElement"],$=function(t){function n(n){var r;return(r=t.call(this,n)||this).prevInputNames=null,r.componentDidMount=function(){r.prevInputNames=r.inputs.map((function(t){return t.props.name})),r.validateForm()},r.componentDidUpdate=function(t){var e=r.props,n=e.validationErrors,o=e.disabled;n&&s(n)&&Object.keys(n).length>0&&r.setInputValidationErrors(n);var a=r.inputs.map((function(t){return t.props.name}));r.prevInputNames&&!g(r.prevInputNames,a)&&(r.prevInputNames=a,r.validateForm()),o!==t.disabled&&r.setState((function(t){return i({},t,{contextValue:i({},t.contextValue,{isFormDisabled:o})})}))},r.getCurrentValues=function(){return r.inputs.reduce((function(t,e){return t[e.props.name]=V(e.state.value),t}),{})},r.getModel=function(){var t=r.getCurrentValues();return r.mapModel(t)},r.getPristineValues=function(){return r.inputs.reduce((function(t,e){var n=e.props;return t[n.name]=V(n.value),t}),{})},r.setFormPristine=function(t){r.setState({formSubmitted:!t}),r.inputs.forEach((function(e){e.setState({formSubmitted:!t,isPristine:t})}))},r.setInputValidationErrors=function(t){var e=r.props.preventExternalInvalidation,n=r.state.isValid;r.inputs.forEach((function(e){var n=e.props.name;e.setState({isValid:!(n in t),validationError:c(t[n])?[t[n]]:t[n]})})),!e&&n&&r.setFormValidState(!1)},r.setFormValidState=function(t){var e=r.props,n=e.onValid,i=e.onInvalid;r.setState({isValid:t}),t?n():i()},r.isValidValue=function(t,e){return r.runValidation(t,e).isValid},r.isFormDisabled=function(){return r.props.disabled},r.mapModel=function(t){var n=r.props.mapping;if(n)return n(t);var i={};return Object.keys(t).forEach((function(n){e.set(i,n,t[n])})),i},r.reset=function(t){r.setFormPristine(!0),r.resetModel(t)},r.resetInternal=function(t){var e=r.props.onReset;t.preventDefault(),r.reset(),e&&e()},r.resetModel=function(t){r.inputs.forEach((function(n){var r=n.props.name;t&&e.has(t,r)?n.setValue(e.get(t,r)):n.resetValue()})),r.validateForm()},r.runValidation=function(t,e){void 0===e&&(e=t.state.value);var n=r.props.validationErrors,i=t.props,o=i.validationError,a=i.validationErrors,u=i.name,s=r.getCurrentValues(),l=b(e,s,t.validations,P),d=b(e,s,t.requiredValidations,P),f=!!Object.keys(t.requiredValidations).length&&!!d.success.length,p=!(l.failed.length||n&&n[t.props.name]);return{isRequired:f,isValid:!f&&p,validationError:function(){if(p&&!f)return r.emptyArray;if(l.errors.length)return l.errors;if(n&&n[u])return c(n[u])?[n[u]]:n[u];if(f){var t=a[d.success[0]]||o;return t?[t]:null}return l.failed.length?l.failed.map((function(t){return a[t]?a[t]:o})).filter((function(t,e,n){return n.indexOf(t)===e})):void 0}()}},r.attachToForm=function(t){-1===r.inputs.indexOf(t)&&r.inputs.push(t),r.state.canChange&&(0,r.props.onChange)(r.getModel(),r.isChanged()),r.debouncedValidateForm()},r.detachFromForm=function(t){r.inputs=r.inputs.filter((function(e){return e!==t})),r.debouncedValidateForm()},r.isChanged=function(){return!g(r.getPristineValues(),r.getCurrentValues())},r.submit=function(t){var e=r.props,n=e.onSubmit,i=e.onValidSubmit,o=e.onInvalidSubmit,a=r.state.isValid;e.preventDefaultSubmit&&t&&t.preventDefault&&t.preventDefault(),r.setFormPristine(!1);var u=r.getModel();n(u,r.resetModel,r.updateInputsWithError,t),a?i(u,r.resetModel,r.updateInputsWithError,t):o(u,r.resetModel,r.updateInputsWithError,t)},r.updateInputsWithError=function(t,e){var n=r.props.preventExternalInvalidation,i=r.state.isValid;Object.entries(t).forEach((function(e){var i=e[0],o=e[1],a=r.inputs.find((function(t){return t.props.name===i}));if(!a)throw new Error("You are trying to update an input that does not exist. Verify errors object with input names. "+JSON.stringify(t));a.setState({isValid:n,validationError:c(o)?[o]:o})})),e&&i&&r.setFormValidState(!1)},r.updateInputsWithValue=function(t,n){r.inputs.forEach((function(r){var i=r.props.name;t&&e.has(t,i)&&r.setValue(e.get(t,i),n)}))},r.validate=function(t){r.state.canChange&&(0,r.props.onChange)(r.getModel(),r.isChanged());var e=r.runValidation(t);t.setState(e,r.validateForm)},r.validateForm=function(){var t=function(){var t=r.inputs.every((function(t){return t.state.isValid}));r.setFormValidState(t),r.setState({canChange:!0})};0===r.inputs.length?t():r.inputs.forEach((function(e,n){var i=r.runValidation(e);e.setState(i,n===r.inputs.length-1?t:null)}))},r.state={canChange:!1,isSubmitting:!1,isValid:!0,contextValue:{attachToForm:r.attachToForm,detachFromForm:r.detachFromForm,isFormDisabled:n.disabled,isValidValue:r.isValidValue,validate:r.validate,runValidation:r.runValidation}},r.inputs=[],r.emptyArray=[],r.debouncedValidateForm=function(t,e){var n,r=this;return function(){for(var e=arguments.length,i=new Array(e),o=0;o<e;o++)i[o]=arguments[o];clearTimeout(n),n=setTimeout((function(){t.apply(r,i)}),66)}}(r.validateForm),r}return o(n,t),n.prototype.render=function(){var t=this.props,e=t.children,n=t.disabled,o=t.formElement,a=function(t,e){if(null==t)return{};var n,r,i={},o=Object.keys(t);for(r=0;r<o.length;r++)e.indexOf(n=o[r])>=0||(i[n]=t[n]);return i}(t,k);return r.createElement(T.Provider,{value:this.state.contextValue},r.createElement(o,i({onReset:this.resetInternal,onSubmit:this.submit},a,{disabled:n}),e))},n}(r.Component);$.displayName="Formsy",$.propTypes={disabled:n.bool,mapping:n.func,formElement:n.oneOfType([n.string,n.object,n.func]),onChange:n.func,onInvalid:n.func,onInvalidSubmit:n.func,onReset:n.func,onSubmit:n.func,onValid:n.func,onValidSubmit:n.func,preventDefaultSubmit:n.bool,preventExternalInvalidation:n.bool,validationErrors:n.object},$.defaultProps={disabled:!1,mapping:null,onChange:h,onInvalid:h,onInvalidSubmit:h,onReset:h,onSubmit:h,onValid:h,onValidSubmit:h,preventDefaultSubmit:!0,preventExternalInvalidation:!1,validationErrors:{},formElement:"form"},exports.addValidationRule=function(t,e){P[t]=e},exports.default=$,exports.propTypes=N,exports.validationRules=P,exports.withFormsy=function(t){var e,n=function(e){function n(t){var n;(n=e.call(this,t)||this).getErrorMessage=function(){var t=n.getErrorMessages();return t.length?t[0]:null},n.getErrorMessages=function(){var t=n.state.validationError;return(!n.isValid()||n.showRequired())&&t||[]},n.getValue=function(){return n.state.value},n.setValidations=function(t,e){n.validations=A(t)||{},n.requiredValidations=!0===e?{isDefaultRequiredValue:e}:A(e)},n.setValue=function(t,e){void 0===e&&(e=!0);var r=n.props.validate;e?n.setState({value:t,isPristine:!1},(function(){r(a(n))})):n.setState({value:t})},n.hasValue=function(){return F(n.state.value)},n.isFormDisabled=function(){return n.props.isFormDisabled},n.isFormSubmitted=function(){return n.state.formSubmitted},n.isPristine=function(){return n.state.isPristine},n.isRequired=function(){return!!n.props.required},n.isValid=function(){return n.state.isValid},n.isValidValue=function(t){return n.props.isValidValue(a(n),t)},n.resetValue=function(){var t=n.props.validate;n.setState({value:n.state.pristineValue,isPristine:!0},(function(){t(a(n))}))},n.showError=function(){return!n.showRequired()&&!n.isValid()},n.showRequired=function(){return n.state.isRequired};var r=t.runValidation,o=t.validations,u=t.required;return n.state={value:t.value},n.setValidations(o,u),n.state=i({formSubmitted:!1,isPristine:!0,pristineValue:t.value,value:t.value},r(a(n),t.value)),n}o(n,e);var u=n.prototype;return u.componentDidMount=function(){var t=this.props,e=t.attachToForm;if(!t.name)throw new Error("Form Input requires a name property when used");e(this)},u.shouldComponentUpdate=function(t,e){var n=this.state,r=function(t,e){return Object.keys(t).some((function(n){return t[n]!==e[n]}))},i=r(this.props,t),o=r(n,e);return i||o},u.componentDidUpdate=function(t){var e=this.props,n=e.value,r=e.validations,i=e.required,o=e.validate;g(n,t.value)||this.setValue(n),g(r,t.validations)&&g(i,t.required)||(this.setValidations(r,i),o(this))},u.componentWillUnmount=function(){(0,this.props.detachFromForm)(this)},u.render=function(){var e=this.props.innerRef,n=i({},this.props,{errorMessage:this.getErrorMessage(),errorMessages:this.getErrorMessages(),hasValue:this.hasValue(),isFormDisabled:this.isFormDisabled(),isFormSubmitted:this.isFormSubmitted(),isPristine:this.isPristine(),isRequired:this.isRequired(),isValid:this.isValid(),isValidValue:this.isValidValue,resetValue:this.resetValue,setValidations:this.setValidations,setValue:this.setValue,showError:this.showError(),showRequired:this.showRequired(),value:this.getValue()});return e&&(n.ref=e),r.createElement(t,n)},n}(r.Component);return n.displayName="Formsy("+((e=t).displayName||e.name||(c(e)?e:"Component"))+")",n.propTypes=N,n.defaultProps={innerRef:null,required:!1,validationError:"",validationErrors:{},validations:null,value:t.defaultValue},function(t){return r.createElement(T.Consumer,null,(function(e){return r.createElement(n,i({},t,e))}))}}; | ||
//# sourceMappingURL=formsy-react.cjs.production.min.js.map |
@@ -155,14 +155,13 @@ import { isPlainObject, set, has, get } from 'lodash-es'; | ||
} | ||
function throttle(callback, interval) { | ||
var enableCall = true; | ||
function debounce(callback, timeout) { | ||
var _this = this; | ||
var timer; | ||
return function () { | ||
if (!enableCall) return; | ||
enableCall = false; | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
callback.apply(this, args); | ||
setTimeout(function () { | ||
return enableCall = true; | ||
}, interval); | ||
clearTimeout(timer); | ||
timer = setTimeout(function () { | ||
callback.apply(_this, args); | ||
}, timeout); | ||
}; | ||
@@ -718,4 +717,3 @@ } | ||
} | ||
// Will be triggered immediately & every one frame rate | ||
_this.throttledValidateForm(); | ||
_this.debouncedValidateForm(); | ||
}; | ||
@@ -725,7 +723,6 @@ // Method put on each input component to unregister | ||
_this.detachFromForm = function (component) { | ||
var componentPos = _this.inputs.indexOf(component); | ||
if (componentPos !== -1) { | ||
_this.inputs = _this.inputs.slice(0, componentPos).concat(_this.inputs.slice(componentPos + 1)); | ||
} | ||
_this.validateForm(); | ||
_this.inputs = _this.inputs.filter(function (input) { | ||
return input !== component; | ||
}); | ||
_this.debouncedValidateForm(); | ||
}; | ||
@@ -811,3 +808,3 @@ // Checks if the values have changed from their initial value | ||
// We need a callback as we are validating all inputs again. This will | ||
// run when the last component has set its state | ||
// run when the last input has set its state | ||
var onValidationComplete = function onValidationComplete() { | ||
@@ -823,16 +820,13 @@ var allIsValid = _this.inputs.every(function (component) { | ||
}; | ||
// Run validation again in case affected by other inputs. The | ||
// last component validated will run the onValidationComplete callback | ||
_this.inputs.forEach(function (component, index) { | ||
var validationState = _this.runValidation(component); | ||
var isFinalInput = index === _this.inputs.length - 1; | ||
var callback = isFinalInput ? onValidationComplete : null; | ||
component.setState(validationState, callback); | ||
}); | ||
// If there are no inputs, set state where form is ready to trigger | ||
// change event. New inputs might be added later | ||
if (!_this.inputs.length) { | ||
_this.setState({ | ||
canChange: true | ||
}, onValidationComplete); | ||
if (_this.inputs.length === 0) { | ||
onValidationComplete(); | ||
} else { | ||
// Run validation again in case affected by other inputs. The | ||
// last component validated will run the onValidationComplete callback | ||
_this.inputs.forEach(function (component, index) { | ||
var validationState = _this.runValidation(component); | ||
var isLastInput = index === _this.inputs.length - 1; | ||
var callback = isLastInput ? onValidationComplete : null; | ||
component.setState(validationState, callback); | ||
}); | ||
} | ||
@@ -855,3 +849,3 @@ }; | ||
_this.emptyArray = []; | ||
_this.throttledValidateForm = throttle(_this.validateForm, ONE_RENDER_FRAME); | ||
_this.debouncedValidateForm = debounce(_this.validateForm, ONE_RENDER_FRAME); | ||
return _this; | ||
@@ -858,0 +852,0 @@ } |
@@ -57,3 +57,3 @@ import PropTypes from 'prop-types'; | ||
static defaultProps: Partial<FormsyProps>; | ||
private readonly throttledValidateForm; | ||
private readonly debouncedValidateForm; | ||
constructor(props: FormsyProps); | ||
@@ -60,0 +60,0 @@ componentDidMount: () => void; |
@@ -22,3 +22,3 @@ import { ValidationError, Validations, Values } from './interfaces'; | ||
export declare function runRules<V>(value: V, currentValues: Values, validations: Validations<V>, validationRules: Validations<V>): RulesResult; | ||
export declare function throttle(callback: any, interval: any): (...args: any[]) => void; | ||
export declare function debounce(callback: any, timeout: number): (...args: any[]) => void; | ||
export {}; |
{ | ||
"name": "formsy-react", | ||
"version": "2.3.0", | ||
"version": "2.3.1", | ||
"description": "A form input builder and validator for React", | ||
@@ -5,0 +5,0 @@ "keywords": [ |
@@ -15,3 +15,3 @@ /* eslint-disable react/no-unused-state, react/default-props-match-prop-types */ | ||
} from './interfaces'; | ||
import { throttle, isObject, isString } from './utils'; | ||
import { debounce, isObject, isString } from './utils'; | ||
import * as utils from './utils'; | ||
@@ -107,3 +107,3 @@ import validationRules from './validationRules'; | ||
private readonly throttledValidateForm: () => void; | ||
private readonly debouncedValidateForm: () => void; | ||
@@ -127,3 +127,3 @@ public constructor(props: FormsyProps) { | ||
this.emptyArray = []; | ||
this.throttledValidateForm = throttle(this.validateForm, ONE_RENDER_FRAME); | ||
this.debouncedValidateForm = debounce(this.validateForm, ONE_RENDER_FRAME); | ||
} | ||
@@ -342,4 +342,3 @@ | ||
// Will be triggered immediately & every one frame rate | ||
this.throttledValidateForm(); | ||
this.debouncedValidateForm(); | ||
}; | ||
@@ -350,9 +349,5 @@ | ||
public detachFromForm = <V>(component: InputComponent<V>) => { | ||
const componentPos = this.inputs.indexOf(component); | ||
this.inputs = this.inputs.filter((input) => input !== component); | ||
if (componentPos !== -1) { | ||
this.inputs = this.inputs.slice(0, componentPos).concat(this.inputs.slice(componentPos + 1)); | ||
} | ||
this.validateForm(); | ||
this.debouncedValidateForm(); | ||
}; | ||
@@ -445,3 +440,3 @@ | ||
// We need a callback as we are validating all inputs again. This will | ||
// run when the last component has set its state | ||
// run when the last input has set its state | ||
const onValidationComplete = () => { | ||
@@ -458,20 +453,13 @@ const allIsValid = this.inputs.every((component) => component.state.isValid); | ||
// Run validation again in case affected by other inputs. The | ||
// last component validated will run the onValidationComplete callback | ||
this.inputs.forEach((component, index) => { | ||
const validationState = this.runValidation(component); | ||
const isFinalInput = index === this.inputs.length - 1; | ||
const callback = isFinalInput ? onValidationComplete : null; | ||
component.setState(validationState, callback); | ||
}); | ||
// If there are no inputs, set state where form is ready to trigger | ||
// change event. New inputs might be added later | ||
if (!this.inputs.length) { | ||
this.setState( | ||
{ | ||
canChange: true, | ||
}, | ||
onValidationComplete, | ||
); | ||
if (this.inputs.length === 0) { | ||
onValidationComplete(); | ||
} else { | ||
// Run validation again in case affected by other inputs. The | ||
// last component validated will run the onValidationComplete callback | ||
this.inputs.forEach((component, index) => { | ||
const validationState = this.runValidation(component); | ||
const isLastInput = index === this.inputs.length - 1; | ||
const callback = isLastInput ? onValidationComplete : null; | ||
component.setState(validationState, callback); | ||
}); | ||
} | ||
@@ -478,0 +466,0 @@ }; |
@@ -146,12 +146,10 @@ import { isPlainObject } from 'lodash'; | ||
export function throttle(callback, interval) { | ||
let enableCall = true; | ||
return function (...args) { | ||
if (!enableCall) return; | ||
enableCall = false; | ||
callback.apply(this, args); | ||
setTimeout(() => (enableCall = true), interval); | ||
export function debounce(callback, timeout: number) { | ||
let timer; | ||
return (...args) => { | ||
clearTimeout(timer); | ||
timer = setTimeout(() => { | ||
callback.apply(this, args); | ||
}, timeout); | ||
}; | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
303873
24
3024