diff --git a/dist/formulario.esm.js b/dist/formulario.esm.js index 583a1b6..b7bd3e6 100644 --- a/dist/formulario.esm.js +++ b/dist/formulario.esm.js @@ -193,6 +193,9 @@ function setNested(obj, field, value) { for (let i = 0; i < fieldParts.length; i++) { const fieldPart = fieldParts[i]; const matches = fieldPart.match(/(.+)\[(\d+)\]$/); + if (subProxy === undefined) { + break; + } if (matches) { if (subProxy[matches[1]] === undefined) { subProxy[matches[1]] = []; diff --git a/dist/formulario.min.js b/dist/formulario.min.js index bebd747..5a1d030 100644 --- a/dist/formulario.min.js +++ b/dist/formulario.min.js @@ -31,4 +31,4 @@ var e}function r(t){var r,o;return!1!==e(t)&&("function"==typeof(r=t.constructor * vue-class-component v7.2.3 * (c) 2015-present Evan You * @license MIT - */}function g(t){return(g="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function b(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function O(t){return function(t){if(Array.isArray(t)){for(var e=0,r=new Array(t.length);e0&&N("Component class must inherit Vue or its descendant class when class property is used."),n}var V=["data","beforeCreate","created","beforeMount","mounted","beforeDestroy","destroyed","beforeUpdate","updated","activated","deactivated","render","errorCaptured","serverPrefetch"];function F(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};r.name=r.name||e._componentTag||e.name;var o=e.prototype;Object.getOwnPropertyNames(o).forEach((function(t){if("constructor"!==t)if(V.indexOf(t)>-1)r[t]=o[t];else{var e=Object.getOwnPropertyDescriptor(o,t);void 0!==e.value?"function"==typeof e.value?(r.methods||(r.methods={}))[t]=e.value:(r.mixins||(r.mixins=[])).push({data:function(){return b({},t,e.value)}}):(e.get||e.set)&&((r.computed||(r.computed={}))[t]={get:e.get,set:e.set})}})),(r.mixins||(r.mixins=[])).push({data:function(){return w(this,e)}});var i=e.__decorators__;i&&(i.forEach((function(t){return t(r)})),delete e.__decorators__);var n=Object.getPrototypeOf(e.prototype),a=n instanceof t?n.constructor:t,s=a.extend(r);return M(s,e,a),E()&&x(s,e),s}var R=["cid","super","options","superOptions","extendOptions","sealedOptions","component","directive","filter"],A={prototype:!0,arguments:!0,callee:!0,caller:!0};function M(t,e,r){Object.getOwnPropertyNames(e).forEach((function(o){if(!A[o]){var i=Object.getOwnPropertyDescriptor(t,o);if(!i||i.configurable){var n,a,s=Object.getOwnPropertyDescriptor(e,o);if(!_){if("cid"===o)return;var l=Object.getOwnPropertyDescriptor(r,o);if(n=s.value,a=g(n),null!=n&&("object"===a||"function"===a)&&l&&l.value===s.value)return}"production"!==process.env.NODE_ENV&&R.indexOf(o)>=0&&N("Static property name '".concat(o,"' declared on class '").concat(e.name,"' ")+"conflicts with reserved property name of Vue internal. It may cause unexpected behavior of the component. Consider renaming the property."),Object.defineProperty(t,o,s)}}}))}function P(t){return"function"==typeof t?F(t):function(e){return F(e,t)}}P.registerHooks=function(t){V.push.apply(V,O(t))};function D(t){return j((function(e,r){void 0===e.inject&&(e.inject={}),Array.isArray(e.inject)||(e.inject[r]=t||r)}))}function S(t){return j((function(e,r){var o,i=e.provide;("function"!=typeof(o=i)||!o.managed&&!o.managedReactive)&&(i=e.provide=function(t){var e=function(){var r=this,o="function"==typeof t?t.call(this):t;for(var i in(o=Object.create(o||null)).__reactiveInject__=this.__reactiveInject__||{},e.managed)o[e.managed[i]]=this[i];var n=function(t){o[e.managedReactive[t]]=a[t],Object.defineProperty(o.__reactiveInject__,e.managedReactive[t],{enumerable:!0,get:function(){return r[t]}})},a=this;for(var i in e.managedReactive)n(i);return o};return e.managed={},e.managedReactive={},e}(i)),i.managed[r]=t||r}))}var C="undefined"!=typeof Reflect&&void 0!==Reflect.getMetadata;function k(t,e,r){if(C&&!Array.isArray(t)&&"function"!=typeof t&&void 0===t.type){var o=Reflect.getMetadata("design:type",e,r);o!==Object&&(t.type=o)}}function I(t,e){return void 0===e&&(e={}),function(r,o){k(e,r,o),j((function(r,o){(r.props||(r.props={}))[o]=e,r.model={prop:o,event:t||o}}))(r,o)}}function T(t){return void 0===t&&(t={}),function(e,r){k(t,e,r),j((function(e,r){(e.props||(e.props={}))[r]=t}))(e,r)}}function z(t,e){void 0===e&&(e={});var r=e.deep,o=void 0!==r&&r,i=e.immediate,n=void 0!==i&&i;return j((function(e,r){"object"!=typeof e.watch&&(e.watch=Object.create(null));var i=e.watch;"object"!=typeof i[t]||Array.isArray(i[t])?void 0===i[t]&&(i[t]=[]):i[t]=[i[t]],i[t].push({handler:r,deep:o,immediate:n})}))}class W{constructor(t){this.registry=new Map,this.ctx=t}add(t,e){if(this.registry.has(t))return;this.registry.set(t,e);const r=f(this.ctx.initialValues,t),i=o(e.$options.propsData||{},"value");!i&&this.ctx.hasInitialValue&&void 0!==r?e.context.model=r:i&&!c(e.proxy,r)&&this.ctx.setFieldValueAndEmit(t,e.proxy)}remove(t){this.registry.delete(t);const e=this.ctx.proxy,r=t,o=(e[r],m(e,["symbol"==typeof r?r:r+""]));this.ctx.proxy=o}has(t){return this.registry.has(t)}hasNested(t){for(const e of this.registry.keys())if(e===t||e.includes(t+"."))return!0;return!1}get(t){return this.registry.get(t)}getNested(t){const e=new Map;for(const r of this.registry.keys()){const o=t+".",i=t+"[";r!==t&&r.substring(0,o.length)!==o&&r.substring(0,i.length)!==i||e.set(r,this.registry.get(r))}return e}forEach(t){this.registry.forEach((e,r)=>{t(e,r)})}keys(){return Array.from(this.registry.keys())}reduce(t,e){return this.registry.forEach((r,o)=>{e=t(e,r,o)}),e}}class Y{constructor(t=[]){this.observers=[],this.observers=t}add(t){this.observers.some(e=>e.callback===t.callback)||this.observers.push(t)}remove(t){this.observers=this.observers.filter(e=>e.callback!==t)}filter(t){return new Y(this.observers.filter(t))}some(t){return this.observers.some(t)}observe(t){this.observers.forEach(e=>{"form"===e.type?e.callback(t):e.field&&!Array.isArray(t)&&(o(t,e.field)?e.callback(t[e.field]):e.callback([]))})}}let q=class extends t{constructor(){super(...arguments),this.path="",this.proxy={},this.registry=new W(this),this.errorObserverRegistry=new Y,this.localFormErrors=[],this.localFieldErrors={}}get initialValues(){return this.hasModel&&"object"==typeof this.formularioValue?Object.assign({},this.formularioValue):{}}get mergedFormErrors(){return[...this.formErrors,...this.localFormErrors]}get mergedFieldErrors(){return i(this.errors||{},this.localFieldErrors)}get hasModel(){return o(this.$options.propsData||{},"formularioValue")}get hasInitialValue(){return this.formularioValue&&"object"==typeof this.formularioValue}onFormularioValueChanged(t){this.hasModel&&t&&"object"==typeof t&&this.setValues(t)}onMergedFormErrorsChanged(t){this.errorObserverRegistry.filter(t=>"form"===t.type).observe(t)}onMergedFieldErrorsChanged(t){this.errorObserverRegistry.filter(t=>"input"===t.type).observe(t)}created(){this.initProxy()}getFormValues(){return this.proxy}onFormSubmit(){return this.hasValidationErrors().then(t=>t?void 0:function t(e){if("object"!=typeof e)return e;const r=Array.isArray(e)?[]:{};for(const i in e)o(e,i)&&(u(e[i])?r[i]=e[i]:e instanceof Date?r[i]=new Date(r[i]):r[i]=t(e[i]));return r}(this.proxy)).then(t=>{void 0!==t?this.$emit("submit",t):this.$emit("error")})}onFormularioFieldValidation(t){this.$emit("validation",t)}addErrorObserver(t){this.errorObserverRegistry.add(t),"form"===t.type?t.callback(this.mergedFormErrors):t.field&&o(this.mergedFieldErrors,t.field)&&t.callback(this.mergedFieldErrors[t.field])}removeErrorObserver(t){this.errorObserverRegistry.remove(t)}register(t,e){this.registry.add(t,e)}deregister(t){this.registry.remove(t)}initProxy(){this.hasInitialValue&&(this.proxy=this.initialValues)}setValues(t){const e=Array.from(new Set([...Object.keys(t),...Object.keys(this.proxy)]));let r=!1;e.forEach(e=>{this.registry.hasNested(e)&&this.registry.getNested(e).forEach((e,o)=>{const i=this.registry.get(o),n=f(this.proxy,o),a=f(t,o);c(a,n)||(this.setFieldValue(o,a),r=!0),c(a,i.proxy)||(i.context.model=a)})}),this.initProxy(),r&&this.$emit("input",Object.assign({},this.proxy))}setFieldValue(t,e){if(void 0===e){const e=this.proxy,r=t,o=(e[r],m(e,["symbol"==typeof r?r:r+""]));this.proxy=o}else!function(t,e,r){const o=e.split(".");let i=t;for(let t=0;t(t.push(e.runValidation()&&e.hasValidationErrors()),t),[])).then(t=>t.some(t=>t))}resetValidation(){this.localFormErrors=[],this.localFieldErrors={},this.registry.forEach(t=>{t.resetValidation()})}};function Q(t,e,r,o,i,n,a,s,l,u){"boolean"!=typeof a&&(l=s,s=a,a=!1);const c="function"==typeof r?r.options:r;let d;if(t&&t.render&&(c.render=t.render,c.staticRenderFns=t.staticRenderFns,c._compiled=!0,i&&(c.functional=!0)),o&&(c._scopeId=o),n?(d=function(t){(t=t||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(t=__VUE_SSR_CONTEXT__),e&&e.call(this,l(t)),t&&t._registeredComponents&&t._registeredComponents.add(n)},c._ssrRegister=d):e&&(d=a?function(t){e.call(this,u(t,this.$root.$options.shadowRoot))}:function(t){e.call(this,s(t))}),d)if(c.functional){const t=c.render;c.render=function(e,r){return d.call(r),t(e,r)}}else{const t=c.beforeCreate;c.beforeCreate=t?[].concat(t,d):[d]}return r}y([I("input",{default:()=>({})})],q.prototype,"formularioValue",void 0),y([T({default:()=>({})})],q.prototype,"errors",void 0),y([T({default:()=>[]})],q.prototype,"formErrors",void 0),y([S()],q.prototype,"path",void 0),y([z("formularioValue",{deep:!0})],q.prototype,"onFormularioValueChanged",null),y([z("mergedFormErrors")],q.prototype,"onMergedFormErrorsChanged",null),y([z("mergedFieldErrors",{deep:!0,immediate:!0})],q.prototype,"onMergedFieldErrorsChanged",null),y([S()],q.prototype,"getFormValues",null),y([S()],q.prototype,"onFormularioFieldValidation",null),y([S()],q.prototype,"addErrorObserver",null),y([S()],q.prototype,"removeErrorObserver",null),y([S("formularioRegister")],q.prototype,"register",null),y([S("formularioDeregister")],q.prototype,"deregister",null),y([S("formularioSetter")],q.prototype,"setFieldValueAndEmit",null),q=y([P({name:"FormularioForm"})],q);const U=q;var B=function(){var t=this,e=t.$createElement;return(t._self._c||e)("form",{on:{submit:function(e){return e.preventDefault(),t.onFormSubmit(e)}}},[t._t("default",null,{errors:t.mergedFormErrors})],2)};B._withStripped=!0;const G=Q({render:B,staticRenderFns:[]},void 0,U,void 0,!1,void 0,!1,void 0,void 0,void 0);let L=class extends t{get groupPath(){return this.isArrayItem?`${this.path}[${this.name}]`:""===this.path?this.name:`${this.path}.${this.name}`}};y([D({default:""})],L.prototype,"path",void 0),y([T({required:!0})],L.prototype,"name",void 0),y([T({default:!1})],L.prototype,"isArrayItem",void 0),y([S("path")],L.prototype,"groupPath",null),L=y([P({name:"FormularioGrouping"})],L);const Z=L;var K=function(){var t=this.$createElement;return(this._self._c||t)("div",[this._t("default")],2)};K._withStripped=!0;const X=Q({render:K,staticRenderFns:[]},void 0,Z,void 0,!1,void 0,!1,void 0,void 0,void 0);function H(t,e,r,o){return i=>Promise.resolve(t(i,...r)).then(t=>t?null:{rule:e,args:r,context:i,message:o(i,...r)})}function J(t){return/^[\^]/.test(t.charAt(0))?[d(t.substr(1)),t.charAt(0)]:[d(t),null]}function tt(t,e,r){return"function"==typeof t?[t,null,null]:Array.isArray(t)&&t.length?function(t,e,r){const i=t.slice(),n=i.shift();if("function"==typeof n)return[n,null,null];if("string"!=typeof n)throw new Error("[Formulario]: For array constraint first element must be rule name or Validator function");const[a,s]=J(n);if(o(e,a))return[H(e[a],a,i,r[a]||r.default),a,s];throw new Error("[Formulario] Can't create validator for constraint: "+JSON.stringify(t))}(t,e,r):"string"==typeof t?function(t,e,r){const i=t.split(":"),[n,a]=J(i.shift()||"");if(o(e,n))return[H(e[n],n,i.length?i.join(":").split(","):[],r[n]||r.default),n,a];throw new Error("[Formulario] Can't create validator for constraint: "+t)}(t,e,r):[()=>Promise.resolve(null),null,null]}function et(t){const e=[];if(t.length){let r=t.shift();e.push(r),t.forEach(t=>{t.bail||t.bail!==r.bail?(r=Object.assign({},t),e.push(r)):r.validators.push(...t.validators)})}return e}function rt(t,e){return new Promise(r=>{const o=(t,i=[])=>{if(t.length){const n=t.shift();(function(t,e){return Promise.all(t.validators.map(t=>t(e))).then(t=>t.filter(t=>null!==t))})(n,e).then(e=>0!==e.length&&n.bail||!t.length?r(i.concat(e)):o(t,i.concat(e)))}else r([])};o(function(t){const e=([t,,e])=>({validators:[t],bail:"^"===e}),r=[],o=t.findIndex(([,t])=>t&&"bail"===t.toLowerCase());return o>=0?(r.push(...et(t.splice(0,o+1).slice(0,-1).map(e))),r.push(...t.map(([t])=>({validators:[t],bail:!0})))):r.push(...et(t.map(e))),r}(t))})}const ot={DEMAND:"demand",LIVE:"live",SUBMIT:"submit"};let it=class extends t{constructor(){super(...arguments),this.proxy=this.getInitialValue(),this.localErrors=[],this.violations=[],this.validationRun=Promise.resolve()}get fullQualifiedName(){return""!==this.path?`${this.path}.${this.name}`:this.name}get model(){const t=this.hasModel?"value":"proxy";return this.modelGetConverter(this[t])}set model(t){c(t=this.modelSetConverter(t,this.proxy),this.proxy)||(this.proxy=t),this.$emit("input",t),"function"==typeof this.formularioSetter&&this.formularioSetter(this.context.name,t)}get context(){return Object.defineProperty({name:this.fullQualifiedName,runValidation:this.runValidation.bind(this),violations:this.violations,errors:this.localErrors,allErrors:[...this.localErrors,...this.violations.map(t=>t.message)]},"model",{get:()=>this.model,set:t=>{this.model=t}})}get normalizedValidationRules(){const t={};return Object.keys(this.validationRules).forEach(e=>{t[d(e)]=this.validationRules[e]}),t}get normalizedValidationMessages(){const t={};return Object.keys(this.validationMessages).forEach(e=>{t[d(e)]=this.validationMessages[e]}),t}get hasModel(){return o(this.$options.propsData||{},"value")}onProxyChanged(t,e){this.hasModel||c(t,e)||(this.context.model=t),this.validationBehavior===ot.LIVE?this.runValidation():this.violations=[]}onValueChanged(t,e){this.hasModel&&!c(t,e)&&(this.context.model=t)}created(){this.initProxy(),"function"==typeof this.formularioRegister&&this.formularioRegister(this.fullQualifiedName,this),"function"!=typeof this.addErrorObserver||this.errorsDisabled||this.addErrorObserver({callback:this.setErrors,type:"input",field:this.fullQualifiedName}),this.validationBehavior===ot.LIVE&&this.runValidation()}beforeDestroy(){this.errorsDisabled||"function"!=typeof this.removeErrorObserver||this.removeErrorObserver(this.setErrors),"function"==typeof this.formularioDeregister&&this.formularioDeregister(this.fullQualifiedName)}getInitialValue(){return o(this.$options.propsData||{},"value")?this.value:""}initProxy(){c(this.context.model,this.proxy)||(this.context.model=this.proxy)}runValidation(){return this.validationRun=this.validate().then(t=>{const e=!c(t,this.violations);if(this.violations=t,e){const t={name:this.context.name,violations:this.violations};this.$emit("validation",t),"function"==typeof this.onFormularioFieldValidation&&this.onFormularioFieldValidation(t)}return this.violations}),this.validationRun}validate(){return rt(function t(e,r,o){return"string"==typeof e?t(e.split("|").filter(t=>t.length),r,o):Array.isArray(e)?e.map(t=>tt(t,r,o)):[]}(this.validation,this.$formulario.getRules(this.normalizedValidationRules),this.$formulario.getMessages(this,this.normalizedValidationMessages)),{value:this.context.model,name:this.context.name,formValues:this.getFormValues()})}hasValidationErrors(){return new Promise(t=>{this.$nextTick(()=>{this.validationRun.then(()=>t(this.violations.length>0))})})}setErrors(t){var e;this.localErrors=(e=t)?"string"==typeof e?[e]:Array.isArray(e)?e:"object"==typeof e?Object.values(e):[]:[]}resetValidation(){this.localErrors=[],this.violations=[]}};y([D({default:void 0})],it.prototype,"formularioSetter",void 0),y([D({default:()=>()=>{}})],it.prototype,"onFormularioFieldValidation",void 0),y([D({default:void 0})],it.prototype,"formularioRegister",void 0),y([D({default:void 0})],it.prototype,"formularioDeregister",void 0),y([D({default:()=>()=>({})})],it.prototype,"getFormValues",void 0),y([D({default:void 0})],it.prototype,"addErrorObserver",void 0),y([D({default:void 0})],it.prototype,"removeErrorObserver",void 0),y([D({default:""})],it.prototype,"path",void 0),y([I("input",{default:""})],it.prototype,"value",void 0),y([T({required:!0,validator:t=>"string"==typeof t&&t.length>0})],it.prototype,"name",void 0),y([T({default:""})],it.prototype,"validation",void 0),y([T({default:()=>({})})],it.prototype,"validationRules",void 0),y([T({default:()=>({})})],it.prototype,"validationMessages",void 0),y([T({default:ot.DEMAND,validator:t=>Object.values(ot).includes(t)})],it.prototype,"validationBehavior",void 0),y([T({default:!1})],it.prototype,"errorsDisabled",void 0),y([T({default:()=>t=>t})],it.prototype,"modelGetConverter",void 0),y([T({default:()=>t=>t})],it.prototype,"modelSetConverter",void 0),y([z("proxy")],it.prototype,"onProxyChanged",null),y([z("value")],it.prototype,"onValueChanged",null),it=y([P({name:"FormularioInput",inheritAttrs:!1})],it);const nt=it;var at=function(){var t=this.$createElement;return(this._self._c||t)("div",{staticClass:"formulario-input"},[this._t("default",null,{context:this.context})],2)};at._withStripped=!0;const st=Q({render:at,staticRenderFns:[]},void 0,nt,void 0,!1,void 0,!1,void 0,void 0,void 0);return{install(t,e){t.component("FormularioForm",G),t.component("FormularioGrouping",X),t.component("FormularioInput",st),t.mixin({beforeCreate(){const t=this.$options;"function"==typeof t.formulario?this.$formulario=t.formulario():t.parent&&t.parent.$formulario?this.$formulario=t.parent.$formulario:this.$formulario=new v(e)}})}}}(Vue); + */}function g(t){return(g="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function b(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function O(t){return function(t){if(Array.isArray(t)){for(var e=0,r=new Array(t.length);e0&&N("Component class must inherit Vue or its descendant class when class property is used."),n}var V=["data","beforeCreate","created","beforeMount","mounted","beforeDestroy","destroyed","beforeUpdate","updated","activated","deactivated","render","errorCaptured","serverPrefetch"];function F(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};r.name=r.name||e._componentTag||e.name;var o=e.prototype;Object.getOwnPropertyNames(o).forEach((function(t){if("constructor"!==t)if(V.indexOf(t)>-1)r[t]=o[t];else{var e=Object.getOwnPropertyDescriptor(o,t);void 0!==e.value?"function"==typeof e.value?(r.methods||(r.methods={}))[t]=e.value:(r.mixins||(r.mixins=[])).push({data:function(){return b({},t,e.value)}}):(e.get||e.set)&&((r.computed||(r.computed={}))[t]={get:e.get,set:e.set})}})),(r.mixins||(r.mixins=[])).push({data:function(){return w(this,e)}});var i=e.__decorators__;i&&(i.forEach((function(t){return t(r)})),delete e.__decorators__);var n=Object.getPrototypeOf(e.prototype),a=n instanceof t?n.constructor:t,s=a.extend(r);return M(s,e,a),E()&&x(s,e),s}var R=["cid","super","options","superOptions","extendOptions","sealedOptions","component","directive","filter"],A={prototype:!0,arguments:!0,callee:!0,caller:!0};function M(t,e,r){Object.getOwnPropertyNames(e).forEach((function(o){if(!A[o]){var i=Object.getOwnPropertyDescriptor(t,o);if(!i||i.configurable){var n,a,s=Object.getOwnPropertyDescriptor(e,o);if(!_){if("cid"===o)return;var l=Object.getOwnPropertyDescriptor(r,o);if(n=s.value,a=g(n),null!=n&&("object"===a||"function"===a)&&l&&l.value===s.value)return}"production"!==process.env.NODE_ENV&&R.indexOf(o)>=0&&N("Static property name '".concat(o,"' declared on class '").concat(e.name,"' ")+"conflicts with reserved property name of Vue internal. It may cause unexpected behavior of the component. Consider renaming the property."),Object.defineProperty(t,o,s)}}}))}function P(t){return"function"==typeof t?F(t):function(e){return F(e,t)}}P.registerHooks=function(t){V.push.apply(V,O(t))};function D(t){return j((function(e,r){void 0===e.inject&&(e.inject={}),Array.isArray(e.inject)||(e.inject[r]=t||r)}))}function S(t){return j((function(e,r){var o,i=e.provide;("function"!=typeof(o=i)||!o.managed&&!o.managedReactive)&&(i=e.provide=function(t){var e=function(){var r=this,o="function"==typeof t?t.call(this):t;for(var i in(o=Object.create(o||null)).__reactiveInject__=this.__reactiveInject__||{},e.managed)o[e.managed[i]]=this[i];var n=function(t){o[e.managedReactive[t]]=a[t],Object.defineProperty(o.__reactiveInject__,e.managedReactive[t],{enumerable:!0,get:function(){return r[t]}})},a=this;for(var i in e.managedReactive)n(i);return o};return e.managed={},e.managedReactive={},e}(i)),i.managed[r]=t||r}))}var C="undefined"!=typeof Reflect&&void 0!==Reflect.getMetadata;function k(t,e,r){if(C&&!Array.isArray(t)&&"function"!=typeof t&&void 0===t.type){var o=Reflect.getMetadata("design:type",e,r);o!==Object&&(t.type=o)}}function I(t,e){return void 0===e&&(e={}),function(r,o){k(e,r,o),j((function(r,o){(r.props||(r.props={}))[o]=e,r.model={prop:o,event:t||o}}))(r,o)}}function T(t){return void 0===t&&(t={}),function(e,r){k(t,e,r),j((function(e,r){(e.props||(e.props={}))[r]=t}))(e,r)}}function z(t,e){void 0===e&&(e={});var r=e.deep,o=void 0!==r&&r,i=e.immediate,n=void 0!==i&&i;return j((function(e,r){"object"!=typeof e.watch&&(e.watch=Object.create(null));var i=e.watch;"object"!=typeof i[t]||Array.isArray(i[t])?void 0===i[t]&&(i[t]=[]):i[t]=[i[t]],i[t].push({handler:r,deep:o,immediate:n})}))}class W{constructor(t){this.registry=new Map,this.ctx=t}add(t,e){if(this.registry.has(t))return;this.registry.set(t,e);const r=f(this.ctx.initialValues,t),i=o(e.$options.propsData||{},"value");!i&&this.ctx.hasInitialValue&&void 0!==r?e.context.model=r:i&&!c(e.proxy,r)&&this.ctx.setFieldValueAndEmit(t,e.proxy)}remove(t){this.registry.delete(t);const e=this.ctx.proxy,r=t,o=(e[r],m(e,["symbol"==typeof r?r:r+""]));this.ctx.proxy=o}has(t){return this.registry.has(t)}hasNested(t){for(const e of this.registry.keys())if(e===t||e.includes(t+"."))return!0;return!1}get(t){return this.registry.get(t)}getNested(t){const e=new Map;for(const r of this.registry.keys()){const o=t+".",i=t+"[";r!==t&&r.substring(0,o.length)!==o&&r.substring(0,i.length)!==i||e.set(r,this.registry.get(r))}return e}forEach(t){this.registry.forEach((e,r)=>{t(e,r)})}keys(){return Array.from(this.registry.keys())}reduce(t,e){return this.registry.forEach((r,o)=>{e=t(e,r,o)}),e}}class Y{constructor(t=[]){this.observers=[],this.observers=t}add(t){this.observers.some(e=>e.callback===t.callback)||this.observers.push(t)}remove(t){this.observers=this.observers.filter(e=>e.callback!==t)}filter(t){return new Y(this.observers.filter(t))}some(t){return this.observers.some(t)}observe(t){this.observers.forEach(e=>{"form"===e.type?e.callback(t):e.field&&!Array.isArray(t)&&(o(t,e.field)?e.callback(t[e.field]):e.callback([]))})}}let q=class extends t{constructor(){super(...arguments),this.path="",this.proxy={},this.registry=new W(this),this.errorObserverRegistry=new Y,this.localFormErrors=[],this.localFieldErrors={}}get initialValues(){return this.hasModel&&"object"==typeof this.formularioValue?Object.assign({},this.formularioValue):{}}get mergedFormErrors(){return[...this.formErrors,...this.localFormErrors]}get mergedFieldErrors(){return i(this.errors||{},this.localFieldErrors)}get hasModel(){return o(this.$options.propsData||{},"formularioValue")}get hasInitialValue(){return this.formularioValue&&"object"==typeof this.formularioValue}onFormularioValueChanged(t){this.hasModel&&t&&"object"==typeof t&&this.setValues(t)}onMergedFormErrorsChanged(t){this.errorObserverRegistry.filter(t=>"form"===t.type).observe(t)}onMergedFieldErrorsChanged(t){this.errorObserverRegistry.filter(t=>"input"===t.type).observe(t)}created(){this.initProxy()}getFormValues(){return this.proxy}onFormSubmit(){return this.hasValidationErrors().then(t=>t?void 0:function t(e){if("object"!=typeof e)return e;const r=Array.isArray(e)?[]:{};for(const i in e)o(e,i)&&(u(e[i])?r[i]=e[i]:e instanceof Date?r[i]=new Date(r[i]):r[i]=t(e[i]));return r}(this.proxy)).then(t=>{void 0!==t?this.$emit("submit",t):this.$emit("error")})}onFormularioFieldValidation(t){this.$emit("validation",t)}addErrorObserver(t){this.errorObserverRegistry.add(t),"form"===t.type?t.callback(this.mergedFormErrors):t.field&&o(this.mergedFieldErrors,t.field)&&t.callback(this.mergedFieldErrors[t.field])}removeErrorObserver(t){this.errorObserverRegistry.remove(t)}register(t,e){this.registry.add(t,e)}deregister(t){this.registry.remove(t)}initProxy(){this.hasInitialValue&&(this.proxy=this.initialValues)}setValues(t){const e=Array.from(new Set([...Object.keys(t),...Object.keys(this.proxy)]));let r=!1;e.forEach(e=>{this.registry.hasNested(e)&&this.registry.getNested(e).forEach((e,o)=>{const i=this.registry.get(o),n=f(this.proxy,o),a=f(t,o);c(a,n)||(this.setFieldValue(o,a),r=!0),c(a,i.proxy)||(i.context.model=a)})}),this.initProxy(),r&&this.$emit("input",Object.assign({},this.proxy))}setFieldValue(t,e){if(void 0===e){const e=this.proxy,r=t,o=(e[r],m(e,["symbol"==typeof r?r:r+""]));this.proxy=o}else!function(t,e,r){const o=e.split(".");let i=t;for(let t=0;t(t.push(e.runValidation()&&e.hasValidationErrors()),t),[])).then(t=>t.some(t=>t))}resetValidation(){this.localFormErrors=[],this.localFieldErrors={},this.registry.forEach(t=>{t.resetValidation()})}};function Q(t,e,r,o,i,n,a,s,l,u){"boolean"!=typeof a&&(l=s,s=a,a=!1);const c="function"==typeof r?r.options:r;let d;if(t&&t.render&&(c.render=t.render,c.staticRenderFns=t.staticRenderFns,c._compiled=!0,i&&(c.functional=!0)),o&&(c._scopeId=o),n?(d=function(t){(t=t||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(t=__VUE_SSR_CONTEXT__),e&&e.call(this,l(t)),t&&t._registeredComponents&&t._registeredComponents.add(n)},c._ssrRegister=d):e&&(d=a?function(t){e.call(this,u(t,this.$root.$options.shadowRoot))}:function(t){e.call(this,s(t))}),d)if(c.functional){const t=c.render;c.render=function(e,r){return d.call(r),t(e,r)}}else{const t=c.beforeCreate;c.beforeCreate=t?[].concat(t,d):[d]}return r}y([I("input",{default:()=>({})})],q.prototype,"formularioValue",void 0),y([T({default:()=>({})})],q.prototype,"errors",void 0),y([T({default:()=>[]})],q.prototype,"formErrors",void 0),y([S()],q.prototype,"path",void 0),y([z("formularioValue",{deep:!0})],q.prototype,"onFormularioValueChanged",null),y([z("mergedFormErrors")],q.prototype,"onMergedFormErrorsChanged",null),y([z("mergedFieldErrors",{deep:!0,immediate:!0})],q.prototype,"onMergedFieldErrorsChanged",null),y([S()],q.prototype,"getFormValues",null),y([S()],q.prototype,"onFormularioFieldValidation",null),y([S()],q.prototype,"addErrorObserver",null),y([S()],q.prototype,"removeErrorObserver",null),y([S("formularioRegister")],q.prototype,"register",null),y([S("formularioDeregister")],q.prototype,"deregister",null),y([S("formularioSetter")],q.prototype,"setFieldValueAndEmit",null),q=y([P({name:"FormularioForm"})],q);const U=q;var B=function(){var t=this,e=t.$createElement;return(t._self._c||e)("form",{on:{submit:function(e){return e.preventDefault(),t.onFormSubmit(e)}}},[t._t("default",null,{errors:t.mergedFormErrors})],2)};B._withStripped=!0;const G=Q({render:B,staticRenderFns:[]},void 0,U,void 0,!1,void 0,!1,void 0,void 0,void 0);let L=class extends t{get groupPath(){return this.isArrayItem?`${this.path}[${this.name}]`:""===this.path?this.name:`${this.path}.${this.name}`}};y([D({default:""})],L.prototype,"path",void 0),y([T({required:!0})],L.prototype,"name",void 0),y([T({default:!1})],L.prototype,"isArrayItem",void 0),y([S("path")],L.prototype,"groupPath",null),L=y([P({name:"FormularioGrouping"})],L);const Z=L;var K=function(){var t=this.$createElement;return(this._self._c||t)("div",[this._t("default")],2)};K._withStripped=!0;const X=Q({render:K,staticRenderFns:[]},void 0,Z,void 0,!1,void 0,!1,void 0,void 0,void 0);function H(t,e,r,o){return i=>Promise.resolve(t(i,...r)).then(t=>t?null:{rule:e,args:r,context:i,message:o(i,...r)})}function J(t){return/^[\^]/.test(t.charAt(0))?[d(t.substr(1)),t.charAt(0)]:[d(t),null]}function tt(t,e,r){return"function"==typeof t?[t,null,null]:Array.isArray(t)&&t.length?function(t,e,r){const i=t.slice(),n=i.shift();if("function"==typeof n)return[n,null,null];if("string"!=typeof n)throw new Error("[Formulario]: For array constraint first element must be rule name or Validator function");const[a,s]=J(n);if(o(e,a))return[H(e[a],a,i,r[a]||r.default),a,s];throw new Error("[Formulario] Can't create validator for constraint: "+JSON.stringify(t))}(t,e,r):"string"==typeof t?function(t,e,r){const i=t.split(":"),[n,a]=J(i.shift()||"");if(o(e,n))return[H(e[n],n,i.length?i.join(":").split(","):[],r[n]||r.default),n,a];throw new Error("[Formulario] Can't create validator for constraint: "+t)}(t,e,r):[()=>Promise.resolve(null),null,null]}function et(t){const e=[];if(t.length){let r=t.shift();e.push(r),t.forEach(t=>{t.bail||t.bail!==r.bail?(r=Object.assign({},t),e.push(r)):r.validators.push(...t.validators)})}return e}function rt(t,e){return new Promise(r=>{const o=(t,i=[])=>{if(t.length){const n=t.shift();(function(t,e){return Promise.all(t.validators.map(t=>t(e))).then(t=>t.filter(t=>null!==t))})(n,e).then(e=>0!==e.length&&n.bail||!t.length?r(i.concat(e)):o(t,i.concat(e)))}else r([])};o(function(t){const e=([t,,e])=>({validators:[t],bail:"^"===e}),r=[],o=t.findIndex(([,t])=>t&&"bail"===t.toLowerCase());return o>=0?(r.push(...et(t.splice(0,o+1).slice(0,-1).map(e))),r.push(...t.map(([t])=>({validators:[t],bail:!0})))):r.push(...et(t.map(e))),r}(t))})}const ot={DEMAND:"demand",LIVE:"live",SUBMIT:"submit"};let it=class extends t{constructor(){super(...arguments),this.proxy=this.getInitialValue(),this.localErrors=[],this.violations=[],this.validationRun=Promise.resolve()}get fullQualifiedName(){return""!==this.path?`${this.path}.${this.name}`:this.name}get model(){const t=this.hasModel?"value":"proxy";return this.modelGetConverter(this[t])}set model(t){c(t=this.modelSetConverter(t,this.proxy),this.proxy)||(this.proxy=t),this.$emit("input",t),"function"==typeof this.formularioSetter&&this.formularioSetter(this.context.name,t)}get context(){return Object.defineProperty({name:this.fullQualifiedName,runValidation:this.runValidation.bind(this),violations:this.violations,errors:this.localErrors,allErrors:[...this.localErrors,...this.violations.map(t=>t.message)]},"model",{get:()=>this.model,set:t=>{this.model=t}})}get normalizedValidationRules(){const t={};return Object.keys(this.validationRules).forEach(e=>{t[d(e)]=this.validationRules[e]}),t}get normalizedValidationMessages(){const t={};return Object.keys(this.validationMessages).forEach(e=>{t[d(e)]=this.validationMessages[e]}),t}get hasModel(){return o(this.$options.propsData||{},"value")}onProxyChanged(t,e){this.hasModel||c(t,e)||(this.context.model=t),this.validationBehavior===ot.LIVE?this.runValidation():this.violations=[]}onValueChanged(t,e){this.hasModel&&!c(t,e)&&(this.context.model=t)}created(){this.initProxy(),"function"==typeof this.formularioRegister&&this.formularioRegister(this.fullQualifiedName,this),"function"!=typeof this.addErrorObserver||this.errorsDisabled||this.addErrorObserver({callback:this.setErrors,type:"input",field:this.fullQualifiedName}),this.validationBehavior===ot.LIVE&&this.runValidation()}beforeDestroy(){this.errorsDisabled||"function"!=typeof this.removeErrorObserver||this.removeErrorObserver(this.setErrors),"function"==typeof this.formularioDeregister&&this.formularioDeregister(this.fullQualifiedName)}getInitialValue(){return o(this.$options.propsData||{},"value")?this.value:""}initProxy(){c(this.context.model,this.proxy)||(this.context.model=this.proxy)}runValidation(){return this.validationRun=this.validate().then(t=>{const e=!c(t,this.violations);if(this.violations=t,e){const t={name:this.context.name,violations:this.violations};this.$emit("validation",t),"function"==typeof this.onFormularioFieldValidation&&this.onFormularioFieldValidation(t)}return this.violations}),this.validationRun}validate(){return rt(function t(e,r,o){return"string"==typeof e?t(e.split("|").filter(t=>t.length),r,o):Array.isArray(e)?e.map(t=>tt(t,r,o)):[]}(this.validation,this.$formulario.getRules(this.normalizedValidationRules),this.$formulario.getMessages(this,this.normalizedValidationMessages)),{value:this.context.model,name:this.context.name,formValues:this.getFormValues()})}hasValidationErrors(){return new Promise(t=>{this.$nextTick(()=>{this.validationRun.then(()=>t(this.violations.length>0))})})}setErrors(t){var e;this.localErrors=(e=t)?"string"==typeof e?[e]:Array.isArray(e)?e:"object"==typeof e?Object.values(e):[]:[]}resetValidation(){this.localErrors=[],this.violations=[]}};y([D({default:void 0})],it.prototype,"formularioSetter",void 0),y([D({default:()=>()=>{}})],it.prototype,"onFormularioFieldValidation",void 0),y([D({default:void 0})],it.prototype,"formularioRegister",void 0),y([D({default:void 0})],it.prototype,"formularioDeregister",void 0),y([D({default:()=>()=>({})})],it.prototype,"getFormValues",void 0),y([D({default:void 0})],it.prototype,"addErrorObserver",void 0),y([D({default:void 0})],it.prototype,"removeErrorObserver",void 0),y([D({default:""})],it.prototype,"path",void 0),y([I("input",{default:""})],it.prototype,"value",void 0),y([T({required:!0,validator:t=>"string"==typeof t&&t.length>0})],it.prototype,"name",void 0),y([T({default:""})],it.prototype,"validation",void 0),y([T({default:()=>({})})],it.prototype,"validationRules",void 0),y([T({default:()=>({})})],it.prototype,"validationMessages",void 0),y([T({default:ot.DEMAND,validator:t=>Object.values(ot).includes(t)})],it.prototype,"validationBehavior",void 0),y([T({default:!1})],it.prototype,"errorsDisabled",void 0),y([T({default:()=>t=>t})],it.prototype,"modelGetConverter",void 0),y([T({default:()=>t=>t})],it.prototype,"modelSetConverter",void 0),y([z("proxy")],it.prototype,"onProxyChanged",null),y([z("value")],it.prototype,"onValueChanged",null),it=y([P({name:"FormularioInput",inheritAttrs:!1})],it);const nt=it;var at=function(){var t=this.$createElement;return(this._self._c||t)("div",{staticClass:"formulario-input"},[this._t("default",null,{context:this.context})],2)};at._withStripped=!0;const st=Q({render:at,staticRenderFns:[]},void 0,nt,void 0,!1,void 0,!1,void 0,void 0,void 0);return{install(t,e){t.component("FormularioForm",G),t.component("FormularioGrouping",X),t.component("FormularioInput",st),t.mixin({beforeCreate(){const t=this.$options;"function"==typeof t.formulario?this.$formulario=t.formulario():t.parent&&t.parent.$formulario?this.$formulario=t.parent.$formulario:this.$formulario=new v(e)}})}}}(Vue); diff --git a/dist/formulario.umd.js b/dist/formulario.umd.js index f973965..eea3c0d 100644 --- a/dist/formulario.umd.js +++ b/dist/formulario.umd.js @@ -198,6 +198,9 @@ for (let i = 0; i < fieldParts.length; i++) { const fieldPart = fieldParts[i]; const matches = fieldPart.match(/(.+)\[(\d+)\]$/); + if (subProxy === undefined) { + break; + } if (matches) { if (subProxy[matches[1]] === undefined) { subProxy[matches[1]] = []; @@ -212,9 +215,6 @@ } } else { - if (subProxy === undefined) { - break; - } if (i === fieldParts.length - 1) { subProxy[fieldPart] = value; break; diff --git a/package.json b/package.json index 5d7fccf..e000e7a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@retailcrm/vue-formulario", - "version": "0.5.0", + "version": "0.5.1", "author": "RetailDriverLLC ", "scripts": { "build": "npm run build:esm & npm run build:umd & npm run build:iife & wait && echo \"Build complete:\nesm: $(gzip -c dist/formulario.esm.js | wc -c)b gzip\numd: $(gzip -c dist/formulario.umd.js | wc -c)b gzip\nmin: $(gzip -c dist/formulario.min.js | wc -c)b gzip\"",