UNPKG

@zensen/form-service

Version:
1,016 lines (1,007 loc) 37.3 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.FormService = factory()); })(this, (function () { 'use strict'; function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var n = 0, F = function () {}; return { s: F, n: function () { return n >= r.length ? { done: !0 } : { done: !1, value: r[n++] }; }, e: function (r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function () { t = t.call(r); }, n: function () { var r = t.next(); return a = r.done, r; }, e: function (r) { u = !0, o = r; }, f: function () { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function () { return !!t; })(); } function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function (t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } function printValue(v) { return _typeof(v) === 'object' ? JSON.stringify(v, '', 2) : v; } var ValidationError = /*#__PURE__*/function (_Error) { function ValidationError(message) { _classCallCheck(this, ValidationError); return _callSuper(this, ValidationError, [message]); } _inherits(ValidationError, _Error); return _createClass(ValidationError); }(/*#__PURE__*/_wrapNativeSuper(Error)); var VerificationError = /*#__PURE__*/function (_Error2) { function VerificationError(message) { var _this; _classCallCheck(this, VerificationError); _this = _callSuper(this, VerificationError, [message]); _this.name = 'VerificationError'; return _this; } _inherits(VerificationError, _Error2); return _createClass(VerificationError); }(/*#__PURE__*/_wrapNativeSuper(Error)); var PristineError = /*#__PURE__*/function (_Error3) { function PristineError(keyPath) { var _this2; _classCallCheck(this, PristineError); _this2 = _callSuper(this, PristineError, ["Selector (".concat(keyPath.join('.'), ") cannot have pristine state")]); _this2.name = 'PristineError'; return _this2; } _inherits(PristineError, _Error3); return _createClass(PristineError); }(/*#__PURE__*/_wrapNativeSuper(Error)); var MutationError = /*#__PURE__*/function (_Error4) { function MutationError(keyPath, oldValue, newValue) { var _this3; _classCallCheck(this, MutationError); _this3 = _callSuper(this, MutationError, ["Reshaping on mutation not allowed at path: ".concat(keyPath.join('.'), "\nOld Value: ").concat(printValue(oldValue), "\nNew Value: ").concat(printValue(newValue))]); _this3.name = 'MutationError'; return _this3; } _inherits(MutationError, _Error4); return _createClass(MutationError); }(/*#__PURE__*/_wrapNativeSuper(Error)); var PathError = /*#__PURE__*/function (_Error5) { function PathError(keyPath) { var _this4; _classCallCheck(this, PathError); _this4 = _callSuper(this, PathError, ["No key found in state for path: ".concat(keyPath.join('.'))]); _this4.name = 'PathError'; return _this4; } _inherits(PathError, _Error5); return _createClass(PathError); }(/*#__PURE__*/_wrapNativeSuper(Error)); function moveItem(arr, fromIndex, toIndex) { var target = arr[fromIndex]; var result = _toConsumableArray(arr); result.splice(fromIndex, 1); result.splice(toIndex, 0, target); return result; } function swap(arr, index1, index2) { var result = _toConsumableArray(arr); result.splice(index1, 1); result.splice(index1, 0, arr[index2]); result.splice(index2, 1); result.splice(index2, 0, arr[index1]); return result; } function traverse(obj, onKey) { var includeRoot = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var path = ['']; var _fn = function fn(target) { Object.entries(target).forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), k = _ref2[0], v = _ref2[1]; path[path.length - 1] = k; var dateType = v instanceof Date; var clip = onKey([].concat(path), v) === false; var updatedVal = getValueByPath(obj, path); var nonNullObj = updatedVal !== null && _typeof(updatedVal) === 'object'; if (!clip && !dateType && nonNullObj) { path.push(''); _fn(updatedVal); path.pop(); } }); }; if (includeRoot) { onKey([], obj); } _fn(obj); } function map(obj, onKey) { var result = Array.isArray(obj) ? [] : {}; traverse(obj, function (keyPath, value) { var dateType = value instanceof Date; if (!dateType && value !== null && _typeof(value) === 'object') { setValueByPath(result, keyPath, Array.isArray(value) ? [] : {}); } else { setValueByPath(result, keyPath, onKey(keyPath, value)); } }); return result; } /* Comes from the fast-deep-equal package. Copied and pasted to try to solve ESM rules... */ function deepEqual(a, b) { if (a === b) { return true; } if (a && b && _typeof(a) == 'object' && _typeof(b) == 'object') { if (a.constructor !== b.constructor) { return false; } var length, i, keys; if (Array.isArray(a)) { length = a.length; if (length != b.length) { return false; } for (i = length; i-- !== 0;) { if (!deepEqual(a[i], b[i])) { return false; } } return true; } if (a instanceof Map && b instanceof Map) { if (a.size !== b.size) { return false; } var _iterator = _createForOfIteratorHelper(a.entries()), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { i = _step.value; if (!b.has(i[0])) { return false; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } var _iterator2 = _createForOfIteratorHelper(a.entries()), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { i = _step2.value; if (!deepEqual(i[1], b.get(i[0]))) { return false; } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return true; } if (a instanceof Set && b instanceof Set) { if (a.size !== b.size) { return false; } var _iterator3 = _createForOfIteratorHelper(a.entries()), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { i = _step3.value; if (!b.has(i[0])) { return false; } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } return true; } if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) { length = a.length; if (length != b.length) { return false; } for (i = length; i-- !== 0;) { if (a[i] !== b[i]) { return false; } } return true; } if (a.constructor === RegExp) { return a.source === b.source && a.flags === b.flags; } if (a.valueOf !== Object.prototype.valueOf) { return a.valueOf() === b.valueOf(); } if (a.toString !== Object.prototype.toString) { return a.toString() === b.toString(); } keys = Object.keys(a); length = keys.length; if (length !== Object.keys(b).length) { return false; } for (i = length; i-- !== 0;) { if (!Object.prototype.hasOwnProperty.call(b, keys[i])) { return false; } } for (i = length; i-- !== 0;) { var key = keys[i]; if (!deepEqual(a[key], b[key])) { return false; } } return true; } return a !== a && b !== b; } function deepCopy(obj) { return map(obj, function (_, value) { return value; }); } function setValueByPath(obj, keyPath, value) { keyPath.reduce(function (subObj, key, index) { if (index === keyPath.length - 1) { subObj[key] = value; } else { return subObj[key]; } }, obj); } function getValueByPath(obj, keyPath) { return keyPath.reduce(function (obj, key) { return typeof obj !== 'undefined' ? obj[key] : undefined; }, obj); } function getKeyPaths(obj) { var result = []; traverse(obj, function (keyPath) { return result.push(keyPath); }); return result; } var errCb = function errCb(selector) { return Array.isArray(selector) || selector.validators; }; var pristineCb = function pristineCb(selector) { return selector.clipPristine; }; function pathToKeyPath(path) { var str = "".concat(path); return str ? str.split('.') : []; } var Service = /*#__PURE__*/function () { function Service(model, selectors, onChange) { _classCallCheck(this, Service); this.__state = {}; this.__errors = {}; this.__pristine = {}; this.__selectors = selectors; this.__onChange = onChange; this.refresh(model); this.__verifySelectors(); } return _createClass(Service, [{ key: "isDirty", get: function get() { return !deepEqual(this.__state, this.__initialState); } }, { key: "isPristine", get: function get() { var _fn = function fn(obj) { return !Object.values(obj).filter(function (v) { return _typeof(v) === 'object' ? _fn(v) : v; }).length; }; return _typeof(this.__pristine) === 'object' ? _fn(this.__pristine) : this.__pristine; } }, { key: "hasErrors", get: function get() { var _fn2 = function fn(obj) { return Object.values(obj).filter(function (v) { return _typeof(v) === 'object' ? _fn2(v) : v; }).length > 0; }; return _typeof(this.__errors) === 'object' ? _fn2(this.__errors) : Boolean(this.__errors); } }, { key: "state", get: function get() { return this.__state; } }, { key: "errors", get: function get() { return this.__errors; } }, { key: "refresh", value: function refresh(model) { this.__state = deepCopy(model); this.__state = this.convert(model, 'format'); this.__initialState = deepCopy(this.__state); this.__refreshErrors(); this.__refreshPristine(); this.__change(); } }, { key: "reset", value: function reset() { this.__state = deepCopy(this.__initialState); this.__refreshErrors(); this.__refreshPristine(); this.__change(); } }, { key: "apply", value: function apply(path, value) { var keyPath = pathToKeyPath(path); if (path && value === this.__state) { throw new MutationError(keyPath, value, this.__state); } var pristine = getValueByPath(this.__pristine, keyPath); if (_typeof(pristine) === 'object') { throw new PristineError(keyPath); } this.__verifyValue(keyPath, value); setValueByPath(this.__state, keyPath, value); this.validateKey(keyPath); setValueByPath(this.__pristine, keyPath, false); this.__spreadSchema('__state', keyPath); this.__modify(keyPath); } }, { key: "addItem", value: function addItem(path) { var index = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1; var keyPath = pathToKeyPath(path); var items = getValueByPath(this.__state, keyPath); var shiftedIndex = index !== -1 ? index : items.length; var selector = this.getSelector(keyPath); var model = this.convert(this.__state, 'unformat'); var rawItem = selector.createItem(keyPath, shiftedIndex, model, this); var item = this.__convertItem(rawItem, keyPath); items.splice(shiftedIndex, 0, item); this.__spreadSchema('__state', [].concat(_toConsumableArray(keyPath), [shiftedIndex])); this.__addItemToSchema('__errors', keyPath, shiftedIndex, item, '', errCb); this.__addItemToSchema('__pristine', keyPath, shiftedIndex, item, true, pristineCb); this.__modifyPristineItem([].concat(_toConsumableArray(keyPath), [shiftedIndex])); this.__modify(keyPath); this.__change(); } }, { key: "removeItem", value: function removeItem(path) { var index = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1; var keyPath = pathToKeyPath(path); var items = getValueByPath(this.__state, keyPath); var shiftedIndex = index === -1 ? items.length - 1 : index; items.splice(shiftedIndex, 1); this.__spreadSchema('__state', [].concat(_toConsumableArray(keyPath), ["".concat(shiftedIndex)])); this.__removeItemFromSchema('__errors', keyPath, shiftedIndex); this.__removeItemFromSchema('__pristine', keyPath, shiftedIndex); this.__modify(keyPath); this.__change(); } }, { key: "moveItem", value: function moveItem(path, fromIndex, toIndex) { var keyPath = pathToKeyPath(path); this.__moveItemInSchema('__state', keyPath, fromIndex, toIndex); this.__moveItemInSchema('__errors', keyPath, fromIndex, toIndex); this.__moveItemInSchema('__pristine', keyPath, fromIndex, toIndex); this.__change(); } }, { key: "swapItems", value: function swapItems(path, index1, index2) { var keyPath = pathToKeyPath(path); this.__swapItemsInSchema('__state', keyPath, index1, index2); this.__swapItemsInSchema('__errors', keyPath, index1, index2); this.__swapItemsInSchema('__pristine', keyPath, index1, index2); setValueByPath(this.__pristine, [].concat(_toConsumableArray(keyPath), [index1]), false); setValueByPath(this.__pristine, [].concat(_toConsumableArray(keyPath), [index2]), false); this.__change(); } }, { key: "convert", value: function convert(data, op) { var _this = this; var rootPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; var rootSelector = this.getSelector([], true); var action = rootSelector && rootSelector[op]; var copy = _typeof(data) === 'object' ? deepCopy(data) : data; var result = action ? action(copy, rootPath, data) : copy; traverse(result, function (keyPath, value) { var fullPath = [].concat(_toConsumableArray(rootPath), _toConsumableArray(keyPath)); var selector = _this.getSelector(fullPath, true); if (selector && selector[op]) { var selVal = selector[op](value, fullPath, data); if (selVal !== null && _typeof(selVal) === 'object') { var _copy = selVal instanceof Date ? new Date(selVal.getTime()) : deepCopy(selVal); setValueByPath(result, keyPath, _copy); } else { setValueByPath(result, keyPath, selVal); } } }); return result; } }, { key: "build", value: function build() { return this.convert(this.__state, 'unformat'); } }, { key: "validate", value: function validate() { var _this2 = this; this.__pristine = map(this.__pristine, function () { return false; }); traverse(this.__state, function (keyPath) { var pristine = getValueByPath(_this2.__pristine, keyPath); if (pristine !== undefined && _typeof(pristine) !== 'object') { _this2.validateKey(keyPath, true); } }); return !this.hasErrors; } }, { key: "validateKey", value: function validateKey(keyPath) { var _this3 = this; var force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var clippedPathIndex = keyPath.findIndex(function (_, index) { var subPath = keyPath.slice(0, index); return _this3.getValidators(subPath); }); var validatorPathLength = clippedPathIndex !== -1 ? clippedPathIndex : keyPath.length; var validatorPath = keyPath.slice(0, validatorPathLength); var validators = this.getValidators(validatorPath); var pristine = getValueByPath(this.__pristine, keyPath); var prevErrors = this.__errors; if (validators && (!pristine || force)) { var selector = this.getSelector(validatorPath); var useRaw = selector.validateRaw || false; if (!selector.validateManually || force) { this.__processValidator(validatorPath, validators, useRaw); } } if (prevErrors !== this.__errors) { this.__change(); } } }, { key: "unsetPristine", value: function unsetPristine(keyPath) { if (typeof getValueByPath(this.__pristine, keyPath) !== 'boolean') { throw new TypeError("Invalid path: ".concat(keyPath.join('.'))); } setValueByPath(this.__pristine, keyPath, false); } }, { key: "getSelectorPath", value: function getSelectorPath(keyPath) { var _this4 = this; var ignoreCheck = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (!ignoreCheck) { var value = getValueByPath(this.__state, keyPath); if (value === undefined) { throw new PathError(keyPath); } } var initialValue = keyPath.length ? ['children'] : []; return keyPath.reduce(function (accum, curr, index) { var parentPath = keyPath.slice(0, index); var parent = getValueByPath(_this4.__state, parentPath); var key = Array.isArray(parent) ? '$' : curr; return index < keyPath.length - 1 ? [].concat(_toConsumableArray(accum), [key, 'children']) : [].concat(_toConsumableArray(accum), [key]); }, initialValue); } }, { key: "getSelector", value: function getSelector(keyPath) { var ignoreCheck = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var selectorPath = this.getSelectorPath(keyPath, ignoreCheck); return getValueByPath(this.__selectors, selectorPath); } }, { key: "getValidators", value: function getValidators(keyPath) { var selector = this.getSelector(keyPath); if (selector) { return Array.isArray(selector) ? selector : selector.validators; } return null; } }, { key: "__change", value: function __change() { this.__onChange(this.isDirty, this.__state, this.__errors, this.__pristine); } }, { key: "__verifySelectors", value: function __verifySelectors() { var _this5 = this; traverse(this.__state, function (keyPath, v) { var validators = _this5.getValidators(keyPath); if (validators) { var parentPath = keyPath.slice(0, keyPath.length - 1); parentPath.forEach(function (_, index) { var ancestorPath = parentPath.slice(0, index + 1); var ancestorValidators = _this5.getValidators(ancestorPath); if (ancestorValidators) { throw new VerificationError("Selector (".concat(keyPath.join('.'), ") has ancestor selector with validators: ").concat(ancestorPath.join('.'))); } }); } if (_typeof(v) === 'object') { var selectors = _this5.getSelector(keyPath); if (selectors && selectors.ignorePristine && !selectors.clipPristine) { var msg = "ignorePristine set object-type key for path: ".concat(keyPath.join('.'), ". Perhaps you meant to use clipPristine?"); throw new VerificationError(msg); } } }); } }, { key: "__verifyValue", value: function __verifyValue(keyPath, value) { var selector = this.getSelector(keyPath, true); var oldValue = getValueByPath(this.__state, keyPath); if (!selector || !selector.unsafe) { if (oldValue === undefined) { throw new TypeError("Invalid path: ".concat(keyPath.join('.'))); } if (oldValue !== null && value !== null) { if (_typeof(oldValue) === 'object') { var oldPathMap = getKeyPaths(oldValue); if (_typeof(value) === 'object') { var pathMap = getKeyPaths(value); if (!deepEqual(oldPathMap, pathMap)) { throw new MutationError(keyPath, oldValue, value); } } else { throw new MutationError(keyPath, oldValue, value); } } } } } }, { key: "__buildSchema", value: function __buildSchema(refSchema, initialValue, fn) { var _this6 = this; var rootPath = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; var result = Array.isArray(refSchema) ? [] : {}; var rootSelector = this.getSelector(rootPath); if (rootSelector && fn(rootSelector)) { return initialValue; } traverse(refSchema, function (keyPath, value) { var dateType = value instanceof Date; if (!dateType && value !== null && _typeof(value) === 'object') { var fullPath = [].concat(_toConsumableArray(rootPath), _toConsumableArray(keyPath)); var selector = _this6.getSelector(fullPath); if (selector && fn(selector)) { setValueByPath(result, keyPath, initialValue); return false; } setValueByPath(result, keyPath, Array.isArray(value) ? [] : {}); } else { setValueByPath(result, keyPath, initialValue); } }, true); return result; } }, { key: "__convertItem", value: function __convertItem(data) { var rootPath = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var item = _typeof(data) === 'object' ? deepCopy(data) : data; var result = this.convert([item], 'format', rootPath); return result[0]; } }, { key: "__spreadSchema", value: function __spreadSchema(schemaKey, keyPath) { var _this7 = this; var ref = this[schemaKey]; this[schemaKey] = Array.isArray(ref) ? _toConsumableArray(ref) : _objectSpread2({}, ref); if (keyPath.length > 1) { keyPath.slice(0, keyPath.length - 1).forEach(function (_, index) { var subPath = keyPath.slice(0, index + 1); var subObj = getValueByPath(_this7[schemaKey], subPath); var result = Array.isArray(subObj) ? _toConsumableArray(subObj) : _objectSpread2({}, subObj); setValueByPath(_this7[schemaKey], subPath, result); }); } } }, { key: "__addItemToSchema", value: function __addItemToSchema(schemaKey, keyPath, index, item, defaultValue, fn) { var value = getValueByPath(this[schemaKey], keyPath); if (_typeof(value) === 'object') { var selector = this.getSelector(keyPath); var clipElement = selector && selector.children && selector.children.$ && fn(selector.children.$); var subObj = !clipElement && _typeof(item) === 'object' ? this.__buildSchema(item, defaultValue, fn, [].concat(_toConsumableArray(keyPath), ["".concat(index)])) : defaultValue; value.splice(index, 0, subObj); this.__spreadSchema(schemaKey, [].concat(_toConsumableArray(keyPath), ["".concat(index)])); } } }, { key: "__removeItemFromSchema", value: function __removeItemFromSchema(schemaKey, keyPath, index) { var item = getValueByPath(this[schemaKey], keyPath); if (Array.isArray(item)) { item.splice(index, 1); this.__spreadSchema(schemaKey, [].concat(_toConsumableArray(keyPath), ["".concat(index)])); } } }, { key: "__moveItemInSchema", value: function __moveItemInSchema(schemaKey, keyPath, fromIndex, toIndex) { var items = getValueByPath(this[schemaKey], keyPath); if (Array.isArray(items)) { var result = moveItem(items, fromIndex, toIndex).map(function (item) { if (_typeof(item) === 'object') { return Array.isArray(item) ? _toConsumableArray(item) : _objectSpread2({}, item); } return item; }); if (keyPath.length) { setValueByPath(this[schemaKey], keyPath, result); } else { this[schemaKey] = result; } this.__spreadSchema(schemaKey, keyPath); } } }, { key: "__swapItemsInSchema", value: function __swapItemsInSchema(schemaKey, keyPath, index1, index2) { var items = getValueByPath(this[schemaKey], keyPath); if (Array.isArray(items)) { var result = swap(items, index1, index2); if (keyPath.length) { setValueByPath(this[schemaKey], keyPath, result); } else { this[schemaKey] = result; } this.__spreadSchema(schemaKey, [].concat(_toConsumableArray(keyPath), [index1])); this.__spreadSchema(schemaKey, [].concat(_toConsumableArray(keyPath), [index2])); } } }, { key: "__modify", value: function __modify(keyPath) { var pristine = getValueByPath(this.__pristine, keyPath); if (pristine && _typeof(pristine) !== 'object') { setValueByPath(this.__pristine, keyPath, false); } this.__change(); } }, { key: "__processValidator", value: function __processValidator(keyPath, validators, useRaw) { var _this8 = this; var data = useRaw ? this.convert(this.__state, 'unformat') : this.__state; var value = getValueByPath(data, keyPath); try { validators.forEach(function (validator) { if (!validator.validate(value, keyPath, data, _this8)) { throw new ValidationError(validator.error); } }); this.__setError(keyPath, ''); } catch (e) { if (e instanceof ValidationError) { this.__setError(keyPath, e.message); } else { throw e; } } } }, { key: "__refreshErrors", value: function __refreshErrors() { this.__errors = this.__buildSchema(this.__state, '', function (selector) { return Array.isArray(selector) || selector.validators; }); } }, { key: "__setError", value: function __setError(keyPath, message) { if (keyPath.length) { setValueByPath(this.__errors, keyPath, message); this.__spreadSchema('__errors', keyPath); } else { this.__errors = message; } } }, { key: "__refreshPristine", value: function __refreshPristine() { var _this9 = this; this.__pristine = this.__buildSchema(this.__state, true, function (selector) { return selector.clipPristine; }); traverse(this.__pristine, function (keyPath) { var selector = _this9.getSelector(keyPath); if (selector && selector.ignorePristine) { setValueByPath(_this9.__pristine, keyPath, false); } }); } }, { key: "__modifyPristineItem", value: function __modifyPristineItem(keyPath) { var _this0 = this; var pristine = getValueByPath(this.__pristine, keyPath); if (_typeof(pristine) === 'object') { traverse(pristine, function (subPath) { var fullPath = [].concat(_toConsumableArray(keyPath), _toConsumableArray(subPath)); var selector = _this0.getSelector(fullPath); if (selector && selector.ignorePristine) { setValueByPath(_this0.__pristine, fullPath, false); } }); } else { var selector = this.getSelector(keyPath); if (selector && selector.ignorePristine) { setValueByPath(this.__pristine, keyPath, false); } } } }]); }(); return Service; })); //# sourceMappingURL=form-service.umd.js.map