UNPKG

ngrx-forms

Version:

Proper integration of forms in Angular 4 applications using ngrx

1,154 lines (1,127 loc) 202 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common'), require('@angular/forms'), require('@ngrx/store')) : typeof define === 'function' && define.amd ? define('ngrx-forms', ['exports', '@angular/core', '@angular/common', '@angular/forms', '@ngrx/store'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["ngrx-forms"] = {}, global.ng.core, global.ng.common, global.ng.forms, global.i1)); })(this, (function (exports, i0, common, forms, i1) { 'use strict'; function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n["default"] = e; return Object.freeze(n); } var i0__namespace = /*#__PURE__*/_interopNamespace(i0); var i1__namespace = /*#__PURE__*/_interopNamespace(i1); // NOTE: the explicit type declaration for the `TYPE` properties is required // for the output declarations to properly use the literal string type instead // of just `string` var SetValueAction = /** @class */ (function () { function SetValueAction(controlId, value) { this.controlId = controlId; this.value = value; this.type = SetValueAction.TYPE; } return SetValueAction; }()); SetValueAction.TYPE = 'ngrx/forms/SET_VALUE'; var SetErrorsAction = /** @class */ (function () { function SetErrorsAction(controlId, errors) { this.controlId = controlId; this.errors = errors; this.type = SetErrorsAction.TYPE; } return SetErrorsAction; }()); SetErrorsAction.TYPE = 'ngrx/forms/SET_ERRORS'; var SetAsyncErrorAction = /** @class */ (function () { function SetAsyncErrorAction(controlId, name, value) { this.controlId = controlId; this.name = name; this.value = value; this.type = SetAsyncErrorAction.TYPE; } return SetAsyncErrorAction; }()); SetAsyncErrorAction.TYPE = 'ngrx/forms/SET_ASYNC_ERROR'; var ClearAsyncErrorAction = /** @class */ (function () { function ClearAsyncErrorAction(controlId, name) { this.controlId = controlId; this.name = name; this.type = ClearAsyncErrorAction.TYPE; } return ClearAsyncErrorAction; }()); ClearAsyncErrorAction.TYPE = 'ngrx/forms/CLEAR_ASYNC_ERROR'; var StartAsyncValidationAction = /** @class */ (function () { function StartAsyncValidationAction(controlId, name) { this.controlId = controlId; this.name = name; this.type = StartAsyncValidationAction.TYPE; } return StartAsyncValidationAction; }()); StartAsyncValidationAction.TYPE = 'ngrx/forms/START_ASYNC_VALIDATION'; var MarkAsDirtyAction = /** @class */ (function () { function MarkAsDirtyAction(controlId) { this.controlId = controlId; this.type = MarkAsDirtyAction.TYPE; } return MarkAsDirtyAction; }()); MarkAsDirtyAction.TYPE = 'ngrx/forms/MARK_AS_DIRTY'; var MarkAsPristineAction = /** @class */ (function () { function MarkAsPristineAction(controlId) { this.controlId = controlId; this.type = MarkAsPristineAction.TYPE; } return MarkAsPristineAction; }()); MarkAsPristineAction.TYPE = 'ngrx/forms/MARK_AS_PRISTINE'; var EnableAction = /** @class */ (function () { function EnableAction(controlId) { this.controlId = controlId; this.type = EnableAction.TYPE; } return EnableAction; }()); EnableAction.TYPE = 'ngrx/forms/ENABLE'; var DisableAction = /** @class */ (function () { function DisableAction(controlId) { this.controlId = controlId; this.type = DisableAction.TYPE; } return DisableAction; }()); DisableAction.TYPE = 'ngrx/forms/DISABLE'; var MarkAsTouchedAction = /** @class */ (function () { function MarkAsTouchedAction(controlId) { this.controlId = controlId; this.type = MarkAsTouchedAction.TYPE; } return MarkAsTouchedAction; }()); MarkAsTouchedAction.TYPE = 'ngrx/forms/MARK_AS_TOUCHED'; var MarkAsUntouchedAction = /** @class */ (function () { function MarkAsUntouchedAction(controlId) { this.controlId = controlId; this.type = MarkAsUntouchedAction.TYPE; } return MarkAsUntouchedAction; }()); MarkAsUntouchedAction.TYPE = 'ngrx/forms/MARK_AS_UNTOUCHED'; var FocusAction = /** @class */ (function () { function FocusAction(controlId) { this.controlId = controlId; this.type = FocusAction.TYPE; } return FocusAction; }()); FocusAction.TYPE = 'ngrx/forms/FOCUS'; var UnfocusAction = /** @class */ (function () { function UnfocusAction(controlId) { this.controlId = controlId; this.type = UnfocusAction.TYPE; } return UnfocusAction; }()); UnfocusAction.TYPE = 'ngrx/forms/UNFOCUS'; var MarkAsSubmittedAction = /** @class */ (function () { function MarkAsSubmittedAction(controlId) { this.controlId = controlId; this.type = MarkAsSubmittedAction.TYPE; } return MarkAsSubmittedAction; }()); MarkAsSubmittedAction.TYPE = 'ngrx/forms/MARK_AS_SUBMITTED'; var MarkAsUnsubmittedAction = /** @class */ (function () { function MarkAsUnsubmittedAction(controlId) { this.controlId = controlId; this.type = MarkAsUnsubmittedAction.TYPE; } return MarkAsUnsubmittedAction; }()); MarkAsUnsubmittedAction.TYPE = 'ngrx/forms/MARK_AS_UNSUBMITTED'; var AddArrayControlAction = /** @class */ (function () { function AddArrayControlAction(controlId, value, index) { this.controlId = controlId; this.value = value; this.index = index; this.type = AddArrayControlAction.TYPE; } return AddArrayControlAction; }()); AddArrayControlAction.TYPE = 'ngrx/forms/ADD_ARRAY_CONTROL'; var AddGroupControlAction = /** @class */ (function () { function AddGroupControlAction(controlId, name, value) { this.controlId = controlId; this.name = name; this.value = value; this.type = AddGroupControlAction.TYPE; } return AddGroupControlAction; }()); AddGroupControlAction.TYPE = 'ngrx/forms/ADD_GROUP_CONTROL'; var RemoveArrayControlAction = /** @class */ (function () { function RemoveArrayControlAction(controlId, index) { this.controlId = controlId; this.index = index; this.type = RemoveArrayControlAction.TYPE; } return RemoveArrayControlAction; }()); RemoveArrayControlAction.TYPE = 'ngrx/forms/REMOVE_ARRAY_CONTROL'; var SwapArrayControlAction = /** @class */ (function () { function SwapArrayControlAction(controlId, fromIndex, toIndex) { this.controlId = controlId; this.fromIndex = fromIndex; this.toIndex = toIndex; this.type = SwapArrayControlAction.TYPE; } return SwapArrayControlAction; }()); SwapArrayControlAction.TYPE = 'ngrx/forms/SWAP_ARRAY_CONTROL'; var MoveArrayControlAction = /** @class */ (function () { function MoveArrayControlAction(controlId, fromIndex, toIndex) { this.controlId = controlId; this.fromIndex = fromIndex; this.toIndex = toIndex; this.type = MoveArrayControlAction.TYPE; } return MoveArrayControlAction; }()); MoveArrayControlAction.TYPE = 'ngrx/forms/MOVE_ARRAY_CONTROL'; var RemoveGroupControlAction = /** @class */ (function () { function RemoveGroupControlAction(controlId, name) { this.controlId = controlId; this.name = name; this.type = RemoveGroupControlAction.TYPE; } return RemoveGroupControlAction; }()); RemoveGroupControlAction.TYPE = 'ngrx/forms/REMOVE_CONTROL'; var SetUserDefinedPropertyAction = /** @class */ (function () { function SetUserDefinedPropertyAction(controlId, name, value) { this.controlId = controlId; this.name = name; this.value = value; this.type = SetUserDefinedPropertyAction.TYPE; } return SetUserDefinedPropertyAction; }()); SetUserDefinedPropertyAction.TYPE = 'ngrx/forms/SET_USER_DEFINED_PROPERTY'; var ResetAction = /** @class */ (function () { function ResetAction(controlId) { this.controlId = controlId; this.type = ResetAction.TYPE; } return ResetAction; }()); ResetAction.TYPE = 'ngrx/forms/RESET'; function isNgrxFormsAction(action) { return !!action.type && action.type.startsWith('ngrx/forms/'); } var ALL_NGRX_FORMS_ACTION_TYPES = [ SetValueAction.TYPE, SetErrorsAction.TYPE, SetAsyncErrorAction.TYPE, ClearAsyncErrorAction.TYPE, StartAsyncValidationAction.TYPE, MarkAsDirtyAction.TYPE, MarkAsPristineAction.TYPE, EnableAction.TYPE, DisableAction.TYPE, MarkAsTouchedAction.TYPE, MarkAsUntouchedAction.TYPE, FocusAction.TYPE, UnfocusAction.TYPE, MarkAsSubmittedAction.TYPE, MarkAsUnsubmittedAction.TYPE, AddGroupControlAction.TYPE, RemoveGroupControlAction.TYPE, AddArrayControlAction.TYPE, RemoveArrayControlAction.TYPE, SetUserDefinedPropertyAction.TYPE, ResetAction.TYPE, SwapArrayControlAction.TYPE, MoveArrayControlAction.TYPE, ]; function isBoxed(value) { return !!value && value.__boxed === ''; } function box(value) { return { __boxed: '', value: value, }; } function unbox(value) { if (['string', 'boolean', 'number', 'undefined'].indexOf(typeof value) >= 0 || value === null || value === undefined) { return value; } if (isBoxed(value)) { return value.value; } if (Array.isArray(value)) { return value.map(unbox); } return Object.keys(value).reduce(function (a, k) { var _a; return Object.assign(a, (_a = {}, _a[k] = unbox(value[k]), _a)); }, {}); } /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function () { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); }; } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function () { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var __createBinding = Object.create ? (function (o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } }); }) : (function (o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }); function __exportStar(m, o) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } /** @deprecated */ function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } /** @deprecated */ function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; } ; var __setModuleDefault = Object.create ? (function (o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function (o, v) { o["default"] = v; }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } function __classPrivateFieldSet(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; } function isEmpty(obj) { return Object.keys(obj).length === 0; } var defaultOptions = { treatUndefinedAndMissingKeyAsSame: false, }; function deepEquals(_1, _2, options) { if (options === void 0) { options = {}; } var treatUndefinedAndMissingKeyAsSame = Object.assign({}, defaultOptions, options).treatUndefinedAndMissingKeyAsSame; var leftChain = []; var rightChain = []; function compare2Objects(x, y) { var p; // remember that NaN === NaN returns false // and isNaN(undefined) returns true if (isNaN(x) && isNaN(y) && typeof x === 'number' && typeof y === 'number') { return true; } // Compare primitives and functions. // Check if both arguments link to the same object. // Especially useful on the step where we compare prototypes if (x === y) { return true; } // Works in case when functions are created in constructor. // Comparing dates is a common scenario. Another built-ins? // We can even handle functions passed across iframes if ((typeof x === 'function' && typeof y === 'function') || (x instanceof Date && y instanceof Date) || (x instanceof RegExp && y instanceof RegExp) || (x instanceof String && y instanceof String) || (x instanceof Number && y instanceof Number)) { return x.toString() === y.toString(); } // At last checking prototypes as good as we can if (!(x instanceof Object && y instanceof Object)) { return false; } if (x.isPrototypeOf(y) || y.isPrototypeOf(x)) { return false; } if (x.constructor !== y.constructor) { return false; } // Check for infinitive linking loops if (leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1) { return false; } // Quick checking of one object being a subset of another. for (p in y) { if (treatUndefinedAndMissingKeyAsSame && y.hasOwnProperty(p) && !x.hasOwnProperty(p) && y[p] === undefined) { continue; } if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) { return false; } else if (typeof y[p] !== typeof x[p]) { return false; } } // tslint:disable:forin for (p in x) { if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) { if (!treatUndefinedAndMissingKeyAsSame || !x.hasOwnProperty(p) || y.hasOwnProperty(p) || x[p] !== undefined) { return false; } } switch (typeof (x[p])) { case 'object': case 'function': leftChain.push(x); rightChain.push(y); if (!compare2Objects(x[p], y[p])) { return false; } leftChain.pop(); rightChain.pop(); break; default: if (x[p] !== y[p]) { return false; } break; } } return true; } if (arguments.length <= 1) { throw new Error('Need two or more arguments to compare'); } return compare2Objects(_1, _2); } /** * This function determines if a value is a form state. */ function isFormState(state) { return !!state && state.hasOwnProperty('id') && state.hasOwnProperty('value') && state.hasOwnProperty('errors'); } /** * This function determines if a value is an array state. */ function isArrayState(state) { return isFormState(state) && state.hasOwnProperty('controls') && Array.isArray(state.controls); } /** * This function determines if a value is a group state. */ function isGroupState(state) { return isFormState(state) && state.hasOwnProperty('controls') && !Array.isArray(state.controls) && typeof state.controls !== 'function'; } function createChildState(id, childValue) { if (isBoxed(childValue)) { return createFormControlState(id, childValue); } if (childValue !== null && Array.isArray(childValue)) { return createFormArrayState(id, childValue); } if (childValue !== null && typeof childValue === 'object') { return createFormGroupState(id, childValue); } return createFormControlState(id, childValue); } function verifyFormControlValueIsValid(value) { if (value === null || ['string', 'number', 'boolean', 'undefined'].indexOf(typeof value) >= 0) { return value; } if (!isBoxed(value)) { var errorMsg = 'Form control states only support undefined, null, string, number, and boolean values as well as boxed values'; throw new Error(errorMsg + "; got " + JSON.stringify(value) + " of type " + typeof value); // `; } if (value.value === null || ['string', 'number', 'boolean', 'undefined'].indexOf(typeof value.value) >= 0) { return value; } var serialized = JSON.stringify(value); var deserialized = JSON.parse(serialized); if (deepEquals(value, deserialized, { treatUndefinedAndMissingKeyAsSame: true })) { return value; } throw new Error("A form control value must be serializable (i.e. value === JSON.parse(JSON.stringify(value))), got: " + JSON.stringify(value)); } /** * This function creates a form control state with an ID and a value. */ function createFormControlState(id, value) { return { id: id, value: verifyFormControlValueIsValid(value), errors: {}, pendingValidations: [], isValidationPending: false, isValid: true, isInvalid: false, isEnabled: true, isDisabled: false, isDirty: false, isPristine: true, isTouched: false, isUntouched: true, isSubmitted: false, isUnsubmitted: true, isFocused: false, isUnfocused: true, userDefinedProperties: {}, }; } function getFormGroupValue(controls, originalValue) { var hasChanged = Object.keys(originalValue).length !== Object.keys(controls).length; var newValue = Object.keys(controls).reduce(function (res, key) { var control = controls[key]; hasChanged = hasChanged || originalValue[key] !== control.value; res[key] = control.value; return res; }, {}); return hasChanged ? newValue : originalValue; } function getFormGroupErrors(controls, originalErrors) { var hasChanged = false; var groupErrors = Object.keys(originalErrors) .filter(function (key) { return !key.startsWith('_'); }) .reduce(function (res, key) { var _a; return Object.assign(res, (_a = {}, _a[key] = originalErrors[key], _a)); }, {}); var newErrors = Object.keys(controls).reduce(function (res, key) { var _a; var control = controls[key]; var controlErrors = control.errors; if (!isEmpty(controlErrors)) { hasChanged = hasChanged || originalErrors["_" + key] !== controlErrors; Object.assign(res, (_a = {}, _a["_" + key] = control.errors, _a)); } else { hasChanged = hasChanged || originalErrors.hasOwnProperty("_" + key); } return res; }, groupErrors); hasChanged = hasChanged || Object.keys(originalErrors).length !== Object.keys(newErrors).length; return hasChanged ? newErrors : originalErrors; } function computeGroupState(id, controls, value, errors, pendingValidations, userDefinedProperties, flags) { value = getFormGroupValue(controls, value); errors = getFormGroupErrors(controls, errors); var isValid = isEmpty(errors); var isDirty = flags.wasOrShouldBeDirty || Object.keys(controls).some(function (key) { return controls[key].isDirty; }); var isEnabled = flags.wasOrShouldBeEnabled || Object.keys(controls).some(function (key) { return controls[key].isEnabled; }); var isTouched = flags.wasOrShouldBeTouched || Object.keys(controls).some(function (key) { return controls[key].isTouched; }); var isSubmitted = flags.wasOrShouldBeSubmitted || Object.keys(controls).some(function (key) { return controls[key].isSubmitted; }); var isValidationPending = pendingValidations.length > 0 || Object.keys(controls).some(function (key) { return controls[key].isValidationPending; }); return { id: id, value: value, errors: errors, pendingValidations: pendingValidations, isValidationPending: isValidationPending, isValid: isValid, isInvalid: !isValid, isEnabled: isEnabled, isDisabled: !isEnabled, isDirty: isDirty, isPristine: !isDirty, isTouched: isTouched, isUntouched: !isTouched, isSubmitted: isSubmitted, isUnsubmitted: !isSubmitted, userDefinedProperties: userDefinedProperties, controls: controls, }; } /** * This function creates a form group state with an ID and a value. * From the value the shape of the group state is inferred, i.e. * object properties are inferred as form groups, array properties * are inferred as form arrays, and primitive properties are inferred * as form controls. */ function createFormGroupState(id, initialValue) { var controls = Object.keys(initialValue) .map(function (key) { return [key, createChildState(id + "." + key, initialValue[key])]; }) .reduce(function (res, _a) { var _b; var _c = __read(_a, 2), controlId = _c[0], state = _c[1]; return Object.assign(res, (_b = {}, _b[controlId] = state, _b)); }, {}); return computeGroupState(id, controls, initialValue, {}, [], {}, { wasOrShouldBeEnabled: true }); } function getFormArrayValue(controls, originalValue) { var hasChanged = Object.keys(originalValue).length !== Object.keys(controls).length; var newValue = controls.map(function (state, i) { hasChanged = hasChanged || originalValue[i] !== state.value; return state.value; }); return hasChanged ? newValue : originalValue; } function getFormArrayErrors(controls, originalErrors) { var hasChanged = false; var groupErrors = Object.keys(originalErrors) .filter(function (key) { return !key.startsWith('_'); }) .reduce(function (res, key) { var _a; return Object.assign(res, (_a = {}, _a[key] = originalErrors[key], _a)); }, {}); var newErrors = controls.reduce(function (res, state, i) { var _a; var controlErrors = state.errors; if (!isEmpty(controlErrors)) { hasChanged = hasChanged || originalErrors["_" + i] !== controlErrors; Object.assign(res, (_a = {}, _a["_" + i] = controlErrors, _a)); } else { hasChanged = hasChanged || originalErrors.hasOwnProperty("_" + i); } return res; }, groupErrors); hasChanged = hasChanged || Object.keys(originalErrors).length !== Object.keys(newErrors).length; return hasChanged ? newErrors : originalErrors; } function computeArrayState(id, inferredControls, value, errors, pendingValidations, userDefinedProperties, flags) { var controls = inferredControls; value = getFormArrayValue(controls, value); errors = getFormArrayErrors(controls, errors); var isValid = isEmpty(errors); var isDirty = flags.wasOrShouldBeDirty || controls.some(function (state) { return state.isDirty; }); var isEnabled = flags.wasOrShouldBeEnabled || controls.some(function (state) { return state.isEnabled; }); var isTouched = flags.wasOrShouldBeTouched || controls.some(function (state) { return state.isTouched; }); var isSubmitted = flags.wasOrShouldBeSubmitted || controls.some(function (state) { return state.isSubmitted; }); var isValidationPending = pendingValidations.length > 0 || controls.some(function (state) { return state.isValidationPending; }); return { id: id, value: value, errors: errors, pendingValidations: pendingValidations, isValidationPending: isValidationPending, isValid: isValid, isInvalid: !isValid, isEnabled: isEnabled, isDisabled: !isEnabled, isDirty: isDirty, isPristine: !isDirty, isTouched: isTouched, isUntouched: !isTouched, isSubmitted: isSubmitted, isUnsubmitted: !isSubmitted, userDefinedProperties: userDefinedProperties, controls: inferredControls, }; } /** * This function creates a form array state with an ID and a value. * From the value the shape of the array state is inferred, i.e. * object values are inferred as form groups, array values * are inferred as form arrays, and primitive values are inferred * as form controls. */ function createFormArrayState(id, initialValue) { var controls = initialValue .map(function (value, i) { return createChildState(id + "." + i, value); }); return computeArrayState(id, controls, initialValue, {}, [], {}, { wasOrShouldBeEnabled: true }); } function clearAsyncErrorReducer$2(state, action) { if (action.type !== ClearAsyncErrorAction.TYPE) { return state; } var name = "$" + action.name; var errors = state.errors; if (errors.hasOwnProperty(name)) { errors = Object.assign({}, state.errors); delete errors[name]; } var pendingValidations = state.pendingValidations.filter(function (v) { return v !== action.name; }); var isValid = isEmpty(errors); if (errors === state.errors && isValid === state.isValid && pendingValidations.length === state.pendingValidations.length) { return state; } return Object.assign(Object.assign({}, state), { isValid: isValid, isInvalid: !isValid, errors: errors, pendingValidations: pendingValidations, isValidationPending: pendingValidations.length > 0 }); } function disableReducer$2(state, action) { if (action.type !== DisableAction.TYPE) { return state; } if (state.isDisabled) { return state; } return Object.assign(Object.assign({}, state), { isEnabled: false, isDisabled: true, isValid: true, isInvalid: false, errors: {}, pendingValidations: [], isValidationPending: false }); } function enableReducer$2(state, action) { if (action.type !== EnableAction.TYPE) { return state; } if (state.isEnabled) { return state; } return Object.assign(Object.assign({}, state), { isEnabled: true, isDisabled: false }); } function focusReducer(state, action) { if (action.type !== FocusAction.TYPE) { return state; } if (state.isFocused) { return state; } return Object.assign(Object.assign({}, state), { isFocused: true, isUnfocused: false }); } function markAsDirtyReducer$2(state, action) { if (action.type !== MarkAsDirtyAction.TYPE) { return state; } if (state.isDirty) { return state; } return Object.assign(Object.assign({}, state), { isDirty: true, isPristine: false }); } function markAsPristineReducer$2(state, action) { if (action.type !== MarkAsPristineAction.TYPE) { return state; } if (state.isPristine) { return state; } return Object.assign(Object.assign({}, state), { isDirty: false, isPristine: true }); } function markAsSubmittedReducer$2(state, action) { if (action.type !== MarkAsSubmittedAction.TYPE) { return state; } if (state.isSubmitted) { return state; } return Object.assign(Object.assign({}, state), { isSubmitted: true, isUnsubmitted: false }); } function markAsTouchedReducer$2(state, action) { if (action.type !== MarkAsTouchedAction.TYPE) { return state; } if (state.isTouched) { return state; } return Object.assign(Object.assign({}, state), { isTouched: true, isUntouched: false }); } function markAsUnsubmittedReducer$2(state, action) { if (action.type !== MarkAsUnsubmittedAction.TYPE) { return state; } if (state.isUnsubmitted) { return state; } return Object.assign(Object.assign({}, state), { isSubmitted: false, isUnsubmitted: true }); } function markAsUntouchedReducer$2(state, action) { if (action.type !== MarkAsUntouchedAction.TYPE) { return state; } if (state.isUntouched) { return state; } return Object.assign(Object.assign({}, state), { isTouched: false, isUntouched: true }); } function resetReducer$2(state, action) { if (action.type !== ResetAction.TYPE) { return state; } if (state.isPristine && state.isUntouched && state.isUnsubmitted) { return state; } return Object.assign(Object.assign({}, state), { isDirty: false, isPristine: true, isTouched: false, isUntouched: true, isSubmitted: false, isUnsubmitted: true }); } function setAsyncErrorReducer$2(state, action) { var _a; if (action.type !== SetAsyncErrorAction.TYPE) { return state; } if (state.isDisabled) { return state; } var name = "$" + action.name; var value = action.value; if (deepEquals(state.errors[name], action.value)) { value = state.errors[name]; } var errors = Object.assign(Object.assign({}, state.errors), (_a = {}, _a[name] = value, _a)); var pendingValidations = state.pendingValidations.filter(function (v) { return v !== action.name; }); return Object.assign(Object.assign({}, state), { isValid: false, isInvalid: true, errors: errors, pendingValidations: pendingValidations, isValidationPending: pendingValidations.length > 0 }); } function setErrorsReducer$2(state, action) { if (action.type !== SetErrorsAction.TYPE) { return state; } if (state.isDisabled) { return state; } if (state.errors === action.errors) { return state; } if (deepEquals(state.errors, action.errors)) { return state; } if (!action.errors || typeof action.errors !== 'object' || Array.isArray(action.errors)) { throw new Error("Control errors must be an object; got " + action.errors); // `; } if (Object.keys(action.errors).some(function (key) { return key.startsWith('$'); })) { throw new Error("Control errors must not use $ as a prefix; got " + JSON.stringify(action.errors)); // `; } var asyncErrors = Object.keys(state.errors) .filter(function (key) { return key.startsWith('$'); }) .reduce(function (res, key) { var _a; return Object.assign(res, (_a = {}, _a[key] = state.errors[key], _a)); }, {}); var newErrors = isEmpty(asyncErrors) ? action.errors : Object.assign(asyncErrors, action.errors); var isValid = isEmpty(newErrors); return Object.assign(Object.assign({}, state), { isValid: isValid, isInvalid: !isValid, errors: newErrors }); } function setUserDefinedPropertyReducer$2(state, action) { var _a; if (action.type !== SetUserDefinedPropertyAction.TYPE) { return state; } if (state.userDefinedProperties[action.name] === action.value) { return state; } return Object.assign(Object.assign({}, state), { userDefinedProperties: Object.assign(Object.assign({}, state.userDefinedProperties), (_a = {}, _a[action.name] = action.value, _a)) }); } function setValueReducer$2(state, action) { if (action.type !== SetValueAction.TYPE) { return state; } if (state.value === action.value) { return state; } return Object.assign(Object.assign({}, state), { value: verifyFormControlValueIsValid(action.value) }); } function startAsyncValidationReducer$2(state, action) { if (action.type !== StartAsyncValidationAction.TYPE) { return state; } if (state.pendingValidations.indexOf(action.name) >= 0) { return state; } return Object.assign(Object.assign({}, state), { pendingValidations: __spreadArray(__spreadArray([], __read(state.pendingValidations)), [action.name]), isValidationPending: true }); } function unfocusReducer(state, action) { if (action.type !== UnfocusAction.TYPE) { return state; } if (state.isUnfocused) { return state; } return Object.assign(Object.assign({}, state), { isFocused: false, isUnfocused: true }); } function formControlReducerInternal(state, action) { if (isGroupState(state) || isArrayState(state)) { throw new Error('The state must be a control state'); } if (action.controlId !== state.id) { return state; } state = setValueReducer$2(state, action); state = setErrorsReducer$2(state, action); state = startAsyncValidationReducer$2(state, action); state = setAsyncErrorReducer$2(state, action); state = clearAsyncErrorReducer$2(state, action); state = enableReducer$2(state, action); state = disableReducer$2(state, action); state = focusReducer(state, action); state = unfocusReducer(state, action); state = markAsDirtyReducer$2(state, action); state = markAsPristineReducer$2(state, action); state = markAsTouchedReducer$2(state, action); state = markAsUntouchedReducer$2(state, action); st