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