final-form
Advanced tools
Comparing version 4.20.9 to 4.20.10
'use strict'; | ||
Object.defineProperty(exports, '__esModule', { value: true }); | ||
var _extends = require('@babel/runtime/helpers/extends'); | ||
var _objectWithoutPropertiesLoose = require('@babel/runtime/helpers/objectWithoutPropertiesLoose'); | ||
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } | ||
// | ||
var _extends__default = /*#__PURE__*/_interopDefaultLegacy(_extends); | ||
var _objectWithoutPropertiesLoose__default = /*#__PURE__*/_interopDefaultLegacy(_objectWithoutPropertiesLoose); | ||
// | ||
var charCodeOfDot = ".".charCodeAt(0); | ||
var reEscapeChar = /\\(\\)?/g; | ||
var rePropName = RegExp( // Match anything that isn't a dot or bracket. | ||
"[^.[\\]]+" + "|" + // Or match property names within brackets. | ||
"\\[(?:" + // Match a non-string expression. | ||
"([^\"'][^[]*)" + "|" + // Or match strings (supports escaping characters). | ||
"([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2" + ")\\]" + "|" + // Or match "" as the space between consecutive dots or empty brackets. | ||
var rePropName = RegExp( | ||
// Match anything that isn't a dot or bracket. | ||
"[^.[\\]]+" + "|" + | ||
// Or match property names within brackets. | ||
"\\[(?:" + | ||
// Match a non-string expression. | ||
"([^\"'][^[]*)" + "|" + | ||
// Or match strings (supports escaping characters). | ||
"([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2" + ")\\]" + "|" + | ||
// Or match "" as the space between consecutive dots or empty brackets. | ||
"(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))", "g"); | ||
/** | ||
@@ -29,13 +29,9 @@ * Converts `string` to a property path array. | ||
*/ | ||
var stringToPath = function stringToPath(string) { | ||
var result = []; | ||
if (string.charCodeAt(0) === charCodeOfDot) { | ||
result.push(""); | ||
} | ||
string.replace(rePropName, function (match, expression, quote, subString) { | ||
var key = match; | ||
if (quote) { | ||
@@ -46,3 +42,2 @@ key = subString.replace(reEscapeChar, "$1"); | ||
} | ||
result.push(key); | ||
@@ -52,6 +47,4 @@ }); | ||
}; | ||
var keysCache = {}; | ||
var keysRegex = /[.[\]]+/; | ||
var toPath = function toPath(key) { | ||
@@ -61,7 +54,5 @@ if (key === null || key === undefined || !key.length) { | ||
} | ||
if (typeof key !== "string") { | ||
throw new Error("toPath() expects a string"); | ||
} | ||
if (keysCache[key] == null) { | ||
@@ -89,3 +80,2 @@ /** | ||
} | ||
return keysCache[key]; | ||
@@ -95,3 +85,2 @@ }; | ||
// | ||
var getIn = function getIn(state, complexKey) { | ||
@@ -101,13 +90,9 @@ // Intentionally using iteration rather than recursion | ||
var current = state; | ||
for (var i = 0; i < path.length; i++) { | ||
var key = path[i]; | ||
if (current === undefined || current === null || typeof current !== "object" || Array.isArray(current) && isNaN(key)) { | ||
return undefined; | ||
} | ||
current = current[key]; | ||
} | ||
return current; | ||
@@ -117,5 +102,3 @@ }; | ||
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } | ||
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } | ||
var setInRecursor = function setInRecursor(current, index, path, value, destroyArrays) { | ||
@@ -126,29 +109,23 @@ if (index >= path.length) { | ||
} | ||
var key = path[index]; | ||
var key = path[index]; // determine type of key | ||
// determine type of key | ||
if (isNaN(key)) { | ||
var _extends2; | ||
// object set | ||
if (current === undefined || current === null) { | ||
var _ref; | ||
// recurse | ||
var _result2 = setInRecursor(undefined, index + 1, path, value, destroyArrays); // delete or create an object | ||
var _result = setInRecursor(undefined, index + 1, path, value, destroyArrays); | ||
return _result2 === undefined ? undefined : (_ref = {}, _ref[key] = _result2, _ref); | ||
// delete or create an object | ||
return _result === undefined ? undefined : (_ref = {}, _ref[key] = _result, _ref); | ||
} | ||
if (Array.isArray(current)) { | ||
throw new Error("Cannot set a non-numeric property on an array"); | ||
} // current exists, so make a copy of all its values, and add/update the new one | ||
var _result = setInRecursor(current[key], index + 1, path, value, destroyArrays); | ||
if (_result === undefined) { | ||
} | ||
// current exists, so make a copy of all its values, and add/update the new one | ||
var _result2 = setInRecursor(current[key], index + 1, path, value, destroyArrays); | ||
if (_result2 === undefined) { | ||
var numKeys = Object.keys(current).length; | ||
if (current[key] === undefined && numKeys === 0) { | ||
@@ -158,3 +135,2 @@ // object was already empty | ||
} | ||
if (current[key] !== undefined && numKeys <= 1) { | ||
@@ -169,26 +145,21 @@ // only key we had was the one we are deleting | ||
} | ||
current[key]; | ||
var _final = _objectWithoutPropertiesLoose__default["default"](current, [key].map(_toPropertyKey)); | ||
var _final = _objectWithoutPropertiesLoose(current, [key].map(_toPropertyKey)); | ||
return _final; | ||
} // set result in key | ||
return _extends__default["default"]({}, current, (_extends2 = {}, _extends2[key] = _result, _extends2)); | ||
} // array set | ||
} | ||
// set result in key | ||
return _extends({}, current, (_extends2 = {}, _extends2[key] = _result2, _extends2)); | ||
} | ||
// array set | ||
var numericKey = Number(key); | ||
if (current === undefined || current === null) { | ||
// recurse | ||
var _result3 = setInRecursor(undefined, index + 1, path, value, destroyArrays); // if nothing returned, delete it | ||
var _result3 = setInRecursor(undefined, index + 1, path, value, destroyArrays); | ||
// if nothing returned, delete it | ||
if (_result3 === undefined) { | ||
return undefined; | ||
} // create an array | ||
} | ||
// create an array | ||
var _array = []; | ||
@@ -198,16 +169,13 @@ _array[numericKey] = _result3; | ||
} | ||
if (!Array.isArray(current)) { | ||
throw new Error("Cannot set a numeric property on an object"); | ||
} // recurse | ||
} | ||
// recurse | ||
var existingValue = current[numericKey]; | ||
var result = setInRecursor(existingValue, index + 1, path, value, destroyArrays); // current exists, so make a copy of all its values, and add/update the new one | ||
var result = setInRecursor(existingValue, index + 1, path, value, destroyArrays); | ||
// current exists, so make a copy of all its values, and add/update the new one | ||
var array = [].concat(current); | ||
if (destroyArrays && result === undefined) { | ||
array.splice(numericKey, 1); | ||
if (array.length === 0) { | ||
@@ -219,6 +187,4 @@ return undefined; | ||
} | ||
return array; | ||
}; | ||
var setIn = function setIn(state, key, value, destroyArrays) { | ||
@@ -228,13 +194,10 @@ if (destroyArrays === void 0) { | ||
} | ||
if (state === undefined || state === null) { | ||
throw new Error("Cannot call setIn() with " + String(state) + " state"); | ||
} | ||
if (key === undefined || key === null) { | ||
throw new Error("Cannot call setIn() with " + String(key) + " key"); | ||
} // Recursive function needs to accept and return State, but public API should | ||
} | ||
// Recursive function needs to accept and return State, but public API should | ||
// only deal with Objects | ||
return setInRecursor(state, 0, toPath(key), value, destroyArrays); | ||
@@ -247,33 +210,32 @@ }; | ||
// | ||
/** | ||
* Converts internal field state to published field state | ||
*/ | ||
function publishFieldState(formState, field) { | ||
var errors = formState.errors, | ||
initialValues = formState.initialValues, | ||
lastSubmittedValues = formState.lastSubmittedValues, | ||
submitErrors = formState.submitErrors, | ||
submitFailed = formState.submitFailed, | ||
submitSucceeded = formState.submitSucceeded, | ||
submitting = formState.submitting, | ||
values = formState.values; | ||
initialValues = formState.initialValues, | ||
lastSubmittedValues = formState.lastSubmittedValues, | ||
submitErrors = formState.submitErrors, | ||
submitFailed = formState.submitFailed, | ||
submitSucceeded = formState.submitSucceeded, | ||
submitting = formState.submitting, | ||
values = formState.values; | ||
var active = field.active, | ||
blur = field.blur, | ||
change = field.change, | ||
data = field.data, | ||
focus = field.focus, | ||
modified = field.modified, | ||
modifiedSinceLastSubmit = field.modifiedSinceLastSubmit, | ||
name = field.name, | ||
touched = field.touched, | ||
validating = field.validating, | ||
visited = field.visited; | ||
blur = field.blur, | ||
change = field.change, | ||
data = field.data, | ||
focus = field.focus, | ||
modified = field.modified, | ||
modifiedSinceLastSubmit = field.modifiedSinceLastSubmit, | ||
name = field.name, | ||
touched = field.touched, | ||
validating = field.validating, | ||
visited = field.visited; | ||
var value = getIn(values, name); | ||
var error = getIn(errors, name); | ||
if (error && error[ARRAY_ERROR]) { | ||
error = error[ARRAY_ERROR]; | ||
} | ||
var submitError = submitErrors && getIn(submitErrors, name); | ||
@@ -316,2 +278,3 @@ var initial = initialValues && getIn(initialValues, name); | ||
// | ||
var shallowEqual = function shallowEqual(a, b) { | ||
@@ -321,19 +284,13 @@ if (a === b) { | ||
} | ||
if (typeof a !== "object" || !a || typeof b !== "object" || !b) { | ||
return false; | ||
} | ||
var keysA = Object.keys(a); | ||
var keysB = Object.keys(b); | ||
if (keysA.length !== keysB.length) { | ||
return false; | ||
} | ||
var bHasOwnProperty = Object.prototype.hasOwnProperty.bind(b); | ||
for (var idx = 0; idx < keysA.length; idx++) { | ||
var key = keysA[idx]; | ||
if (!bHasOwnProperty(key) || a[key] !== b[key]) { | ||
@@ -343,3 +300,2 @@ return false; | ||
} | ||
return true; | ||
@@ -354,3 +310,2 @@ }; | ||
dest[key] = src[key]; | ||
if (!previous || (~shallowEqualKeys.indexOf(key) ? !shallowEqual(src[key], previous[key]) : src[key] !== previous[key])) { | ||
@@ -366,6 +321,6 @@ different = true; | ||
var shallowEqualKeys$1 = ["data"]; | ||
/** | ||
* Filters items in a FieldState based on a FieldSubscription | ||
*/ | ||
var filterFieldState = function filterFieldState(state, previousState, subscription, force) { | ||
@@ -387,6 +342,6 @@ var result = { | ||
var shallowEqualKeys = ["touched", "visited"]; | ||
/** | ||
* Filters items in a FormState based on a FormSubscription | ||
*/ | ||
function filterFormState(state, previousState, subscription, force) { | ||
@@ -399,3 +354,2 @@ var result = {}; | ||
// | ||
var memoize = function memoize(fn) { | ||
@@ -408,3 +362,2 @@ var lastArgs; | ||
} | ||
if (!lastArgs || args.length !== lastArgs.length || args.some(function (arg, index) { | ||
@@ -416,3 +369,2 @@ return !shallowEqual(lastArgs[index], arg); | ||
} | ||
return lastResult; | ||
@@ -426,38 +378,33 @@ }; | ||
var version = "4.20.9"; | ||
var version = "4.20.10"; | ||
var configOptions = ["debug", "initialValues", "keepDirtyOnReinitialize", "mutators", "onSubmit", "validate", "validateOnBlur"]; | ||
var tripleEquals = function tripleEquals(a, b) { | ||
return a === b; | ||
}; | ||
var hasAnyError = function hasAnyError(errors) { | ||
return Object.keys(errors).some(function (key) { | ||
var value = errors[key]; | ||
if (value && typeof value === "object" && !(value instanceof Error)) { | ||
return hasAnyError(value); | ||
} | ||
return typeof value !== "undefined"; | ||
}); | ||
}; | ||
function convertToExternalFormState(_ref) { | ||
var active = _ref.active, | ||
dirtySinceLastSubmit = _ref.dirtySinceLastSubmit, | ||
modifiedSinceLastSubmit = _ref.modifiedSinceLastSubmit, | ||
error = _ref.error, | ||
errors = _ref.errors, | ||
initialValues = _ref.initialValues, | ||
pristine = _ref.pristine, | ||
submitting = _ref.submitting, | ||
submitFailed = _ref.submitFailed, | ||
submitSucceeded = _ref.submitSucceeded, | ||
submitError = _ref.submitError, | ||
submitErrors = _ref.submitErrors, | ||
valid = _ref.valid, | ||
validating = _ref.validating, | ||
values = _ref.values; | ||
dirtySinceLastSubmit = _ref.dirtySinceLastSubmit, | ||
modifiedSinceLastSubmit = _ref.modifiedSinceLastSubmit, | ||
error = _ref.error, | ||
errors = _ref.errors, | ||
initialValues = _ref.initialValues, | ||
pristine = _ref.pristine, | ||
submitting = _ref.submitting, | ||
submitFailed = _ref.submitFailed, | ||
submitSucceeded = _ref.submitSucceeded, | ||
submitError = _ref.submitError, | ||
submitErrors = _ref.submitErrors, | ||
valid = _ref.valid, | ||
validating = _ref.validating, | ||
values = _ref.values; | ||
return { | ||
@@ -485,6 +432,4 @@ active: active, | ||
} | ||
function notifySubscriber(subscriber, subscription, state, lastState, filter, force) { | ||
var notification = filter(state, lastState, subscription, force); | ||
if (notification) { | ||
@@ -494,16 +439,13 @@ subscriber(notification); | ||
} | ||
return false; | ||
} | ||
function notify(_ref2, state, lastState, filter, force) { | ||
var entries = _ref2.entries; | ||
Object.keys(entries).forEach(function (key) { | ||
var entry = entries[Number(key)]; // istanbul ignore next | ||
var entry = entries[Number(key)]; | ||
// istanbul ignore next | ||
if (entry) { | ||
var subscription = entry.subscription, | ||
subscriber = entry.subscriber, | ||
notified = entry.notified; | ||
subscriber = entry.subscriber, | ||
notified = entry.notified; | ||
if (notifySubscriber(subscriber, subscription, state, lastState, filter, force || !notified)) { | ||
@@ -515,3 +457,2 @@ entry.notified = true; | ||
} | ||
function createForm(config) { | ||
@@ -521,16 +462,13 @@ if (!config) { | ||
} | ||
var debug = config.debug, | ||
destroyOnUnregister = config.destroyOnUnregister, | ||
keepDirtyOnReinitialize = config.keepDirtyOnReinitialize, | ||
initialValues = config.initialValues, | ||
mutators = config.mutators, | ||
onSubmit = config.onSubmit, | ||
validate = config.validate, | ||
validateOnBlur = config.validateOnBlur; | ||
destroyOnUnregister = config.destroyOnUnregister, | ||
keepDirtyOnReinitialize = config.keepDirtyOnReinitialize, | ||
initialValues = config.initialValues, | ||
mutators = config.mutators, | ||
onSubmit = config.onSubmit, | ||
validate = config.validate, | ||
validateOnBlur = config.validateOnBlur; | ||
if (!onSubmit) { | ||
throw new Error("No onSubmit function specified"); | ||
} | ||
var state = { | ||
@@ -548,3 +486,3 @@ subscribers: { | ||
errors: {}, | ||
initialValues: initialValues && _extends__default["default"]({}, initialValues), | ||
initialValues: initialValues && _extends({}, initialValues), | ||
invalid: false, | ||
@@ -558,3 +496,3 @@ pristine: true, | ||
validating: 0, | ||
values: initialValues ? _extends__default["default"]({}, initialValues) : {} | ||
values: initialValues ? _extends({}, initialValues) : {} | ||
}, | ||
@@ -569,3 +507,2 @@ lastFormState: undefined | ||
var asyncValidationPromises = {}; | ||
var clearAsyncValidationPromise = function clearAsyncValidationPromise(key) { | ||
@@ -577,3 +514,2 @@ return function (result) { | ||
}; | ||
var changeValue = function changeValue(state, name, mutate) { | ||
@@ -584,8 +520,6 @@ var before = getIn(state.formState.values, name); | ||
}; | ||
var renameField = function renameField(state, from, to) { | ||
if (state.fields[from]) { | ||
var _extends2, _extends3; | ||
state.fields = _extends__default["default"]({}, state.fields, (_extends2 = {}, _extends2[to] = _extends__default["default"]({}, state.fields[from], { | ||
state.fields = _extends({}, state.fields, (_extends2 = {}, _extends2[to] = _extends({}, state.fields[from], { | ||
name: to, | ||
@@ -605,3 +539,3 @@ // rebind event handlers | ||
delete state.fields[from]; | ||
state.fieldSubscribers = _extends__default["default"]({}, state.fieldSubscribers, (_extends3 = {}, _extends3[to] = state.fieldSubscribers[from], _extends3)); | ||
state.fieldSubscribers = _extends({}, state.fieldSubscribers, (_extends3 = {}, _extends3[to] = state.fieldSubscribers[from], _extends3)); | ||
delete state.fieldSubscribers[from]; | ||
@@ -613,5 +547,5 @@ var value = getIn(state.formState.values, from); | ||
} | ||
}; // bind state to mutators | ||
}; | ||
// bind state to mutators | ||
var getMutatorApi = function getMutatorApi(key) { | ||
@@ -628,7 +562,5 @@ return function () { | ||
}; | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
var returnValue = mutators[key](args, mutatableState, { | ||
@@ -654,3 +586,2 @@ changeValue: changeValue, | ||
}; | ||
var mutatorsApi = mutators ? Object.keys(mutators).reduce(function (result, key) { | ||
@@ -660,9 +591,6 @@ result[key] = getMutatorApi(key); | ||
}, {}) : {}; | ||
var runRecordLevelValidation = function runRecordLevelValidation(setErrors) { | ||
var promises = []; | ||
if (validate) { | ||
var errorsOrPromise = validate(_extends__default["default"]({}, state.formState.values)); // clone to avoid writing | ||
var errorsOrPromise = validate(_extends({}, state.formState.values)); // clone to avoid writing | ||
if (isPromise(errorsOrPromise)) { | ||
@@ -676,22 +604,16 @@ promises.push(errorsOrPromise.then(function (errors) { | ||
} | ||
return promises; | ||
}; | ||
var getValidators = function getValidators(field) { | ||
return Object.keys(field.validators).reduce(function (result, index) { | ||
var validator = field.validators[Number(index)](); | ||
if (validator) { | ||
result.push(validator); | ||
} | ||
return result; | ||
}, []); | ||
}; | ||
var runFieldLevelValidation = function runFieldLevelValidation(field, setError) { | ||
var promises = []; | ||
var validators = getValidators(field); | ||
if (validators.length) { | ||
@@ -701,3 +623,2 @@ var error; | ||
var errorOrPromise = validator(getIn(state.formState.values, field.name), state.formState.values, validator.length === 0 || validator.length === 3 ? publishFieldState(state.formState, state.fields[field.name]) : undefined); | ||
if (errorOrPromise && isPromise(errorOrPromise)) { | ||
@@ -711,3 +632,2 @@ field.validating = true; | ||
}); // errors must be resolved, not rejected | ||
promises.push(promise); | ||
@@ -721,6 +641,4 @@ } else if (!error) { | ||
} | ||
return promises; | ||
}; | ||
var runValidation = function runValidation(fieldChanged, callback) { | ||
@@ -732,10 +650,6 @@ if (validationPaused) { | ||
} | ||
var fields = state.fields, | ||
formState = state.formState; | ||
var safeFields = _extends__default["default"]({}, fields); | ||
formState = state.formState; | ||
var safeFields = _extends({}, fields); | ||
var fieldKeys = Object.keys(safeFields); | ||
if (!validate && !fieldKeys.some(function (key) { | ||
@@ -746,13 +660,10 @@ return getValidators(safeFields[key]).length; | ||
return; // no validation rules | ||
} // pare down field keys to actually validate | ||
} | ||
// pare down field keys to actually validate | ||
var limitedFieldLevelValidation = false; | ||
if (fieldChanged) { | ||
var changedField = safeFields[fieldChanged]; | ||
if (changedField) { | ||
var validateFields = changedField.validateFields; | ||
if (validateFields) { | ||
@@ -764,3 +675,2 @@ limitedFieldLevelValidation = true; | ||
} | ||
var recordLevelErrors = {}; | ||
@@ -782,12 +692,11 @@ var asyncRecordLevelErrors = {}; | ||
var asyncValidationPromiseKey = ++nextAsyncValidationKey; | ||
var promise = Promise.all(promises).then(clearAsyncValidationPromise(asyncValidationPromiseKey)); // backwards-compat: add promise to submit-blocking promises iff there are any promises to await | ||
var promise = Promise.all(promises).then(clearAsyncValidationPromise(asyncValidationPromiseKey)); | ||
// backwards-compat: add promise to submit-blocking promises iff there are any promises to await | ||
if (hasAsyncValidations) { | ||
asyncValidationPromises[asyncValidationPromiseKey] = promise; | ||
} | ||
var processErrors = function processErrors(afterAsync) { | ||
var merged = _extends__default["default"]({}, limitedFieldLevelValidation ? formState.errors : {}, recordLevelErrors, afterAsync ? asyncRecordLevelErrors // new async errors | ||
var merged = _extends({}, limitedFieldLevelValidation ? formState.errors : {}, recordLevelErrors, afterAsync ? asyncRecordLevelErrors // new async errors | ||
: formState.asyncErrors); | ||
var forEachError = function forEachError(fn) { | ||
@@ -806,3 +715,2 @@ fieldKeys.forEach(function (name) { | ||
}; | ||
forEachError(function (name, error) { | ||
@@ -819,14 +727,10 @@ merged = setIn(merged, name, error) || {}; | ||
}); | ||
if (!shallowEqual(formState.errors, merged)) { | ||
formState.errors = merged; | ||
} | ||
if (afterAsync) { | ||
formState.asyncErrors = asyncRecordLevelErrors; | ||
} | ||
formState.error = recordLevelErrors[FORM_ERROR]; | ||
}; | ||
if (hasAsyncValidations) { | ||
@@ -836,9 +740,8 @@ // async validations are running, ensure validating is true before notifying | ||
callback(); | ||
} // process sync errors | ||
} | ||
processErrors(false); // sync errors have been set. notify listeners while we wait for others | ||
// process sync errors | ||
processErrors(false); | ||
// sync errors have been set. notify listeners while we wait for others | ||
callback(); | ||
if (hasAsyncValidations) { | ||
@@ -848,4 +751,9 @@ var afterPromise = function afterPromise() { | ||
callback(); | ||
// field async validation may affect formState validating | ||
// so force notifyFormListeners if validating is still 0 after callback finished | ||
// and lastFormState validating is true | ||
if (state.formState.validating === 0 && state.lastFormState.validating) { | ||
notifyFormListeners(); | ||
} | ||
}; | ||
promise.then(function () { | ||
@@ -856,3 +764,2 @@ if (nextAsyncValidationKey > asyncValidationPromiseKey) { | ||
} | ||
processErrors(true); | ||
@@ -862,3 +769,2 @@ }).then(afterPromise, afterPromise); | ||
}; | ||
var notifyFieldListeners = function notifyFieldListeners(name) { | ||
@@ -868,9 +774,6 @@ if (inBatch) { | ||
} | ||
var fields = state.fields, | ||
fieldSubscribers = state.fieldSubscribers, | ||
formState = state.formState; | ||
var safeFields = _extends__default["default"]({}, fields); | ||
fieldSubscribers = state.fieldSubscribers, | ||
formState = state.formState; | ||
var safeFields = _extends({}, fields); | ||
var notifyField = function notifyField(name) { | ||
@@ -882,3 +785,2 @@ var field = safeFields[name]; | ||
var fieldSubscriber = fieldSubscribers[name]; | ||
if (fieldSubscriber) { | ||
@@ -888,3 +790,2 @@ notify(fieldSubscriber, fieldState, lastFieldState, filterFieldState, lastFieldState === undefined); | ||
}; | ||
if (name) { | ||
@@ -896,3 +797,2 @@ notifyField(name); | ||
}; | ||
var markAllFieldsTouched = function markAllFieldsTouched() { | ||
@@ -903,20 +803,16 @@ Object.keys(state.fields).forEach(function (key) { | ||
}; | ||
var hasSyncErrors = function hasSyncErrors() { | ||
return !!(state.formState.error || hasAnyError(state.formState.errors)); | ||
}; | ||
var calculateNextFormState = function calculateNextFormState() { | ||
var fields = state.fields, | ||
formState = state.formState, | ||
lastFormState = state.lastFormState; | ||
formState = state.formState, | ||
lastFormState = state.lastFormState; | ||
var safeFields = _extends({}, fields); | ||
var safeFieldKeys = Object.keys(safeFields); | ||
var safeFields = _extends__default["default"]({}, fields); | ||
var safeFieldKeys = Object.keys(safeFields); // calculate dirty/pristine | ||
// calculate dirty/pristine | ||
var foundDirty = false; | ||
var dirtyFields = safeFieldKeys.reduce(function (result, key) { | ||
var dirty = !safeFields[key].isEqual(getIn(formState.values, key), getIn(formState.initialValues || {}, key)); | ||
if (dirty) { | ||
@@ -926,3 +822,2 @@ foundDirty = true; | ||
} | ||
return result; | ||
@@ -933,7 +828,5 @@ }, {}); | ||
var nonNullLastSubmittedValues = formState.lastSubmittedValues || {}; // || {} is for flow, but causes branch coverage complaint | ||
if (!safeFields[key].isEqual(getIn(formState.values, key), getIn(nonNullLastSubmittedValues, key))) { | ||
result[key] = true; | ||
} | ||
return result; | ||
@@ -945,3 +838,4 @@ }, {}); | ||
})); | ||
formState.modifiedSinceLastSubmit = !!(formState.lastSubmittedValues && // Object.values would treat values as mixed (facebook/flow#2221) | ||
formState.modifiedSinceLastSubmit = !!(formState.lastSubmittedValues && | ||
// Object.values would treat values as mixed (facebook/flow#2221) | ||
Object.keys(safeFields).some(function (value) { | ||
@@ -952,17 +846,15 @@ return safeFields[value].modifiedSinceLastSubmit; | ||
var nextFormState = convertToExternalFormState(formState); | ||
var _safeFieldKeys$reduce = safeFieldKeys.reduce(function (result, key) { | ||
result.modified[key] = safeFields[key].modified; | ||
result.touched[key] = safeFields[key].touched; | ||
result.visited[key] = safeFields[key].visited; | ||
return result; | ||
}, { | ||
modified: {}, | ||
touched: {}, | ||
visited: {} | ||
}), | ||
modified = _safeFieldKeys$reduce.modified, | ||
touched = _safeFieldKeys$reduce.touched, | ||
visited = _safeFieldKeys$reduce.visited; | ||
result.modified[key] = safeFields[key].modified; | ||
result.touched[key] = safeFields[key].touched; | ||
result.visited[key] = safeFields[key].visited; | ||
return result; | ||
}, { | ||
modified: {}, | ||
touched: {}, | ||
visited: {} | ||
}), | ||
modified = _safeFieldKeys$reduce.modified, | ||
touched = _safeFieldKeys$reduce.touched, | ||
visited = _safeFieldKeys$reduce.visited; | ||
nextFormState.dirtyFields = lastFormState && shallowEqual(lastFormState.dirtyFields, dirtyFields) ? lastFormState.dirtyFields : dirtyFields; | ||
@@ -975,3 +867,2 @@ nextFormState.dirtyFieldsSinceLastSubmit = lastFormState && shallowEqual(lastFormState.dirtyFieldsSinceLastSubmit, dirtyFieldsSinceLastSubmit) ? lastFormState.dirtyFieldsSinceLastSubmit : dirtyFieldsSinceLastSubmit; | ||
}; | ||
var callDebug = function callDebug() { | ||
@@ -983,6 +874,4 @@ return debug && process.env.NODE_ENV !== "production" && debug(calculateNextFormState(), Object.keys(state.fields).reduce(function (result, key) { | ||
}; | ||
var notifying = false; | ||
var scheduleNotification = false; | ||
var notifyFormListeners = function notifyFormListeners() { | ||
@@ -994,7 +883,5 @@ if (notifying) { | ||
callDebug(); | ||
if (!inBatch && !(validationPaused && preventNotificationWhileValidationPaused)) { | ||
var lastFormState = state.lastFormState; | ||
var nextFormState = calculateNextFormState(); | ||
if (nextFormState !== lastFormState) { | ||
@@ -1005,5 +892,3 @@ state.lastFormState = nextFormState; | ||
} | ||
notifying = false; | ||
if (scheduleNotification) { | ||
@@ -1015,3 +900,2 @@ scheduleNotification = false; | ||
}; | ||
var beforeSubmit = function beforeSubmit() { | ||
@@ -1022,3 +906,2 @@ return Object.keys(state.fields).some(function (name) { | ||
}; | ||
var afterSubmit = function afterSubmit() { | ||
@@ -1029,3 +912,2 @@ return Object.keys(state.fields).forEach(function (name) { | ||
}; | ||
var resetModifiedAfterSubmit = function resetModifiedAfterSubmit() { | ||
@@ -1035,5 +917,5 @@ return Object.keys(state.fields).forEach(function (key) { | ||
}); | ||
}; // generate initial errors | ||
}; | ||
// generate initial errors | ||
runValidation(undefined, function () { | ||
@@ -1052,13 +934,11 @@ notifyFormListeners(); | ||
var fields = state.fields, | ||
formState = state.formState; | ||
formState = state.formState; | ||
var previous = fields[name]; | ||
if (previous) { | ||
// can only blur registered fields | ||
delete formState.active; | ||
fields[name] = _extends__default["default"]({}, previous, { | ||
fields[name] = _extends({}, previous, { | ||
active: false, | ||
touched: true | ||
}); | ||
if (validateOnBlur) { | ||
@@ -1077,4 +957,3 @@ runValidation(name, function () { | ||
var fields = state.fields, | ||
formState = state.formState; | ||
formState = state.formState; | ||
if (getIn(formState.values, name) !== value) { | ||
@@ -1085,6 +964,5 @@ changeValue(state, name, function () { | ||
var previous = fields[name]; | ||
if (previous) { | ||
// only track modified for registered fields | ||
fields[name] = _extends__default["default"]({}, previous, { | ||
fields[name] = _extends({}, previous, { | ||
modified: true, | ||
@@ -1094,3 +972,2 @@ modifiedSinceLastSubmit: !!formState.lastSubmittedValues | ||
} | ||
if (validateOnBlur) { | ||
@@ -1107,14 +984,10 @@ notifyFieldListeners(); | ||
}, | ||
get destroyOnUnregister() { | ||
return !!destroyOnUnregister; | ||
}, | ||
set destroyOnUnregister(value) { | ||
destroyOnUnregister = value; | ||
}, | ||
focus: function focus(name) { | ||
var field = state.fields[name]; | ||
if (field && !field.active) { | ||
@@ -1141,8 +1014,5 @@ state.formState.active = name; | ||
var fields = state.fields, | ||
formState = state.formState; | ||
var safeFields = _extends__default["default"]({}, fields); | ||
formState = state.formState; | ||
var safeFields = _extends({}, fields); | ||
var values = typeof data === "function" ? data(formState.values) : data; | ||
if (!keepDirtyOnReinitialize) { | ||
@@ -1157,19 +1027,16 @@ formState.values = values; | ||
*/ | ||
// save dirty values | ||
var savedDirtyValues = keepDirtyOnReinitialize ? Object.keys(safeFields).reduce(function (result, key) { | ||
var field = safeFields[key]; | ||
var pristine = field.isEqual(getIn(formState.values, key), getIn(formState.initialValues || {}, key)); | ||
if (!pristine) { | ||
result[key] = getIn(formState.values, key); | ||
} | ||
return result; | ||
}, {}) : {}; // update initalValues and values | ||
}, {}) : {}; | ||
// update initalValues and values | ||
formState.initialValues = values; | ||
formState.values = values; // restore the dirty values | ||
formState.values = values; | ||
// restore the dirty values | ||
Object.keys(savedDirtyValues).forEach(function (key) { | ||
@@ -1190,3 +1057,2 @@ formState.values = setIn(formState.values, key, savedDirtyValues[key]) || {}; | ||
} | ||
validationPaused = true; | ||
@@ -1199,3 +1065,2 @@ preventNotificationWhileValidationPaused = preventNotification; | ||
} | ||
if (!state.fieldSubscribers[name]) { | ||
@@ -1207,5 +1072,5 @@ state.fieldSubscribers[name] = { | ||
} | ||
var index = state.fieldSubscribers[name].index++; | ||
var index = state.fieldSubscribers[name].index++; // save field subscriber callback | ||
// save field subscriber callback | ||
state.fieldSubscribers[name].entries[index] = { | ||
@@ -1215,4 +1080,5 @@ subscriber: memoize(subscriber), | ||
notified: false | ||
}; // create initial field state if not exists | ||
}; | ||
// create initial field state if not exists | ||
var field = state.fields[name] || { | ||
@@ -1234,21 +1100,17 @@ active: false, | ||
visited: false | ||
}; // Mutators can create a field in order to keep the field states | ||
}; | ||
// Mutators can create a field in order to keep the field states | ||
// We must update this field when registerField is called afterwards | ||
field.blur = field.blur || function () { | ||
return api.blur(name); | ||
}; | ||
field.change = field.change || function (value) { | ||
return api.change(name, value); | ||
}; | ||
field.focus = field.focus || function () { | ||
return api.focus(name); | ||
}; | ||
state.fields[name] = field; | ||
var haveValidator = false; | ||
var silent = fieldConfig && fieldConfig.silent; | ||
var notify = function notify() { | ||
@@ -1262,13 +1124,10 @@ if (silent && state.fields[name]) { | ||
}; | ||
if (fieldConfig) { | ||
haveValidator = !!(fieldConfig.getValidator && fieldConfig.getValidator()); | ||
if (fieldConfig.getValidator) { | ||
state.fields[name].validators[index] = fieldConfig.getValidator; | ||
} | ||
var noValueInFormState = getIn(state.formState.values, name) === undefined; | ||
if (fieldConfig.initialValue !== undefined && (noValueInFormState || getIn(state.formState.values, name) === getIn(state.formState.initialValues, name)) // only initialize if we don't yet have any value for this field | ||
if (fieldConfig.initialValue !== undefined && (noValueInFormState || getIn(state.formState.values, name) === getIn(state.formState.initialValues, name)) | ||
// only initialize if we don't yet have any value for this field | ||
) { | ||
@@ -1278,5 +1137,5 @@ state.formState.initialValues = setIn(state.formState.initialValues || {}, name, fieldConfig.initialValue); | ||
runValidation(undefined, notify); | ||
} // only use defaultValue if we don't yet have any value for this field | ||
} | ||
// only use defaultValue if we don't yet have any value for this field | ||
if (fieldConfig.defaultValue !== undefined && fieldConfig.initialValue === undefined && getIn(state.formState.initialValues, name) === undefined && noValueInFormState) { | ||
@@ -1286,3 +1145,2 @@ state.formState.values = setIn(state.formState.values, name, fieldConfig.defaultValue); | ||
} | ||
if (haveValidator) { | ||
@@ -1293,6 +1151,5 @@ runValidation(undefined, notify); | ||
} | ||
return function () { | ||
var validatorRemoved = false; // istanbul ignore next | ||
var validatorRemoved = false; | ||
// istanbul ignore next | ||
if (state.fields[name]) { | ||
@@ -1303,5 +1160,3 @@ // state.fields[name] may have been removed by a mutator | ||
} | ||
var hasFieldSubscribers = !!state.fieldSubscribers[name]; | ||
if (hasFieldSubscribers) { | ||
@@ -1311,13 +1166,9 @@ // state.fieldSubscribers[name] may have been removed by a mutator | ||
} | ||
var lastOne = hasFieldSubscribers && !Object.keys(state.fieldSubscribers[name].entries).length; | ||
if (lastOne) { | ||
delete state.fieldSubscribers[name]; | ||
delete state.fields[name]; | ||
if (validatorRemoved) { | ||
state.formState.errors = setIn(state.formState.errors, name, undefined) || {}; | ||
} | ||
if (destroyOnUnregister) { | ||
@@ -1327,3 +1178,2 @@ state.formState.values = setIn(state.formState.values, name, undefined, true) || {}; | ||
} | ||
if (!silent) { | ||
@@ -1346,7 +1196,5 @@ if (validatorRemoved) { | ||
} | ||
if (state.formState.submitting) { | ||
state.formState.resetWhileSubmitting = true; | ||
} | ||
state.formState.submitFailed = false; | ||
@@ -1359,3 +1207,2 @@ state.formState.submitSucceeded = false; | ||
}, | ||
/** | ||
@@ -1365,3 +1212,3 @@ * Resets all field flags (e.g. touched, visited, etc.) to their initial state | ||
resetFieldState: function resetFieldState(name) { | ||
state.fields[name] = _extends__default["default"]({}, state.fields[name], { | ||
state.fields[name] = _extends({}, state.fields[name], { | ||
active: false, | ||
@@ -1380,3 +1227,2 @@ lastFieldState: undefined, | ||
}, | ||
/** | ||
@@ -1391,7 +1237,6 @@ * Returns the form to a clean slate; that is: | ||
} | ||
api.batch(function () { | ||
for (var name in state.fields) { | ||
api.resetFieldState(name); | ||
state.fields[name] = _extends__default["default"]({}, state.fields[name], { | ||
state.fields[name] = _extends({}, state.fields[name], { | ||
active: false, | ||
@@ -1407,3 +1252,2 @@ lastFieldState: undefined, | ||
} | ||
api.reset(initialValues); | ||
@@ -1415,3 +1259,2 @@ }); | ||
preventNotificationWhileValidationPaused = false; | ||
if (validationBlocked) { | ||
@@ -1424,3 +1267,2 @@ // validation was attempted while it was paused, so run it now | ||
} | ||
validationBlocked = false; | ||
@@ -1433,18 +1275,13 @@ }, | ||
break; | ||
case "destroyOnUnregister": | ||
destroyOnUnregister = value; | ||
break; | ||
case "initialValues": | ||
api.initialize(value); | ||
break; | ||
case "keepDirtyOnReinitialize": | ||
keepDirtyOnReinitialize = value; | ||
break; | ||
case "mutators": | ||
mutators = value; | ||
if (value) { | ||
@@ -1464,9 +1301,6 @@ Object.keys(mutatorsApi).forEach(function (key) { | ||
} | ||
break; | ||
case "onSubmit": | ||
onSubmit = value; | ||
break; | ||
case "validate": | ||
@@ -1479,7 +1313,5 @@ validate = value; | ||
break; | ||
case "validateOnBlur": | ||
validateOnBlur = value; | ||
break; | ||
default: | ||
@@ -1491,11 +1323,8 @@ throw new Error("Unrecognised option " + name); | ||
var formState = state.formState; | ||
if (formState.submitting) { | ||
return; | ||
} | ||
delete formState.submitErrors; | ||
delete formState.submitError; | ||
formState.lastSubmittedValues = _extends__default["default"]({}, formState.values); | ||
formState.lastSubmittedValues = _extends({}, formState.values); | ||
if (hasSyncErrors()) { | ||
@@ -1511,3 +1340,2 @@ markAllFieldsTouched(); | ||
var asyncValidationPromisesKeys = Object.keys(asyncValidationPromises); | ||
if (asyncValidationPromisesKeys.length) { | ||
@@ -1520,20 +1348,14 @@ // still waiting on async validation to complete... | ||
} | ||
var submitIsBlocked = beforeSubmit(); | ||
if (submitIsBlocked) { | ||
return; | ||
} | ||
var resolvePromise; | ||
var completeCalled = false; | ||
var complete = function complete(errors) { | ||
formState.submitting = false; | ||
var resetWhileSubmitting = formState.resetWhileSubmitting; | ||
if (resetWhileSubmitting) { | ||
formState.resetWhileSubmitting = false; | ||
} | ||
if (errors && hasAnyError(errors)) { | ||
@@ -1550,25 +1372,20 @@ formState.submitFailed = true; | ||
} | ||
afterSubmit(); | ||
} | ||
notifyFormListeners(); | ||
notifyFieldListeners(); | ||
completeCalled = true; | ||
if (resolvePromise) { | ||
resolvePromise(errors); | ||
} | ||
return errors; | ||
}; | ||
formState.submitting = true; | ||
formState.submitFailed = false; | ||
formState.submitSucceeded = false; | ||
formState.lastSubmittedValues = _extends__default["default"]({}, formState.values); | ||
resetModifiedAfterSubmit(); // onSubmit is either sync, callback or async with a Promise | ||
formState.lastSubmittedValues = _extends({}, formState.values); | ||
resetModifiedAfterSubmit(); | ||
// onSubmit is either sync, callback or async with a Promise | ||
var result = onSubmit(formState.values, api, complete); | ||
if (!completeCalled) { | ||
@@ -1578,5 +1395,3 @@ if (result && isPromise(result)) { | ||
notifyFormListeners(); // let everyone know we are submitting | ||
notifyFieldListeners(); // notify fields also | ||
return result.then(complete, function (error) { | ||
@@ -1589,5 +1404,3 @@ complete(); | ||
notifyFormListeners(); // let everyone know we are submitting | ||
notifyFieldListeners(); // notify fields also | ||
return new Promise(function (resolve) { | ||
@@ -1606,7 +1419,5 @@ resolvePromise = resolve; | ||
} | ||
if (!subscription) { | ||
throw new Error("No subscription provided. What values do you want to listen to?"); | ||
} | ||
var memoized = memoize(subscriber); | ||
@@ -1613,0 +1424,0 @@ var subscribers = state.subscribers; |
@@ -5,10 +5,17 @@ import _extends from '@babel/runtime/helpers/esm/extends'; | ||
// | ||
var charCodeOfDot = ".".charCodeAt(0); | ||
var reEscapeChar = /\\(\\)?/g; | ||
var rePropName = RegExp( // Match anything that isn't a dot or bracket. | ||
"[^.[\\]]+" + "|" + // Or match property names within brackets. | ||
"\\[(?:" + // Match a non-string expression. | ||
"([^\"'][^[]*)" + "|" + // Or match strings (supports escaping characters). | ||
"([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2" + ")\\]" + "|" + // Or match "" as the space between consecutive dots or empty brackets. | ||
var rePropName = RegExp( | ||
// Match anything that isn't a dot or bracket. | ||
"[^.[\\]]+" + "|" + | ||
// Or match property names within brackets. | ||
"\\[(?:" + | ||
// Match a non-string expression. | ||
"([^\"'][^[]*)" + "|" + | ||
// Or match strings (supports escaping characters). | ||
"([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2" + ")\\]" + "|" + | ||
// Or match "" as the space between consecutive dots or empty brackets. | ||
"(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))", "g"); | ||
/** | ||
@@ -21,13 +28,9 @@ * Converts `string` to a property path array. | ||
*/ | ||
var stringToPath = function stringToPath(string) { | ||
var result = []; | ||
if (string.charCodeAt(0) === charCodeOfDot) { | ||
result.push(""); | ||
} | ||
string.replace(rePropName, function (match, expression, quote, subString) { | ||
var key = match; | ||
if (quote) { | ||
@@ -38,3 +41,2 @@ key = subString.replace(reEscapeChar, "$1"); | ||
} | ||
result.push(key); | ||
@@ -44,6 +46,4 @@ }); | ||
}; | ||
var keysCache = {}; | ||
var keysRegex = /[.[\]]+/; | ||
var toPath = function toPath(key) { | ||
@@ -53,7 +53,5 @@ if (key === null || key === undefined || !key.length) { | ||
} | ||
if (typeof key !== "string") { | ||
throw new Error("toPath() expects a string"); | ||
} | ||
if (keysCache[key] == null) { | ||
@@ -81,3 +79,2 @@ /** | ||
} | ||
return keysCache[key]; | ||
@@ -87,3 +84,2 @@ }; | ||
// | ||
var getIn = function getIn(state, complexKey) { | ||
@@ -93,13 +89,9 @@ // Intentionally using iteration rather than recursion | ||
var current = state; | ||
for (var i = 0; i < path.length; i++) { | ||
var key = path[i]; | ||
if (current === undefined || current === null || typeof current !== "object" || Array.isArray(current) && isNaN(key)) { | ||
return undefined; | ||
} | ||
current = current[key]; | ||
} | ||
return current; | ||
@@ -109,5 +101,3 @@ }; | ||
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } | ||
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } | ||
var setInRecursor = function setInRecursor(current, index, path, value, destroyArrays) { | ||
@@ -118,29 +108,23 @@ if (index >= path.length) { | ||
} | ||
var key = path[index]; | ||
var key = path[index]; // determine type of key | ||
// determine type of key | ||
if (isNaN(key)) { | ||
var _extends2; | ||
// object set | ||
if (current === undefined || current === null) { | ||
var _ref; | ||
// recurse | ||
var _result2 = setInRecursor(undefined, index + 1, path, value, destroyArrays); // delete or create an object | ||
var _result = setInRecursor(undefined, index + 1, path, value, destroyArrays); | ||
return _result2 === undefined ? undefined : (_ref = {}, _ref[key] = _result2, _ref); | ||
// delete or create an object | ||
return _result === undefined ? undefined : (_ref = {}, _ref[key] = _result, _ref); | ||
} | ||
if (Array.isArray(current)) { | ||
throw new Error("Cannot set a non-numeric property on an array"); | ||
} // current exists, so make a copy of all its values, and add/update the new one | ||
var _result = setInRecursor(current[key], index + 1, path, value, destroyArrays); | ||
if (_result === undefined) { | ||
} | ||
// current exists, so make a copy of all its values, and add/update the new one | ||
var _result2 = setInRecursor(current[key], index + 1, path, value, destroyArrays); | ||
if (_result2 === undefined) { | ||
var numKeys = Object.keys(current).length; | ||
if (current[key] === undefined && numKeys === 0) { | ||
@@ -150,3 +134,2 @@ // object was already empty | ||
} | ||
if (current[key] !== undefined && numKeys <= 1) { | ||
@@ -161,26 +144,21 @@ // only key we had was the one we are deleting | ||
} | ||
current[key]; | ||
var _final = _objectWithoutPropertiesLoose(current, [key].map(_toPropertyKey)); | ||
var _final = _objectWithoutPropertiesLoose(current, [key].map(_toPropertyKey)); | ||
return _final; | ||
} // set result in key | ||
return _extends({}, current, (_extends2 = {}, _extends2[key] = _result, _extends2)); | ||
} // array set | ||
} | ||
// set result in key | ||
return _extends({}, current, (_extends2 = {}, _extends2[key] = _result2, _extends2)); | ||
} | ||
// array set | ||
var numericKey = Number(key); | ||
if (current === undefined || current === null) { | ||
// recurse | ||
var _result3 = setInRecursor(undefined, index + 1, path, value, destroyArrays); // if nothing returned, delete it | ||
var _result3 = setInRecursor(undefined, index + 1, path, value, destroyArrays); | ||
// if nothing returned, delete it | ||
if (_result3 === undefined) { | ||
return undefined; | ||
} // create an array | ||
} | ||
// create an array | ||
var _array = []; | ||
@@ -190,16 +168,13 @@ _array[numericKey] = _result3; | ||
} | ||
if (!Array.isArray(current)) { | ||
throw new Error("Cannot set a numeric property on an object"); | ||
} // recurse | ||
} | ||
// recurse | ||
var existingValue = current[numericKey]; | ||
var result = setInRecursor(existingValue, index + 1, path, value, destroyArrays); // current exists, so make a copy of all its values, and add/update the new one | ||
var result = setInRecursor(existingValue, index + 1, path, value, destroyArrays); | ||
// current exists, so make a copy of all its values, and add/update the new one | ||
var array = [].concat(current); | ||
if (destroyArrays && result === undefined) { | ||
array.splice(numericKey, 1); | ||
if (array.length === 0) { | ||
@@ -211,6 +186,4 @@ return undefined; | ||
} | ||
return array; | ||
}; | ||
var setIn = function setIn(state, key, value, destroyArrays) { | ||
@@ -220,13 +193,10 @@ if (destroyArrays === void 0) { | ||
} | ||
if (state === undefined || state === null) { | ||
throw new Error("Cannot call setIn() with " + String(state) + " state"); | ||
} | ||
if (key === undefined || key === null) { | ||
throw new Error("Cannot call setIn() with " + String(key) + " key"); | ||
} // Recursive function needs to accept and return State, but public API should | ||
} | ||
// Recursive function needs to accept and return State, but public API should | ||
// only deal with Objects | ||
return setInRecursor(state, 0, toPath(key), value, destroyArrays); | ||
@@ -239,33 +209,32 @@ }; | ||
// | ||
/** | ||
* Converts internal field state to published field state | ||
*/ | ||
function publishFieldState(formState, field) { | ||
var errors = formState.errors, | ||
initialValues = formState.initialValues, | ||
lastSubmittedValues = formState.lastSubmittedValues, | ||
submitErrors = formState.submitErrors, | ||
submitFailed = formState.submitFailed, | ||
submitSucceeded = formState.submitSucceeded, | ||
submitting = formState.submitting, | ||
values = formState.values; | ||
initialValues = formState.initialValues, | ||
lastSubmittedValues = formState.lastSubmittedValues, | ||
submitErrors = formState.submitErrors, | ||
submitFailed = formState.submitFailed, | ||
submitSucceeded = formState.submitSucceeded, | ||
submitting = formState.submitting, | ||
values = formState.values; | ||
var active = field.active, | ||
blur = field.blur, | ||
change = field.change, | ||
data = field.data, | ||
focus = field.focus, | ||
modified = field.modified, | ||
modifiedSinceLastSubmit = field.modifiedSinceLastSubmit, | ||
name = field.name, | ||
touched = field.touched, | ||
validating = field.validating, | ||
visited = field.visited; | ||
blur = field.blur, | ||
change = field.change, | ||
data = field.data, | ||
focus = field.focus, | ||
modified = field.modified, | ||
modifiedSinceLastSubmit = field.modifiedSinceLastSubmit, | ||
name = field.name, | ||
touched = field.touched, | ||
validating = field.validating, | ||
visited = field.visited; | ||
var value = getIn(values, name); | ||
var error = getIn(errors, name); | ||
if (error && error[ARRAY_ERROR]) { | ||
error = error[ARRAY_ERROR]; | ||
} | ||
var submitError = submitErrors && getIn(submitErrors, name); | ||
@@ -308,2 +277,3 @@ var initial = initialValues && getIn(initialValues, name); | ||
// | ||
var shallowEqual = function shallowEqual(a, b) { | ||
@@ -313,19 +283,13 @@ if (a === b) { | ||
} | ||
if (typeof a !== "object" || !a || typeof b !== "object" || !b) { | ||
return false; | ||
} | ||
var keysA = Object.keys(a); | ||
var keysB = Object.keys(b); | ||
if (keysA.length !== keysB.length) { | ||
return false; | ||
} | ||
var bHasOwnProperty = Object.prototype.hasOwnProperty.bind(b); | ||
for (var idx = 0; idx < keysA.length; idx++) { | ||
var key = keysA[idx]; | ||
if (!bHasOwnProperty(key) || a[key] !== b[key]) { | ||
@@ -335,3 +299,2 @@ return false; | ||
} | ||
return true; | ||
@@ -346,3 +309,2 @@ }; | ||
dest[key] = src[key]; | ||
if (!previous || (~shallowEqualKeys.indexOf(key) ? !shallowEqual(src[key], previous[key]) : src[key] !== previous[key])) { | ||
@@ -358,6 +320,6 @@ different = true; | ||
var shallowEqualKeys$1 = ["data"]; | ||
/** | ||
* Filters items in a FieldState based on a FieldSubscription | ||
*/ | ||
var filterFieldState = function filterFieldState(state, previousState, subscription, force) { | ||
@@ -379,6 +341,6 @@ var result = { | ||
var shallowEqualKeys = ["touched", "visited"]; | ||
/** | ||
* Filters items in a FormState based on a FormSubscription | ||
*/ | ||
function filterFormState(state, previousState, subscription, force) { | ||
@@ -391,3 +353,2 @@ var result = {}; | ||
// | ||
var memoize = function memoize(fn) { | ||
@@ -400,3 +361,2 @@ var lastArgs; | ||
} | ||
if (!lastArgs || args.length !== lastArgs.length || args.some(function (arg, index) { | ||
@@ -408,3 +368,2 @@ return !shallowEqual(lastArgs[index], arg); | ||
} | ||
return lastResult; | ||
@@ -418,38 +377,33 @@ }; | ||
var version = "4.20.9"; | ||
var version = "4.20.10"; | ||
var configOptions = ["debug", "initialValues", "keepDirtyOnReinitialize", "mutators", "onSubmit", "validate", "validateOnBlur"]; | ||
var tripleEquals = function tripleEquals(a, b) { | ||
return a === b; | ||
}; | ||
var hasAnyError = function hasAnyError(errors) { | ||
return Object.keys(errors).some(function (key) { | ||
var value = errors[key]; | ||
if (value && typeof value === "object" && !(value instanceof Error)) { | ||
return hasAnyError(value); | ||
} | ||
return typeof value !== "undefined"; | ||
}); | ||
}; | ||
function convertToExternalFormState(_ref) { | ||
var active = _ref.active, | ||
dirtySinceLastSubmit = _ref.dirtySinceLastSubmit, | ||
modifiedSinceLastSubmit = _ref.modifiedSinceLastSubmit, | ||
error = _ref.error, | ||
errors = _ref.errors, | ||
initialValues = _ref.initialValues, | ||
pristine = _ref.pristine, | ||
submitting = _ref.submitting, | ||
submitFailed = _ref.submitFailed, | ||
submitSucceeded = _ref.submitSucceeded, | ||
submitError = _ref.submitError, | ||
submitErrors = _ref.submitErrors, | ||
valid = _ref.valid, | ||
validating = _ref.validating, | ||
values = _ref.values; | ||
dirtySinceLastSubmit = _ref.dirtySinceLastSubmit, | ||
modifiedSinceLastSubmit = _ref.modifiedSinceLastSubmit, | ||
error = _ref.error, | ||
errors = _ref.errors, | ||
initialValues = _ref.initialValues, | ||
pristine = _ref.pristine, | ||
submitting = _ref.submitting, | ||
submitFailed = _ref.submitFailed, | ||
submitSucceeded = _ref.submitSucceeded, | ||
submitError = _ref.submitError, | ||
submitErrors = _ref.submitErrors, | ||
valid = _ref.valid, | ||
validating = _ref.validating, | ||
values = _ref.values; | ||
return { | ||
@@ -477,6 +431,4 @@ active: active, | ||
} | ||
function notifySubscriber(subscriber, subscription, state, lastState, filter, force) { | ||
var notification = filter(state, lastState, subscription, force); | ||
if (notification) { | ||
@@ -486,16 +438,13 @@ subscriber(notification); | ||
} | ||
return false; | ||
} | ||
function notify(_ref2, state, lastState, filter, force) { | ||
var entries = _ref2.entries; | ||
Object.keys(entries).forEach(function (key) { | ||
var entry = entries[Number(key)]; // istanbul ignore next | ||
var entry = entries[Number(key)]; | ||
// istanbul ignore next | ||
if (entry) { | ||
var subscription = entry.subscription, | ||
subscriber = entry.subscriber, | ||
notified = entry.notified; | ||
subscriber = entry.subscriber, | ||
notified = entry.notified; | ||
if (notifySubscriber(subscriber, subscription, state, lastState, filter, force || !notified)) { | ||
@@ -507,3 +456,2 @@ entry.notified = true; | ||
} | ||
function createForm(config) { | ||
@@ -513,16 +461,13 @@ if (!config) { | ||
} | ||
var debug = config.debug, | ||
destroyOnUnregister = config.destroyOnUnregister, | ||
keepDirtyOnReinitialize = config.keepDirtyOnReinitialize, | ||
initialValues = config.initialValues, | ||
mutators = config.mutators, | ||
onSubmit = config.onSubmit, | ||
validate = config.validate, | ||
validateOnBlur = config.validateOnBlur; | ||
destroyOnUnregister = config.destroyOnUnregister, | ||
keepDirtyOnReinitialize = config.keepDirtyOnReinitialize, | ||
initialValues = config.initialValues, | ||
mutators = config.mutators, | ||
onSubmit = config.onSubmit, | ||
validate = config.validate, | ||
validateOnBlur = config.validateOnBlur; | ||
if (!onSubmit) { | ||
throw new Error("No onSubmit function specified"); | ||
} | ||
var state = { | ||
@@ -559,3 +504,2 @@ subscribers: { | ||
var asyncValidationPromises = {}; | ||
var clearAsyncValidationPromise = function clearAsyncValidationPromise(key) { | ||
@@ -567,3 +511,2 @@ return function (result) { | ||
}; | ||
var changeValue = function changeValue(state, name, mutate) { | ||
@@ -574,7 +517,5 @@ var before = getIn(state.formState.values, name); | ||
}; | ||
var renameField = function renameField(state, from, to) { | ||
if (state.fields[from]) { | ||
var _extends2, _extends3; | ||
state.fields = _extends({}, state.fields, (_extends2 = {}, _extends2[to] = _extends({}, state.fields[from], { | ||
@@ -602,5 +543,5 @@ name: to, | ||
} | ||
}; // bind state to mutators | ||
}; | ||
// bind state to mutators | ||
var getMutatorApi = function getMutatorApi(key) { | ||
@@ -617,7 +558,5 @@ return function () { | ||
}; | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
var returnValue = mutators[key](args, mutatableState, { | ||
@@ -643,3 +582,2 @@ changeValue: changeValue, | ||
}; | ||
var mutatorsApi = mutators ? Object.keys(mutators).reduce(function (result, key) { | ||
@@ -649,9 +587,6 @@ result[key] = getMutatorApi(key); | ||
}, {}) : {}; | ||
var runRecordLevelValidation = function runRecordLevelValidation(setErrors) { | ||
var promises = []; | ||
if (validate) { | ||
var errorsOrPromise = validate(_extends({}, state.formState.values)); // clone to avoid writing | ||
if (isPromise(errorsOrPromise)) { | ||
@@ -665,22 +600,16 @@ promises.push(errorsOrPromise.then(function (errors) { | ||
} | ||
return promises; | ||
}; | ||
var getValidators = function getValidators(field) { | ||
return Object.keys(field.validators).reduce(function (result, index) { | ||
var validator = field.validators[Number(index)](); | ||
if (validator) { | ||
result.push(validator); | ||
} | ||
return result; | ||
}, []); | ||
}; | ||
var runFieldLevelValidation = function runFieldLevelValidation(field, setError) { | ||
var promises = []; | ||
var validators = getValidators(field); | ||
if (validators.length) { | ||
@@ -690,3 +619,2 @@ var error; | ||
var errorOrPromise = validator(getIn(state.formState.values, field.name), state.formState.values, validator.length === 0 || validator.length === 3 ? publishFieldState(state.formState, state.fields[field.name]) : undefined); | ||
if (errorOrPromise && isPromise(errorOrPromise)) { | ||
@@ -700,3 +628,2 @@ field.validating = true; | ||
}); // errors must be resolved, not rejected | ||
promises.push(promise); | ||
@@ -710,6 +637,4 @@ } else if (!error) { | ||
} | ||
return promises; | ||
}; | ||
var runValidation = function runValidation(fieldChanged, callback) { | ||
@@ -721,10 +646,6 @@ if (validationPaused) { | ||
} | ||
var fields = state.fields, | ||
formState = state.formState; | ||
formState = state.formState; | ||
var safeFields = _extends({}, fields); | ||
var fieldKeys = Object.keys(safeFields); | ||
if (!validate && !fieldKeys.some(function (key) { | ||
@@ -735,13 +656,10 @@ return getValidators(safeFields[key]).length; | ||
return; // no validation rules | ||
} // pare down field keys to actually validate | ||
} | ||
// pare down field keys to actually validate | ||
var limitedFieldLevelValidation = false; | ||
if (fieldChanged) { | ||
var changedField = safeFields[fieldChanged]; | ||
if (changedField) { | ||
var validateFields = changedField.validateFields; | ||
if (validateFields) { | ||
@@ -753,3 +671,2 @@ limitedFieldLevelValidation = true; | ||
} | ||
var recordLevelErrors = {}; | ||
@@ -771,12 +688,11 @@ var asyncRecordLevelErrors = {}; | ||
var asyncValidationPromiseKey = ++nextAsyncValidationKey; | ||
var promise = Promise.all(promises).then(clearAsyncValidationPromise(asyncValidationPromiseKey)); // backwards-compat: add promise to submit-blocking promises iff there are any promises to await | ||
var promise = Promise.all(promises).then(clearAsyncValidationPromise(asyncValidationPromiseKey)); | ||
// backwards-compat: add promise to submit-blocking promises iff there are any promises to await | ||
if (hasAsyncValidations) { | ||
asyncValidationPromises[asyncValidationPromiseKey] = promise; | ||
} | ||
var processErrors = function processErrors(afterAsync) { | ||
var merged = _extends({}, limitedFieldLevelValidation ? formState.errors : {}, recordLevelErrors, afterAsync ? asyncRecordLevelErrors // new async errors | ||
: formState.asyncErrors); | ||
var forEachError = function forEachError(fn) { | ||
@@ -795,3 +711,2 @@ fieldKeys.forEach(function (name) { | ||
}; | ||
forEachError(function (name, error) { | ||
@@ -808,14 +723,10 @@ merged = setIn(merged, name, error) || {}; | ||
}); | ||
if (!shallowEqual(formState.errors, merged)) { | ||
formState.errors = merged; | ||
} | ||
if (afterAsync) { | ||
formState.asyncErrors = asyncRecordLevelErrors; | ||
} | ||
formState.error = recordLevelErrors[FORM_ERROR]; | ||
}; | ||
if (hasAsyncValidations) { | ||
@@ -825,9 +736,8 @@ // async validations are running, ensure validating is true before notifying | ||
callback(); | ||
} // process sync errors | ||
} | ||
processErrors(false); // sync errors have been set. notify listeners while we wait for others | ||
// process sync errors | ||
processErrors(false); | ||
// sync errors have been set. notify listeners while we wait for others | ||
callback(); | ||
if (hasAsyncValidations) { | ||
@@ -837,4 +747,9 @@ var afterPromise = function afterPromise() { | ||
callback(); | ||
// field async validation may affect formState validating | ||
// so force notifyFormListeners if validating is still 0 after callback finished | ||
// and lastFormState validating is true | ||
if (state.formState.validating === 0 && state.lastFormState.validating) { | ||
notifyFormListeners(); | ||
} | ||
}; | ||
promise.then(function () { | ||
@@ -845,3 +760,2 @@ if (nextAsyncValidationKey > asyncValidationPromiseKey) { | ||
} | ||
processErrors(true); | ||
@@ -851,3 +765,2 @@ }).then(afterPromise, afterPromise); | ||
}; | ||
var notifyFieldListeners = function notifyFieldListeners(name) { | ||
@@ -857,9 +770,6 @@ if (inBatch) { | ||
} | ||
var fields = state.fields, | ||
fieldSubscribers = state.fieldSubscribers, | ||
formState = state.formState; | ||
fieldSubscribers = state.fieldSubscribers, | ||
formState = state.formState; | ||
var safeFields = _extends({}, fields); | ||
var notifyField = function notifyField(name) { | ||
@@ -871,3 +781,2 @@ var field = safeFields[name]; | ||
var fieldSubscriber = fieldSubscribers[name]; | ||
if (fieldSubscriber) { | ||
@@ -877,3 +786,2 @@ notify(fieldSubscriber, fieldState, lastFieldState, filterFieldState, lastFieldState === undefined); | ||
}; | ||
if (name) { | ||
@@ -885,3 +793,2 @@ notifyField(name); | ||
}; | ||
var markAllFieldsTouched = function markAllFieldsTouched() { | ||
@@ -892,20 +799,16 @@ Object.keys(state.fields).forEach(function (key) { | ||
}; | ||
var hasSyncErrors = function hasSyncErrors() { | ||
return !!(state.formState.error || hasAnyError(state.formState.errors)); | ||
}; | ||
var calculateNextFormState = function calculateNextFormState() { | ||
var fields = state.fields, | ||
formState = state.formState, | ||
lastFormState = state.lastFormState; | ||
formState = state.formState, | ||
lastFormState = state.lastFormState; | ||
var safeFields = _extends({}, fields); | ||
var safeFieldKeys = Object.keys(safeFields); | ||
var safeFieldKeys = Object.keys(safeFields); // calculate dirty/pristine | ||
// calculate dirty/pristine | ||
var foundDirty = false; | ||
var dirtyFields = safeFieldKeys.reduce(function (result, key) { | ||
var dirty = !safeFields[key].isEqual(getIn(formState.values, key), getIn(formState.initialValues || {}, key)); | ||
if (dirty) { | ||
@@ -915,3 +818,2 @@ foundDirty = true; | ||
} | ||
return result; | ||
@@ -922,7 +824,5 @@ }, {}); | ||
var nonNullLastSubmittedValues = formState.lastSubmittedValues || {}; // || {} is for flow, but causes branch coverage complaint | ||
if (!safeFields[key].isEqual(getIn(formState.values, key), getIn(nonNullLastSubmittedValues, key))) { | ||
result[key] = true; | ||
} | ||
return result; | ||
@@ -934,3 +834,4 @@ }, {}); | ||
})); | ||
formState.modifiedSinceLastSubmit = !!(formState.lastSubmittedValues && // Object.values would treat values as mixed (facebook/flow#2221) | ||
formState.modifiedSinceLastSubmit = !!(formState.lastSubmittedValues && | ||
// Object.values would treat values as mixed (facebook/flow#2221) | ||
Object.keys(safeFields).some(function (value) { | ||
@@ -941,17 +842,15 @@ return safeFields[value].modifiedSinceLastSubmit; | ||
var nextFormState = convertToExternalFormState(formState); | ||
var _safeFieldKeys$reduce = safeFieldKeys.reduce(function (result, key) { | ||
result.modified[key] = safeFields[key].modified; | ||
result.touched[key] = safeFields[key].touched; | ||
result.visited[key] = safeFields[key].visited; | ||
return result; | ||
}, { | ||
modified: {}, | ||
touched: {}, | ||
visited: {} | ||
}), | ||
modified = _safeFieldKeys$reduce.modified, | ||
touched = _safeFieldKeys$reduce.touched, | ||
visited = _safeFieldKeys$reduce.visited; | ||
result.modified[key] = safeFields[key].modified; | ||
result.touched[key] = safeFields[key].touched; | ||
result.visited[key] = safeFields[key].visited; | ||
return result; | ||
}, { | ||
modified: {}, | ||
touched: {}, | ||
visited: {} | ||
}), | ||
modified = _safeFieldKeys$reduce.modified, | ||
touched = _safeFieldKeys$reduce.touched, | ||
visited = _safeFieldKeys$reduce.visited; | ||
nextFormState.dirtyFields = lastFormState && shallowEqual(lastFormState.dirtyFields, dirtyFields) ? lastFormState.dirtyFields : dirtyFields; | ||
@@ -964,3 +863,2 @@ nextFormState.dirtyFieldsSinceLastSubmit = lastFormState && shallowEqual(lastFormState.dirtyFieldsSinceLastSubmit, dirtyFieldsSinceLastSubmit) ? lastFormState.dirtyFieldsSinceLastSubmit : dirtyFieldsSinceLastSubmit; | ||
}; | ||
var callDebug = function callDebug() { | ||
@@ -972,6 +870,4 @@ return debug && "development" !== "production" && debug(calculateNextFormState(), Object.keys(state.fields).reduce(function (result, key) { | ||
}; | ||
var notifying = false; | ||
var scheduleNotification = false; | ||
var notifyFormListeners = function notifyFormListeners() { | ||
@@ -983,7 +879,5 @@ if (notifying) { | ||
callDebug(); | ||
if (!inBatch && !(validationPaused && preventNotificationWhileValidationPaused)) { | ||
var lastFormState = state.lastFormState; | ||
var nextFormState = calculateNextFormState(); | ||
if (nextFormState !== lastFormState) { | ||
@@ -994,5 +888,3 @@ state.lastFormState = nextFormState; | ||
} | ||
notifying = false; | ||
if (scheduleNotification) { | ||
@@ -1004,3 +896,2 @@ scheduleNotification = false; | ||
}; | ||
var beforeSubmit = function beforeSubmit() { | ||
@@ -1011,3 +902,2 @@ return Object.keys(state.fields).some(function (name) { | ||
}; | ||
var afterSubmit = function afterSubmit() { | ||
@@ -1018,3 +908,2 @@ return Object.keys(state.fields).forEach(function (name) { | ||
}; | ||
var resetModifiedAfterSubmit = function resetModifiedAfterSubmit() { | ||
@@ -1024,5 +913,5 @@ return Object.keys(state.fields).forEach(function (key) { | ||
}); | ||
}; // generate initial errors | ||
}; | ||
// generate initial errors | ||
runValidation(undefined, function () { | ||
@@ -1041,5 +930,4 @@ notifyFormListeners(); | ||
var fields = state.fields, | ||
formState = state.formState; | ||
formState = state.formState; | ||
var previous = fields[name]; | ||
if (previous) { | ||
@@ -1052,3 +940,2 @@ // can only blur registered fields | ||
}); | ||
if (validateOnBlur) { | ||
@@ -1067,4 +954,3 @@ runValidation(name, function () { | ||
var fields = state.fields, | ||
formState = state.formState; | ||
formState = state.formState; | ||
if (getIn(formState.values, name) !== value) { | ||
@@ -1075,3 +961,2 @@ changeValue(state, name, function () { | ||
var previous = fields[name]; | ||
if (previous) { | ||
@@ -1084,3 +969,2 @@ // only track modified for registered fields | ||
} | ||
if (validateOnBlur) { | ||
@@ -1097,14 +981,10 @@ notifyFieldListeners(); | ||
}, | ||
get destroyOnUnregister() { | ||
return !!destroyOnUnregister; | ||
}, | ||
set destroyOnUnregister(value) { | ||
destroyOnUnregister = value; | ||
}, | ||
focus: function focus(name) { | ||
var field = state.fields[name]; | ||
if (field && !field.active) { | ||
@@ -1131,8 +1011,5 @@ state.formState.active = name; | ||
var fields = state.fields, | ||
formState = state.formState; | ||
formState = state.formState; | ||
var safeFields = _extends({}, fields); | ||
var values = typeof data === "function" ? data(formState.values) : data; | ||
if (!keepDirtyOnReinitialize) { | ||
@@ -1147,19 +1024,16 @@ formState.values = values; | ||
*/ | ||
// save dirty values | ||
var savedDirtyValues = keepDirtyOnReinitialize ? Object.keys(safeFields).reduce(function (result, key) { | ||
var field = safeFields[key]; | ||
var pristine = field.isEqual(getIn(formState.values, key), getIn(formState.initialValues || {}, key)); | ||
if (!pristine) { | ||
result[key] = getIn(formState.values, key); | ||
} | ||
return result; | ||
}, {}) : {}; // update initalValues and values | ||
}, {}) : {}; | ||
// update initalValues and values | ||
formState.initialValues = values; | ||
formState.values = values; // restore the dirty values | ||
formState.values = values; | ||
// restore the dirty values | ||
Object.keys(savedDirtyValues).forEach(function (key) { | ||
@@ -1180,3 +1054,2 @@ formState.values = setIn(formState.values, key, savedDirtyValues[key]) || {}; | ||
} | ||
validationPaused = true; | ||
@@ -1189,3 +1062,2 @@ preventNotificationWhileValidationPaused = preventNotification; | ||
} | ||
if (!state.fieldSubscribers[name]) { | ||
@@ -1197,5 +1069,5 @@ state.fieldSubscribers[name] = { | ||
} | ||
var index = state.fieldSubscribers[name].index++; | ||
var index = state.fieldSubscribers[name].index++; // save field subscriber callback | ||
// save field subscriber callback | ||
state.fieldSubscribers[name].entries[index] = { | ||
@@ -1205,4 +1077,5 @@ subscriber: memoize(subscriber), | ||
notified: false | ||
}; // create initial field state if not exists | ||
}; | ||
// create initial field state if not exists | ||
var field = state.fields[name] || { | ||
@@ -1224,21 +1097,17 @@ active: false, | ||
visited: false | ||
}; // Mutators can create a field in order to keep the field states | ||
}; | ||
// Mutators can create a field in order to keep the field states | ||
// We must update this field when registerField is called afterwards | ||
field.blur = field.blur || function () { | ||
return api.blur(name); | ||
}; | ||
field.change = field.change || function (value) { | ||
return api.change(name, value); | ||
}; | ||
field.focus = field.focus || function () { | ||
return api.focus(name); | ||
}; | ||
state.fields[name] = field; | ||
var haveValidator = false; | ||
var silent = fieldConfig && fieldConfig.silent; | ||
var notify = function notify() { | ||
@@ -1252,13 +1121,10 @@ if (silent && state.fields[name]) { | ||
}; | ||
if (fieldConfig) { | ||
haveValidator = !!(fieldConfig.getValidator && fieldConfig.getValidator()); | ||
if (fieldConfig.getValidator) { | ||
state.fields[name].validators[index] = fieldConfig.getValidator; | ||
} | ||
var noValueInFormState = getIn(state.formState.values, name) === undefined; | ||
if (fieldConfig.initialValue !== undefined && (noValueInFormState || getIn(state.formState.values, name) === getIn(state.formState.initialValues, name)) // only initialize if we don't yet have any value for this field | ||
if (fieldConfig.initialValue !== undefined && (noValueInFormState || getIn(state.formState.values, name) === getIn(state.formState.initialValues, name)) | ||
// only initialize if we don't yet have any value for this field | ||
) { | ||
@@ -1268,5 +1134,5 @@ state.formState.initialValues = setIn(state.formState.initialValues || {}, name, fieldConfig.initialValue); | ||
runValidation(undefined, notify); | ||
} // only use defaultValue if we don't yet have any value for this field | ||
} | ||
// only use defaultValue if we don't yet have any value for this field | ||
if (fieldConfig.defaultValue !== undefined && fieldConfig.initialValue === undefined && getIn(state.formState.initialValues, name) === undefined && noValueInFormState) { | ||
@@ -1276,3 +1142,2 @@ state.formState.values = setIn(state.formState.values, name, fieldConfig.defaultValue); | ||
} | ||
if (haveValidator) { | ||
@@ -1283,6 +1148,5 @@ runValidation(undefined, notify); | ||
} | ||
return function () { | ||
var validatorRemoved = false; // istanbul ignore next | ||
var validatorRemoved = false; | ||
// istanbul ignore next | ||
if (state.fields[name]) { | ||
@@ -1293,5 +1157,3 @@ // state.fields[name] may have been removed by a mutator | ||
} | ||
var hasFieldSubscribers = !!state.fieldSubscribers[name]; | ||
if (hasFieldSubscribers) { | ||
@@ -1301,13 +1163,9 @@ // state.fieldSubscribers[name] may have been removed by a mutator | ||
} | ||
var lastOne = hasFieldSubscribers && !Object.keys(state.fieldSubscribers[name].entries).length; | ||
if (lastOne) { | ||
delete state.fieldSubscribers[name]; | ||
delete state.fields[name]; | ||
if (validatorRemoved) { | ||
state.formState.errors = setIn(state.formState.errors, name, undefined) || {}; | ||
} | ||
if (destroyOnUnregister) { | ||
@@ -1317,3 +1175,2 @@ state.formState.values = setIn(state.formState.values, name, undefined, true) || {}; | ||
} | ||
if (!silent) { | ||
@@ -1336,7 +1193,5 @@ if (validatorRemoved) { | ||
} | ||
if (state.formState.submitting) { | ||
state.formState.resetWhileSubmitting = true; | ||
} | ||
state.formState.submitFailed = false; | ||
@@ -1349,3 +1204,2 @@ state.formState.submitSucceeded = false; | ||
}, | ||
/** | ||
@@ -1369,3 +1223,2 @@ * Resets all field flags (e.g. touched, visited, etc.) to their initial state | ||
}, | ||
/** | ||
@@ -1380,3 +1233,2 @@ * Returns the form to a clean slate; that is: | ||
} | ||
api.batch(function () { | ||
@@ -1396,3 +1248,2 @@ for (var name in state.fields) { | ||
} | ||
api.reset(initialValues); | ||
@@ -1404,3 +1255,2 @@ }); | ||
preventNotificationWhileValidationPaused = false; | ||
if (validationBlocked) { | ||
@@ -1413,3 +1263,2 @@ // validation was attempted while it was paused, so run it now | ||
} | ||
validationBlocked = false; | ||
@@ -1422,18 +1271,13 @@ }, | ||
break; | ||
case "destroyOnUnregister": | ||
destroyOnUnregister = value; | ||
break; | ||
case "initialValues": | ||
api.initialize(value); | ||
break; | ||
case "keepDirtyOnReinitialize": | ||
keepDirtyOnReinitialize = value; | ||
break; | ||
case "mutators": | ||
mutators = value; | ||
if (value) { | ||
@@ -1453,9 +1297,6 @@ Object.keys(mutatorsApi).forEach(function (key) { | ||
} | ||
break; | ||
case "onSubmit": | ||
onSubmit = value; | ||
break; | ||
case "validate": | ||
@@ -1468,7 +1309,5 @@ validate = value; | ||
break; | ||
case "validateOnBlur": | ||
validateOnBlur = value; | ||
break; | ||
default: | ||
@@ -1480,11 +1319,8 @@ throw new Error("Unrecognised option " + name); | ||
var formState = state.formState; | ||
if (formState.submitting) { | ||
return; | ||
} | ||
delete formState.submitErrors; | ||
delete formState.submitError; | ||
formState.lastSubmittedValues = _extends({}, formState.values); | ||
if (hasSyncErrors()) { | ||
@@ -1500,3 +1336,2 @@ markAllFieldsTouched(); | ||
var asyncValidationPromisesKeys = Object.keys(asyncValidationPromises); | ||
if (asyncValidationPromisesKeys.length) { | ||
@@ -1509,20 +1344,14 @@ // still waiting on async validation to complete... | ||
} | ||
var submitIsBlocked = beforeSubmit(); | ||
if (submitIsBlocked) { | ||
return; | ||
} | ||
var resolvePromise; | ||
var completeCalled = false; | ||
var complete = function complete(errors) { | ||
formState.submitting = false; | ||
var resetWhileSubmitting = formState.resetWhileSubmitting; | ||
if (resetWhileSubmitting) { | ||
formState.resetWhileSubmitting = false; | ||
} | ||
if (errors && hasAnyError(errors)) { | ||
@@ -1539,17 +1368,12 @@ formState.submitFailed = true; | ||
} | ||
afterSubmit(); | ||
} | ||
notifyFormListeners(); | ||
notifyFieldListeners(); | ||
completeCalled = true; | ||
if (resolvePromise) { | ||
resolvePromise(errors); | ||
} | ||
return errors; | ||
}; | ||
formState.submitting = true; | ||
@@ -1559,6 +1383,6 @@ formState.submitFailed = false; | ||
formState.lastSubmittedValues = _extends({}, formState.values); | ||
resetModifiedAfterSubmit(); // onSubmit is either sync, callback or async with a Promise | ||
resetModifiedAfterSubmit(); | ||
// onSubmit is either sync, callback or async with a Promise | ||
var result = onSubmit(formState.values, api, complete); | ||
if (!completeCalled) { | ||
@@ -1568,5 +1392,3 @@ if (result && isPromise(result)) { | ||
notifyFormListeners(); // let everyone know we are submitting | ||
notifyFieldListeners(); // notify fields also | ||
return result.then(complete, function (error) { | ||
@@ -1579,5 +1401,3 @@ complete(); | ||
notifyFormListeners(); // let everyone know we are submitting | ||
notifyFieldListeners(); // notify fields also | ||
return new Promise(function (resolve) { | ||
@@ -1596,7 +1416,5 @@ resolvePromise = resolve; | ||
} | ||
if (!subscription) { | ||
throw new Error("No subscription provided. What values do you want to listen to?"); | ||
} | ||
var memoized = memoize(subscriber); | ||
@@ -1603,0 +1421,0 @@ var subscribers = state.subscribers; |
(function (global, factory) { | ||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@babel/runtime/helpers/esm/extends'), require('@babel/runtime/helpers/esm/objectWithoutPropertiesLoose')) : | ||
typeof define === 'function' && define.amd ? define(['exports', '@babel/runtime/helpers/esm/extends', '@babel/runtime/helpers/esm/objectWithoutPropertiesLoose'], factory) : | ||
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["final-form"] = {}, global._extends, global._objectWithoutPropertiesLoose)); | ||
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.FinalForm = {}, global._extends, global._objectWithoutPropertiesLoose)); | ||
})(this, (function (exports, _extends, _objectWithoutPropertiesLoose) { 'use strict'; | ||
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } | ||
// | ||
var _extends__default = /*#__PURE__*/_interopDefaultLegacy(_extends); | ||
var _objectWithoutPropertiesLoose__default = /*#__PURE__*/_interopDefaultLegacy(_objectWithoutPropertiesLoose); | ||
// | ||
var charCodeOfDot = ".".charCodeAt(0); | ||
var reEscapeChar = /\\(\\)?/g; | ||
var rePropName = RegExp( // Match anything that isn't a dot or bracket. | ||
"[^.[\\]]+" + "|" + // Or match property names within brackets. | ||
"\\[(?:" + // Match a non-string expression. | ||
"([^\"'][^[]*)" + "|" + // Or match strings (supports escaping characters). | ||
"([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2" + ")\\]" + "|" + // Or match "" as the space between consecutive dots or empty brackets. | ||
var rePropName = RegExp( | ||
// Match anything that isn't a dot or bracket. | ||
"[^.[\\]]+" + "|" + | ||
// Or match property names within brackets. | ||
"\\[(?:" + | ||
// Match a non-string expression. | ||
"([^\"'][^[]*)" + "|" + | ||
// Or match strings (supports escaping characters). | ||
"([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2" + ")\\]" + "|" + | ||
// Or match "" as the space between consecutive dots or empty brackets. | ||
"(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))", "g"); | ||
/** | ||
@@ -28,13 +30,9 @@ * Converts `string` to a property path array. | ||
*/ | ||
var stringToPath = function stringToPath(string) { | ||
var result = []; | ||
if (string.charCodeAt(0) === charCodeOfDot) { | ||
result.push(""); | ||
} | ||
string.replace(rePropName, function (match, expression, quote, subString) { | ||
var key = match; | ||
if (quote) { | ||
@@ -45,3 +43,2 @@ key = subString.replace(reEscapeChar, "$1"); | ||
} | ||
result.push(key); | ||
@@ -51,6 +48,4 @@ }); | ||
}; | ||
var keysCache = {}; | ||
var keysRegex = /[.[\]]+/; | ||
var toPath = function toPath(key) { | ||
@@ -60,7 +55,5 @@ if (key === null || key === undefined || !key.length) { | ||
} | ||
if (typeof key !== "string") { | ||
throw new Error("toPath() expects a string"); | ||
} | ||
if (keysCache[key] == null) { | ||
@@ -88,3 +81,2 @@ /** | ||
} | ||
return keysCache[key]; | ||
@@ -94,3 +86,2 @@ }; | ||
// | ||
var getIn = function getIn(state, complexKey) { | ||
@@ -100,13 +91,9 @@ // Intentionally using iteration rather than recursion | ||
var current = state; | ||
for (var i = 0; i < path.length; i++) { | ||
var key = path[i]; | ||
if (current === undefined || current === null || typeof current !== "object" || Array.isArray(current) && isNaN(key)) { | ||
return undefined; | ||
} | ||
current = current[key]; | ||
} | ||
return current; | ||
@@ -116,5 +103,3 @@ }; | ||
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } | ||
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } | ||
var setInRecursor = function setInRecursor(current, index, path, value, destroyArrays) { | ||
@@ -125,29 +110,23 @@ if (index >= path.length) { | ||
} | ||
var key = path[index]; | ||
var key = path[index]; // determine type of key | ||
// determine type of key | ||
if (isNaN(key)) { | ||
var _extends2; | ||
// object set | ||
if (current === undefined || current === null) { | ||
var _ref; | ||
// recurse | ||
var _result2 = setInRecursor(undefined, index + 1, path, value, destroyArrays); // delete or create an object | ||
var _result = setInRecursor(undefined, index + 1, path, value, destroyArrays); | ||
return _result2 === undefined ? undefined : (_ref = {}, _ref[key] = _result2, _ref); | ||
// delete or create an object | ||
return _result === undefined ? undefined : (_ref = {}, _ref[key] = _result, _ref); | ||
} | ||
if (Array.isArray(current)) { | ||
throw new Error("Cannot set a non-numeric property on an array"); | ||
} // current exists, so make a copy of all its values, and add/update the new one | ||
var _result = setInRecursor(current[key], index + 1, path, value, destroyArrays); | ||
if (_result === undefined) { | ||
} | ||
// current exists, so make a copy of all its values, and add/update the new one | ||
var _result2 = setInRecursor(current[key], index + 1, path, value, destroyArrays); | ||
if (_result2 === undefined) { | ||
var numKeys = Object.keys(current).length; | ||
if (current[key] === undefined && numKeys === 0) { | ||
@@ -157,3 +136,2 @@ // object was already empty | ||
} | ||
if (current[key] !== undefined && numKeys <= 1) { | ||
@@ -168,26 +146,21 @@ // only key we had was the one we are deleting | ||
} | ||
current[key]; | ||
var _final = _objectWithoutPropertiesLoose__default["default"](current, [key].map(_toPropertyKey)); | ||
var _final = _objectWithoutPropertiesLoose(current, [key].map(_toPropertyKey)); | ||
return _final; | ||
} // set result in key | ||
return _extends__default["default"]({}, current, (_extends2 = {}, _extends2[key] = _result, _extends2)); | ||
} // array set | ||
} | ||
// set result in key | ||
return _extends({}, current, (_extends2 = {}, _extends2[key] = _result2, _extends2)); | ||
} | ||
// array set | ||
var numericKey = Number(key); | ||
if (current === undefined || current === null) { | ||
// recurse | ||
var _result3 = setInRecursor(undefined, index + 1, path, value, destroyArrays); // if nothing returned, delete it | ||
var _result3 = setInRecursor(undefined, index + 1, path, value, destroyArrays); | ||
// if nothing returned, delete it | ||
if (_result3 === undefined) { | ||
return undefined; | ||
} // create an array | ||
} | ||
// create an array | ||
var _array = []; | ||
@@ -197,16 +170,13 @@ _array[numericKey] = _result3; | ||
} | ||
if (!Array.isArray(current)) { | ||
throw new Error("Cannot set a numeric property on an object"); | ||
} // recurse | ||
} | ||
// recurse | ||
var existingValue = current[numericKey]; | ||
var result = setInRecursor(existingValue, index + 1, path, value, destroyArrays); // current exists, so make a copy of all its values, and add/update the new one | ||
var result = setInRecursor(existingValue, index + 1, path, value, destroyArrays); | ||
// current exists, so make a copy of all its values, and add/update the new one | ||
var array = [].concat(current); | ||
if (destroyArrays && result === undefined) { | ||
array.splice(numericKey, 1); | ||
if (array.length === 0) { | ||
@@ -218,6 +188,4 @@ return undefined; | ||
} | ||
return array; | ||
}; | ||
var setIn = function setIn(state, key, value, destroyArrays) { | ||
@@ -227,13 +195,10 @@ if (destroyArrays === void 0) { | ||
} | ||
if (state === undefined || state === null) { | ||
throw new Error("Cannot call setIn() with " + String(state) + " state"); | ||
} | ||
if (key === undefined || key === null) { | ||
throw new Error("Cannot call setIn() with " + String(key) + " key"); | ||
} // Recursive function needs to accept and return State, but public API should | ||
} | ||
// Recursive function needs to accept and return State, but public API should | ||
// only deal with Objects | ||
return setInRecursor(state, 0, toPath(key), value, destroyArrays); | ||
@@ -246,33 +211,32 @@ }; | ||
// | ||
/** | ||
* Converts internal field state to published field state | ||
*/ | ||
function publishFieldState(formState, field) { | ||
var errors = formState.errors, | ||
initialValues = formState.initialValues, | ||
lastSubmittedValues = formState.lastSubmittedValues, | ||
submitErrors = formState.submitErrors, | ||
submitFailed = formState.submitFailed, | ||
submitSucceeded = formState.submitSucceeded, | ||
submitting = formState.submitting, | ||
values = formState.values; | ||
initialValues = formState.initialValues, | ||
lastSubmittedValues = formState.lastSubmittedValues, | ||
submitErrors = formState.submitErrors, | ||
submitFailed = formState.submitFailed, | ||
submitSucceeded = formState.submitSucceeded, | ||
submitting = formState.submitting, | ||
values = formState.values; | ||
var active = field.active, | ||
blur = field.blur, | ||
change = field.change, | ||
data = field.data, | ||
focus = field.focus, | ||
modified = field.modified, | ||
modifiedSinceLastSubmit = field.modifiedSinceLastSubmit, | ||
name = field.name, | ||
touched = field.touched, | ||
validating = field.validating, | ||
visited = field.visited; | ||
blur = field.blur, | ||
change = field.change, | ||
data = field.data, | ||
focus = field.focus, | ||
modified = field.modified, | ||
modifiedSinceLastSubmit = field.modifiedSinceLastSubmit, | ||
name = field.name, | ||
touched = field.touched, | ||
validating = field.validating, | ||
visited = field.visited; | ||
var value = getIn(values, name); | ||
var error = getIn(errors, name); | ||
if (error && error[ARRAY_ERROR]) { | ||
error = error[ARRAY_ERROR]; | ||
} | ||
var submitError = submitErrors && getIn(submitErrors, name); | ||
@@ -315,2 +279,3 @@ var initial = initialValues && getIn(initialValues, name); | ||
// | ||
var shallowEqual = function shallowEqual(a, b) { | ||
@@ -320,19 +285,13 @@ if (a === b) { | ||
} | ||
if (typeof a !== "object" || !a || typeof b !== "object" || !b) { | ||
return false; | ||
} | ||
var keysA = Object.keys(a); | ||
var keysB = Object.keys(b); | ||
if (keysA.length !== keysB.length) { | ||
return false; | ||
} | ||
var bHasOwnProperty = Object.prototype.hasOwnProperty.bind(b); | ||
for (var idx = 0; idx < keysA.length; idx++) { | ||
var key = keysA[idx]; | ||
if (!bHasOwnProperty(key) || a[key] !== b[key]) { | ||
@@ -342,3 +301,2 @@ return false; | ||
} | ||
return true; | ||
@@ -353,3 +311,2 @@ }; | ||
dest[key] = src[key]; | ||
if (!previous || (~shallowEqualKeys.indexOf(key) ? !shallowEqual(src[key], previous[key]) : src[key] !== previous[key])) { | ||
@@ -365,6 +322,6 @@ different = true; | ||
var shallowEqualKeys$1 = ["data"]; | ||
/** | ||
* Filters items in a FieldState based on a FieldSubscription | ||
*/ | ||
var filterFieldState = function filterFieldState(state, previousState, subscription, force) { | ||
@@ -386,6 +343,6 @@ var result = { | ||
var shallowEqualKeys = ["touched", "visited"]; | ||
/** | ||
* Filters items in a FormState based on a FormSubscription | ||
*/ | ||
function filterFormState(state, previousState, subscription, force) { | ||
@@ -398,3 +355,2 @@ var result = {}; | ||
// | ||
var memoize = function memoize(fn) { | ||
@@ -407,3 +363,2 @@ var lastArgs; | ||
} | ||
if (!lastArgs || args.length !== lastArgs.length || args.some(function (arg, index) { | ||
@@ -415,3 +370,2 @@ return !shallowEqual(lastArgs[index], arg); | ||
} | ||
return lastResult; | ||
@@ -425,38 +379,33 @@ }; | ||
var version = "4.20.9"; | ||
var version = "4.20.10"; | ||
var configOptions = ["debug", "initialValues", "keepDirtyOnReinitialize", "mutators", "onSubmit", "validate", "validateOnBlur"]; | ||
var tripleEquals = function tripleEquals(a, b) { | ||
return a === b; | ||
}; | ||
var hasAnyError = function hasAnyError(errors) { | ||
return Object.keys(errors).some(function (key) { | ||
var value = errors[key]; | ||
if (value && typeof value === "object" && !(value instanceof Error)) { | ||
return hasAnyError(value); | ||
} | ||
return typeof value !== "undefined"; | ||
}); | ||
}; | ||
function convertToExternalFormState(_ref) { | ||
var active = _ref.active, | ||
dirtySinceLastSubmit = _ref.dirtySinceLastSubmit, | ||
modifiedSinceLastSubmit = _ref.modifiedSinceLastSubmit, | ||
error = _ref.error, | ||
errors = _ref.errors, | ||
initialValues = _ref.initialValues, | ||
pristine = _ref.pristine, | ||
submitting = _ref.submitting, | ||
submitFailed = _ref.submitFailed, | ||
submitSucceeded = _ref.submitSucceeded, | ||
submitError = _ref.submitError, | ||
submitErrors = _ref.submitErrors, | ||
valid = _ref.valid, | ||
validating = _ref.validating, | ||
values = _ref.values; | ||
dirtySinceLastSubmit = _ref.dirtySinceLastSubmit, | ||
modifiedSinceLastSubmit = _ref.modifiedSinceLastSubmit, | ||
error = _ref.error, | ||
errors = _ref.errors, | ||
initialValues = _ref.initialValues, | ||
pristine = _ref.pristine, | ||
submitting = _ref.submitting, | ||
submitFailed = _ref.submitFailed, | ||
submitSucceeded = _ref.submitSucceeded, | ||
submitError = _ref.submitError, | ||
submitErrors = _ref.submitErrors, | ||
valid = _ref.valid, | ||
validating = _ref.validating, | ||
values = _ref.values; | ||
return { | ||
@@ -484,6 +433,4 @@ active: active, | ||
} | ||
function notifySubscriber(subscriber, subscription, state, lastState, filter, force) { | ||
var notification = filter(state, lastState, subscription, force); | ||
if (notification) { | ||
@@ -493,16 +440,13 @@ subscriber(notification); | ||
} | ||
return false; | ||
} | ||
function notify(_ref2, state, lastState, filter, force) { | ||
var entries = _ref2.entries; | ||
Object.keys(entries).forEach(function (key) { | ||
var entry = entries[Number(key)]; // istanbul ignore next | ||
var entry = entries[Number(key)]; | ||
// istanbul ignore next | ||
if (entry) { | ||
var subscription = entry.subscription, | ||
subscriber = entry.subscriber, | ||
notified = entry.notified; | ||
subscriber = entry.subscriber, | ||
notified = entry.notified; | ||
if (notifySubscriber(subscriber, subscription, state, lastState, filter, force || !notified)) { | ||
@@ -514,3 +458,2 @@ entry.notified = true; | ||
} | ||
function createForm(config) { | ||
@@ -520,16 +463,13 @@ if (!config) { | ||
} | ||
var debug = config.debug, | ||
destroyOnUnregister = config.destroyOnUnregister, | ||
keepDirtyOnReinitialize = config.keepDirtyOnReinitialize, | ||
initialValues = config.initialValues, | ||
mutators = config.mutators, | ||
onSubmit = config.onSubmit, | ||
validate = config.validate, | ||
validateOnBlur = config.validateOnBlur; | ||
destroyOnUnregister = config.destroyOnUnregister, | ||
keepDirtyOnReinitialize = config.keepDirtyOnReinitialize, | ||
initialValues = config.initialValues, | ||
mutators = config.mutators, | ||
onSubmit = config.onSubmit, | ||
validate = config.validate, | ||
validateOnBlur = config.validateOnBlur; | ||
if (!onSubmit) { | ||
throw new Error("No onSubmit function specified"); | ||
} | ||
var state = { | ||
@@ -547,3 +487,3 @@ subscribers: { | ||
errors: {}, | ||
initialValues: initialValues && _extends__default["default"]({}, initialValues), | ||
initialValues: initialValues && _extends({}, initialValues), | ||
invalid: false, | ||
@@ -557,3 +497,3 @@ pristine: true, | ||
validating: 0, | ||
values: initialValues ? _extends__default["default"]({}, initialValues) : {} | ||
values: initialValues ? _extends({}, initialValues) : {} | ||
}, | ||
@@ -568,3 +508,2 @@ lastFormState: undefined | ||
var asyncValidationPromises = {}; | ||
var clearAsyncValidationPromise = function clearAsyncValidationPromise(key) { | ||
@@ -576,3 +515,2 @@ return function (result) { | ||
}; | ||
var changeValue = function changeValue(state, name, mutate) { | ||
@@ -583,8 +521,6 @@ var before = getIn(state.formState.values, name); | ||
}; | ||
var renameField = function renameField(state, from, to) { | ||
if (state.fields[from]) { | ||
var _extends2, _extends3; | ||
state.fields = _extends__default["default"]({}, state.fields, (_extends2 = {}, _extends2[to] = _extends__default["default"]({}, state.fields[from], { | ||
state.fields = _extends({}, state.fields, (_extends2 = {}, _extends2[to] = _extends({}, state.fields[from], { | ||
name: to, | ||
@@ -604,3 +540,3 @@ // rebind event handlers | ||
delete state.fields[from]; | ||
state.fieldSubscribers = _extends__default["default"]({}, state.fieldSubscribers, (_extends3 = {}, _extends3[to] = state.fieldSubscribers[from], _extends3)); | ||
state.fieldSubscribers = _extends({}, state.fieldSubscribers, (_extends3 = {}, _extends3[to] = state.fieldSubscribers[from], _extends3)); | ||
delete state.fieldSubscribers[from]; | ||
@@ -612,5 +548,5 @@ var value = getIn(state.formState.values, from); | ||
} | ||
}; // bind state to mutators | ||
}; | ||
// bind state to mutators | ||
var getMutatorApi = function getMutatorApi(key) { | ||
@@ -627,7 +563,5 @@ return function () { | ||
}; | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
var returnValue = mutators[key](args, mutatableState, { | ||
@@ -653,3 +587,2 @@ changeValue: changeValue, | ||
}; | ||
var mutatorsApi = mutators ? Object.keys(mutators).reduce(function (result, key) { | ||
@@ -659,9 +592,6 @@ result[key] = getMutatorApi(key); | ||
}, {}) : {}; | ||
var runRecordLevelValidation = function runRecordLevelValidation(setErrors) { | ||
var promises = []; | ||
if (validate) { | ||
var errorsOrPromise = validate(_extends__default["default"]({}, state.formState.values)); // clone to avoid writing | ||
var errorsOrPromise = validate(_extends({}, state.formState.values)); // clone to avoid writing | ||
if (isPromise(errorsOrPromise)) { | ||
@@ -675,22 +605,16 @@ promises.push(errorsOrPromise.then(function (errors) { | ||
} | ||
return promises; | ||
}; | ||
var getValidators = function getValidators(field) { | ||
return Object.keys(field.validators).reduce(function (result, index) { | ||
var validator = field.validators[Number(index)](); | ||
if (validator) { | ||
result.push(validator); | ||
} | ||
return result; | ||
}, []); | ||
}; | ||
var runFieldLevelValidation = function runFieldLevelValidation(field, setError) { | ||
var promises = []; | ||
var validators = getValidators(field); | ||
if (validators.length) { | ||
@@ -700,3 +624,2 @@ var error; | ||
var errorOrPromise = validator(getIn(state.formState.values, field.name), state.formState.values, validator.length === 0 || validator.length === 3 ? publishFieldState(state.formState, state.fields[field.name]) : undefined); | ||
if (errorOrPromise && isPromise(errorOrPromise)) { | ||
@@ -710,3 +633,2 @@ field.validating = true; | ||
}); // errors must be resolved, not rejected | ||
promises.push(promise); | ||
@@ -720,6 +642,4 @@ } else if (!error) { | ||
} | ||
return promises; | ||
}; | ||
var runValidation = function runValidation(fieldChanged, callback) { | ||
@@ -731,10 +651,6 @@ if (validationPaused) { | ||
} | ||
var fields = state.fields, | ||
formState = state.formState; | ||
var safeFields = _extends__default["default"]({}, fields); | ||
formState = state.formState; | ||
var safeFields = _extends({}, fields); | ||
var fieldKeys = Object.keys(safeFields); | ||
if (!validate && !fieldKeys.some(function (key) { | ||
@@ -745,13 +661,10 @@ return getValidators(safeFields[key]).length; | ||
return; // no validation rules | ||
} // pare down field keys to actually validate | ||
} | ||
// pare down field keys to actually validate | ||
var limitedFieldLevelValidation = false; | ||
if (fieldChanged) { | ||
var changedField = safeFields[fieldChanged]; | ||
if (changedField) { | ||
var validateFields = changedField.validateFields; | ||
if (validateFields) { | ||
@@ -763,3 +676,2 @@ limitedFieldLevelValidation = true; | ||
} | ||
var recordLevelErrors = {}; | ||
@@ -781,12 +693,11 @@ var asyncRecordLevelErrors = {}; | ||
var asyncValidationPromiseKey = ++nextAsyncValidationKey; | ||
var promise = Promise.all(promises).then(clearAsyncValidationPromise(asyncValidationPromiseKey)); // backwards-compat: add promise to submit-blocking promises iff there are any promises to await | ||
var promise = Promise.all(promises).then(clearAsyncValidationPromise(asyncValidationPromiseKey)); | ||
// backwards-compat: add promise to submit-blocking promises iff there are any promises to await | ||
if (hasAsyncValidations) { | ||
asyncValidationPromises[asyncValidationPromiseKey] = promise; | ||
} | ||
var processErrors = function processErrors(afterAsync) { | ||
var merged = _extends__default["default"]({}, limitedFieldLevelValidation ? formState.errors : {}, recordLevelErrors, afterAsync ? asyncRecordLevelErrors // new async errors | ||
var merged = _extends({}, limitedFieldLevelValidation ? formState.errors : {}, recordLevelErrors, afterAsync ? asyncRecordLevelErrors // new async errors | ||
: formState.asyncErrors); | ||
var forEachError = function forEachError(fn) { | ||
@@ -805,3 +716,2 @@ fieldKeys.forEach(function (name) { | ||
}; | ||
forEachError(function (name, error) { | ||
@@ -818,14 +728,10 @@ merged = setIn(merged, name, error) || {}; | ||
}); | ||
if (!shallowEqual(formState.errors, merged)) { | ||
formState.errors = merged; | ||
} | ||
if (afterAsync) { | ||
formState.asyncErrors = asyncRecordLevelErrors; | ||
} | ||
formState.error = recordLevelErrors[FORM_ERROR]; | ||
}; | ||
if (hasAsyncValidations) { | ||
@@ -835,9 +741,8 @@ // async validations are running, ensure validating is true before notifying | ||
callback(); | ||
} // process sync errors | ||
} | ||
processErrors(false); // sync errors have been set. notify listeners while we wait for others | ||
// process sync errors | ||
processErrors(false); | ||
// sync errors have been set. notify listeners while we wait for others | ||
callback(); | ||
if (hasAsyncValidations) { | ||
@@ -847,4 +752,9 @@ var afterPromise = function afterPromise() { | ||
callback(); | ||
// field async validation may affect formState validating | ||
// so force notifyFormListeners if validating is still 0 after callback finished | ||
// and lastFormState validating is true | ||
if (state.formState.validating === 0 && state.lastFormState.validating) { | ||
notifyFormListeners(); | ||
} | ||
}; | ||
promise.then(function () { | ||
@@ -855,3 +765,2 @@ if (nextAsyncValidationKey > asyncValidationPromiseKey) { | ||
} | ||
processErrors(true); | ||
@@ -861,3 +770,2 @@ }).then(afterPromise, afterPromise); | ||
}; | ||
var notifyFieldListeners = function notifyFieldListeners(name) { | ||
@@ -867,9 +775,6 @@ if (inBatch) { | ||
} | ||
var fields = state.fields, | ||
fieldSubscribers = state.fieldSubscribers, | ||
formState = state.formState; | ||
var safeFields = _extends__default["default"]({}, fields); | ||
fieldSubscribers = state.fieldSubscribers, | ||
formState = state.formState; | ||
var safeFields = _extends({}, fields); | ||
var notifyField = function notifyField(name) { | ||
@@ -881,3 +786,2 @@ var field = safeFields[name]; | ||
var fieldSubscriber = fieldSubscribers[name]; | ||
if (fieldSubscriber) { | ||
@@ -887,3 +791,2 @@ notify(fieldSubscriber, fieldState, lastFieldState, filterFieldState, lastFieldState === undefined); | ||
}; | ||
if (name) { | ||
@@ -895,3 +798,2 @@ notifyField(name); | ||
}; | ||
var markAllFieldsTouched = function markAllFieldsTouched() { | ||
@@ -902,20 +804,16 @@ Object.keys(state.fields).forEach(function (key) { | ||
}; | ||
var hasSyncErrors = function hasSyncErrors() { | ||
return !!(state.formState.error || hasAnyError(state.formState.errors)); | ||
}; | ||
var calculateNextFormState = function calculateNextFormState() { | ||
var fields = state.fields, | ||
formState = state.formState, | ||
lastFormState = state.lastFormState; | ||
formState = state.formState, | ||
lastFormState = state.lastFormState; | ||
var safeFields = _extends({}, fields); | ||
var safeFieldKeys = Object.keys(safeFields); | ||
var safeFields = _extends__default["default"]({}, fields); | ||
var safeFieldKeys = Object.keys(safeFields); // calculate dirty/pristine | ||
// calculate dirty/pristine | ||
var foundDirty = false; | ||
var dirtyFields = safeFieldKeys.reduce(function (result, key) { | ||
var dirty = !safeFields[key].isEqual(getIn(formState.values, key), getIn(formState.initialValues || {}, key)); | ||
if (dirty) { | ||
@@ -925,3 +823,2 @@ foundDirty = true; | ||
} | ||
return result; | ||
@@ -932,7 +829,5 @@ }, {}); | ||
var nonNullLastSubmittedValues = formState.lastSubmittedValues || {}; // || {} is for flow, but causes branch coverage complaint | ||
if (!safeFields[key].isEqual(getIn(formState.values, key), getIn(nonNullLastSubmittedValues, key))) { | ||
result[key] = true; | ||
} | ||
return result; | ||
@@ -944,3 +839,4 @@ }, {}); | ||
})); | ||
formState.modifiedSinceLastSubmit = !!(formState.lastSubmittedValues && // Object.values would treat values as mixed (facebook/flow#2221) | ||
formState.modifiedSinceLastSubmit = !!(formState.lastSubmittedValues && | ||
// Object.values would treat values as mixed (facebook/flow#2221) | ||
Object.keys(safeFields).some(function (value) { | ||
@@ -951,17 +847,15 @@ return safeFields[value].modifiedSinceLastSubmit; | ||
var nextFormState = convertToExternalFormState(formState); | ||
var _safeFieldKeys$reduce = safeFieldKeys.reduce(function (result, key) { | ||
result.modified[key] = safeFields[key].modified; | ||
result.touched[key] = safeFields[key].touched; | ||
result.visited[key] = safeFields[key].visited; | ||
return result; | ||
}, { | ||
modified: {}, | ||
touched: {}, | ||
visited: {} | ||
}), | ||
modified = _safeFieldKeys$reduce.modified, | ||
touched = _safeFieldKeys$reduce.touched, | ||
visited = _safeFieldKeys$reduce.visited; | ||
result.modified[key] = safeFields[key].modified; | ||
result.touched[key] = safeFields[key].touched; | ||
result.visited[key] = safeFields[key].visited; | ||
return result; | ||
}, { | ||
modified: {}, | ||
touched: {}, | ||
visited: {} | ||
}), | ||
modified = _safeFieldKeys$reduce.modified, | ||
touched = _safeFieldKeys$reduce.touched, | ||
visited = _safeFieldKeys$reduce.visited; | ||
nextFormState.dirtyFields = lastFormState && shallowEqual(lastFormState.dirtyFields, dirtyFields) ? lastFormState.dirtyFields : dirtyFields; | ||
@@ -974,3 +868,2 @@ nextFormState.dirtyFieldsSinceLastSubmit = lastFormState && shallowEqual(lastFormState.dirtyFieldsSinceLastSubmit, dirtyFieldsSinceLastSubmit) ? lastFormState.dirtyFieldsSinceLastSubmit : dirtyFieldsSinceLastSubmit; | ||
}; | ||
var callDebug = function callDebug() { | ||
@@ -982,6 +875,4 @@ return debug && "development" !== "production" && debug(calculateNextFormState(), Object.keys(state.fields).reduce(function (result, key) { | ||
}; | ||
var notifying = false; | ||
var scheduleNotification = false; | ||
var notifyFormListeners = function notifyFormListeners() { | ||
@@ -993,7 +884,5 @@ if (notifying) { | ||
callDebug(); | ||
if (!inBatch && !(validationPaused && preventNotificationWhileValidationPaused)) { | ||
var lastFormState = state.lastFormState; | ||
var nextFormState = calculateNextFormState(); | ||
if (nextFormState !== lastFormState) { | ||
@@ -1004,5 +893,3 @@ state.lastFormState = nextFormState; | ||
} | ||
notifying = false; | ||
if (scheduleNotification) { | ||
@@ -1014,3 +901,2 @@ scheduleNotification = false; | ||
}; | ||
var beforeSubmit = function beforeSubmit() { | ||
@@ -1021,3 +907,2 @@ return Object.keys(state.fields).some(function (name) { | ||
}; | ||
var afterSubmit = function afterSubmit() { | ||
@@ -1028,3 +913,2 @@ return Object.keys(state.fields).forEach(function (name) { | ||
}; | ||
var resetModifiedAfterSubmit = function resetModifiedAfterSubmit() { | ||
@@ -1034,5 +918,5 @@ return Object.keys(state.fields).forEach(function (key) { | ||
}); | ||
}; // generate initial errors | ||
}; | ||
// generate initial errors | ||
runValidation(undefined, function () { | ||
@@ -1051,13 +935,11 @@ notifyFormListeners(); | ||
var fields = state.fields, | ||
formState = state.formState; | ||
formState = state.formState; | ||
var previous = fields[name]; | ||
if (previous) { | ||
// can only blur registered fields | ||
delete formState.active; | ||
fields[name] = _extends__default["default"]({}, previous, { | ||
fields[name] = _extends({}, previous, { | ||
active: false, | ||
touched: true | ||
}); | ||
if (validateOnBlur) { | ||
@@ -1076,4 +958,3 @@ runValidation(name, function () { | ||
var fields = state.fields, | ||
formState = state.formState; | ||
formState = state.formState; | ||
if (getIn(formState.values, name) !== value) { | ||
@@ -1084,6 +965,5 @@ changeValue(state, name, function () { | ||
var previous = fields[name]; | ||
if (previous) { | ||
// only track modified for registered fields | ||
fields[name] = _extends__default["default"]({}, previous, { | ||
fields[name] = _extends({}, previous, { | ||
modified: true, | ||
@@ -1093,3 +973,2 @@ modifiedSinceLastSubmit: !!formState.lastSubmittedValues | ||
} | ||
if (validateOnBlur) { | ||
@@ -1106,14 +985,10 @@ notifyFieldListeners(); | ||
}, | ||
get destroyOnUnregister() { | ||
return !!destroyOnUnregister; | ||
}, | ||
set destroyOnUnregister(value) { | ||
destroyOnUnregister = value; | ||
}, | ||
focus: function focus(name) { | ||
var field = state.fields[name]; | ||
if (field && !field.active) { | ||
@@ -1140,8 +1015,5 @@ state.formState.active = name; | ||
var fields = state.fields, | ||
formState = state.formState; | ||
var safeFields = _extends__default["default"]({}, fields); | ||
formState = state.formState; | ||
var safeFields = _extends({}, fields); | ||
var values = typeof data === "function" ? data(formState.values) : data; | ||
if (!keepDirtyOnReinitialize) { | ||
@@ -1156,19 +1028,16 @@ formState.values = values; | ||
*/ | ||
// save dirty values | ||
var savedDirtyValues = keepDirtyOnReinitialize ? Object.keys(safeFields).reduce(function (result, key) { | ||
var field = safeFields[key]; | ||
var pristine = field.isEqual(getIn(formState.values, key), getIn(formState.initialValues || {}, key)); | ||
if (!pristine) { | ||
result[key] = getIn(formState.values, key); | ||
} | ||
return result; | ||
}, {}) : {}; // update initalValues and values | ||
}, {}) : {}; | ||
// update initalValues and values | ||
formState.initialValues = values; | ||
formState.values = values; // restore the dirty values | ||
formState.values = values; | ||
// restore the dirty values | ||
Object.keys(savedDirtyValues).forEach(function (key) { | ||
@@ -1189,3 +1058,2 @@ formState.values = setIn(formState.values, key, savedDirtyValues[key]) || {}; | ||
} | ||
validationPaused = true; | ||
@@ -1198,3 +1066,2 @@ preventNotificationWhileValidationPaused = preventNotification; | ||
} | ||
if (!state.fieldSubscribers[name]) { | ||
@@ -1206,5 +1073,5 @@ state.fieldSubscribers[name] = { | ||
} | ||
var index = state.fieldSubscribers[name].index++; | ||
var index = state.fieldSubscribers[name].index++; // save field subscriber callback | ||
// save field subscriber callback | ||
state.fieldSubscribers[name].entries[index] = { | ||
@@ -1214,4 +1081,5 @@ subscriber: memoize(subscriber), | ||
notified: false | ||
}; // create initial field state if not exists | ||
}; | ||
// create initial field state if not exists | ||
var field = state.fields[name] || { | ||
@@ -1233,21 +1101,17 @@ active: false, | ||
visited: false | ||
}; // Mutators can create a field in order to keep the field states | ||
}; | ||
// Mutators can create a field in order to keep the field states | ||
// We must update this field when registerField is called afterwards | ||
field.blur = field.blur || function () { | ||
return api.blur(name); | ||
}; | ||
field.change = field.change || function (value) { | ||
return api.change(name, value); | ||
}; | ||
field.focus = field.focus || function () { | ||
return api.focus(name); | ||
}; | ||
state.fields[name] = field; | ||
var haveValidator = false; | ||
var silent = fieldConfig && fieldConfig.silent; | ||
var notify = function notify() { | ||
@@ -1261,13 +1125,10 @@ if (silent && state.fields[name]) { | ||
}; | ||
if (fieldConfig) { | ||
haveValidator = !!(fieldConfig.getValidator && fieldConfig.getValidator()); | ||
if (fieldConfig.getValidator) { | ||
state.fields[name].validators[index] = fieldConfig.getValidator; | ||
} | ||
var noValueInFormState = getIn(state.formState.values, name) === undefined; | ||
if (fieldConfig.initialValue !== undefined && (noValueInFormState || getIn(state.formState.values, name) === getIn(state.formState.initialValues, name)) // only initialize if we don't yet have any value for this field | ||
if (fieldConfig.initialValue !== undefined && (noValueInFormState || getIn(state.formState.values, name) === getIn(state.formState.initialValues, name)) | ||
// only initialize if we don't yet have any value for this field | ||
) { | ||
@@ -1277,5 +1138,5 @@ state.formState.initialValues = setIn(state.formState.initialValues || {}, name, fieldConfig.initialValue); | ||
runValidation(undefined, notify); | ||
} // only use defaultValue if we don't yet have any value for this field | ||
} | ||
// only use defaultValue if we don't yet have any value for this field | ||
if (fieldConfig.defaultValue !== undefined && fieldConfig.initialValue === undefined && getIn(state.formState.initialValues, name) === undefined && noValueInFormState) { | ||
@@ -1285,3 +1146,2 @@ state.formState.values = setIn(state.formState.values, name, fieldConfig.defaultValue); | ||
} | ||
if (haveValidator) { | ||
@@ -1292,6 +1152,5 @@ runValidation(undefined, notify); | ||
} | ||
return function () { | ||
var validatorRemoved = false; // istanbul ignore next | ||
var validatorRemoved = false; | ||
// istanbul ignore next | ||
if (state.fields[name]) { | ||
@@ -1302,5 +1161,3 @@ // state.fields[name] may have been removed by a mutator | ||
} | ||
var hasFieldSubscribers = !!state.fieldSubscribers[name]; | ||
if (hasFieldSubscribers) { | ||
@@ -1310,13 +1167,9 @@ // state.fieldSubscribers[name] may have been removed by a mutator | ||
} | ||
var lastOne = hasFieldSubscribers && !Object.keys(state.fieldSubscribers[name].entries).length; | ||
if (lastOne) { | ||
delete state.fieldSubscribers[name]; | ||
delete state.fields[name]; | ||
if (validatorRemoved) { | ||
state.formState.errors = setIn(state.formState.errors, name, undefined) || {}; | ||
} | ||
if (destroyOnUnregister) { | ||
@@ -1326,3 +1179,2 @@ state.formState.values = setIn(state.formState.values, name, undefined, true) || {}; | ||
} | ||
if (!silent) { | ||
@@ -1345,7 +1197,5 @@ if (validatorRemoved) { | ||
} | ||
if (state.formState.submitting) { | ||
state.formState.resetWhileSubmitting = true; | ||
} | ||
state.formState.submitFailed = false; | ||
@@ -1358,3 +1208,2 @@ state.formState.submitSucceeded = false; | ||
}, | ||
/** | ||
@@ -1364,3 +1213,3 @@ * Resets all field flags (e.g. touched, visited, etc.) to their initial state | ||
resetFieldState: function resetFieldState(name) { | ||
state.fields[name] = _extends__default["default"]({}, state.fields[name], { | ||
state.fields[name] = _extends({}, state.fields[name], { | ||
active: false, | ||
@@ -1379,3 +1228,2 @@ lastFieldState: undefined, | ||
}, | ||
/** | ||
@@ -1390,7 +1238,6 @@ * Returns the form to a clean slate; that is: | ||
} | ||
api.batch(function () { | ||
for (var name in state.fields) { | ||
api.resetFieldState(name); | ||
state.fields[name] = _extends__default["default"]({}, state.fields[name], { | ||
state.fields[name] = _extends({}, state.fields[name], { | ||
active: false, | ||
@@ -1406,3 +1253,2 @@ lastFieldState: undefined, | ||
} | ||
api.reset(initialValues); | ||
@@ -1414,3 +1260,2 @@ }); | ||
preventNotificationWhileValidationPaused = false; | ||
if (validationBlocked) { | ||
@@ -1423,3 +1268,2 @@ // validation was attempted while it was paused, so run it now | ||
} | ||
validationBlocked = false; | ||
@@ -1432,18 +1276,13 @@ }, | ||
break; | ||
case "destroyOnUnregister": | ||
destroyOnUnregister = value; | ||
break; | ||
case "initialValues": | ||
api.initialize(value); | ||
break; | ||
case "keepDirtyOnReinitialize": | ||
keepDirtyOnReinitialize = value; | ||
break; | ||
case "mutators": | ||
mutators = value; | ||
if (value) { | ||
@@ -1463,9 +1302,6 @@ Object.keys(mutatorsApi).forEach(function (key) { | ||
} | ||
break; | ||
case "onSubmit": | ||
onSubmit = value; | ||
break; | ||
case "validate": | ||
@@ -1478,7 +1314,5 @@ validate = value; | ||
break; | ||
case "validateOnBlur": | ||
validateOnBlur = value; | ||
break; | ||
default: | ||
@@ -1490,11 +1324,8 @@ throw new Error("Unrecognised option " + name); | ||
var formState = state.formState; | ||
if (formState.submitting) { | ||
return; | ||
} | ||
delete formState.submitErrors; | ||
delete formState.submitError; | ||
formState.lastSubmittedValues = _extends__default["default"]({}, formState.values); | ||
formState.lastSubmittedValues = _extends({}, formState.values); | ||
if (hasSyncErrors()) { | ||
@@ -1510,3 +1341,2 @@ markAllFieldsTouched(); | ||
var asyncValidationPromisesKeys = Object.keys(asyncValidationPromises); | ||
if (asyncValidationPromisesKeys.length) { | ||
@@ -1519,20 +1349,14 @@ // still waiting on async validation to complete... | ||
} | ||
var submitIsBlocked = beforeSubmit(); | ||
if (submitIsBlocked) { | ||
return; | ||
} | ||
var resolvePromise; | ||
var completeCalled = false; | ||
var complete = function complete(errors) { | ||
formState.submitting = false; | ||
var resetWhileSubmitting = formState.resetWhileSubmitting; | ||
if (resetWhileSubmitting) { | ||
formState.resetWhileSubmitting = false; | ||
} | ||
if (errors && hasAnyError(errors)) { | ||
@@ -1549,25 +1373,20 @@ formState.submitFailed = true; | ||
} | ||
afterSubmit(); | ||
} | ||
notifyFormListeners(); | ||
notifyFieldListeners(); | ||
completeCalled = true; | ||
if (resolvePromise) { | ||
resolvePromise(errors); | ||
} | ||
return errors; | ||
}; | ||
formState.submitting = true; | ||
formState.submitFailed = false; | ||
formState.submitSucceeded = false; | ||
formState.lastSubmittedValues = _extends__default["default"]({}, formState.values); | ||
resetModifiedAfterSubmit(); // onSubmit is either sync, callback or async with a Promise | ||
formState.lastSubmittedValues = _extends({}, formState.values); | ||
resetModifiedAfterSubmit(); | ||
// onSubmit is either sync, callback or async with a Promise | ||
var result = onSubmit(formState.values, api, complete); | ||
if (!completeCalled) { | ||
@@ -1577,5 +1396,3 @@ if (result && isPromise(result)) { | ||
notifyFormListeners(); // let everyone know we are submitting | ||
notifyFieldListeners(); // notify fields also | ||
return result.then(complete, function (error) { | ||
@@ -1588,5 +1405,3 @@ complete(); | ||
notifyFormListeners(); // let everyone know we are submitting | ||
notifyFieldListeners(); // notify fields also | ||
return new Promise(function (resolve) { | ||
@@ -1605,7 +1420,5 @@ resolvePromise = resolve; | ||
} | ||
if (!subscription) { | ||
throw new Error("No subscription provided. What values do you want to listen to?"); | ||
} | ||
var memoized = memoize(subscriber); | ||
@@ -1639,5 +1452,3 @@ var subscribers = state.subscribers; | ||
Object.defineProperty(exports, '__esModule', { value: true }); | ||
})); | ||
//# sourceMappingURL=final-form.umd.js.map |
@@ -1,2 +0,2 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@babel/runtime/helpers/esm/extends"),require("@babel/runtime/helpers/esm/objectWithoutPropertiesLoose")):"function"==typeof define&&define.amd?define(["exports","@babel/runtime/helpers/esm/extends","@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["final-form"]={},e._extends,e._objectWithoutPropertiesLoose)}(this,function(e,t,i){"use strict";function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function u(e){if(null==e||!e.length)return[];if("string"!=typeof e)throw new Error("toPath() expects a string");var t,n;return null==d[e]&&(e.endsWith("[]")?d[e]=e.split(l).filter(Boolean):d[e]=(n=[],(t=e).charCodeAt(0)===a&&n.push(""),t.replace(s,function(e,t,i,r){var a=e;i?a=r.replace(o,"$1"):t&&(a=t.trim()),n.push(a)}),n)),d[e]}var A=r(t),h=r(i),a=".".charCodeAt(0),o=/\\(\\)?/g,s=RegExp("[^.[\\]]+|\\[(?:([^\"'][^[]*)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))","g"),d={},l=/[.[\]]+/,R=function(e,t){for(var i=u(t),r=e,a=0;a<i.length;a++){var n=i[a];if(null==r||"object"!=typeof r||Array.isArray(r)&&isNaN(n))return;r=r[n]}return r};function g(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var i=e[Symbol.toPrimitive];if(void 0===i)return("string"===t?String:Number)(e);var r=i.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}(e,"string");return"symbol"==typeof t?t:String(t)}function L(e,t,i,r){if(void 0===r&&(r=!1),null==e)throw new Error("Cannot call setIn() with "+String(e)+" state");if(null==t)throw new Error("Cannot call setIn() with "+String(t)+" key");return function e(t,i,r,a,n){if(i>=r.length)return a;var u=r[i];if(isNaN(u)){var o;if(null==t){var s,d=e(void 0,i+1,r,a,n);return void 0===d?void 0:((s={})[u]=d,s)}if(Array.isArray(t))throw new Error("Cannot set a non-numeric property on an array");var l=e(t[u],i+1,r,a,n);if(void 0!==l)return A.default({},t,((o={})[u]=l,o));var f=Object.keys(t).length;if(void 0===t[u]&&0===f)return;return void 0!==t[u]&&f<=1?isNaN(r[i-1])||n?void 0:{}:(t[u],h.default(t,[u].map(g)))}var c=Number(u);if(null==t){var v=e(void 0,i+1,r,a,n);if(void 0===v)return;var m=[];return m[c]=v,m}if(!Array.isArray(t))throw new Error("Cannot set a numeric property on an object");var b=e(t[c],i+1,r,a,n),S=[].concat(t);if(n&&void 0===b){if(S.splice(c,1),0===S.length)return}else S[c]=b;return S}(e,0,u(t),i,r)}var x="FINAL_FORM/form-error",P="FINAL_FORM/array-error";function q(e,t){var i=e.errors,r=e.initialValues,a=e.lastSubmittedValues,n=e.submitErrors,u=e.submitFailed,o=e.submitSucceeded,s=e.submitting,d=e.values,l=t.active,f=t.blur,c=t.change,v=t.data,m=t.focus,b=t.modified,S=t.modifiedSinceLastSubmit,h=t.name,g=t.touched,y=t.validating,p=t.visited,E=R(d,h),F=R(i,h);F&&F[P]&&(F=F[P]);var O=n&&R(n,h),V=r&&R(r,h),j=t.isEqual(V,E),k=!F&&!O;return{active:l,blur:f,change:c,data:v,dirty:!j,dirtySinceLastSubmit:!(!a||t.isEqual(R(a,h),E)),error:F,focus:m,initial:V,invalid:!k,length:Array.isArray(E)?E.length:void 0,modified:b,modifiedSinceLastSubmit:S,name:h,pristine:j,submitError:O,submitFailed:u,submitSucceeded:o,submitting:s,touched:g,valid:k,value:E,visited:p,validating:y}}var n=["active","data","dirty","dirtySinceLastSubmit","error","initial","invalid","length","modified","modifiedSinceLastSubmit","pristine","submitError","submitFailed","submitSucceeded","submitting","touched","valid","value","visited","validating"],I=function(e,t){if(e===t)return!0;if("object"!=typeof e||!e||"object"!=typeof t||!t)return!1;var i=Object.keys(e),r=Object.keys(t);if(i.length!==r.length)return!1;for(var a=Object.prototype.hasOwnProperty.bind(t),n=0;n<i.length;n++){var u=i[n];if(!a(u)||e[u]!==t[u])return!1}return!0};function f(t,i,r,a,e,n){var u=!1;return e.forEach(function(e){a[e]&&(t[e]=i[e],r&&(~n.indexOf(e)?I(i[e],r[e]):i[e]===r[e])||(u=!0))}),u}function W(e,t,i,r){var a={blur:e.blur,change:e.change,focus:e.focus,name:e.name};return f(a,e,t,i,n,c)||!t||r?a:void 0}var c=["data"],v=["active","dirty","dirtyFields","dirtyFieldsSinceLastSubmit","dirtySinceLastSubmit","error","errors","hasSubmitErrors","hasValidationErrors","initialValues","invalid","modified","modifiedSinceLastSubmit","pristine","submitting","submitError","submitErrors","submitFailed","submitSucceeded","touched","valid","validating","values","visited"],m=["touched","visited"];function _(e,t,i,r){var a={};return f(a,e,t,i,v,m)||!t||r?a:void 0}function C(r){var a,n;return function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return a&&t.length===a.length&&!t.some(function(e,t){return!I(a[t],e)})||(a=t,n=r.apply(void 0,t)),n}}function z(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function U(e,t){return e===t}var B=function i(r){return Object.keys(r).some(function(e){var t=r[e];return!t||"object"!=typeof t||t instanceof Error?void 0!==t:i(t)})};function M(e,t,i,r,a,n){var u=a(i,r,t,n);return u&&(e(u),1)}function D(e,n,u,o,s){var d=e.entries;Object.keys(d).forEach(function(e){var t=d[Number(e)];if(t){var i=t.subscription,r=t.subscriber,a=t.notified;M(r,i,n,u,o,s||!a)&&(t.notified=!0)}})}e.ARRAY_ERROR=P,e.FORM_ERROR=x,e.configOptions=["debug","initialValues","keepDirtyOnReinitialize","mutators","onSubmit","validate","validateOnBlur"],e.createForm=function(e){if(!e)throw new Error("No config specified");e.debug;var l=e.destroyOnUnregister,u=e.keepDirtyOnReinitialize,t=e.initialValues,o=e.mutators,s=e.onSubmit,y=e.validate,n=e.validateOnBlur;if(!s)throw new Error("No onSubmit function specified");function d(e,t,i){var r=i(R(e.formState.values,t));e.formState.values=L(e.formState.values,t,r)||{}}function f(e,t,i){if(e.fields[t]){var r,a;e.fields=A.default({},e.fields,((r={})[i]=A.default({},e.fields[t],{name:i,blur:function(){return w.blur(i)},change:function(e){return w.change(i,e)},focus:function(){return w.focus(i)},lastFieldState:void 0}),r)),delete e.fields[t],e.fieldSubscribers=A.default({},e.fieldSubscribers,((a={})[i]=e.fieldSubscribers[t],a)),delete e.fieldSubscribers[t];var n=R(e.formState.values,t);e.formState.values=L(e.formState.values,t,void 0)||{},e.formState.values=L(e.formState.values,i,n),delete e.lastFormState}}function i(n){return function(){if(o){for(var e={formState:N.formState,fields:N.fields,fieldSubscribers:N.fieldSubscribers,lastFormState:N.lastFormState},t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];var a=o[n](i,e,{changeValue:d,getIn:R,renameField:f,resetFieldState:w.resetFieldState,setIn:L,shallowEqual:I});return N.formState=e.formState,N.fields=e.fields,N.fieldSubscribers=e.fieldSubscribers,N.lastFormState=e.lastFormState,S(void 0,function(){h(),k()}),a}}}function p(r){return Object.keys(r.validators).reduce(function(e,t){var i=r.validators[Number(t)]();return i&&e.push(i),e},[])}function c(){Object.keys(N.fields).forEach(function(e){N.fields[e].touched=!0})}function v(){var e=N.fields,r=N.formState,t=N.lastFormState,a=A.default({},e),i=Object.keys(a),n=!1,u=i.reduce(function(e,t){return!a[t].isEqual(R(r.values,t),R(r.initialValues||{},t))&&(n=!0,e[t]=!0),e},{}),o=i.reduce(function(e,t){var i=r.lastSubmittedValues||{};return a[t].isEqual(R(r.values,t),R(i,t))||(e[t]=!0),e},{});r.pristine=!n,r.dirtySinceLastSubmit=!(!r.lastSubmittedValues||!Object.values(o).some(function(e){return e})),r.modifiedSinceLastSubmit=!(!r.lastSubmittedValues||!Object.keys(a).some(function(e){return a[e].modifiedSinceLastSubmit})),r.valid=!(r.error||r.submitError||B(r.errors)||r.submitErrors&&B(r.submitErrors));var s,d,l,f,c,v,m,b,S,h,g,y,p,E,F,O,V=(d=(s=r).active,l=s.dirtySinceLastSubmit,f=s.modifiedSinceLastSubmit,c=s.error,v=s.errors,m=s.initialValues,b=s.pristine,S=s.submitting,h=s.submitFailed,g=s.submitSucceeded,y=s.submitError,p=s.submitErrors,E=s.valid,F=s.validating,O=s.values,{active:d,dirty:!b,dirtySinceLastSubmit:l,modifiedSinceLastSubmit:f,error:c,errors:v,hasSubmitErrors:!!(y||p&&B(p)),hasValidationErrors:!(!c&&!B(v)),invalid:!E,initialValues:m,pristine:b,submitting:S,submitFailed:h,submitSucceeded:g,submitError:y,submitErrors:p,valid:E,validating:0<F,values:O}),j=i.reduce(function(e,t){return e.modified[t]=a[t].modified,e.touched[t]=a[t].touched,e.visited[t]=a[t].visited,e},{modified:{},touched:{},visited:{}}),k=j.modified,w=j.touched,L=j.visited;return V.dirtyFields=t&&I(t.dirtyFields,u)?t.dirtyFields:u,V.dirtyFieldsSinceLastSubmit=t&&I(t.dirtyFieldsSinceLastSubmit,o)?t.dirtyFieldsSinceLastSubmit:o,V.modified=t&&I(t.modified,k)?t.modified:k,V.touched=t&&I(t.touched,w)?t.touched:w,V.visited=t&&I(t.visited,L)?t.visited:L,t&&I(t,V)?t:V}function m(){return Object.keys(N.fields).forEach(function(e){return N.fields[e].modifiedSinceLastSubmit=!1})}var N={subscribers:{index:0,entries:{}},fieldSubscribers:{},fields:{},formState:{asyncErrors:{},dirtySinceLastSubmit:!1,modifiedSinceLastSubmit:!1,errors:{},initialValues:t&&A.default({},t),invalid:!1,pristine:!0,submitting:!1,submitFailed:!1,submitSucceeded:!1,resetWhileSubmitting:!1,valid:!0,validating:0,values:t?A.default({},t):{}},lastFormState:void 0},r=0,E=!1,F=!1,a=!1,O=0,V={},b=o?Object.keys(o).reduce(function(e,t){return e[t]=i(t),e},{}):{},S=function(e,t){if(E)return F=!0,void t();var o=N.fields,i=N.formState,s=A.default({},o),r=Object.keys(s);if(y||r.some(function(e){return p(s[e]).length})){var d=!1;if(e){var a=s[e];if(a){var n=a.validateFields;n&&(d=!0,r=n.length?n.concat(e):[e])}}var u,l={},f={},c={},v=[].concat(function(t){var e=[];if(y){var i=y(A.default({},N.formState.values));z(i)?e.push(i.then(function(e){return t(e,!0)})):t(i,!1)}return e}(function(e,t){t?f=e||{}:l=e||{}}),r.reduce(function(e,t){return e.concat(function(r,a){var n,u=[],e=p(r);e.length&&(e.forEach(function(e){var t=e(R(N.formState.values,r.name),N.formState.values,0===e.length||3===e.length?q(N.formState,N.fields[r.name]):void 0);if(t&&z(t)){r.validating=!0;var i=t.then(function(e){N.fields[r.name]&&(N.fields[r.name].validating=!1,a(e))});u.push(i)}else n=n||t}),a(n));return u}(o[t],function(e){c[t]=e}))},[])),m=0<v.length,b=++O,S=Promise.all(v).then((u=b,function(e){return delete V[u],e}));m&&(V[b]=S);var h=function(e){function t(n){r.forEach(function(e){if(o[e]){var t=R(l,e),i=R(u,e),r=p(s[e]).length,a=c[e];n(e,r&&a||y&&t||(t||d?void 0:i))}})}var u=A.default({},d?i.errors:{},l,e?f:i.asyncErrors);t(function(e,t){u=L(u,e,t)||{}}),t(function(e,t){if(t&&t[P]){var i=R(u,e),r=[].concat(i);r[P]=t[P],u=L(u,e,r)}}),I(i.errors,u)||(i.errors=u),e&&(i.asyncErrors=f),i.error=l[x]};if(m&&(N.formState.validating++,t()),h(!1),t(),m){var g=function(){N.formState.validating--,t()};S.then(function(){b<O||h(!0)}).then(g,g)}}else t()},h=function(e){if(!r){var t=N.fields,n=N.fieldSubscribers,u=N.formState,o=A.default({},t),i=function(e){var t=o[e],i=q(u,t),r=t.lastFieldState;t.lastFieldState=i;var a=n[e];a&&D(a,i,r,W,void 0===r)};e?i(e):Object.keys(o).forEach(i)}},g=!1,j=!1,k=function e(){if(g)j=!0;else{if(g=!0,!(r||E&&a)){var t=N.lastFormState,i=v();i!==t&&(N.lastFormState=i,D(N.subscribers,i,t,_))}g=!1,j&&(j=!1,e())}};S(void 0,function(){k()});var w={batch:function(e){r++,e(),r--,h(),k()},blur:function(e){var t=N.fields,i=N.formState,r=t[e];r&&(delete i.active,t[e]=A.default({},r,{active:!1,touched:!0}),n?S(e,function(){h(),k()}):(h(),k()))},change:function(e,t){var i=N.fields,r=N.formState;if(R(r.values,e)!==t){d(N,e,function(){return t});var a=i[e];a&&(i[e]=A.default({},a,{modified:!0,modifiedSinceLastSubmit:!!r.lastSubmittedValues})),n?(h(),k()):S(e,function(){h(),k()})}},get destroyOnUnregister(){return!!l},set destroyOnUnregister(e){l=e},focus:function(e){var t=N.fields[e];t&&!t.active&&(N.formState.active=e,t.active=!0,t.visited=!0,h(),k())},mutators:b,getFieldState:function(e){var t=N.fields[e];return t&&t.lastFieldState},getRegisteredFields:function(){return Object.keys(N.fields)},getState:function(){return v()},initialize:function(e){var t=N.fields,i=N.formState,r=A.default({},t),a="function"==typeof e?e(i.values):e;u||(i.values=a);var n=u?Object.keys(r).reduce(function(e,t){return r[t].isEqual(R(i.values,t),R(i.initialValues||{},t))||(e[t]=R(i.values,t)),e},{}):{};i.initialValues=a,i.values=a,Object.keys(n).forEach(function(e){i.values=L(i.values,e,n[e])||{}}),S(void 0,function(){h(),k()})},isValidationPaused:function(){return E},pauseValidation:function(e){void 0===e&&(e=!0),E=!0,a=e},registerField:function(r,e,t,i){void 0===t&&(t={}),N.fieldSubscribers[r]||(N.fieldSubscribers[r]={index:0,entries:{}});var a=N.fieldSubscribers[r].index++;N.fieldSubscribers[r].entries[a]={subscriber:C(e),subscription:t,notified:!1};var n=N.fields[r]||{active:!1,afterSubmit:i&&i.afterSubmit,beforeSubmit:i&&i.beforeSubmit,data:i&&i.data||{},isEqual:i&&i.isEqual||U,lastFieldState:void 0,modified:!1,modifiedSinceLastSubmit:!1,name:r,touched:!1,valid:!0,validateFields:i&&i.validateFields,validators:{},validating:!1,visited:!1};n.blur=n.blur||function(){return w.blur(r)},n.change=n.change||function(e){return w.change(r,e)},n.focus=n.focus||function(){return w.focus(r)},N.fields[r]=n;function u(){s&&N.fields[r]?h(r):(k(),h())}var o=!1,s=i&&i.silent;if(i){o=!(!i.getValidator||!i.getValidator()),i.getValidator&&(N.fields[r].validators[a]=i.getValidator);var d=void 0===R(N.formState.values,r);void 0===i.initialValue||!d&&R(N.formState.values,r)!==R(N.formState.initialValues,r)||(N.formState.initialValues=L(N.formState.initialValues||{},r,i.initialValue),N.formState.values=L(N.formState.values,r,i.initialValue),S(void 0,u)),void 0!==i.defaultValue&&void 0===i.initialValue&&void 0===R(N.formState.initialValues,r)&&d&&(N.formState.values=L(N.formState.values,r,i.defaultValue))}return o?S(void 0,u):u(),function(){var e=!1;N.fields[r]&&(e=!(!N.fields[r].validators[a]||!N.fields[r].validators[a]()),delete N.fields[r].validators[a]);var t=!!N.fieldSubscribers[r];t&&delete N.fieldSubscribers[r].entries[a];var i=t&&!Object.keys(N.fieldSubscribers[r].entries).length;i&&(delete N.fieldSubscribers[r],delete N.fields[r],e&&(N.formState.errors=L(N.formState.errors,r,void 0)||{}),l&&(N.formState.values=L(N.formState.values,r,void 0,!0)||{})),s||(e?S(void 0,function(){k(),h()}):i&&k())}},reset:function(e){void 0===e&&(e=N.formState.initialValues),N.formState.submitting&&(N.formState.resetWhileSubmitting=!0),N.formState.submitFailed=!1,N.formState.submitSucceeded=!1,delete N.formState.submitError,delete N.formState.submitErrors,delete N.formState.lastSubmittedValues,w.initialize(e||{})},resetFieldState:function(e){N.fields[e]=A.default({},N.fields[e],{active:!1,lastFieldState:void 0,modified:!1,touched:!1,valid:!0,validating:!1,visited:!1}),S(void 0,function(){h(),k()})},restart:function(t){void 0===t&&(t=N.formState.initialValues),w.batch(function(){for(var e in N.fields)w.resetFieldState(e),N.fields[e]=A.default({},N.fields[e],{active:!1,lastFieldState:void 0,modified:!1,modifiedSinceLastSubmit:!1,touched:!1,valid:!0,validating:!1,visited:!1});w.reset(t)})},resumeValidation:function(){a=E=!1,F&&S(void 0,function(){h(),k()}),F=!1},setConfig:function(e,t){switch(e){case"debug":0;break;case"destroyOnUnregister":l=t;break;case"initialValues":w.initialize(t);break;case"keepDirtyOnReinitialize":u=t;break;case"mutators":(o=t)?(Object.keys(b).forEach(function(e){e in t||delete b[e]}),Object.keys(t).forEach(function(e){b[e]=i(e)})):Object.keys(b).forEach(function(e){delete b[e]});break;case"onSubmit":s=t;break;case"validate":y=t,S(void 0,function(){h(),k()});break;case"validateOnBlur":n=t;break;default:throw new Error("Unrecognised option "+e)}},submit:function(){var i=N.formState;if(!i.submitting){if(delete i.submitErrors,delete i.submitError,i.lastSubmittedValues=A.default({},i.values),N.formState.error||B(N.formState.errors))return c(),m(),N.formState.submitFailed=!0,k(),void h();var e=Object.keys(V);if(e.length)Promise.all(e.map(function(e){return V[Number(e)]})).then(w.submit,console.error);else if(!Object.keys(N.fields).some(function(e){return N.fields[e].beforeSubmit&&!1===N.fields[e].beforeSubmit()})){var r,a=!1,t=function(e){i.submitting=!1;var t=i.resetWhileSubmitting;return t&&(i.resetWhileSubmitting=!1),e&&B(e)?(i.submitFailed=!0,i.submitSucceeded=!1,i.submitErrors=e,i.submitError=e[x],c()):(t||(i.submitFailed=!1,i.submitSucceeded=!0),Object.keys(N.fields).forEach(function(e){return N.fields[e].afterSubmit&&N.fields[e].afterSubmit()})),k(),h(),a=!0,r&&r(e),e};i.submitting=!0,i.submitFailed=!1,i.submitSucceeded=!1,i.lastSubmittedValues=A.default({},i.values),m();var n=s(i.values,w,t);if(!a){if(n&&z(n))return k(),h(),n.then(t,function(e){throw t(),e});if(3<=s.length)return k(),h(),new Promise(function(e){r=e});t(n)}}}},subscribe:function(e,t){if(!e)throw new Error("No callback given.");if(!t)throw new Error("No subscription provided. What values do you want to listen to?");var i=C(e),r=N.subscribers,a=r.index++;r.entries[a]={subscriber:i,subscription:t,notified:!1};var n=v();return M(i,t,n,n,_,!0),function(){delete r.entries[a]}}};return w},e.fieldSubscriptionItems=n,e.formSubscriptionItems=v,e.getIn=R,e.setIn=L,e.version="4.20.9",Object.defineProperty(e,"__esModule",{value:!0})}); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@babel/runtime/helpers/esm/extends"),require("@babel/runtime/helpers/esm/objectWithoutPropertiesLoose")):"function"==typeof define&&define.amd?define(["exports","@babel/runtime/helpers/esm/extends","@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).FinalForm={},e._extends,e._objectWithoutPropertiesLoose)}(this,(function(e,t,i){"use strict";var r=".".charCodeAt(0),n=/\\(\\)?/g,a=RegExp("[^.[\\]]+|\\[(?:([^\"'][^[]*)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))","g"),o={},s=/[.[\]]+/,u=function(e){if(null==e||!e.length)return[];if("string"!=typeof e)throw new Error("toPath() expects a string");var t,i;return null==o[e]&&(e.endsWith("[]")?o[e]=e.split(s).filter(Boolean):o[e]=(i=[],(t=e).charCodeAt(0)===r&&i.push(""),t.replace(a,(function(e,t,r,a){var o=e;r?o=a.replace(n,"$1"):t&&(o=t.trim()),i.push(o)})),i)),o[e]},l=function(e,t){for(var i=u(t),r=e,n=0;n<i.length;n++){var a=i[n];if(null==r||"object"!=typeof r||Array.isArray(r)&&isNaN(a))return;r=r[a]}return r};function d(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}var f=function e(r,n,a,o,s){if(n>=a.length)return o;var u=a[n];if(isNaN(u)){var l;if(null==r){var f,c=e(void 0,n+1,a,o,s);return void 0===c?void 0:((f={})[u]=c,f)}if(Array.isArray(r))throw new Error("Cannot set a non-numeric property on an array");var v=e(r[u],n+1,a,o,s);if(void 0===v){var m=Object.keys(r).length;if(void 0===r[u]&&0===m)return;return void 0!==r[u]&&m<=1?isNaN(a[n-1])||s?void 0:{}:(r[u],i(r,[u].map(d)))}return t({},r,((l={})[u]=v,l))}var b=Number(u);if(null==r){var S=e(void 0,n+1,a,o,s);if(void 0===S)return;var h=[];return h[b]=S,h}if(!Array.isArray(r))throw new Error("Cannot set a numeric property on an object");var g=e(r[b],n+1,a,o,s),y=[].concat(r);if(s&&void 0===g){if(y.splice(b,1),0===y.length)return}else y[b]=g;return y},c=function(e,t,i,r){if(void 0===r&&(r=!1),null==e)throw new Error("Cannot call setIn() with "+String(e)+" state");if(null==t)throw new Error("Cannot call setIn() with "+String(t)+" key");return f(e,0,u(t),i,r)},v="FINAL_FORM/form-error",m="FINAL_FORM/array-error";function b(e,t){var i=e.errors,r=e.initialValues,n=e.lastSubmittedValues,a=e.submitErrors,o=e.submitFailed,s=e.submitSucceeded,u=e.submitting,d=e.values,f=t.active,c=t.blur,v=t.change,b=t.data,S=t.focus,h=t.modified,g=t.modifiedSinceLastSubmit,y=t.name,p=t.touched,E=t.validating,F=t.visited,O=l(d,y),V=l(i,y);V&&V[m]&&(V=V[m]);var j=a&&l(a,y),k=r&&l(r,y),w=t.isEqual(k,O),L=!V&&!j;return{active:f,blur:c,change:v,data:b,dirty:!w,dirtySinceLastSubmit:!(!n||t.isEqual(l(n,y),O)),error:V,focus:S,initial:k,invalid:!L,length:Array.isArray(O)?O.length:void 0,modified:h,modifiedSinceLastSubmit:g,name:y,pristine:w,submitError:j,submitFailed:o,submitSucceeded:s,submitting:u,touched:p,valid:L,value:O,visited:F,validating:E}}var S=["active","data","dirty","dirtySinceLastSubmit","error","initial","invalid","length","modified","modifiedSinceLastSubmit","pristine","submitError","submitFailed","submitSucceeded","submitting","touched","valid","value","visited","validating"],h=function(e,t){if(e===t)return!0;if("object"!=typeof e||!e||"object"!=typeof t||!t)return!1;var i=Object.keys(e),r=Object.keys(t);if(i.length!==r.length)return!1;for(var n=Object.prototype.hasOwnProperty.bind(t),a=0;a<i.length;a++){var o=i[a];if(!n(o)||e[o]!==t[o])return!1}return!0};function g(e,t,i,r,n,a){var o=!1;return n.forEach((function(n){r[n]&&(e[n]=t[n],i&&(~a.indexOf(n)?h(t[n],i[n]):t[n]===i[n])||(o=!0))})),o}var y=["data"],p=function(e,t,i,r){var n={blur:e.blur,change:e.change,focus:e.focus,name:e.name};return g(n,e,t,i,S,y)||!t||r?n:void 0},E=["active","dirty","dirtyFields","dirtyFieldsSinceLastSubmit","dirtySinceLastSubmit","error","errors","hasSubmitErrors","hasValidationErrors","initialValues","invalid","modified","modifiedSinceLastSubmit","pristine","submitting","submitError","submitErrors","submitFailed","submitSucceeded","touched","valid","validating","values","visited"],F=["touched","visited"];function O(e,t,i,r){var n={};return g(n,e,t,i,E,F)||!t||r?n:void 0}var V=function(e){var t,i;return function(){for(var r=arguments.length,n=new Array(r),a=0;a<r;a++)n[a]=arguments[a];return t&&n.length===t.length&&!n.some((function(e,i){return!h(t[i],e)}))||(t=n,i=e.apply(void 0,n)),i}},j=function(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then},k=function(e,t){return e===t},w=function e(t){return Object.keys(t).some((function(i){var r=t[i];return!r||"object"!=typeof r||r instanceof Error?void 0!==r:e(r)}))};function L(e,t,i,r,n,a){var o=n(i,r,t,a);return!!o&&(e(o),!0)}function N(e,t,i,r,n){var a=e.entries;Object.keys(a).forEach((function(e){var o=a[Number(e)];if(o){var s=o.subscription,u=o.subscriber,l=o.notified;L(u,s,t,i,r,n||!l)&&(o.notified=!0)}}))}e.ARRAY_ERROR=m,e.FORM_ERROR=v,e.configOptions=["debug","initialValues","keepDirtyOnReinitialize","mutators","onSubmit","validate","validateOnBlur"],e.createForm=function(e){if(!e)throw new Error("No config specified");e.debug;var i=e.destroyOnUnregister,r=e.keepDirtyOnReinitialize,n=e.initialValues,a=e.mutators,o=e.onSubmit,s=e.validate,u=e.validateOnBlur;if(!o)throw new Error("No onSubmit function specified");var d={subscribers:{index:0,entries:{}},fieldSubscribers:{},fields:{},formState:{asyncErrors:{},dirtySinceLastSubmit:!1,modifiedSinceLastSubmit:!1,errors:{},initialValues:n&&t({},n),invalid:!1,pristine:!0,submitting:!1,submitFailed:!1,submitSucceeded:!1,resetWhileSubmitting:!1,valid:!0,validating:0,values:n?t({},n):{}},lastFormState:void 0},f=0,S=!1,g=!1,y=!1,E=0,F={},A=function(e,t,i){var r=i(l(e.formState.values,t));e.formState.values=c(e.formState.values,t,r)||{}},R=function(e,i,r){if(e.fields[i]){var n,a;e.fields=t({},e.fields,((n={})[r]=t({},e.fields[i],{name:r,blur:function(){return M.blur(r)},change:function(e){return M.change(r,e)},focus:function(){return M.focus(r)},lastFieldState:void 0}),n)),delete e.fields[i],e.fieldSubscribers=t({},e.fieldSubscribers,((a={})[r]=e.fieldSubscribers[i],a)),delete e.fieldSubscribers[i];var o=l(e.formState.values,i);e.formState.values=c(e.formState.values,i,void 0)||{},e.formState.values=c(e.formState.values,r,o),delete e.lastFormState}},x=function(e){return function(){if(a){for(var t={formState:d.formState,fields:d.fields,fieldSubscribers:d.fieldSubscribers,lastFormState:d.lastFormState},i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];var o=a[e](r,t,{changeValue:A,getIn:l,renameField:R,resetFieldState:M.resetFieldState,setIn:c,shallowEqual:h});return d.formState=t.formState,d.fields=t.fields,d.fieldSubscribers=t.fieldSubscribers,d.lastFormState=t.lastFormState,I(void 0,(function(){W(),B()})),o}}},P=a?Object.keys(a).reduce((function(e,t){return e[t]=x(t),e}),{}):{},q=function(e){return Object.keys(e.validators).reduce((function(t,i){var r=e.validators[Number(i)]();return r&&t.push(r),t}),[])},I=function(e,i){if(S)return g=!0,void i();var r=d.fields,n=d.formState,a=t({},r),o=Object.keys(a);if(s||o.some((function(e){return q(a[e]).length}))){var u=!1;if(e){var f=a[e];if(f){var y=f.validateFields;y&&(u=!0,o=y.length?y.concat(e):[e])}}var p,O={},V={},k={},w=[].concat(function(e){var i=[];if(s){var r=s(t({},d.formState.values));j(r)?i.push(r.then((function(t){return e(t,!0)}))):e(r,!1)}return i}((function(e,t){t?V=e||{}:O=e||{}})),o.reduce((function(e,t){return e.concat(function(e,t){var i,r=[],n=q(e);return n.length&&(n.forEach((function(n){var a=n(l(d.formState.values,e.name),d.formState.values,0===n.length||3===n.length?b(d.formState,d.fields[e.name]):void 0);if(a&&j(a)){e.validating=!0;var o=a.then((function(i){d.fields[e.name]&&(d.fields[e.name].validating=!1,t(i))}));r.push(o)}else i||(i=a)})),t(i)),r}(r[t],(function(e){k[t]=e})))}),[])),L=w.length>0,N=++E,A=Promise.all(w).then((p=N,function(e){return delete F[p],e}));L&&(F[N]=A);var R=function(e){var i=t({},u?n.errors:{},O,e?V:n.asyncErrors),d=function(e){o.forEach((function(t){if(r[t]){var n=l(O,t),o=l(i,t),d=q(a[t]).length,f=k[t];e(t,d&&f||s&&n||(n||u?void 0:o))}}))};d((function(e,t){i=c(i,e,t)||{}})),d((function(e,t){if(t&&t[m]){var r=l(i,e),n=[].concat(r);n[m]=t[m],i=c(i,e,n)}})),h(n.errors,i)||(n.errors=i),e&&(n.asyncErrors=V),n.error=O[v]};if(L&&(d.formState.validating++,i()),R(!1),i(),L){var x=function(){d.formState.validating--,i(),0===d.formState.validating&&d.lastFormState.validating&&B()};A.then((function(){E>N||R(!0)})).then(x,x)}}else i()},W=function(e){if(!f){var i=d.fields,r=d.fieldSubscribers,n=d.formState,a=t({},i),o=function(e){var t=a[e],i=b(n,t),o=t.lastFieldState;t.lastFieldState=i;var s=r[e];s&&N(s,i,o,p,void 0===o)};e?o(e):Object.keys(a).forEach(o)}},C=function(){Object.keys(d.fields).forEach((function(e){d.fields[e].touched=!0}))},z=function(){var e=d.fields,i=d.formState,r=d.lastFormState,n=t({},e),a=Object.keys(n),o=!1,s=a.reduce((function(e,t){return!n[t].isEqual(l(i.values,t),l(i.initialValues||{},t))&&(o=!0,e[t]=!0),e}),{}),u=a.reduce((function(e,t){var r=i.lastSubmittedValues||{};return n[t].isEqual(l(i.values,t),l(r,t))||(e[t]=!0),e}),{});i.pristine=!o,i.dirtySinceLastSubmit=!(!i.lastSubmittedValues||!Object.values(u).some((function(e){return e}))),i.modifiedSinceLastSubmit=!(!i.lastSubmittedValues||!Object.keys(n).some((function(e){return n[e].modifiedSinceLastSubmit}))),i.valid=!(i.error||i.submitError||w(i.errors)||i.submitErrors&&w(i.submitErrors));var f=function(e){var t=e.active,i=e.dirtySinceLastSubmit,r=e.modifiedSinceLastSubmit,n=e.error,a=e.errors,o=e.initialValues,s=e.pristine,u=e.submitting,l=e.submitFailed,d=e.submitSucceeded,f=e.submitError,c=e.submitErrors,v=e.valid,m=e.validating,b=e.values;return{active:t,dirty:!s,dirtySinceLastSubmit:i,modifiedSinceLastSubmit:r,error:n,errors:a,hasSubmitErrors:!!(f||c&&w(c)),hasValidationErrors:!(!n&&!w(a)),invalid:!v,initialValues:o,pristine:s,submitting:u,submitFailed:l,submitSucceeded:d,submitError:f,submitErrors:c,valid:v,validating:m>0,values:b}}(i),c=a.reduce((function(e,t){return e.modified[t]=n[t].modified,e.touched[t]=n[t].touched,e.visited[t]=n[t].visited,e}),{modified:{},touched:{},visited:{}}),v=c.modified,m=c.touched,b=c.visited;return f.dirtyFields=r&&h(r.dirtyFields,s)?r.dirtyFields:s,f.dirtyFieldsSinceLastSubmit=r&&h(r.dirtyFieldsSinceLastSubmit,u)?r.dirtyFieldsSinceLastSubmit:u,f.modified=r&&h(r.modified,v)?r.modified:v,f.touched=r&&h(r.touched,m)?r.touched:m,f.visited=r&&h(r.visited,b)?r.visited:b,r&&h(r,f)?r:f},_=!1,U=!1,B=function e(){if(_)U=!0;else{if(_=!0,!(f||S&&y)){var t=d.lastFormState,i=z();i!==t&&(d.lastFormState=i,N(d.subscribers,i,t,O))}_=!1,U&&(U=!1,e())}},D=function(){return Object.keys(d.fields).forEach((function(e){return d.fields[e].modifiedSinceLastSubmit=!1}))};I(void 0,(function(){B()}));var M={batch:function(e){f++,e(),f--,W(),B()},blur:function(e){var i=d.fields,r=d.formState,n=i[e];n&&(delete r.active,i[e]=t({},n,{active:!1,touched:!0}),u?I(e,(function(){W(),B()})):(W(),B()))},change:function(e,i){var r=d.fields,n=d.formState;if(l(n.values,e)!==i){A(d,e,(function(){return i}));var a=r[e];a&&(r[e]=t({},a,{modified:!0,modifiedSinceLastSubmit:!!n.lastSubmittedValues})),u?(W(),B()):I(e,(function(){W(),B()}))}},get destroyOnUnregister(){return!!i},set destroyOnUnregister(e){i=e},focus:function(e){var t=d.fields[e];t&&!t.active&&(d.formState.active=e,t.active=!0,t.visited=!0,W(),B())},mutators:P,getFieldState:function(e){var t=d.fields[e];return t&&t.lastFieldState},getRegisteredFields:function(){return Object.keys(d.fields)},getState:function(){return z()},initialize:function(e){var i=d.fields,n=d.formState,a=t({},i),o="function"==typeof e?e(n.values):e;r||(n.values=o);var s=r?Object.keys(a).reduce((function(e,t){return a[t].isEqual(l(n.values,t),l(n.initialValues||{},t))||(e[t]=l(n.values,t)),e}),{}):{};n.initialValues=o,n.values=o,Object.keys(s).forEach((function(e){n.values=c(n.values,e,s[e])||{}})),I(void 0,(function(){W(),B()}))},isValidationPaused:function(){return S},pauseValidation:function(e){void 0===e&&(e=!0),S=!0,y=e},registerField:function(e,t,r,n){void 0===r&&(r={}),d.fieldSubscribers[e]||(d.fieldSubscribers[e]={index:0,entries:{}});var a=d.fieldSubscribers[e].index++;d.fieldSubscribers[e].entries[a]={subscriber:V(t),subscription:r,notified:!1};var o=d.fields[e]||{active:!1,afterSubmit:n&&n.afterSubmit,beforeSubmit:n&&n.beforeSubmit,data:n&&n.data||{},isEqual:n&&n.isEqual||k,lastFieldState:void 0,modified:!1,modifiedSinceLastSubmit:!1,name:e,touched:!1,valid:!0,validateFields:n&&n.validateFields,validators:{},validating:!1,visited:!1};o.blur=o.blur||function(){return M.blur(e)},o.change=o.change||function(t){return M.change(e,t)},o.focus=o.focus||function(){return M.focus(e)},d.fields[e]=o;var s=!1,u=n&&n.silent,f=function(){u&&d.fields[e]?W(e):(B(),W())};if(n){s=!(!n.getValidator||!n.getValidator()),n.getValidator&&(d.fields[e].validators[a]=n.getValidator);var v=void 0===l(d.formState.values,e);void 0===n.initialValue||!v&&l(d.formState.values,e)!==l(d.formState.initialValues,e)||(d.formState.initialValues=c(d.formState.initialValues||{},e,n.initialValue),d.formState.values=c(d.formState.values,e,n.initialValue),I(void 0,f)),void 0!==n.defaultValue&&void 0===n.initialValue&&void 0===l(d.formState.initialValues,e)&&v&&(d.formState.values=c(d.formState.values,e,n.defaultValue))}return s?I(void 0,f):f(),function(){var t=!1;d.fields[e]&&(t=!(!d.fields[e].validators[a]||!d.fields[e].validators[a]()),delete d.fields[e].validators[a]);var r=!!d.fieldSubscribers[e];r&&delete d.fieldSubscribers[e].entries[a];var n=r&&!Object.keys(d.fieldSubscribers[e].entries).length;n&&(delete d.fieldSubscribers[e],delete d.fields[e],t&&(d.formState.errors=c(d.formState.errors,e,void 0)||{}),i&&(d.formState.values=c(d.formState.values,e,void 0,!0)||{})),u||(t?I(void 0,(function(){B(),W()})):n&&B())}},reset:function(e){void 0===e&&(e=d.formState.initialValues),d.formState.submitting&&(d.formState.resetWhileSubmitting=!0),d.formState.submitFailed=!1,d.formState.submitSucceeded=!1,delete d.formState.submitError,delete d.formState.submitErrors,delete d.formState.lastSubmittedValues,M.initialize(e||{})},resetFieldState:function(e){d.fields[e]=t({},d.fields[e],{active:!1,lastFieldState:void 0,modified:!1,touched:!1,valid:!0,validating:!1,visited:!1}),I(void 0,(function(){W(),B()}))},restart:function(e){void 0===e&&(e=d.formState.initialValues),M.batch((function(){for(var i in d.fields)M.resetFieldState(i),d.fields[i]=t({},d.fields[i],{active:!1,lastFieldState:void 0,modified:!1,modifiedSinceLastSubmit:!1,touched:!1,valid:!0,validating:!1,visited:!1});M.reset(e)}))},resumeValidation:function(){S=!1,y=!1,g&&I(void 0,(function(){W(),B()})),g=!1},setConfig:function(e,t){switch(e){case"debug":t;break;case"destroyOnUnregister":i=t;break;case"initialValues":M.initialize(t);break;case"keepDirtyOnReinitialize":r=t;break;case"mutators":a=t,t?(Object.keys(P).forEach((function(e){e in t||delete P[e]})),Object.keys(t).forEach((function(e){P[e]=x(e)}))):Object.keys(P).forEach((function(e){delete P[e]}));break;case"onSubmit":o=t;break;case"validate":s=t,I(void 0,(function(){W(),B()}));break;case"validateOnBlur":u=t;break;default:throw new Error("Unrecognised option "+e)}},submit:function(){var e=d.formState;if(!e.submitting){if(delete e.submitErrors,delete e.submitError,e.lastSubmittedValues=t({},e.values),d.formState.error||w(d.formState.errors))return C(),D(),d.formState.submitFailed=!0,B(),void W();var i=Object.keys(F);if(i.length)Promise.all(i.map((function(e){return F[Number(e)]}))).then(M.submit,console.error);else if(!Object.keys(d.fields).some((function(e){return d.fields[e].beforeSubmit&&!1===d.fields[e].beforeSubmit()}))){var r,n=!1,a=function(t){e.submitting=!1;var i=e.resetWhileSubmitting;return i&&(e.resetWhileSubmitting=!1),t&&w(t)?(e.submitFailed=!0,e.submitSucceeded=!1,e.submitErrors=t,e.submitError=t[v],C()):(i||(e.submitFailed=!1,e.submitSucceeded=!0),Object.keys(d.fields).forEach((function(e){return d.fields[e].afterSubmit&&d.fields[e].afterSubmit()}))),B(),W(),n=!0,r&&r(t),t};e.submitting=!0,e.submitFailed=!1,e.submitSucceeded=!1,e.lastSubmittedValues=t({},e.values),D();var s=o(e.values,M,a);if(!n){if(s&&j(s))return B(),W(),s.then(a,(function(e){throw a(),e}));if(o.length>=3)return B(),W(),new Promise((function(e){r=e}));a(s)}}}},subscribe:function(e,t){if(!e)throw new Error("No callback given.");if(!t)throw new Error("No subscription provided. What values do you want to listen to?");var i=V(e),r=d.subscribers,n=r.index++;r.entries[n]={subscriber:i,subscription:t,notified:!1};var a=z();return L(i,t,a,a,O,!0),function(){delete r.entries[n]}}};return M},e.fieldSubscriptionItems=S,e.formSubscriptionItems=E,e.getIn=l,e.setIn=c,e.version="4.20.10"})); | ||
//# sourceMappingURL=final-form.umd.min.js.map |
{ | ||
"name": "final-form", | ||
"version": "4.20.9", | ||
"version": "4.20.10", | ||
"description": "🏁 Framework agnostic, high performance, subscription-based form state management", | ||
@@ -39,2 +39,5 @@ "main": "dist/final-form.cjs.js", | ||
"@babel/preset-flow": "^7.14.5", | ||
"@rollup/plugin-babel": "^6.0.3", | ||
"@rollup/plugin-commonjs": "^25.0.3", | ||
"@rollup/plugin-terser": "^0.4.3", | ||
"@types/node": "^16.10.1", | ||
@@ -51,3 +54,2 @@ "@typescript-eslint/eslint-plugin": "^4.31.2", | ||
"eslint-plugin-babel": "^5.3.1", | ||
"eslint-plugin-flowtype": "^6.1.0", | ||
"eslint-plugin-import": "^2.24.2", | ||
@@ -57,3 +59,2 @@ "eslint-plugin-jsx-a11y": "^6.4.1", | ||
"eslint-plugin-react-hooks": "^4.2.0", | ||
"flow-bin": "^0.160.2", | ||
"husky": "^7.0.2", | ||
@@ -66,9 +67,6 @@ "jest": "^27.2.1", | ||
"prettier-eslint-cli": "^5.0.1", | ||
"rollup": "^2.57.0", | ||
"rollup-plugin-babel": "^4.4.0", | ||
"rollup-plugin-commonjs": "^10.1.0", | ||
"rollup": "^3.28.0", | ||
"rollup-plugin-flow": "^1.1.1", | ||
"rollup-plugin-json": "^4.0.0", | ||
"rollup-plugin-replace": "^2.2.0", | ||
"rollup-plugin-uglify": "^6.0.4", | ||
"tslint": "^6.1.3", | ||
@@ -92,3 +90,3 @@ "typescript": "^4.4.3" | ||
"path": "dist/final-form.umd.min.js", | ||
"maxSize": "5.6kB" | ||
"maxSize": "5.8kB" | ||
}, | ||
@@ -101,5 +99,8 @@ { | ||
"path": "dist/final-form.cjs.js", | ||
"maxSize": "10.5kB" | ||
"maxSize": "10.6kB" | ||
} | ||
], | ||
"engines": { | ||
"node": ">=8" | ||
}, | ||
"dependencies": { | ||
@@ -106,0 +107,0 @@ "@babel/runtime": "^7.10.0" |
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
37
4289
193752