formsy-react
Advanced tools
Comparing version 2.2.8 to 2.3.0
@@ -7,4 +7,10 @@ ### Changelog | ||
#### [v2.3.0](https://github.com/formsy/formsy-react/compare/v2.2.8...v2.3.0) | ||
- Add support for React 18 [`#692`](https://github.com/formsy/formsy-react/pull/692) | ||
#### [v2.2.8](https://github.com/formsy/formsy-react/compare/v2.2.7...v2.2.8) | ||
> 8 November 2022 | ||
- Migrate to react testing lib instead of enzyme [`#679`](https://github.com/formsy/formsy-react/pull/679) | ||
@@ -11,0 +17,0 @@ - Bump deps [`7056b3e`](https://github.com/formsy/formsy-react/commit/7056b3eca1bc8df759f05f88a75f5ff681dc2596) |
@@ -12,6 +12,5 @@ 'use strict'; | ||
function _extends() { | ||
_extends = Object.assign || function (target) { | ||
_extends = Object.assign ? Object.assign.bind() : function (target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
@@ -23,15 +22,18 @@ if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
} | ||
return target; | ||
}; | ||
return _extends.apply(this, arguments); | ||
} | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
subClass.__proto__ = superClass; | ||
_setPrototypeOf(subClass, superClass); | ||
} | ||
function _setPrototypeOf(o, p) { | ||
_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { | ||
o.__proto__ = p; | ||
return o; | ||
}; | ||
return _setPrototypeOf(o, p); | ||
} | ||
function _objectWithoutPropertiesLoose(source, excluded) { | ||
@@ -42,3 +44,2 @@ if (source == null) return {}; | ||
var key, i; | ||
for (i = 0; i < sourceKeys.length; i++) { | ||
@@ -49,6 +50,4 @@ key = sourceKeys[i]; | ||
} | ||
return target; | ||
} | ||
function _assertThisInitialized(self) { | ||
@@ -58,3 +57,2 @@ if (self === void 0) { | ||
} | ||
return self; | ||
@@ -96,3 +94,4 @@ } | ||
} | ||
function noop() {// do nothing. | ||
function noop() { | ||
// do nothing. | ||
} | ||
@@ -109,3 +108,2 @@ function protectAgainstParamReassignment(value) { | ||
} | ||
if (isArray(a) && isArray(b)) { | ||
@@ -115,3 +113,2 @@ if (a.length !== b.length) { | ||
} | ||
return a.every(function (item, index) { | ||
@@ -121,11 +118,8 @@ return isSame(item, b[index]); | ||
} | ||
if (isFunction(a) && isFunction(b)) { | ||
return a.toString() === b.toString(); | ||
} | ||
if (isDate(a) && isDate(b)) { | ||
return a.toString() === b.toString(); | ||
} | ||
if (isObject(a) && isObject(b)) { | ||
@@ -135,3 +129,2 @@ if (Object.keys(a).length !== Object.keys(b).length) { | ||
} | ||
return Object.keys(a).every(function (key) { | ||
@@ -141,7 +134,5 @@ return isSame(a[key], b[key]); | ||
} | ||
if (isRegex(a) && isRegex(b)) { | ||
return a.toString() === b.toString(); | ||
} | ||
return a === b; | ||
@@ -158,3 +149,2 @@ } | ||
var validationRulesVal = validationRules[validationName]; | ||
var addToResults = function addToResults(validation) { | ||
@@ -170,15 +160,11 @@ if (isString(validation)) { | ||
}; | ||
if (validationRulesVal && isFunction(validationsVal)) { | ||
throw new Error("Formsy does not allow you to override default validations: " + validationName); | ||
} | ||
if (!validationRulesVal && !isFunction(validationsVal)) { | ||
throw new Error("Formsy does not have the validation rule: " + validationName); | ||
} | ||
if (isFunction(validationsVal)) { | ||
return addToResults(validationsVal(currentValues, value)); | ||
} | ||
return addToResults(validationRulesVal(currentValues, value, validationsVal)); | ||
@@ -193,7 +179,5 @@ }); | ||
enableCall = false; | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
callback.apply(this, args); | ||
@@ -213,10 +197,7 @@ setTimeout(function () { | ||
} | ||
if (isTypeUndefined(value)) { | ||
return false; | ||
} | ||
return isValueUndefined(value); | ||
} | ||
function _isDefaultRequiredValue(value) { | ||
@@ -307,3 +288,2 @@ return isString(value) ? isValueStringEmpty(value) : isValueNullOrUndefined(value); | ||
var noFormsyErrorMessage = 'Could not find Formsy Context Provider. Did you use withFormsy outside <Formsy />?'; | ||
var throwNoFormsyProvider = function throwNoFormsyProvider() { | ||
@@ -313,3 +293,2 @@ // istanbul ignore next | ||
}; | ||
var defaultValue = { | ||
@@ -326,3 +305,2 @@ attachToForm: throwNoFormsyProvider, | ||
/* eslint-disable react/default-props-match-prop-types */ | ||
var convertValidationsToObject = function convertValidationsToObject(validations) { | ||
@@ -343,7 +321,5 @@ if (isString(validations)) { | ||
throw new Error('Formsy does not support multiple args on string validations. Use object format of validations instead.'); | ||
} // Avoid parameter reassignment | ||
} | ||
// Avoid parameter reassignment | ||
var validationsAccumulatorCopy = _extends({}, validationsAccumulator); | ||
validationsAccumulatorCopy[validateMethod] = args.length ? args[0] : true; | ||
@@ -353,6 +329,4 @@ return validationsAccumulatorCopy; | ||
} | ||
return validations || {}; | ||
}; | ||
var propTypes = { | ||
@@ -365,37 +339,26 @@ innerRef: PropTypes.func, | ||
}; | ||
function getDisplayName(component) { | ||
return component.displayName || component.name || (isString(component) ? component : 'Component'); | ||
} | ||
function withFormsy(WrappedComponent) { | ||
var WithFormsyWrapper = /*#__PURE__*/function (_React$Component) { | ||
_inheritsLoose(WithFormsyWrapper, _React$Component); | ||
function WithFormsyWrapper(props) { | ||
var _this; | ||
_this = _React$Component.call(this, props) || this; | ||
_this.getErrorMessage = function () { | ||
var messages = _this.getErrorMessages(); | ||
return messages.length ? messages[0] : null; | ||
}; | ||
_this.getErrorMessages = function () { | ||
var validationError = _this.state.validationError; | ||
if (!_this.isValid() || _this.showRequired()) { | ||
return validationError || []; | ||
} | ||
return []; | ||
}; // eslint-disable-next-line react/destructuring-assignment | ||
}; | ||
// eslint-disable-next-line react/destructuring-assignment | ||
_this.getValue = function () { | ||
return _this.state.value; | ||
}; | ||
_this.setValidations = function (validations, required) { | ||
@@ -407,6 +370,5 @@ // Add validations to the store itself as the props object can not be modified | ||
} : convertValidationsToObject(required); | ||
}; // By default, we validate after the value has been set. | ||
}; | ||
// By default, we validate after the value has been set. | ||
// A user can override this and pass a second parameter of `false` to skip validation. | ||
_this.setValue = function (value, validate) { | ||
@@ -416,5 +378,3 @@ if (validate === void 0) { | ||
} | ||
var validateForm = _this.props.validate; | ||
if (!validate) { | ||
@@ -432,44 +392,35 @@ _this.setState({ | ||
} | ||
}; // eslint-disable-next-line react/destructuring-assignment | ||
}; | ||
// eslint-disable-next-line react/destructuring-assignment | ||
_this.hasValue = function () { | ||
var value = _this.state.value; | ||
return _isDefaultRequiredValue(value); | ||
}; // eslint-disable-next-line react/destructuring-assignment | ||
}; | ||
// eslint-disable-next-line react/destructuring-assignment | ||
_this.isFormDisabled = function () { | ||
return _this.props.isFormDisabled; | ||
}; // eslint-disable-next-line react/destructuring-assignment | ||
}; | ||
// eslint-disable-next-line react/destructuring-assignment | ||
_this.isFormSubmitted = function () { | ||
return _this.state.formSubmitted; | ||
}; // eslint-disable-next-line react/destructuring-assignment | ||
}; | ||
// eslint-disable-next-line react/destructuring-assignment | ||
_this.isPristine = function () { | ||
return _this.state.isPristine; | ||
}; // eslint-disable-next-line react/destructuring-assignment | ||
}; | ||
// eslint-disable-next-line react/destructuring-assignment | ||
_this.isRequired = function () { | ||
return !!_this.props.required; | ||
}; // eslint-disable-next-line react/destructuring-assignment | ||
}; | ||
// eslint-disable-next-line react/destructuring-assignment | ||
_this.isValid = function () { | ||
return _this.state.isValid; | ||
}; // eslint-disable-next-line react/destructuring-assignment | ||
}; | ||
// eslint-disable-next-line react/destructuring-assignment | ||
_this.isValidValue = function (value) { | ||
return _this.props.isValidValue(_assertThisInitialized(_this), value); | ||
}; | ||
_this.resetValue = function () { | ||
var pristineValue = _this.state.pristineValue; | ||
var validate = _this.props.validate; | ||
_this.setState({ | ||
@@ -482,22 +433,17 @@ value: pristineValue, | ||
}; | ||
_this.showError = function () { | ||
return !_this.showRequired() && !_this.isValid(); | ||
}; // eslint-disable-next-line react/destructuring-assignment | ||
}; | ||
// eslint-disable-next-line react/destructuring-assignment | ||
_this.showRequired = function () { | ||
return _this.state.isRequired; | ||
}; | ||
var runValidation = props.runValidation, | ||
validations = props.validations, | ||
required = props.required, | ||
value = props.value; | ||
validations = props.validations, | ||
required = props.required, | ||
value = props.value; | ||
_this.state = { | ||
value: value | ||
}; | ||
_this.setValidations(validations, required); | ||
_this.state = _extends({ | ||
@@ -511,21 +457,15 @@ formSubmitted: false, | ||
} | ||
var _proto = WithFormsyWrapper.prototype; | ||
_proto.componentDidMount = function componentDidMount() { | ||
var _this$props = this.props, | ||
name = _this$props.name, | ||
attachToForm = _this$props.attachToForm; | ||
name = _this$props.name, | ||
attachToForm = _this$props.attachToForm; | ||
if (!name) { | ||
throw new Error('Form Input requires a name property when used'); | ||
} | ||
attachToForm(this); | ||
}; | ||
_proto.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) { | ||
var props = this.props, | ||
state = this.state; | ||
state = this.state; | ||
var isChanged = function isChanged(a, b) { | ||
@@ -536,3 +476,2 @@ return Object.keys(a).some(function (k) { | ||
}; | ||
var isPropsChanged = isChanged(props, nextProps); | ||
@@ -542,16 +481,14 @@ var isStateChanged = isChanged(state, nextState); | ||
}; | ||
_proto.componentDidUpdate = function componentDidUpdate(prevProps) { | ||
var _this$props2 = this.props, | ||
value = _this$props2.value, | ||
validations = _this$props2.validations, | ||
required = _this$props2.required, | ||
validate = _this$props2.validate; // If the value passed has changed, set it. If value is not passed it will | ||
value = _this$props2.value, | ||
validations = _this$props2.validations, | ||
required = _this$props2.required, | ||
validate = _this$props2.validate; | ||
// If the value passed has changed, set it. If value is not passed it will | ||
// internally update, and this will never run | ||
if (!isSame(value, prevProps.value)) { | ||
this.setValue(value); | ||
} // If validations or required is changed, run a new validation | ||
} | ||
// If validations or required is changed, run a new validation | ||
if (!isSame(validations, prevProps.validations) || !isSame(required, prevProps.required)) { | ||
@@ -561,5 +498,5 @@ this.setValidations(validations, required); | ||
} | ||
} // Detach it when component unmounts | ||
} | ||
// Detach it when component unmounts | ||
; | ||
_proto.componentWillUnmount = function componentWillUnmount() { | ||
@@ -569,6 +506,4 @@ var detachFromForm = this.props.detachFromForm; | ||
}; | ||
_proto.render = function render() { | ||
var innerRef = this.props.innerRef; | ||
var propsForElement = _extends({}, this.props, { | ||
@@ -591,13 +526,9 @@ errorMessage: this.getErrorMessage(), | ||
}); | ||
if (innerRef) { | ||
propsForElement.ref = innerRef; | ||
} | ||
return React.createElement(WrappedComponent, propsForElement); | ||
}; | ||
return WithFormsyWrapper; | ||
}(React.Component); | ||
WithFormsyWrapper.displayName = "Formsy(" + getDisplayName(WrappedComponent) + ")"; | ||
@@ -612,4 +543,4 @@ WithFormsyWrapper.propTypes = propTypes; | ||
value: WrappedComponent.defaultValue | ||
}; // eslint-disable-next-line react/display-name | ||
}; | ||
// eslint-disable-next-line react/display-name | ||
return function (props) { | ||
@@ -622,12 +553,10 @@ return React.createElement(FormsyContext.Consumer, null, function (contextValue) { | ||
var _excluded = ["children", "mapping", "onChange", "onInvalid", "onInvalidSubmit", "onReset", "onSubmit", "onValid", "onValidSubmit", "preventDefaultSubmit", "preventExternalInvalidation", "validationErrors", "disabled", "formElement"]; | ||
var ONE_RENDER_FRAME = 66; | ||
var Formsy = /*#__PURE__*/function (_React$Component) { | ||
_inheritsLoose(Formsy, _React$Component); | ||
function Formsy(props) { | ||
var _this; | ||
_this = _React$Component.call(this, props) || this; | ||
_this.prevInputNames = null; | ||
_this.componentDidMount = function () { | ||
@@ -637,26 +566,19 @@ _this.prevInputNames = _this.inputs.map(function (component) { | ||
}); | ||
_this.validateForm(); | ||
}; | ||
_this.componentDidUpdate = function (prevProps) { | ||
var _this$props = _this.props, | ||
validationErrors = _this$props.validationErrors, | ||
disabled = _this$props.disabled; | ||
validationErrors = _this$props.validationErrors, | ||
disabled = _this$props.disabled; | ||
if (validationErrors && isObject(validationErrors) && Object.keys(validationErrors).length > 0) { | ||
_this.setInputValidationErrors(validationErrors); | ||
} | ||
var newInputNames = _this.inputs.map(function (component) { | ||
return component.props.name; | ||
}); | ||
if (_this.prevInputNames && !isSame(_this.prevInputNames, newInputNames)) { | ||
_this.prevInputNames = newInputNames; | ||
_this.validateForm(); | ||
} // Keep the disabled value in state/context the same as from props | ||
} | ||
// Keep the disabled value in state/context the same as from props | ||
if (disabled !== prevProps.disabled) { | ||
@@ -673,8 +595,7 @@ // eslint-disable-next-line | ||
}; | ||
_this.getCurrentValues = function () { | ||
return _this.inputs.reduce(function (valueAccumulator, component) { | ||
var name = component.props.name, | ||
value = component.state.value; // eslint-disable-next-line no-param-reassign | ||
value = component.state.value; | ||
// eslint-disable-next-line no-param-reassign | ||
valueAccumulator[name] = protectAgainstParamReassignment(value); | ||
@@ -684,15 +605,12 @@ return valueAccumulator; | ||
}; | ||
_this.getModel = function () { | ||
var currentValues = _this.getCurrentValues(); | ||
return _this.mapModel(currentValues); | ||
}; | ||
_this.getPristineValues = function () { | ||
return _this.inputs.reduce(function (valueAccumulator, component) { | ||
var _component$props = component.props, | ||
name = _component$props.name, | ||
value = _component$props.value; // eslint-disable-next-line no-param-reassign | ||
name = _component$props.name, | ||
value = _component$props.value; | ||
// eslint-disable-next-line no-param-reassign | ||
valueAccumulator[name] = protectAgainstParamReassignment(value); | ||
@@ -702,10 +620,8 @@ return valueAccumulator; | ||
}; | ||
_this.setFormPristine = function (isPristine) { | ||
_this.setState({ | ||
formSubmitted: !isPristine | ||
}); // Iterate through each component and set it as pristine | ||
}); | ||
// Iterate through each component and set it as pristine | ||
// or "dirty". | ||
_this.inputs.forEach(function (component) { | ||
@@ -718,7 +634,5 @@ component.setState({ | ||
}; | ||
_this.setInputValidationErrors = function (errors) { | ||
var preventExternalInvalidation = _this.props.preventExternalInvalidation; | ||
var isValid = _this.state.isValid; | ||
_this.inputs.forEach(function (component) { | ||
@@ -731,3 +645,2 @@ var name = component.props.name; | ||
}); | ||
if (!preventExternalInvalidation && isValid) { | ||
@@ -737,12 +650,9 @@ _this.setFormValidState(false); | ||
}; | ||
_this.setFormValidState = function (allIsValid) { | ||
var _this$props2 = _this.props, | ||
onValid = _this$props2.onValid, | ||
onInvalid = _this$props2.onInvalid; | ||
onValid = _this$props2.onValid, | ||
onInvalid = _this$props2.onInvalid; | ||
_this.setState({ | ||
isValid: allIsValid | ||
}); | ||
if (allIsValid) { | ||
@@ -754,19 +664,14 @@ onValid(); | ||
}; | ||
_this.isValidValue = function (component, value) { | ||
return _this.runValidation(component, value).isValid; | ||
}; // eslint-disable-next-line react/destructuring-assignment | ||
}; | ||
// eslint-disable-next-line react/destructuring-assignment | ||
_this.isFormDisabled = function () { | ||
return _this.props.disabled; | ||
}; | ||
_this.mapModel = function (model) { | ||
var mapping = _this.props.mapping; | ||
if (mapping) { | ||
return mapping(model); | ||
} | ||
var returnModel = {}; | ||
@@ -778,25 +683,18 @@ Object.keys(model).forEach(function (key) { | ||
}; | ||
_this.reset = function (model) { | ||
_this.setFormPristine(true); | ||
_this.resetModel(model); | ||
}; | ||
_this.resetInternal = function (event) { | ||
var onReset = _this.props.onReset; | ||
event.preventDefault(); | ||
_this.reset(); | ||
if (onReset) { | ||
onReset(); | ||
} | ||
}; // Reset each key in the model to the original / initial / specified value | ||
}; | ||
// Reset each key in the model to the original / initial / specified value | ||
_this.resetModel = function (data) { | ||
_this.inputs.forEach(function (component) { | ||
var name = component.props.name; | ||
if (data && lodash.has(data, name)) { | ||
@@ -808,7 +706,5 @@ component.setValue(lodash.get(data, name)); | ||
}); | ||
_this.validateForm(); | ||
}; // Checks validation on current value or a passed value | ||
}; | ||
// Checks validation on current value or a passed value | ||
_this.runValidation = function (component, value) { | ||
@@ -818,11 +714,8 @@ if (value === void 0) { | ||
} | ||
var validationErrors = _this.props.validationErrors; | ||
var _component$props2 = component.props, | ||
validationError = _component$props2.validationError, | ||
componentValidationErrors = _component$props2.validationErrors, | ||
name = _component$props2.name; | ||
validationError = _component$props2.validationError, | ||
componentValidationErrors = _component$props2.validationErrors, | ||
name = _component$props2.name; | ||
var currentValues = _this.getCurrentValues(); | ||
var validationResults = runRules(value, currentValues, component.validations, validations); | ||
@@ -839,11 +732,8 @@ var requiredResults = runRules(value, currentValues, component.requiredValidations, validations); | ||
} | ||
if (validationResults.errors.length) { | ||
return validationResults.errors; | ||
} | ||
if (validationErrors && validationErrors[name]) { | ||
return isString(validationErrors[name]) ? [validationErrors[name]] : validationErrors[name]; | ||
} | ||
if (isRequired) { | ||
@@ -853,3 +743,2 @@ var error = componentValidationErrors[requiredResults.success[0]] || validationError; | ||
} | ||
if (validationResults.failed.length) { | ||
@@ -861,13 +750,11 @@ return validationResults.failed.map(function (failed) { | ||
}); // remove duplicates | ||
} // This line is not reachable | ||
} | ||
// This line is not reachable | ||
// istanbul ignore next | ||
return undefined; | ||
}() | ||
}; | ||
}; // Method put on each input component to register | ||
}; | ||
// Method put on each input component to register | ||
// itself to the form | ||
_this.attachToForm = function (component) { | ||
@@ -877,53 +764,41 @@ if (_this.inputs.indexOf(component) === -1) { | ||
} | ||
var onChange = _this.props.onChange; | ||
var canChange = _this.state.canChange; // Trigger onChange | ||
var canChange = _this.state.canChange; | ||
// Trigger onChange | ||
if (canChange) { | ||
onChange(_this.getModel(), _this.isChanged()); | ||
} // Will be triggered immediately & every one frame rate | ||
} | ||
// Will be triggered immediately & every one frame rate | ||
_this.throttledValidateForm(); | ||
}; // Method put on each input component to unregister | ||
}; | ||
// Method put on each input component to unregister | ||
// itself from the form | ||
_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(); | ||
}; // Checks if the values have changed from their initial value | ||
}; | ||
// Checks if the values have changed from their initial value | ||
_this.isChanged = function () { | ||
return !isSame(_this.getPristineValues(), _this.getCurrentValues()); | ||
}; // Update model, submit to url prop and send the model | ||
}; | ||
// Update model, submit to url prop and send the model | ||
_this.submit = function (event) { | ||
var _this$props3 = _this.props, | ||
onSubmit = _this$props3.onSubmit, | ||
onValidSubmit = _this$props3.onValidSubmit, | ||
onInvalidSubmit = _this$props3.onInvalidSubmit, | ||
preventDefaultSubmit = _this$props3.preventDefaultSubmit; | ||
onSubmit = _this$props3.onSubmit, | ||
onValidSubmit = _this$props3.onValidSubmit, | ||
onInvalidSubmit = _this$props3.onInvalidSubmit, | ||
preventDefaultSubmit = _this$props3.preventDefaultSubmit; | ||
var isValid = _this.state.isValid; | ||
if (preventDefaultSubmit && event && event.preventDefault) { | ||
event.preventDefault(); | ||
} // Trigger form as not pristine. | ||
} | ||
// Trigger form as not pristine. | ||
// If any inputs have not been touched yet this will make them dirty | ||
// so validation becomes visible (if based on isPristine) | ||
_this.setFormPristine(false); | ||
var model = _this.getModel(); | ||
onSubmit(model, _this.resetModel, _this.updateInputsWithError, event); | ||
if (isValid) { | ||
@@ -934,7 +809,6 @@ onValidSubmit(model, _this.resetModel, _this.updateInputsWithError, event); | ||
} | ||
}; // Go through errors from server and grab the components | ||
}; | ||
// Go through errors from server and grab the components | ||
// stored in the inputs map. Change their state to invalid | ||
// and set the serverError message | ||
_this.updateInputsWithError = function (errors, invalidate) { | ||
@@ -945,12 +819,9 @@ var preventExternalInvalidation = _this.props.preventExternalInvalidation; | ||
var name = _ref[0], | ||
error = _ref[1]; | ||
error = _ref[1]; | ||
var component = _this.inputs.find(function (input) { | ||
return input.props.name === name; | ||
}); | ||
if (!component) { | ||
throw new Error("You are trying to update an input that does not exist. Verify errors object with input names. " + JSON.stringify(errors)); | ||
} | ||
component.setState({ | ||
@@ -961,13 +832,10 @@ isValid: preventExternalInvalidation, | ||
}); | ||
if (invalidate && isValid) { | ||
_this.setFormValidState(false); | ||
} | ||
}; // Set the value of components | ||
}; | ||
// Set the value of components | ||
_this.updateInputsWithValue = function (data, validate) { | ||
_this.inputs.forEach(function (component) { | ||
var name = component.props.name; | ||
if (data && lodash.has(data, name)) { | ||
@@ -977,24 +845,20 @@ component.setValue(lodash.get(data, name), validate); | ||
}); | ||
}; // Use the binded values and the actual input value to | ||
}; | ||
// Use the binded values and the actual input value to | ||
// validate the input and set its state. Then check the | ||
// state of the form itself | ||
_this.validate = function (component) { | ||
var onChange = _this.props.onChange; | ||
var canChange = _this.state.canChange; // Trigger onChange | ||
var canChange = _this.state.canChange; | ||
// Trigger onChange | ||
if (canChange) { | ||
onChange(_this.getModel(), _this.isChanged()); | ||
} | ||
var validationState = _this.runValidation(component); // Run through the validations, split them up and call | ||
var validationState = _this.runValidation(component); | ||
// Run through the validations, split them up and call | ||
// the validator IF there is a value or it is required | ||
component.setState(validationState, _this.validateForm); | ||
}; // Validate the form by going through all child input components | ||
}; | ||
// Validate the form by going through all child input components | ||
// and check their state | ||
_this.validateForm = function () { | ||
@@ -1007,23 +871,18 @@ // We need a callback as we are validating all inputs again. This will | ||
}); | ||
_this.setFormValidState(allIsValid); // Tell the form that it can start to trigger change events | ||
_this.setFormValidState(allIsValid); | ||
// Tell the form that it can start to trigger change events | ||
_this.setState({ | ||
canChange: true | ||
}); | ||
}; // Run validation again in case affected by other inputs. The | ||
}; | ||
// 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 | ||
}); | ||
// 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) { | ||
@@ -1035,3 +894,2 @@ _this.setState({ | ||
}; | ||
_this.state = { | ||
@@ -1055,12 +913,9 @@ canChange: false, | ||
} | ||
var _proto = Formsy.prototype; | ||
_proto.render = function render() { | ||
var _this$props4 = this.props, | ||
children = _this$props4.children, | ||
disabled = _this$props4.disabled, | ||
formElement = _this$props4.formElement, | ||
nonFormsyProps = _objectWithoutPropertiesLoose(_this$props4, ["children", "mapping", "onChange", "onInvalid", "onInvalidSubmit", "onReset", "onSubmit", "onValid", "onValidSubmit", "preventDefaultSubmit", "preventExternalInvalidation", "validationErrors", "disabled", "formElement"]); | ||
children = _this$props4.children, | ||
disabled = _this$props4.disabled, | ||
formElement = _this$props4.formElement, | ||
nonFormsyProps = _objectWithoutPropertiesLoose(_this$props4, _excluded); | ||
var contextValue = this.state.contextValue; | ||
@@ -1076,3 +931,2 @@ return React.createElement(FormsyContext.Provider, { | ||
}; | ||
return Formsy; | ||
@@ -1079,0 +933,0 @@ }(React.Component); |
@@ -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||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 a(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.__proto__=e}function o(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(a){var o=n[a],u=r[a],s=function(t){c(t)?(i.errors.push(t),i.failed.push(a)):t?i.success.push(a):i.failed.push(a)};if(u&&d(o))throw new Error("Formsy does not allow you to override default validations: "+a);if(!u&&!d(o))throw new Error("Formsy does not have the validation rule: "+a);return d(o)?s(o(e,t)):s(u(e,t,o))})),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,q=/^(([^<>()[\]\\.,;:\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,x=/^(?:[-+]?(?:\d+))?(?:\.\d*)?(?:[eE][+-]?(?:\d+))?$/,R=/^(?:[-+]?(?:0|[1-9]\d*))$/,C=/^[-+]?(?:\d*[.])?\d+$/,O=/^[\sA-ZÀ-ÖØ-öø-ÿ]+$/i,D=/^(?:\w+:)?\/\/([^\s.]+\.\S{2}|localhost[:?\d]*)\S*$/i,j=/^[A-Z\s]+$/i,M={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,q)},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,x)},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,C)},isSpecialWords:function(t,e){return S(0,e,O)},isTrue:function(t,e){return!0===e},isUndefined:function(t,e){return v(e)},isUrl:function(t,e){return S(0,e,D)},isWords:function(t,e){return S(0,e,j)},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}},P=function(){throw new Error("Could not find Formsy Context Provider. Did you use withFormsy outside <Formsy />?")},A=r.createContext({attachToForm:P,detachFromForm:P,isFormDisabled:!0,isValidValue:P,validate:P,runValidation:P}),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 a=i({},t);return a[r]=!n.length||n[0],a}),{}):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=function(t){function n(n){var r,a,o;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,a=e.disabled;n&&s(n)&&Object.keys(n).length>0&&r.setInputValidationErrors(n);var o=r.inputs.map((function(t){return t.props.name}));r.prevInputNames&&!g(r.prevInputNames,o)&&(r.prevInputNames=o,r.validateForm()),a!==t.disabled&&r.setState((function(t){return i({},t,{contextValue:i({},t.contextValue,{isFormDisabled:a})})}))},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,a=i.validationError,o=i.validationErrors,u=i.name,s=r.getCurrentValues(),l=b(e,s,t.validations,M),d=b(e,s,t.requiredValidations,M),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=o[d.success[0]]||a;return t?[t]:null}return l.failed.length?l.failed.map((function(t){return o[t]?o[t]:a})).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,a=e.onInvalidSubmit,o=r.state.isValid;e.preventDefaultSubmit&&t&&t.preventDefault&&t.preventDefault(),r.setFormPristine(!1);var u=r.getModel();n(u,r.resetModel,r.updateInputsWithError,t),o?i(u,r.resetModel,r.updateInputsWithError,t):a(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],a=e[1],o=r.inputs.find((function(t){return t.props.name===i}));if(!o)throw new Error("You are trying to update an input that does not exist. Verify errors object with input names. "+JSON.stringify(t));o.setState({isValid:n,validationError:c(a)?[a]:a})})),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=(a=r.validateForm,o=!0,function(){if(o){o=!1;for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];a.apply(this,e),setTimeout((function(){return o=!0}),66)}}),r}return a(n,t),n.prototype.render=function(){var t=this.props,e=t.children,n=t.disabled,a=t.formElement,o=function(t,e){if(null==t)return{};var n,r,i={},a=Object.keys(t);for(r=0;r<a.length;r++)e.indexOf(n=a[r])>=0||(i[n]=t[n]);return i}(t,["children","mapping","onChange","onInvalid","onInvalidSubmit","onReset","onSubmit","onValid","onValidSubmit","preventDefaultSubmit","preventExternalInvalidation","validationErrors","disabled","formElement"]);return r.createElement(A.Provider,{value:this.state.contextValue},r.createElement(a,i({onReset:this.resetInternal,onSubmit:this.submit},o,{disabled:n}),e))},n}(r.Component);k.displayName="Formsy",k.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},k.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){M[t]=e},exports.default=k,exports.propTypes=N,exports.validationRules=M,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(o(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(o(n),t)},n.resetValue=function(){var t=n.props.validate;n.setState({value:n.state.pristineValue,isPristine:!0},(function(){t(o(n))}))},n.showError=function(){return!n.showRequired()&&!n.isValid()},n.showRequired=function(){return n.state.isRequired};var r=t.runValidation,a=t.validations,u=t.required;return n.state={value:t.value},n.setValidations(a,u),n.state=i({formSubmitted:!1,isPristine:!0,pristineValue:t.value,value:t.value},r(o(n),t.value)),n}a(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),a=r(n,e);return i||a},u.componentDidUpdate=function(t){var e=this.props,n=e.value,r=e.validations,i=e.required,a=e.validate;g(n,t.value)||this.setValue(n),g(r,t.validations)&&g(i,t.required)||(this.setValidations(r,i),a(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,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))}))}}; | ||
//# sourceMappingURL=formsy-react.cjs.production.min.js.map |
@@ -6,6 +6,5 @@ import { isPlainObject, set, has, get } from 'lodash-es'; | ||
function _extends() { | ||
_extends = Object.assign || function (target) { | ||
_extends = Object.assign ? Object.assign.bind() : function (target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
@@ -17,15 +16,18 @@ if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
} | ||
return target; | ||
}; | ||
return _extends.apply(this, arguments); | ||
} | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
subClass.__proto__ = superClass; | ||
_setPrototypeOf(subClass, superClass); | ||
} | ||
function _setPrototypeOf(o, p) { | ||
_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { | ||
o.__proto__ = p; | ||
return o; | ||
}; | ||
return _setPrototypeOf(o, p); | ||
} | ||
function _objectWithoutPropertiesLoose(source, excluded) { | ||
@@ -36,3 +38,2 @@ if (source == null) return {}; | ||
var key, i; | ||
for (i = 0; i < sourceKeys.length; i++) { | ||
@@ -43,6 +44,4 @@ key = sourceKeys[i]; | ||
} | ||
return target; | ||
} | ||
function _assertThisInitialized(self) { | ||
@@ -52,3 +51,2 @@ if (self === void 0) { | ||
} | ||
return self; | ||
@@ -90,3 +88,4 @@ } | ||
} | ||
function noop() {// do nothing. | ||
function noop() { | ||
// do nothing. | ||
} | ||
@@ -103,3 +102,2 @@ function protectAgainstParamReassignment(value) { | ||
} | ||
if (isArray(a) && isArray(b)) { | ||
@@ -109,3 +107,2 @@ if (a.length !== b.length) { | ||
} | ||
return a.every(function (item, index) { | ||
@@ -115,11 +112,8 @@ return isSame(item, b[index]); | ||
} | ||
if (isFunction(a) && isFunction(b)) { | ||
return a.toString() === b.toString(); | ||
} | ||
if (isDate(a) && isDate(b)) { | ||
return a.toString() === b.toString(); | ||
} | ||
if (isObject(a) && isObject(b)) { | ||
@@ -129,3 +123,2 @@ if (Object.keys(a).length !== Object.keys(b).length) { | ||
} | ||
return Object.keys(a).every(function (key) { | ||
@@ -135,7 +128,5 @@ return isSame(a[key], b[key]); | ||
} | ||
if (isRegex(a) && isRegex(b)) { | ||
return a.toString() === b.toString(); | ||
} | ||
return a === b; | ||
@@ -152,3 +143,2 @@ } | ||
var validationRulesVal = validationRules[validationName]; | ||
var addToResults = function addToResults(validation) { | ||
@@ -164,15 +154,11 @@ if (isString(validation)) { | ||
}; | ||
if (validationRulesVal && isFunction(validationsVal)) { | ||
throw new Error("Formsy does not allow you to override default validations: " + validationName); | ||
} | ||
if (!validationRulesVal && !isFunction(validationsVal)) { | ||
throw new Error("Formsy does not have the validation rule: " + validationName); | ||
} | ||
if (isFunction(validationsVal)) { | ||
return addToResults(validationsVal(currentValues, value)); | ||
} | ||
return addToResults(validationRulesVal(currentValues, value, validationsVal)); | ||
@@ -187,7 +173,5 @@ }); | ||
enableCall = false; | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
callback.apply(this, args); | ||
@@ -207,10 +191,7 @@ setTimeout(function () { | ||
} | ||
if (isTypeUndefined(value)) { | ||
return false; | ||
} | ||
return isValueUndefined(value); | ||
} | ||
function _isDefaultRequiredValue(value) { | ||
@@ -301,3 +282,2 @@ return isString(value) ? isValueStringEmpty(value) : isValueNullOrUndefined(value); | ||
var noFormsyErrorMessage = 'Could not find Formsy Context Provider. Did you use withFormsy outside <Formsy />?'; | ||
var throwNoFormsyProvider = function throwNoFormsyProvider() { | ||
@@ -307,3 +287,2 @@ // istanbul ignore next | ||
}; | ||
var defaultValue = { | ||
@@ -320,3 +299,2 @@ attachToForm: throwNoFormsyProvider, | ||
/* eslint-disable react/default-props-match-prop-types */ | ||
var convertValidationsToObject = function convertValidationsToObject(validations) { | ||
@@ -337,7 +315,5 @@ if (isString(validations)) { | ||
throw new Error('Formsy does not support multiple args on string validations. Use object format of validations instead.'); | ||
} // Avoid parameter reassignment | ||
} | ||
// Avoid parameter reassignment | ||
var validationsAccumulatorCopy = _extends({}, validationsAccumulator); | ||
validationsAccumulatorCopy[validateMethod] = args.length ? args[0] : true; | ||
@@ -347,6 +323,4 @@ return validationsAccumulatorCopy; | ||
} | ||
return validations || {}; | ||
}; | ||
var propTypes = { | ||
@@ -359,37 +333,26 @@ innerRef: PropTypes.func, | ||
}; | ||
function getDisplayName(component) { | ||
return component.displayName || component.name || (isString(component) ? component : 'Component'); | ||
} | ||
function withFormsy(WrappedComponent) { | ||
var WithFormsyWrapper = /*#__PURE__*/function (_React$Component) { | ||
_inheritsLoose(WithFormsyWrapper, _React$Component); | ||
function WithFormsyWrapper(props) { | ||
var _this; | ||
_this = _React$Component.call(this, props) || this; | ||
_this.getErrorMessage = function () { | ||
var messages = _this.getErrorMessages(); | ||
return messages.length ? messages[0] : null; | ||
}; | ||
_this.getErrorMessages = function () { | ||
var validationError = _this.state.validationError; | ||
if (!_this.isValid() || _this.showRequired()) { | ||
return validationError || []; | ||
} | ||
return []; | ||
}; // eslint-disable-next-line react/destructuring-assignment | ||
}; | ||
// eslint-disable-next-line react/destructuring-assignment | ||
_this.getValue = function () { | ||
return _this.state.value; | ||
}; | ||
_this.setValidations = function (validations, required) { | ||
@@ -401,6 +364,5 @@ // Add validations to the store itself as the props object can not be modified | ||
} : convertValidationsToObject(required); | ||
}; // By default, we validate after the value has been set. | ||
}; | ||
// By default, we validate after the value has been set. | ||
// A user can override this and pass a second parameter of `false` to skip validation. | ||
_this.setValue = function (value, validate) { | ||
@@ -410,5 +372,3 @@ if (validate === void 0) { | ||
} | ||
var validateForm = _this.props.validate; | ||
if (!validate) { | ||
@@ -426,44 +386,35 @@ _this.setState({ | ||
} | ||
}; // eslint-disable-next-line react/destructuring-assignment | ||
}; | ||
// eslint-disable-next-line react/destructuring-assignment | ||
_this.hasValue = function () { | ||
var value = _this.state.value; | ||
return _isDefaultRequiredValue(value); | ||
}; // eslint-disable-next-line react/destructuring-assignment | ||
}; | ||
// eslint-disable-next-line react/destructuring-assignment | ||
_this.isFormDisabled = function () { | ||
return _this.props.isFormDisabled; | ||
}; // eslint-disable-next-line react/destructuring-assignment | ||
}; | ||
// eslint-disable-next-line react/destructuring-assignment | ||
_this.isFormSubmitted = function () { | ||
return _this.state.formSubmitted; | ||
}; // eslint-disable-next-line react/destructuring-assignment | ||
}; | ||
// eslint-disable-next-line react/destructuring-assignment | ||
_this.isPristine = function () { | ||
return _this.state.isPristine; | ||
}; // eslint-disable-next-line react/destructuring-assignment | ||
}; | ||
// eslint-disable-next-line react/destructuring-assignment | ||
_this.isRequired = function () { | ||
return !!_this.props.required; | ||
}; // eslint-disable-next-line react/destructuring-assignment | ||
}; | ||
// eslint-disable-next-line react/destructuring-assignment | ||
_this.isValid = function () { | ||
return _this.state.isValid; | ||
}; // eslint-disable-next-line react/destructuring-assignment | ||
}; | ||
// eslint-disable-next-line react/destructuring-assignment | ||
_this.isValidValue = function (value) { | ||
return _this.props.isValidValue(_assertThisInitialized(_this), value); | ||
}; | ||
_this.resetValue = function () { | ||
var pristineValue = _this.state.pristineValue; | ||
var validate = _this.props.validate; | ||
_this.setState({ | ||
@@ -476,22 +427,17 @@ value: pristineValue, | ||
}; | ||
_this.showError = function () { | ||
return !_this.showRequired() && !_this.isValid(); | ||
}; // eslint-disable-next-line react/destructuring-assignment | ||
}; | ||
// eslint-disable-next-line react/destructuring-assignment | ||
_this.showRequired = function () { | ||
return _this.state.isRequired; | ||
}; | ||
var runValidation = props.runValidation, | ||
validations = props.validations, | ||
required = props.required, | ||
value = props.value; | ||
validations = props.validations, | ||
required = props.required, | ||
value = props.value; | ||
_this.state = { | ||
value: value | ||
}; | ||
_this.setValidations(validations, required); | ||
_this.state = _extends({ | ||
@@ -505,21 +451,15 @@ formSubmitted: false, | ||
} | ||
var _proto = WithFormsyWrapper.prototype; | ||
_proto.componentDidMount = function componentDidMount() { | ||
var _this$props = this.props, | ||
name = _this$props.name, | ||
attachToForm = _this$props.attachToForm; | ||
name = _this$props.name, | ||
attachToForm = _this$props.attachToForm; | ||
if (!name) { | ||
throw new Error('Form Input requires a name property when used'); | ||
} | ||
attachToForm(this); | ||
}; | ||
_proto.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) { | ||
var props = this.props, | ||
state = this.state; | ||
state = this.state; | ||
var isChanged = function isChanged(a, b) { | ||
@@ -530,3 +470,2 @@ return Object.keys(a).some(function (k) { | ||
}; | ||
var isPropsChanged = isChanged(props, nextProps); | ||
@@ -536,16 +475,14 @@ var isStateChanged = isChanged(state, nextState); | ||
}; | ||
_proto.componentDidUpdate = function componentDidUpdate(prevProps) { | ||
var _this$props2 = this.props, | ||
value = _this$props2.value, | ||
validations = _this$props2.validations, | ||
required = _this$props2.required, | ||
validate = _this$props2.validate; // If the value passed has changed, set it. If value is not passed it will | ||
value = _this$props2.value, | ||
validations = _this$props2.validations, | ||
required = _this$props2.required, | ||
validate = _this$props2.validate; | ||
// If the value passed has changed, set it. If value is not passed it will | ||
// internally update, and this will never run | ||
if (!isSame(value, prevProps.value)) { | ||
this.setValue(value); | ||
} // If validations or required is changed, run a new validation | ||
} | ||
// If validations or required is changed, run a new validation | ||
if (!isSame(validations, prevProps.validations) || !isSame(required, prevProps.required)) { | ||
@@ -555,5 +492,5 @@ this.setValidations(validations, required); | ||
} | ||
} // Detach it when component unmounts | ||
} | ||
// Detach it when component unmounts | ||
; | ||
_proto.componentWillUnmount = function componentWillUnmount() { | ||
@@ -563,6 +500,4 @@ var detachFromForm = this.props.detachFromForm; | ||
}; | ||
_proto.render = function render() { | ||
var innerRef = this.props.innerRef; | ||
var propsForElement = _extends({}, this.props, { | ||
@@ -585,13 +520,9 @@ errorMessage: this.getErrorMessage(), | ||
}); | ||
if (innerRef) { | ||
propsForElement.ref = innerRef; | ||
} | ||
return React.createElement(WrappedComponent, propsForElement); | ||
}; | ||
return WithFormsyWrapper; | ||
}(React.Component); | ||
WithFormsyWrapper.displayName = "Formsy(" + getDisplayName(WrappedComponent) + ")"; | ||
@@ -606,4 +537,4 @@ WithFormsyWrapper.propTypes = propTypes; | ||
value: WrappedComponent.defaultValue | ||
}; // eslint-disable-next-line react/display-name | ||
}; | ||
// eslint-disable-next-line react/display-name | ||
return function (props) { | ||
@@ -616,12 +547,10 @@ return React.createElement(FormsyContext.Consumer, null, function (contextValue) { | ||
var _excluded = ["children", "mapping", "onChange", "onInvalid", "onInvalidSubmit", "onReset", "onSubmit", "onValid", "onValidSubmit", "preventDefaultSubmit", "preventExternalInvalidation", "validationErrors", "disabled", "formElement"]; | ||
var ONE_RENDER_FRAME = 66; | ||
var Formsy = /*#__PURE__*/function (_React$Component) { | ||
_inheritsLoose(Formsy, _React$Component); | ||
function Formsy(props) { | ||
var _this; | ||
_this = _React$Component.call(this, props) || this; | ||
_this.prevInputNames = null; | ||
_this.componentDidMount = function () { | ||
@@ -631,26 +560,19 @@ _this.prevInputNames = _this.inputs.map(function (component) { | ||
}); | ||
_this.validateForm(); | ||
}; | ||
_this.componentDidUpdate = function (prevProps) { | ||
var _this$props = _this.props, | ||
validationErrors = _this$props.validationErrors, | ||
disabled = _this$props.disabled; | ||
validationErrors = _this$props.validationErrors, | ||
disabled = _this$props.disabled; | ||
if (validationErrors && isObject(validationErrors) && Object.keys(validationErrors).length > 0) { | ||
_this.setInputValidationErrors(validationErrors); | ||
} | ||
var newInputNames = _this.inputs.map(function (component) { | ||
return component.props.name; | ||
}); | ||
if (_this.prevInputNames && !isSame(_this.prevInputNames, newInputNames)) { | ||
_this.prevInputNames = newInputNames; | ||
_this.validateForm(); | ||
} // Keep the disabled value in state/context the same as from props | ||
} | ||
// Keep the disabled value in state/context the same as from props | ||
if (disabled !== prevProps.disabled) { | ||
@@ -667,8 +589,7 @@ // eslint-disable-next-line | ||
}; | ||
_this.getCurrentValues = function () { | ||
return _this.inputs.reduce(function (valueAccumulator, component) { | ||
var name = component.props.name, | ||
value = component.state.value; // eslint-disable-next-line no-param-reassign | ||
value = component.state.value; | ||
// eslint-disable-next-line no-param-reassign | ||
valueAccumulator[name] = protectAgainstParamReassignment(value); | ||
@@ -678,15 +599,12 @@ return valueAccumulator; | ||
}; | ||
_this.getModel = function () { | ||
var currentValues = _this.getCurrentValues(); | ||
return _this.mapModel(currentValues); | ||
}; | ||
_this.getPristineValues = function () { | ||
return _this.inputs.reduce(function (valueAccumulator, component) { | ||
var _component$props = component.props, | ||
name = _component$props.name, | ||
value = _component$props.value; // eslint-disable-next-line no-param-reassign | ||
name = _component$props.name, | ||
value = _component$props.value; | ||
// eslint-disable-next-line no-param-reassign | ||
valueAccumulator[name] = protectAgainstParamReassignment(value); | ||
@@ -696,10 +614,8 @@ return valueAccumulator; | ||
}; | ||
_this.setFormPristine = function (isPristine) { | ||
_this.setState({ | ||
formSubmitted: !isPristine | ||
}); // Iterate through each component and set it as pristine | ||
}); | ||
// Iterate through each component and set it as pristine | ||
// or "dirty". | ||
_this.inputs.forEach(function (component) { | ||
@@ -712,7 +628,5 @@ component.setState({ | ||
}; | ||
_this.setInputValidationErrors = function (errors) { | ||
var preventExternalInvalidation = _this.props.preventExternalInvalidation; | ||
var isValid = _this.state.isValid; | ||
_this.inputs.forEach(function (component) { | ||
@@ -725,3 +639,2 @@ var name = component.props.name; | ||
}); | ||
if (!preventExternalInvalidation && isValid) { | ||
@@ -731,12 +644,9 @@ _this.setFormValidState(false); | ||
}; | ||
_this.setFormValidState = function (allIsValid) { | ||
var _this$props2 = _this.props, | ||
onValid = _this$props2.onValid, | ||
onInvalid = _this$props2.onInvalid; | ||
onValid = _this$props2.onValid, | ||
onInvalid = _this$props2.onInvalid; | ||
_this.setState({ | ||
isValid: allIsValid | ||
}); | ||
if (allIsValid) { | ||
@@ -748,19 +658,14 @@ onValid(); | ||
}; | ||
_this.isValidValue = function (component, value) { | ||
return _this.runValidation(component, value).isValid; | ||
}; // eslint-disable-next-line react/destructuring-assignment | ||
}; | ||
// eslint-disable-next-line react/destructuring-assignment | ||
_this.isFormDisabled = function () { | ||
return _this.props.disabled; | ||
}; | ||
_this.mapModel = function (model) { | ||
var mapping = _this.props.mapping; | ||
if (mapping) { | ||
return mapping(model); | ||
} | ||
var returnModel = {}; | ||
@@ -772,25 +677,18 @@ Object.keys(model).forEach(function (key) { | ||
}; | ||
_this.reset = function (model) { | ||
_this.setFormPristine(true); | ||
_this.resetModel(model); | ||
}; | ||
_this.resetInternal = function (event) { | ||
var onReset = _this.props.onReset; | ||
event.preventDefault(); | ||
_this.reset(); | ||
if (onReset) { | ||
onReset(); | ||
} | ||
}; // Reset each key in the model to the original / initial / specified value | ||
}; | ||
// Reset each key in the model to the original / initial / specified value | ||
_this.resetModel = function (data) { | ||
_this.inputs.forEach(function (component) { | ||
var name = component.props.name; | ||
if (data && has(data, name)) { | ||
@@ -802,7 +700,5 @@ component.setValue(get(data, name)); | ||
}); | ||
_this.validateForm(); | ||
}; // Checks validation on current value or a passed value | ||
}; | ||
// Checks validation on current value or a passed value | ||
_this.runValidation = function (component, value) { | ||
@@ -812,11 +708,8 @@ if (value === void 0) { | ||
} | ||
var validationErrors = _this.props.validationErrors; | ||
var _component$props2 = component.props, | ||
validationError = _component$props2.validationError, | ||
componentValidationErrors = _component$props2.validationErrors, | ||
name = _component$props2.name; | ||
validationError = _component$props2.validationError, | ||
componentValidationErrors = _component$props2.validationErrors, | ||
name = _component$props2.name; | ||
var currentValues = _this.getCurrentValues(); | ||
var validationResults = runRules(value, currentValues, component.validations, validations); | ||
@@ -833,11 +726,8 @@ var requiredResults = runRules(value, currentValues, component.requiredValidations, validations); | ||
} | ||
if (validationResults.errors.length) { | ||
return validationResults.errors; | ||
} | ||
if (validationErrors && validationErrors[name]) { | ||
return isString(validationErrors[name]) ? [validationErrors[name]] : validationErrors[name]; | ||
} | ||
if (isRequired) { | ||
@@ -847,3 +737,2 @@ var error = componentValidationErrors[requiredResults.success[0]] || validationError; | ||
} | ||
if (validationResults.failed.length) { | ||
@@ -855,13 +744,11 @@ return validationResults.failed.map(function (failed) { | ||
}); // remove duplicates | ||
} // This line is not reachable | ||
} | ||
// This line is not reachable | ||
// istanbul ignore next | ||
return undefined; | ||
}() | ||
}; | ||
}; // Method put on each input component to register | ||
}; | ||
// Method put on each input component to register | ||
// itself to the form | ||
_this.attachToForm = function (component) { | ||
@@ -871,53 +758,41 @@ if (_this.inputs.indexOf(component) === -1) { | ||
} | ||
var onChange = _this.props.onChange; | ||
var canChange = _this.state.canChange; // Trigger onChange | ||
var canChange = _this.state.canChange; | ||
// Trigger onChange | ||
if (canChange) { | ||
onChange(_this.getModel(), _this.isChanged()); | ||
} // Will be triggered immediately & every one frame rate | ||
} | ||
// Will be triggered immediately & every one frame rate | ||
_this.throttledValidateForm(); | ||
}; // Method put on each input component to unregister | ||
}; | ||
// Method put on each input component to unregister | ||
// itself from the form | ||
_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(); | ||
}; // Checks if the values have changed from their initial value | ||
}; | ||
// Checks if the values have changed from their initial value | ||
_this.isChanged = function () { | ||
return !isSame(_this.getPristineValues(), _this.getCurrentValues()); | ||
}; // Update model, submit to url prop and send the model | ||
}; | ||
// Update model, submit to url prop and send the model | ||
_this.submit = function (event) { | ||
var _this$props3 = _this.props, | ||
onSubmit = _this$props3.onSubmit, | ||
onValidSubmit = _this$props3.onValidSubmit, | ||
onInvalidSubmit = _this$props3.onInvalidSubmit, | ||
preventDefaultSubmit = _this$props3.preventDefaultSubmit; | ||
onSubmit = _this$props3.onSubmit, | ||
onValidSubmit = _this$props3.onValidSubmit, | ||
onInvalidSubmit = _this$props3.onInvalidSubmit, | ||
preventDefaultSubmit = _this$props3.preventDefaultSubmit; | ||
var isValid = _this.state.isValid; | ||
if (preventDefaultSubmit && event && event.preventDefault) { | ||
event.preventDefault(); | ||
} // Trigger form as not pristine. | ||
} | ||
// Trigger form as not pristine. | ||
// If any inputs have not been touched yet this will make them dirty | ||
// so validation becomes visible (if based on isPristine) | ||
_this.setFormPristine(false); | ||
var model = _this.getModel(); | ||
onSubmit(model, _this.resetModel, _this.updateInputsWithError, event); | ||
if (isValid) { | ||
@@ -928,7 +803,6 @@ onValidSubmit(model, _this.resetModel, _this.updateInputsWithError, event); | ||
} | ||
}; // Go through errors from server and grab the components | ||
}; | ||
// Go through errors from server and grab the components | ||
// stored in the inputs map. Change their state to invalid | ||
// and set the serverError message | ||
_this.updateInputsWithError = function (errors, invalidate) { | ||
@@ -939,12 +813,9 @@ var preventExternalInvalidation = _this.props.preventExternalInvalidation; | ||
var name = _ref[0], | ||
error = _ref[1]; | ||
error = _ref[1]; | ||
var component = _this.inputs.find(function (input) { | ||
return input.props.name === name; | ||
}); | ||
if (!component) { | ||
throw new Error("You are trying to update an input that does not exist. Verify errors object with input names. " + JSON.stringify(errors)); | ||
} | ||
component.setState({ | ||
@@ -955,13 +826,10 @@ isValid: preventExternalInvalidation, | ||
}); | ||
if (invalidate && isValid) { | ||
_this.setFormValidState(false); | ||
} | ||
}; // Set the value of components | ||
}; | ||
// Set the value of components | ||
_this.updateInputsWithValue = function (data, validate) { | ||
_this.inputs.forEach(function (component) { | ||
var name = component.props.name; | ||
if (data && has(data, name)) { | ||
@@ -971,24 +839,20 @@ component.setValue(get(data, name), validate); | ||
}); | ||
}; // Use the binded values and the actual input value to | ||
}; | ||
// Use the binded values and the actual input value to | ||
// validate the input and set its state. Then check the | ||
// state of the form itself | ||
_this.validate = function (component) { | ||
var onChange = _this.props.onChange; | ||
var canChange = _this.state.canChange; // Trigger onChange | ||
var canChange = _this.state.canChange; | ||
// Trigger onChange | ||
if (canChange) { | ||
onChange(_this.getModel(), _this.isChanged()); | ||
} | ||
var validationState = _this.runValidation(component); // Run through the validations, split them up and call | ||
var validationState = _this.runValidation(component); | ||
// Run through the validations, split them up and call | ||
// the validator IF there is a value or it is required | ||
component.setState(validationState, _this.validateForm); | ||
}; // Validate the form by going through all child input components | ||
}; | ||
// Validate the form by going through all child input components | ||
// and check their state | ||
_this.validateForm = function () { | ||
@@ -1001,23 +865,18 @@ // We need a callback as we are validating all inputs again. This will | ||
}); | ||
_this.setFormValidState(allIsValid); // Tell the form that it can start to trigger change events | ||
_this.setFormValidState(allIsValid); | ||
// Tell the form that it can start to trigger change events | ||
_this.setState({ | ||
canChange: true | ||
}); | ||
}; // Run validation again in case affected by other inputs. The | ||
}; | ||
// 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 | ||
}); | ||
// 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) { | ||
@@ -1029,3 +888,2 @@ _this.setState({ | ||
}; | ||
_this.state = { | ||
@@ -1049,12 +907,9 @@ canChange: false, | ||
} | ||
var _proto = Formsy.prototype; | ||
_proto.render = function render() { | ||
var _this$props4 = this.props, | ||
children = _this$props4.children, | ||
disabled = _this$props4.disabled, | ||
formElement = _this$props4.formElement, | ||
nonFormsyProps = _objectWithoutPropertiesLoose(_this$props4, ["children", "mapping", "onChange", "onInvalid", "onInvalidSubmit", "onReset", "onSubmit", "onValid", "onValidSubmit", "preventDefaultSubmit", "preventExternalInvalidation", "validationErrors", "disabled", "formElement"]); | ||
children = _this$props4.children, | ||
disabled = _this$props4.disabled, | ||
formElement = _this$props4.formElement, | ||
nonFormsyProps = _objectWithoutPropertiesLoose(_this$props4, _excluded); | ||
var contextValue = this.state.contextValue; | ||
@@ -1070,3 +925,2 @@ return React.createElement(FormsyContext.Provider, { | ||
}; | ||
return Formsy; | ||
@@ -1073,0 +927,0 @@ }(React.Component); |
{ | ||
"name": "formsy-react", | ||
"version": "2.2.8", | ||
"version": "2.3.0", | ||
"description": "A form input builder and validator for React", | ||
@@ -48,9 +48,9 @@ "keywords": [ | ||
"devDependencies": { | ||
"@testing-library/jest-dom": "^5.16.4", | ||
"@testing-library/react": "^12.1.5", | ||
"@types/jest": "^26.0.13", | ||
"@types/lodash": "^4.14.168", | ||
"@types/prop-types": "^15.7.1", | ||
"@types/react": "^17.0.0", | ||
"@types/react-dom": "^17.0.0", | ||
"@testing-library/jest-dom": "^5.16.5", | ||
"@testing-library/react": "^13.4.0", | ||
"@types/jest": "^29.2.2", | ||
"@types/lodash": "^4.14.188", | ||
"@types/prop-types": "^15.7.5", | ||
"@types/react": "^18.0.25", | ||
"@types/react-dom": "^18.0.8", | ||
"auto-changelog": "^2.4.0", | ||
@@ -62,4 +62,4 @@ "coveralls": "^3.1.1", | ||
"prettier": "^2.7.1", | ||
"react": "^16.2.0 || ^16.0.0", | ||
"react-dom": "^16.2.0 || ^16.0.0", | ||
"react": "^18.0.0", | ||
"react-dom": "^18.0.0", | ||
"tsdx": "^0.14.1", | ||
@@ -70,4 +70,4 @@ "tslib": "^2.4.0", | ||
"peerDependencies": { | ||
"react": "^16.0.0 || ^17.0.0", | ||
"react-dom": "^16.0.0 || ^17.0.0" | ||
"react": "^16.0.0 || ^17.0.0 || ^18.0.0", | ||
"react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0" | ||
}, | ||
@@ -74,0 +74,0 @@ "standard-version": { |
@@ -315,5 +315,5 @@ import PropTypes from 'prop-types'; | ||
return (props) => | ||
React.createElement(FormsyContext.Consumer, null, (contextValue) => { | ||
React.createElement(FormsyContext.Consumer, null, ((contextValue) => { | ||
return React.createElement(WithFormsyWrapper, { ...props, ...contextValue }); | ||
}); | ||
}) as any); | ||
} |
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
356600
3046