1
0
mirror of synced 2024-11-22 13:26:06 +03:00
vue-formulario/dist/formulario.esm.js
2020-10-21 10:58:40 +03:00

17 lines
32 KiB
JavaScript

import t from"is-url";import e from"nanoid/non-secure";import r from"is-plain-object";import i from"vue";import{Provide as s,Model as o,Prop as a,Watch as n,Component as l,Inject as h}from"vue-property-decorator";const u=(t,e)=>({classification:t,component:"FormularioInput"+(e||t[0].toUpperCase()+t.substr(1))});var d=Object.assign(Object.assign({},["text","email","number","color","date","hidden","month","password","search","tel","time","url","week","datetime-local"].reduce((t,e)=>Object.assign(Object.assign({},t),{[e]:u("text")}),{})),{range:u("slider"),textarea:u("textarea","TextArea"),checkbox:u("box"),radio:u("box"),submit:u("button"),button:u("button"),select:u("select"),file:u("file"),image:u("file"),group:u("group")});class p{constructor(t,e={},r={}){this.input=t,this.fileList=t.files,this.files=[],this.options=Object.assign({mimes:{}},r),this.results=!1,this.context=e,Array.isArray(this.fileList)?this.rehydrateFileList(this.fileList):this.addFileList(this.fileList)}rehydrateFileList(t){const e=t.reduce((t,e)=>{const r=e[this.options?this.options.fileUrlKey:"url"],i=!(!r||-1===r.lastIndexOf("."))&&r.substr(r.lastIndexOf(".")+1),s=this.options.mimes[i]||!1;return t.push(Object.assign({},e,r?{name:r.substr(r.lastIndexOf("/")+1||0),type:e.type?e.type:s,previewData:r}:{})),t},[]);this.results=t,this.addFileList(e)}addFileList(t){for(let r=0;r<t.length;r++){const i=t[r],s=e();this.files.push({progress:!1,error:!1,complete:!1,justFinished:!1,name:i.name||"file-upload",file:i,uuid:s,path:!1,removeFile:()=>this.removeFile(s),previewData:i.previewData||!1})}}hasUploader(){return!!this.context.uploader}uploaderIsAxios(){return this.hasUploader&&"function"==typeof this.context.uploader.request&&"function"==typeof this.context.uploader.get&&"function"==typeof this.context.uploader.delete&&"function"==typeof this.context.uploader.post}getUploader(...t){if(this.uploaderIsAxios()){const e=new FormData;if(e.append(this.context.name||"file",t[0]),!1===this.context.uploadUrl)throw new Error("No uploadURL specified: https://vueformulate.com/guide/inputs/file/#props");return this.context.uploader.post(this.context.uploadUrl,e,{headers:{"Content-Type":"multipart/form-data"},onUploadProgress:e=>{t[1](Math.round(100*e.loaded/e.total))}}).then(t=>t.data).catch(t[2])}return this.context.uploader(...t)}upload(){return this.results?Promise.resolve(this.results):new Promise((t,e)=>{if(!this.hasUploader)return e(new Error("No uploader has been defined"));Promise.all(this.files.map(t=>t.path?Promise.resolve(t.path):this.getUploader(t.file,e=>{t.progress=e,e>=100&&(t.complete||(t.justFinished=!0,setTimeout(()=>{t.justFinished=!1},this.options.uploadJustCompleteDuration)),t.complete=!0)},e=>{t.progress=0,t.error=e,t.complete=!0},this.options))).then(e=>{this.results=e,t(e)}).catch(t=>{throw new Error(t)})})}removeFile(t){if(this.files=this.files.filter(e=>e.uuid!==t),this.context.performValidation(),window&&this.fileList instanceof FileList){const t=new DataTransfer;this.files.map(({file:e})=>t.items.add(e)),this.fileList=t.files,this.input=t}}loadPreviews(){this.files.map(t=>{if(!t.previewData&&window&&window.FileReader&&/^image\//.test(t.file.type)){const e=new FileReader;e.onload=e=>Object.assign(t,{previewData:e.target.result}),e.readAsDataURL(t.file)}})}getFileList(){return this.fileList}getFiles(){return this.files}toString(){const t=this.files.length?this.files.length+" files":"empty";return this.results?JSON.stringify(this.results,null," "):`FileUpload(${t})`}}function c(t,e){if(t===e)return!0;if(!t||!e)return!1;const r=Object.keys(t);if(Object.keys(e).length!==r.length)return!1;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(0===r.length)return t===e;for(let i=0;i<r.length;i++){const s=r[i];if(t[s]!==e[s])return!1}return!0}function f(t){return"string"==typeof t?t.replace(/([_][a-z0-9])/gi,e=>0!==t.indexOf(e)&&"_"!==t[t.indexOf(e)-1]?e.toUpperCase().replace("_",""):e):t}function m(t){return"string"==typeof t&&/^[\^]/.test(t.charAt(0))?[f(t.substr(1)),t.charAt(0)]:[f(t),null]}function g(t){return t?"string"==typeof t?[t]:Array.isArray(t)?t:"object"==typeof t?Object.values(t):[]:[]}function y(t,e){return"string"==typeof t?y(t.split("|"),e):Array.isArray(t)?t.map(t=>function(t,e){if("function"==typeof t)return[t,[]];if(Array.isArray(t)&&t.length){t=t.slice();const[r,i]=m(t.shift());if("string"==typeof r&&Object.prototype.hasOwnProperty.call(e,r))return[e[r],t,r,i];if("function"==typeof r)return[r,t,r,i]}if("string"==typeof t){const r=t.split(":"),[i,s]=m(r.shift());if(Object.prototype.hasOwnProperty.call(e,i))return[e[i],r.length?r.join(":").split(","):[],i,s];throw new Error("Unknown validation rule "+t)}return!1}(t,e)).filter(t=>!!t):[]}function v(t){switch(typeof t){case"symbol":case"number":case"string":case"boolean":case"undefined":return!0;default:return null===t}}function b(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function E(t,e){const r=e.split(".");let i=t;for(const t in r){const e=r[t].match(/(.+)\[(\d+)\]$/);if(void 0===i)return null;if(e){if(i=i[e[1]],void 0===i)return null;i=i[e[2]]}else i=i[r[t]]}return i}var x={accepted:({value:t})=>Promise.resolve(["yes","on","1",1,!0,"true"].includes(t)),after({value:t},e=!1){const r=!1!==e?Date.parse(e):Date.now(),i=t instanceof Date?t.getTime():Date.parse(t);return Promise.resolve(!isNaN(i)&&i>r)},alpha({value:t},e="default"){const r={default:/^[a-zA-ZÀ-ÖØ-öø-ÿ]+$/,latin:/^[a-zA-Z]+$/},i=b(r,e)?e:"default";return Promise.resolve(r[i].test(t))},alphanumeric({value:t},e="default"){const r={default:/^[a-zA-Z0-9À-ÖØ-öø-ÿ]+$/,latin:/^[a-zA-Z0-9]+$/},i=b(r,e)?e:"default";return Promise.resolve(r[i].test(t))},before({value:t},e=!1){const r=!1!==e?Date.parse(e):Date.now(),i=t instanceof Date?t.getTime():Date.parse(t);return Promise.resolve(!isNaN(i)&&i<r)},between:({value:t},e=0,r=10,i)=>Promise.resolve(null!==e&&null!==r&&!isNaN(e)&&!isNaN(r)&&(!isNaN(Number(t))&&"length"!==i||"value"===i?(t=Number(t),e=Number(e),r=Number(r),t>e&&t<r):("string"==typeof t||"length"===i)&&(t=isNaN(Number(t))?t:t.toString()).length>e&&t.length<r)),confirm:({value:t,getFormValues:e,name:r},i)=>Promise.resolve((()=>{const s=e();let o=i;return o||(o=/_confirm$/.test(r)?r.substr(0,r.length-8):r+"_confirm"),s[o]===t})()),date:({value:t},e=!1)=>Promise.resolve(e?function(t){const e=`^${r=t,r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`;var r;const i={MM:"(0[1-9]|1[012])",M:"([1-9]|1[012])",DD:"([012][1-9]|3[01])",D:"([012]?[1-9]|3[01])",YYYY:"\\d{4}",YY:"\\d{2}"};return new RegExp(Object.keys(i).reduce((t,e)=>t.replace(e,i[e]),e))}(e).test(t):!isNaN(Date.parse(t))),email({value:t}){if(!t)return Promise.resolve(!0);return Promise.resolve(/^(([^<>()\[\].,;:\s@"]+(\.[^<>()\[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/i.test(t))},endsWith:({value:t},...e)=>t?"string"==typeof t?Promise.resolve(0===e.length||e.some(e=>t.endsWith(e))):Promise.resolve(!1):Promise.resolve(!0),in:({value:t},...e)=>Promise.resolve(e.some(e=>"object"==typeof e?c(e,t):e===t)),matches:({value:t},...e)=>Promise.resolve(!!e.find(e=>("string"==typeof e&&"/"===e.substr(0,1)&&"/"===e.substr(-1)&&(e=new RegExp(e.substr(1,e.length-2))),e instanceof RegExp?e.test(t):e===t))),mime({value:t},...e){if(t instanceof p){const r=t.getFiles(),i=t=>e.includes(t.type),s=r.reduce((t,{file:e})=>t&&i(e),!0);return Promise.resolve(s)}return Promise.resolve(!0)},min:({value:t},e=1,r)=>Promise.resolve(Array.isArray(t)?(e=isNaN(e)?e:Number(e),t.length>=e):!isNaN(t)&&"length"!==r||"value"===r?(t=isNaN(t)?t:Number(t))>=e:("string"==typeof t||"length"===r)&&(t=isNaN(t)?t:t.toString()).length>=e),max:({value:t},e=10,r)=>Promise.resolve(Array.isArray(t)?(e=isNaN(Number(e))?e:Number(e),t.length<=e):!isNaN(t)&&"length"!==r||"value"===r?(t=isNaN(t)?t:Number(t))<=e:("string"==typeof t||"length"===r)&&(t=isNaN(t)?t:t.toString()).length<=e),not:({value:t},...e)=>Promise.resolve(!e.some(e=>"object"==typeof e?c(e,t):e===t)),number:({value:t})=>Promise.resolve(!isNaN(Number(t))),required:({value:t},e=!0)=>Promise.resolve(!(e&&!["no","false"].includes(e))||(Array.isArray(t)?!!t.length:t instanceof p?t.getFiles().length>0:"string"==typeof t?!!t:"object"!=typeof t||!!t&&!!Object.keys(t).length)),startsWith:({value:t},...e)=>t?"string"==typeof t?Promise.resolve(0===e.length||e.some(e=>t.startsWith(e))):Promise.resolve(!1):Promise.resolve(!0),url:({value:e})=>Promise.resolve(t(e)),bail:()=>Promise.resolve(!0)},V={csv:"text/csv",gif:"image/gif",jpeg:"image/jpeg",jpg:"image/jpeg",png:"image/png",pdf:"application/pdf",svg:"image/svg+xml"};const w={default:(t,e)=>t.$t("validation.default",e),accepted:(t,e)=>t.$t("validation.accepted",e),after:(t,e)=>Array.isArray(e.args)&&e.args.length?t.$t("validation.after.compare",e):t.$t("validation.after.default",e),alpha:(t,e)=>t.$t("validation.alpha",e),alphanumeric:(t,e)=>t.$t("validation.alphanumeric",e),before:(t,e)=>Array.isArray(e.args)&&e.args.length?t.$t("validation.before.compare",e):t.$t("validation.before.default",e),between(t,e){const r=!(!Array.isArray(e.args)||!e.args[2])&&e.args[2];return!isNaN(e.value)&&"length"!==r||"value"===r?t.$t("validation.between.force",e):t.$t("validation.between.default",e)},confirm:(t,e)=>t.$t("validation.confirm",e),date:(t,e)=>Array.isArray(e.args)&&e.args.length?t.$t("validation.date.format",e):t.$t("validation.date.default",e),email:(t,e)=>t.$t("validation.email.default",e),endsWith:(t,e)=>t.$t("validation.endsWith.default",e),in:function(t,e){return"string"==typeof e.value&&e.value?t.$t("validation.in.string",e):t.$t("validation.in.default",e)},matches:(t,e)=>t.$t("validation.matches.default",e),max(t,e){const r=e.args[0];if(Array.isArray(e.value))return t.$tc("validation.max.array",r,e);const i=!(!Array.isArray(e.args)||!e.args[1])&&e.args[1];return!isNaN(e.value)&&"length"!==i||"value"===i?t.$tc("validation.max.force",r,e):t.$tc("validation.max.default",r,e)},mime:(t,e)=>e.args[0]?t.$t("validation.mime.default",e):t.$t("validation.mime.no_formats_allowed",e),min(t,e){const r=e.args[0];if(Array.isArray(e.value))return t.$tc("validation.min.array",r,e);const i=!(!Array.isArray(e.args)||!e.args[1])&&e.args[1];return!isNaN(e.value)&&"length"!==i||"value"===i?t.$tc("validation.min.force",r,e):t.$tc("validation.min.default",r,e)},not:(t,e)=>t.$t("validation.not.default",e),number:(t,e)=>t.$t("validation.number.default",e),required:(t,e)=>t.$t("validation.required.default",e),startsWith:(t,e)=>t.$t("validation.startsWith.default",e),url:(t,e)=>t.$t("validation.url.default",e)};function O(t){t.extend({validationMessages:w})}function $(t,e,r,i){return new Promise(r=>{const s=(i.fauxUploaderDuration||2e3)*(.5+Math.random()),o=performance.now(),a=()=>setTimeout(()=>{const i=performance.now()-o,n=Math.min(100,Math.round(i/s*100));if(e(n),n>=100)return r({url:"http://via.placeholder.com/350x150.png",name:t.name});a()},20);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.
***************************************************************************** */
function F(t,e){var r={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(t);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(r[i[s]]=t[i[s]])}return r}function j(t,e,r,i){var s,o=arguments.length,a=o<3?e:null===i?i=Object.getOwnPropertyDescriptor(e,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,r,i);else for(var n=t.length-1;n>=0;n--)(s=t[n])&&(a=(o<3?s(a):o>3?s(e,r,a):s(e,r))||a);return o>3&&a&&Object.defineProperty(e,r,a),a}class A{constructor(t){this.registry=new Map,this.ctx=t}add(t,e){this.registry.set(t,e)}remove(t){this.registry.delete(t);const e=this.ctx.proxy,r=t,i=(e[r],F(e,["symbol"==typeof r?r:r+""]));this.ctx.proxy=i}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())(r===t||r.includes(t+"."))&&e.set(r,this.registry.get(r));return e}map(t){const e={};return this.registry.forEach((r,i)=>Object.assign(e,{[i]:t(r,i)})),e}forEach(t){this.registry.forEach((e,r)=>{t(e,r)})}keys(){return Array.from(this.registry.keys())}register(t,e){if(this.registry.has(t))return;this.registry.set(t,e);const r=b(e.$options.propsData,"formularioValue"),i=b(e.$options.propsData,"value");!r&&this.ctx.hasInitialValue&&void 0!==E(this.ctx.initialValues,t)?e.context.model=E(this.ctx.initialValues,t):!r&&!i||c(e.proxy,E(this.ctx.initialValues,t))||this.ctx.setFieldValue(t,e.proxy),this.ctx.childrenShouldShowErrors&&(e.formShouldShowErrors=!0)}reduce(t,e){return this.registry.forEach((r,i)=>{e=t(e,r,i)}),e}}class N{constructor(t){this.form=t}hasValidationErrors(){return this.form.hasValidationErrors()}values(){return new Promise((t,e)=>{const r=this.form,i=[],s=function t(e){if("object"!=typeof e)return e;const r=Array.isArray(e)?[]:{};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(v(e[i])||e[i]instanceof p?r[i]=e[i]:r[i]=t(e[i]));return r}(r.proxy);for(const t in s)Object.prototype.hasOwnProperty.call(s,t)&&"object"==typeof r.proxy[t]&&r.proxy[t]instanceof p&&i.push(r.proxy[t].upload().then(e=>Object.assign(s,{[t]:e})));Promise.all(i).then(()=>t(s)).catch(t=>e(t))})}}let P=class extends i{constructor(){super(...arguments),this.formularioRegister=this.register,this.formularioDeregister=this.deregister,this.formularioSetter=this.setFieldValue,this.getFormValues=()=>this.proxy,this.path="",this.proxy={},this.registry=new A(this),this.childrenShouldShowErrors=!1,this.formShouldShowErrors=!1,this.errorObservers=[],this.namedErrors=[],this.namedFieldErrors={}}formularioFieldValidation(t){this.$emit("validation",t)}removeErrorObserver(t){this.errorObservers=this.errorObservers.filter(e=>e.callback!==t)}get mergedFormErrors(){return this.formErrors.concat(this.namedErrors)}get mergedFieldErrors(){const t={};if(this.errors)for(const e in this.errors)t[e]=g(this.errors[e]);for(const e in this.namedFieldErrors)t[e]=g(this.namedFieldErrors[e]);return t}get hasFormErrorObservers(){return this.errorObservers.some(t=>"form"===t.type)}get hasInitialValue(){return this.formularioValue&&"object"==typeof this.formularioValue||this.values&&"object"==typeof this.values||this.isGrouping&&"object"==typeof this.context.model[this.index]}get isVmodeled(){return!!(b(this.$options.propsData,"formularioValue")&&this._events&&Array.isArray(this._events.input)&&this._events.input.length)}get initialValues(){return b(this.$options.propsData,"formularioValue")&&"object"==typeof this.formularioValue?Object.assign({},this.formularioValue):b(this.$options.propsData,"values")&&"object"==typeof this.values?Object.assign({},this.values):this.isGrouping&&"object"==typeof this.context.model[this.index]?this.context.model[this.index]:{}}onFormularioValueChanged(t){this.isVmodeled&&t&&"object"==typeof t&&this.setValues(t)}onMergedFormErrorsChanged(t){this.errorObservers.filter(t=>"form"===t.type).forEach(e=>e.callback(t))}onMergedFieldErrorsChanged(t){this.errorObservers.filter(t=>"input"===t.type).forEach(e=>e.callback(t[e.field]||[]))}created(){this.$formulario.register(this),this.applyInitialValues()}destroyed(){this.$formulario.deregister(this)}register(t,e){this.registry.register(t,e)}deregister(t){this.registry.remove(t)}applyErrors({formErrors:t,inputErrors:e}){this.namedErrors=t,this.namedFieldErrors=e}addErrorObserver(t){this.errorObservers.find(e=>t.callback===e.callback)||(this.errorObservers.push(t),"form"===t.type?t.callback(this.mergedFormErrors):b(this.mergedFieldErrors,t.field)&&t.callback(this.mergedFieldErrors[t.field]))}registerErrorComponent(t){this.errorComponents.includes(t)||this.errorComponents.push(t)}formSubmitted(){this.showErrors();const t=new N(this);return this.$emit("submit-raw",t),t.hasValidationErrors().then(e=>e?void 0:t.values()).then(t=>{if(void 0!==t)return this.$emit("submit",t),t})}applyInitialValues(){this.hasInitialValue&&(this.proxy=this.initialValues)}setFieldValue(t,e,r=!0){if(void 0===e){const e=this.proxy,r=t,i=(e[r],F(e,["symbol"==typeof r?r:r+""]));this.proxy=i}else!function(t,e,r){const i=e.split(".");let s=t;for(let t=0;t<i.length;t++){const e=i[t],o=e.match(/(.+)\[(\d+)\]$/);if(o){if(void 0===s[o[1]]&&(s[o[1]]=[]),s=s[o[1]],t===i.length-1){s[o[2]]=r;break}s=s[o[2]]}else{if(t===i.length-1){s[e]=r;break}void 0===s[e]&&(s[e]={}),s=s[e]}}}(this.proxy,t,e);r&&this.$emit("input",Object.assign({},this.proxy))}hasValidationErrors(){return Promise.all(this.registry.reduce((t,e)=>(t.push(e.performValidation()&&e.getValidationErrors()),t),[])).then(t=>t.some(t=>t.hasErrors))}showErrors(){this.childrenShouldShowErrors=!0,this.registry.forEach(t=>{t.formShouldShowErrors=!0})}hideErrors(){this.childrenShouldShowErrors=!1,this.registry.forEach(t=>{t.formShouldShowErrors=!1,t.behavioralErrorVisibility=!1})}setValues(t){const e=Array.from(new Set(Object.keys(t).concat(Object.keys(this.proxy))));let r=!1;e.forEach(e=>{this.registry.hasNested(e)&&this.registry.getNested(e).forEach((e,i)=>{c(E(t,i),E(this.proxy,i))||(this.setFieldValue(i,E(t,i),!1),r=!0),c(E(t,i),this.registry.get(i).proxy)||(this.registry.get(i).context.model=E(t,i))})}),this.applyInitialValues(),r&&this.$emit("input",Object.assign({},this.proxy))}};function R(t,e,r,i,s,o,a,n,l,h){"boolean"!=typeof a&&(l=n,n=a,a=!1);const u="function"==typeof r?r.options:r;let d;if(t&&t.render&&(u.render=t.render,u.staticRenderFns=t.staticRenderFns,u._compiled=!0,s&&(u.functional=!0)),i&&(u._scopeId=i),o?(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(o)},u._ssrRegister=d):e&&(d=a?function(t){e.call(this,h(t,this.$root.$options.shadowRoot))}:function(t){e.call(this,n(t))}),d)if(u.functional){const t=u.render;u.render=function(e,r){return d.call(r),t(e,r)}}else{const t=u.beforeCreate;u.beforeCreate=t?[].concat(t,d):[d]}return r}j([s()],P.prototype,"formularioFieldValidation",null),j([s()],P.prototype,"formularioRegister",void 0),j([s()],P.prototype,"formularioDeregister",void 0),j([s()],P.prototype,"formularioSetter",void 0),j([s()],P.prototype,"getFormValues",void 0),j([s()],P.prototype,"path",void 0),j([s()],P.prototype,"removeErrorObserver",null),j([o("input",{type:Object,default:()=>({})})],P.prototype,"formularioValue",void 0),j([a({type:[String,Boolean],default:!1})],P.prototype,"name",void 0),j([a({type:[Object,Boolean],default:!1})],P.prototype,"values",void 0),j([a({default:!1})],P.prototype,"errors",void 0),j([a({default:()=>[]})],P.prototype,"formErrors",void 0),j([n("formularioValue",{deep:!0})],P.prototype,"onFormularioValueChanged",null),j([n("mergedFormErrors")],P.prototype,"onMergedFormErrorsChanged",null),j([n("mergedFieldErrors",{immediate:!0})],P.prototype,"onMergedFieldErrorsChanged",null),j([s()],P.prototype,"addErrorObserver",null),P=j([l({name:"FormularioForm"})],P);const S=P;var D=function(){var t=this,e=t.$createElement;return(t._self._c||e)("form",{on:{submit:function(e){return e.preventDefault(),t.formSubmitted(e)}}},[t._t("default",null,{errors:t.mergedFormErrors})],2)};D._withStripped=!0;const U=R({render:D,staticRenderFns:[]},void 0,S,void 0,!1,void 0,!1,void 0,void 0,void 0),_={BLUR:"blur",LIVE:"live",SUBMIT:"submit"};let I=class extends i{constructor(){super(...arguments),this.formularioRegisterRule=this.registerRule,this.formularioRemoveRule=this.removeRule,this.defaultId=this.$formulario.nextId(this),this.localAttributes={},this.localErrors=[],this.proxy=this.getInitialValue(),this.behavioralErrorVisibility="live"===this.errorBehavior,this.formShouldShowErrors=!1,this.validationErrors=[],this.pendingValidation=Promise.resolve(),this.ruleRegistry=[],this.messageRegistry={}}get context(){return this.defineModel({id:this.id||this.defaultId,name:this.nameOrFallback,attributes:this.elementAttributes,blurHandler:this.blurHandler.bind(this),disableErrors:this.disableErrors,errors:this.explicitErrors,allErrors:this.allErrors,formShouldShowErrors:this.formShouldShowErrors,getValidationErrors:this.getValidationErrors.bind(this),hasGivenName:this.hasGivenName,hasValidationErrors:this.hasValidationErrors.bind(this),imageBehavior:this.imageBehavior,performValidation:this.performValidation.bind(this),preventWindowDrops:this.preventWindowDrops,setErrors:this.setErrors.bind(this),showValidationErrors:this.showValidationErrors,uploadBehavior:this.uploadBehavior,uploadUrl:this.mergedUploadUrl,uploader:this.uploader||this.$formulario.getUploader(),validationErrors:this.validationErrors,value:this.value,visibleValidationErrors:this.visibleValidationErrors})}get parsedValidationRules(){const t={};return Object.keys(this.validationRules).forEach(e=>{t[f(e)]=this.validationRules[e]}),t}get messages(){const t={};return Object.keys(this.validationMessages).forEach(e=>{t[f(e)]=this.validationMessages[e]}),Object.keys(this.messageRegistry).forEach(e=>{t[f(e)]=this.messageRegistry[e]}),t}get elementAttributes(){const t=Object.assign({},this.localAttributes);return this.id?t.id=this.id:t.id=this.defaultId,this.hasGivenName&&(t.name=this.name),this.help&&(t["aria-describedby"]=t.id+"-help"),t}get nameOrFallback(){return""!==this.path?`${this.path}.${this.name}`:this.name}get hasGivenName(){return"boolean"!=typeof this.name}get mergedValidationName(){return this.validationName||this.name}get mergedUploadUrl(){return this.uploadUrl||this.$formulario.getUploadUrl()}get hasErrors(){return this.allErrors.length>0}get hasVisibleErrors(){return this.validationErrors&&this.showValidationErrors||!!this.explicitErrors.length}get allErrors(){return[...this.explicitErrors,...g(this.validationErrors)]}get visibleValidationErrors(){return this.showValidationErrors&&this.validationErrors.length?this.validationErrors:[]}get explicitErrors(){return[...g(this.errors),...this.localErrors].map(t=>({rule:null,context:null,message:t}))}get isVmodeled(){return!!(Object.prototype.hasOwnProperty.call(this.$options.propsData,"formularioValue")&&this._events&&Array.isArray(this._events.input)&&this._events.input.length)}get showValidationErrors(){return this.showErrors||this.formShouldShowErrors||this.behavioralErrorVisibility}onAttrsChanged(t){this.updateLocalAttributes(t)}onProxyChanged(t,e){this.errorBehavior===_.LIVE?this.performValidation():this.validationErrors=[],this.isVmodeled||c(t,e)||(this.context.model=t)}onFormularioValueChanged(t,e){this.isVmodeled&&!c(t,e)&&(this.context.model=t)}onShowValidationErrorsChanged(t){this.$emit("error-visibility",t)}created(){this.applyInitialValue(),this.formularioRegister&&"function"==typeof this.formularioRegister&&this.formularioRegister(this.nameOrFallback,this),this.disableErrors||"function"!=typeof this.addErrorObserver||this.addErrorObserver({callback:this.setErrors,type:"input",field:this.nameOrFallback}),this.updateLocalAttributes(this.$attrs),this.errorBehavior===_.LIVE&&this.performValidation()}beforeDestroy(){this.disableErrors||"function"!=typeof this.removeErrorObserver||this.removeErrorObserver(this.setErrors),"function"==typeof this.formularioDeregister&&this.formularioDeregister(this.nameOrFallback)}defineModel(t){return Object.defineProperty(t,"model",{get:this.modelGetter.bind(this),set:this.modelSetter.bind(this)})}modelGetter(){const t=this.isVmodeled?"formularioValue":"proxy";return void 0===this[t]?"":this[t]}modelSetter(t){c(t,this.proxy)||(this.proxy=t),this.$emit("input",t),this.context.name&&"function"==typeof this.formularioSetter&&this.formularioSetter(this.context.name,t)}blurHandler(){this.$emit("blur"),"blur"===this.errorBehavior&&(this.behavioralErrorVisibility=!0)}getInitialValue(){return b(this.$options.propsData,"value")?this.value:b(this.$options.propsData,"formularioValue")?this.formularioValue:""}applyInitialValue(){c(this.context.model,this.proxy)||(this.context.model=this.proxy)}updateLocalAttributes(t){c(t,this.localAttributes)||(this.localAttributes=t)}performValidation(){let t=y(this.validation,this.$formulario.rules(this.parsedValidationRules));return t=this.ruleRegistry.length?this.ruleRegistry.concat(t):t,this.pendingValidation=this.runRules(t).then(t=>this.didValidate(t)),this.pendingValidation}runRules(t){const e=([t,e,r])=>{let i=t({value:this.context.model,getFormValues:this.getFormValues.bind(this),name:this.context.name},...e);return i=i instanceof Promise?i:Promise.resolve(i),i.then(t=>!t&&this.getMessageObject(r,e))};return new Promise(r=>{const i=(t,s=[])=>{const o=t.shift();Array.isArray(o)&&o.length?Promise.all(o.map(e)).then(t=>t.filter(t=>!!t)).then(e=>(e=Array.isArray(e)?e:[]).length&&o.bail||!t.length?r(s.concat(e)):i(t,s.concat(e))):r([])};i(function(t){const e=[],r=t.findIndex(([,,t])=>"bail"===t.toLowerCase());if(r>=0){const i=t.splice(0,r+1).slice(0,-1);i.length&&e.push(i),t.map(t=>e.push(Object.defineProperty([t],"bail",{value:!0})))}else e.push(t);return e.reduce((t,e)=>{const r=(t,e=!1)=>{if(t.length<2)return Object.defineProperty([t],"bail",{value:e});const i=[],s=t.findIndex(([,,,t])=>"^"===t);if(s>=0){const o=t.splice(0,s);o.length&&i.push(...r(o,e)),i.push(Object.defineProperty([t.shift()],"bail",{value:!0})),t.length&&i.push(...r(t,e))}else i.push(t);return i};return t.concat(r(e))},[])}(t))})}didValidate(t){const e=!c(t,this.validationErrors);if(this.validationErrors=t,e){const t=this.getErrorObject();this.$emit("validation",t),this.formularioFieldValidation&&"function"==typeof this.formularioFieldValidation&&this.formularioFieldValidation(t)}}getMessageObject(t,e){const r={args:e,name:this.mergedValidationName,value:this.context.model,vm:this,formValues:this.getFormValues()};return{rule:t,context:r,message:this.getMessageFunc(t)(r)}}getMessageFunc(t){if(t=f(t),this.messages&&void 0!==this.messages[t])switch(typeof this.messages[t]){case"function":return this.messages[t];case"string":case"boolean":return()=>this.messages[t]}return e=>this.$formulario.validationMessage(t,e,this)}hasValidationErrors(){return new Promise(t=>{this.$nextTick(()=>{this.pendingValidation.then(()=>t(!!this.validationErrors.length))})})}getValidationErrors(){return new Promise(t=>{this.$nextTick(()=>this.pendingValidation.then(()=>t(this.getErrorObject())))})}getErrorObject(){return{name:this.context.nameOrFallback||this.context.name,errors:this.validationErrors.filter(t=>"object"==typeof t),hasErrors:!!this.validationErrors.length}}setErrors(t){this.localErrors=g(t)}registerRule(t,e,r,i=null){this.ruleRegistry.some(t=>t[2]===r)||(this.ruleRegistry.push([t,e,r]),null!==i&&(this.messageRegistry[r]=i))}removeRule(t){const e=this.ruleRegistry.findIndex(e=>e[2]===t);e>=0&&(this.ruleRegistry.splice(e,1),delete this.messageRegistry[t])}};j([h({default:void 0})],I.prototype,"formularioSetter",void 0),j([h({default:()=>()=>{}})],I.prototype,"formularioFieldValidation",void 0),j([h({default:void 0})],I.prototype,"formularioRegister",void 0),j([h({default:void 0})],I.prototype,"formularioDeregister",void 0),j([h({default:()=>()=>({})})],I.prototype,"getFormValues",void 0),j([h({default:void 0})],I.prototype,"addErrorObserver",void 0),j([h({default:void 0})],I.prototype,"removeErrorObserver",void 0),j([h({default:""})],I.prototype,"path",void 0),j([s()],I.prototype,"formularioRegisterRule",void 0),j([s()],I.prototype,"formularioRemoveRule",void 0),j([o("input",{default:""})],I.prototype,"formularioValue",void 0),j([a({type:[String,Number,Boolean],default:!1})],I.prototype,"id",void 0),j([a({default:"text"})],I.prototype,"type",void 0),j([a({required:!0})],I.prototype,"name",void 0),j([a({default:!1})],I.prototype,"value",void 0),j([a({type:[String,Boolean,Array],default:!1})],I.prototype,"validation",void 0),j([a({type:[String,Boolean],default:!1})],I.prototype,"validationName",void 0),j([a({type:Object,default:()=>({})})],I.prototype,"validationRules",void 0),j([a({type:Object,default:()=>({})})],I.prototype,"validationMessages",void 0),j([a({type:[Array,String,Boolean],default:!1})],I.prototype,"errors",void 0),j([a({type:String,default:_.BLUR,validator:t=>[_.BLUR,_.LIVE,_.SUBMIT].includes(t)})],I.prototype,"errorBehavior",void 0),j([a({default:!1})],I.prototype,"showErrors",void 0),j([a({default:!1})],I.prototype,"disableErrors",void 0),j([a({default:!0})],I.prototype,"preventWindowDrops",void 0),j([a({default:"preview"})],I.prototype,"imageBehavior",void 0),j([a({default:!1})],I.prototype,"uploader",void 0),j([a({default:!1})],I.prototype,"uploadUrl",void 0),j([a({default:"live"})],I.prototype,"uploadBehavior",void 0),j([n("$attrs",{deep:!0})],I.prototype,"onAttrsChanged",null),j([n("proxy")],I.prototype,"onProxyChanged",null),j([n("formularioValue")],I.prototype,"onFormularioValueChanged",null),j([n("showValidationErrors",{immediate:!0})],I.prototype,"onShowValidationErrorsChanged",null),I=j([l({name:"FormularioInput",inheritAttrs:!1})],I);const k=I;var C=function(){var t=this,e=t.$createElement;return(t._self._c||e)("div",{staticClass:"formulario-input",attrs:{"data-has-errors":t.hasErrors,"data-is-showing-errors":t.hasVisibleErrors,"data-type":t.type}},[t._t("default",null,{id:t.id,context:t.context,errors:t.errors,validationErrors:t.validationErrors})],2)};C._withStripped=!0;const M=R({render:C,staticRenderFns:[]},void 0,k,void 0,!1,void 0,!1,void 0,void 0,void 0);let L=class extends i{get groupPath(){return this.isArrayItem?`${this.path}[${this.name}]`:""===this.path?this.name:`${this.path}.${this.name}`}};j([h({default:""})],L.prototype,"path",void 0),j([a({required:!0})],L.prototype,"name",void 0),j([a({default:!1})],L.prototype,"isArrayItem",void 0),j([s("path")],L.prototype,"groupPath",null),L=j([l({name:"FormularioGrouping"})],L);const B=L;var T=function(){var t=this.$createElement;return(this._self._c||t)("div",{staticClass:"formulario-group",attrs:{"data-type":"group"}},[this._t("default")],2)};T._withStripped=!0;const W=R({render:T,staticRenderFns:[]},void 0,B,void 0,!1,void 0,!1,void 0,void 0,void 0);var G=new class{constructor(){this.options={},this.defaults={components:{FormularioForm:U,FormularioInput:M,FormularioGrouping:W},library:d,rules:x,mimes:V,locale:!1,uploader:$,uploadUrl:!1,fileUrlKey:"url",uploadJustCompleteDuration:1e3,errorHandler:t=>t,plugins:[O],validationMessages:{},idPrefix:"formulario-"},this.registry=new Map,this.idRegistry={}}install(t,e){t.prototype.$formulario=this,this.options=this.defaults;let r=this.defaults.plugins;e&&Array.isArray(e.plugins)&&e.plugins.length&&(r=r.concat(e.plugins)),r.forEach(t=>"function"==typeof t?t(this):null),this.extend(e||{});for(const e in this.options.components)Object.prototype.hasOwnProperty.call(this.options.components,e)&&t.component(e,this.options.components[e])}nextId(t){const e=this.options,r=!(!t.$route||!t.$route.path)&&t.$route.path?t.$route.path.replace(/[/\\.\s]/g,"-"):"global";return b(this.idRegistry,r)||(this.idRegistry[r]=0),`${e.idPrefix}${r}-${++this.idRegistry[r]}`}extend(t){if("object"==typeof t)return this.options=function t(e,i,s=!0){const o={};for(const a in e)b(i,a)?r(i[a])&&r(e[a])?o[a]=t(e[a],i[a],s):s&&Array.isArray(e[a])&&Array.isArray(i[a])?o[a]=e[a].concat(i[a]):o[a]=i[a]:o[a]=e[a];for(const t in i)b(o,t)||(o[t]=i[t]);return o}(this.options,t),this;throw new Error(`VueFormulario extend() should be passed an object (was ${typeof t})`)}rules(t={}){return Object.assign(Object.assign({},this.options.rules),t)}validationMessage(t,e,r){return b(this.options.validationMessages,t)?this.options.validationMessages[t](r,e):this.options.validationMessages.default(r,e)}register(t){"FormularioForm"===t.$options.name&&t.name&&this.registry.set(t.name,t)}deregister(t){"FormularioForm"===t.$options.name&&t.name&&this.registry.has(t.name)&&this.registry.delete(t.name)}handle(t,e,r=!1){const i=r?t:this.options.errorHandler(t,e);if(e&&this.registry.has(e)){this.registry.get(e).applyErrors({formErrors:g(i.formErrors),inputErrors:i.inputErrors||{}})}return i}reset(t,e={}){this.resetValidation(t),this.setValues(t,e)}resetValidation(t){const e=this.registry.get(t);e.hideErrors(t),e.namedErrors=[],e.namedFieldErrors={}}setValues(t,e){if(e){this.registry.get(t).setValues(Object.assign({},e))}}getUploader(){return this.options.uploader||!1}getUploadUrl(){return this.options.uploadUrl||!1}getFileUrlKey(){return this.options.fileUrlKey||"url"}createUpload(t,e){return new p(t,e,this.options)}};export default G;