easy-forms-core 1.2.12 → 1.2.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/easy-form.d.ts +49 -0
- package/dist/easy-form.js +4 -4
- package/dist/easy-form.js.map +1 -1
- package/dist/index.d.ts +50 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -421,6 +421,23 @@ interface FormSchema {
|
|
|
421
421
|
};
|
|
422
422
|
/** Dirección del layout: vertical (default) u horizontal */
|
|
423
423
|
direction?: 'vertical' | 'horizontal';
|
|
424
|
+
/** Configuración de persistencia/autosave del formulario */
|
|
425
|
+
persistence?: PersistenceConfig;
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* Configuración de persistencia del formulario
|
|
429
|
+
*/
|
|
430
|
+
interface PersistenceConfig {
|
|
431
|
+
/** Habilitar persistencia */
|
|
432
|
+
enabled?: boolean;
|
|
433
|
+
/** Clave para localStorage */
|
|
434
|
+
key: string;
|
|
435
|
+
/** Intervalo de autosave en ms (default: 1000) */
|
|
436
|
+
autoSave?: boolean;
|
|
437
|
+
/** Debounce para guardar en ms (default: 500) */
|
|
438
|
+
debounce?: number;
|
|
439
|
+
/** Callback cuando se restauran datos */
|
|
440
|
+
onRestore?: (values: Record<string, any>) => void;
|
|
424
441
|
}
|
|
425
442
|
/**
|
|
426
443
|
* Estado del formulario
|
|
@@ -508,6 +525,10 @@ declare class EasyForm extends BrowserHTMLElement {
|
|
|
508
525
|
*/
|
|
509
526
|
private slotTemplates;
|
|
510
527
|
private skipPreserveValuesOnNextRender;
|
|
528
|
+
private persistenceConfig;
|
|
529
|
+
private persistenceDebounceTimer;
|
|
530
|
+
private pendingRestoreValues;
|
|
531
|
+
private isRestoringValues;
|
|
511
532
|
static get observedAttributes(): string[];
|
|
512
533
|
constructor();
|
|
513
534
|
/**
|
|
@@ -799,6 +820,34 @@ declare class EasyForm extends BrowserHTMLElement {
|
|
|
799
820
|
* Configura estilos básicos
|
|
800
821
|
*/
|
|
801
822
|
private setupStyles;
|
|
823
|
+
/**
|
|
824
|
+
* Inicializa la persistencia del formulario
|
|
825
|
+
*/
|
|
826
|
+
private initPersistence;
|
|
827
|
+
/**
|
|
828
|
+
* Restaura los valores desde localStorage
|
|
829
|
+
*/
|
|
830
|
+
private restoreFromStorage;
|
|
831
|
+
/**
|
|
832
|
+
* Aplica los valores pendientes de restauración después del render
|
|
833
|
+
*/
|
|
834
|
+
private applyPendingRestoreValues;
|
|
835
|
+
/**
|
|
836
|
+
* Actualiza los valores de los inputs del DOM
|
|
837
|
+
*/
|
|
838
|
+
private updateInputsWithValues;
|
|
839
|
+
/**
|
|
840
|
+
* Guarda los valores en localStorage
|
|
841
|
+
*/
|
|
842
|
+
private saveToStorage;
|
|
843
|
+
/**
|
|
844
|
+
* Programa un guardado debounced
|
|
845
|
+
*/
|
|
846
|
+
private scheduleSave;
|
|
847
|
+
/**
|
|
848
|
+
* Limpia los datos de persistencia
|
|
849
|
+
*/
|
|
850
|
+
private clearPersistence;
|
|
802
851
|
}
|
|
803
852
|
|
|
804
853
|
/**
|
|
@@ -1299,4 +1348,4 @@ declare function getAvailableTemplates(): TemplateName[];
|
|
|
1299
1348
|
*/
|
|
1300
1349
|
declare function extendTemplate(templateName: string, additionalFields: Field[]): FormSchema;
|
|
1301
1350
|
|
|
1302
|
-
export { type AccordionSelectField, type ArrayField, AttemptsLock, type AttemptsLockOptions, type BaseField, type BaseValidation, type ChangeEventDetail, type CheckboxField, type ColorpickerField, type ComponentRegistry, ConditionEngine, type ConditionOperator, type CustomComponent, type CustomField, type CustomMask, type CustomValidation, type DateField, EasyForm, type EmailValidation, type ErrorEventDetail, type Field, type FieldCondition, type FieldDependencies, type FieldType, type FileDropField, type FileField, type FormColors, type FormSchema, type FormState, type FormTheme, type GroupField, INJECTION_VALIDATION_MESSAGE, type ImageGridSelectField, type LabelPosition, type MapField, type MaskConfig, MaskEngine, type MaxLengthValidation, type MaxValidation, type MinLengthValidation, type MinValidation, type NoInjectionValidation, type NumberField, type OTPField, PREDEFINED_MASKS, type PasswordField, type PatternValidation, type PredefinedMask, type QuantityField, type RadioField, type RatingField, type RequiredValidation, type RowField, SchemaParser, type SelectField, type SliderField, type SlotContent, StateManager, type Step, type StepChangeEventDetail, type SubmitButtonConfig, type SubmitEventDetail, type SwitchField, type TemplateName, type TextField, type TextareaField, type Validation, ValidationEngine, type ValidationType, type WizardState, attributeValue, containsInjection, createInput, extendTemplate, generateId, getAvailableTemplates, getColors, getCustomComponent, getNestedValue, getPredefinedMask, getTemplate, getThemeStyles, isSafeFromInjection, isValidEmail, parseAttributeValue, registerComponent, registerComponents, sanitizeId, setNestedValue, templates };
|
|
1351
|
+
export { type AccordionSelectField, type ArrayField, AttemptsLock, type AttemptsLockOptions, type BaseField, type BaseValidation, type ChangeEventDetail, type CheckboxField, type ColorpickerField, type ComponentRegistry, ConditionEngine, type ConditionOperator, type CustomComponent, type CustomField, type CustomMask, type CustomValidation, type DateField, EasyForm, type EmailValidation, type ErrorEventDetail, type Field, type FieldCondition, type FieldDependencies, type FieldType, type FileDropField, type FileField, type FormColors, type FormSchema, type FormState, type FormTheme, type GroupField, INJECTION_VALIDATION_MESSAGE, type ImageGridSelectField, type LabelPosition, type MapField, type MaskConfig, MaskEngine, type MaxLengthValidation, type MaxValidation, type MinLengthValidation, type MinValidation, type NoInjectionValidation, type NumberField, type OTPField, PREDEFINED_MASKS, type PasswordField, type PatternValidation, type PersistenceConfig, type PredefinedMask, type QuantityField, type RadioField, type RatingField, type RequiredValidation, type RowField, SchemaParser, type SelectField, type SliderField, type SlotContent, StateManager, type Step, type StepChangeEventDetail, type SubmitButtonConfig, type SubmitEventDetail, type SwitchField, type TemplateName, type TextField, type TextareaField, type Validation, ValidationEngine, type ValidationType, type WizardState, attributeValue, containsInjection, createInput, extendTemplate, generateId, getAvailableTemplates, getColors, getCustomComponent, getNestedValue, getPredefinedMask, getTemplate, getThemeStyles, isSafeFromInjection, isValidEmail, parseAttributeValue, registerComponent, registerComponents, sanitizeId, setNestedValue, templates };
|
package/dist/index.js
CHANGED
|
@@ -2172,5 +2172,5 @@ var I=class{parse(t){if(!t)throw new Error("Schema es requerido");if(!t.fields&&
|
|
|
2172
2172
|
En tu app: <code>import 'leaflet'</code> y <code>import 'leaflet/dist/leaflet.css'</code><br>
|
|
2173
2173
|
<a href="https://easyforms.dev/docs/tipos-campos#map" target="_blank" rel="noopener" style="color:var(--easy-form-primary,#007bff);">Ver documentaci\xF3n</a>
|
|
2174
2174
|
</div>
|
|
2175
|
-
`;return}delete E.Icon.Default.prototype._getIconUrl,E.Icon.Default.mergeOptions({iconRetinaUrl:"https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png",iconUrl:"https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png",shadowUrl:"https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png"}),this.mapInstance=E.map(u,{preferCanvas:!1,zoomControl:!0}).setView([s,i],r);let v=E.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",{attribution:'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',maxZoom:19}).addTo(this.mapInstance);this.mapInstance.invalidateSize(),v.on("load",()=>{this.mapInstance&&this.mapInstance.invalidateSize()});let C=()=>{this.mapInstance&&this.mapInstance.invalidateSize()};setTimeout(C,100),setTimeout(C,300),setTimeout(C,500),new IntersectionObserver(x=>{x.forEach(w=>{w.isIntersecting&&this.mapInstance&&setTimeout(()=>{this.mapInstance?.invalidateSize()},100)})}).observe(u),this.markerInstance=E.marker([s,i],{draggable:!0}).addTo(this.mapInstance).on("dragend",()=>{let x=this.markerInstance.getLatLng();d.value=String(Number(x.lat.toFixed(6))),m.value=String(Number(x.lng.toFixed(6))),this.onChange({lat:x.lat,lng:x.lng}),this.onBlur()}),this.mapInstance.on("click",x=>{let{lat:w,lng:S}=x.latlng;this.markerInstance.setLatLng([w,S]),d.value=String(Number(w.toFixed(6))),m.value=String(Number(S.toFixed(6))),this.onChange({lat:w,lng:S}),this.onBlur()})})(),this.createFieldContainer(n)}syncMarkerPosition(e,a){this.mapInstance&&this.markerInstance&&(this.markerInstance.setLatLng([e,a]),this.mapInstance.setView([e,a]),setTimeout(()=>{this.mapInstance?.invalidateSize()},50))}};var De=c=>`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="${c?"currentColor":"none"}" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" role="img" aria-hidden="true"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>`,se=class extends y{render(){let t=this.field,e=t.max??5,a=t.half??!1,r=this.value!=null?Number(this.value):0,o=document.createElement("div");o.className="easy-form-rating",o.setAttribute("role","slider"),o.setAttribute("aria-valuemin","0"),o.setAttribute("aria-valuemax",String(e)),o.setAttribute("aria-valuenow",String(r)),o.setAttribute("aria-label",this.field.label||"Rating"),o.setAttribute("tabindex","0");let s=document.createElement("div");s.className="easy-form-rating-stars";for(let i=1;i<=e;i++){let n=document.createElement("button");n.type="button";let l=r>=i||a&&r>=i-.5;n.className=l?"easy-form-rating-star easy-form-rating-star-filled":"easy-form-rating-star",n.innerHTML=De(l),n.setAttribute("aria-label",`${i} de ${e}`),n.addEventListener("click",d=>{d.preventDefault();let m=d.target.closest("button")?.getBoundingClientRect(),p=i;if(a&&m){let u=m.left+m.width/2;p=d.clientX<u?i-.5:i}this.onChange(p),this.onBlur(),this.rerenderStars(o,e,p,a),o.setAttribute("aria-valuenow",String(p))}),s.appendChild(n)}return o.appendChild(s),o.addEventListener("keydown",i=>{let n=Number(o.getAttribute("aria-valuenow"))||0,l=n;i.key==="ArrowRight"||i.key==="ArrowUp"?(i.preventDefault(),l=Math.min(e,a?n+.5:n+1),this.onChange(l)):(i.key==="ArrowLeft"||i.key==="ArrowDown")&&(i.preventDefault(),l=Math.max(0,a?n-.5:n-1),this.onChange(l)),l!==n&&(this.rerenderStars(o,e,l,a),o.setAttribute("aria-valuenow",String(l)))}),this.createFieldContainer(o)}rerenderStars(t,e,a,r){t.querySelectorAll(".easy-form-rating-star").forEach((s,i)=>{let n=i+1,l=a>=n||r&&a>=n-.5;s.className=l?"easy-form-rating-star easy-form-rating-star-filled":"easy-form-rating-star",s.innerHTML=De(l)})}};var ie=class extends y{render(){let t=this.field,e=t.min??0,a=t.max??100,r=t.step??1,o=t.showValue??!1,s=document.createElement("input");s.type="range",s.min=String(e),s.max=String(a),s.step=String(r),s.value=this.value!=null?String(this.value):String(e),s.setAttribute("aria-valuemin",String(e)),s.setAttribute("aria-valuemax",String(a)),s.setAttribute("aria-valuenow",s.value),this.applyCommonProps(s),s.addEventListener("input",n=>{let l=n.target,d=r>=1?parseInt(l.value,10):parseFloat(l.value);this.onChange(isNaN(d)?e:d),i&&(i.textContent=l.value),s.setAttribute("aria-valuenow",l.value)}),s.addEventListener("change",()=>{this.onBlur()});let i=null;if(o){i=document.createElement("span"),i.className="easy-form-slider-value",i.textContent=s.value;let n=document.createElement("div");return n.className="easy-form-slider-wrapper",n.appendChild(s),n.appendChild(i),this.createFieldContainer(n)}return this.createFieldContainer(s)}};var Ue=/^#?([0-9A-Fa-f]{6})$/;function ge(c){let t=c.match(Ue);return t?`#${t[1].toLowerCase()}`:/^[0-9A-Fa-f]{6}$/.test(c)?`#${c.toLowerCase()}`:"#000000"}var ne=class extends y{render(){let e=this.field.defaultValue??"#000000",a=this.value!=null&&typeof this.value=="string"?ge(this.value):e,r=document.createElement("div");r.className="easy-form-color-wrapper";let o=document.createElement("input");o.type="color",o.value=a,o.setAttribute("value",a),o.setAttribute("aria-label",this.field.label||"Color"),o.id=`${this.getFieldId()}-picker`,this.field.disabled&&o.setAttribute("disabled","true");let s=document.createElement("input");s.type="text",s.value=a,s.setAttribute("aria-label",`${this.field.label||"Color"} (hex)`),s.placeholder="#000000",s.className="easy-form-color-text",this.applyCommonProps(s);let i=()=>{let l=o.value||"#000000",d=ge(l);s.value=d,this.onChange(d)},n=()=>{let l=s.value.trim(),d=l.startsWith("#")?l:`#${l}`;if(/^#[0-9A-Fa-f]{6}$/.test(d)){let m=ge(d);o.value=m,this.onChange(m)}};return o.addEventListener("input",i),o.addEventListener("change",()=>{i(),this.onBlur()}),s.addEventListener("input",n),s.addEventListener("blur",()=>{n(),this.onBlur()}),r.appendChild(o),r.appendChild(s),this.createFieldContainer(r)}};function ye(c,t,e,a,r){switch(c.type){case"text":case"email":return new O(c,t,e,a,r).render();case"password":return new re(c,t,e,a,r).render();case"number":return new j(c,t,e,a,r).render();case"textarea":return new W(c,t,e,a,r).render();case"select":return new _(c,t,e,a,r).render();case"checkbox":return new Y(c,t,e,a,r).render();case"radio":return new U(c,t,e,a,r).render();case"switch":return new G(c,t,e,a,r).render();case"date":return new K(c,t,e,a,r).render();case"file":return new Z(c,t,e,a,r).render();case"file-drop":return new ae(c,t,e,a,r).render();case"map":return new oe(c,t,e,a,r).render();case"rating":return new se(c,t,e,a,r).render();case"slider":return new ie(c,t,e,a,r).render();case"colorpicker":return new ne(c,t,e,a,r).render();case"quantity":return new J(c,t,e,a,r).render();case"accordion-select":return new X(c,t,e,a,r).render();case"image-grid-select":return new Q(c,t,e,a,r).render();case"otp":return new ee(c,t,e,a,r).render();default:let o=document.createElement("div");return o.textContent=`Tipo de campo no soportado: ${c.type}`,o}}var He=new Map;function $e(c,t){He.set(c,t)}function be(c){for(let[t,e]of Object.entries(c))$e(t,e)}function le(c){return He.get(c)}var Ge={fields:[{type:"email",name:"email",label:"Email",placeholder:"Enter your email",validations:[{type:"required",message:"Email is required"},{type:"email",message:"Please enter a valid email"}]},{type:"password",name:"password",label:"Password",placeholder:"Enter your password",validations:[{type:"required",message:"Password is required"},{type:"minLength",value:6,message:"Password must be at least 6 characters"}]},{type:"checkbox",name:"rememberMe",label:"Remember me",defaultValue:!1}]},Ke={fields:[{type:"text",name:"name",label:"Full Name",placeholder:"Enter your full name",validations:[{type:"required",message:"Name is required"},{type:"minLength",value:2,message:"Name must be at least 2 characters"}]},{type:"email",name:"email",label:"Email",placeholder:"Enter your email",validations:[{type:"required",message:"Email is required"},{type:"email",message:"Please enter a valid email"}]},{type:"password",name:"password",label:"Password",placeholder:"Create a password",validations:[{type:"required",message:"Password is required"},{type:"minLength",value:8,message:"Password must be at least 8 characters"}]},{type:"password",name:"confirmPassword",label:"Confirm Password",placeholder:"Confirm your password",validations:[{type:"required",message:"Please confirm your password"},{type:"custom",validator:c=>typeof c=="string"&&c.length>=8,message:"Password must be at least 8 characters"}]}]},Ze={fields:[{type:"otp",name:"code",label:"Verification Code",validations:[{type:"required",message:"Verification code is required"}]}]},Je={fields:[{type:"text",name:"name",label:"Name",placeholder:"Enter your name",validations:[{type:"required",message:"Name is required"}]},{type:"email",name:"email",label:"Email",placeholder:"Enter your email",validations:[{type:"required",message:"Email is required"},{type:"email",message:"Please enter a valid email"}]},{type:"text",name:"subject",label:"Subject",placeholder:"Enter the subject",validations:[{type:"required",message:"Subject is required"}]},{type:"textarea",name:"message",label:"Message",placeholder:"Enter your message",rows:5,validations:[{type:"required",message:"Message is required"},{type:"minLength",value:10,message:"Message must be at least 10 characters"}]}]},Xe={fields:[{type:"email",name:"email",label:"Email",placeholder:"Enter your email address",validations:[{type:"required",message:"Email is required"},{type:"email",message:"Please enter a valid email"}]}]},Qe={fields:[{type:"password",name:"currentPassword",label:"Current Password",placeholder:"Enter your current password",validations:[{type:"required",message:"Current password is required"}]},{type:"password",name:"newPassword",label:"New Password",placeholder:"Enter your new password",validations:[{type:"required",message:"New password is required"},{type:"minLength",value:8,message:"Password must be at least 8 characters"}]},{type:"password",name:"confirmPassword",label:"Confirm New Password",placeholder:"Confirm your new password",validations:[{type:"required",message:"Please confirm your new password"},{type:"custom",validator:c=>typeof c=="string"&&c.length>=8,message:"Password must be at least 8 characters"}]}]},et={fields:[{type:"text",name:"name",label:"Full Name",placeholder:"Enter your full name",validations:[{type:"required",message:"Name is required"}]},{type:"email",name:"email",label:"Email",placeholder:"Enter your email",validations:[{type:"required",message:"Email is required"},{type:"email",message:"Please enter a valid email"}]},{type:"text",name:"phone",label:"Phone",placeholder:"Enter your phone number",mask:{type:"phone"}},{type:"textarea",name:"bio",label:"Bio",placeholder:"Tell us about yourself",rows:4},{type:"file",name:"avatar",label:"Profile Picture",accept:"image/*"}]},tt={fields:[{type:"group",name:"billingAddress",label:"Billing Address",fields:[{type:"text",name:"street",label:"Street Address",placeholder:"Enter street address",validations:[{type:"required",message:"Street address is required"}]},{type:"row",name:"cityState",fields:[{type:"text",name:"city",label:"City",placeholder:"City",validations:[{type:"required",message:"City is required"}]},{type:"text",name:"state",label:"State",placeholder:"State",validations:[{type:"required",message:"State is required"}]}]},{type:"text",name:"zipCode",label:"ZIP Code",placeholder:"ZIP Code",validations:[{type:"required",message:"ZIP code is required"}]}]},{type:"select",name:"paymentMethod",label:"Payment Method",options:[{label:"Credit Card",value:"credit-card"},{label:"Debit Card",value:"debit-card"},{label:"PayPal",value:"paypal"},{label:"Bank Transfer",value:"bank-transfer"}],validations:[{type:"required",message:"Payment method is required"}]},{type:"select",name:"shipping",label:"Shipping Method",options:[{label:"Standard (5-7 days)",value:"standard"},{label:"Express (2-3 days)",value:"express"},{label:"Overnight",value:"overnight"}],validations:[{type:"required",message:"Shipping method is required"}]}]},rt={fields:[{type:"select",name:"rating",label:"Rating",options:[{label:"1 - Poor",value:1},{label:"2 - Fair",value:2},{label:"3 - Good",value:3},{label:"4 - Very Good",value:4},{label:"5 - Excellent",value:5}],validations:[{type:"required",message:"Rating is required"}]},{type:"textarea",name:"comment",label:"Comment",placeholder:"Share your feedback",rows:5,validations:[{type:"required",message:"Comment is required"}]},{type:"email",name:"email",label:"Email (optional)",placeholder:"Enter your email if you want a response"}]},at={fields:[{type:"email",name:"email",label:"Email",placeholder:"Enter your email",validations:[{type:"required",message:"Email is required"},{type:"email",message:"Please enter a valid email"}]},{type:"checkbox",name:"weeklyNewsletter",label:"Weekly Newsletter",defaultValue:!0},{type:"checkbox",name:"productUpdates",label:"Product Updates",defaultValue:!1},{type:"checkbox",name:"promotions",label:"Promotions and Special Offers",defaultValue:!1}]},ot={fields:[{type:"date",name:"date",label:"Date",validations:[{type:"required",message:"Date is required"}]},{type:"text",name:"time",label:"Time",placeholder:"HH:MM",mask:{type:"time"},validations:[{type:"required",message:"Time is required"}]},{type:"number",name:"guests",label:"Number of Guests",placeholder:"Enter number of guests",min:1,max:20,validations:[{type:"required",message:"Number of guests is required"},{type:"min",value:1,message:"At least 1 guest is required"}]},{type:"textarea",name:"specialRequests",label:"Special Requests",placeholder:"Any special requests or dietary restrictions?",rows:4}]},st={fields:[{type:"select",name:"rating",label:"Rating",options:[{label:"1 Star",value:1},{label:"2 Stars",value:2},{label:"3 Stars",value:3},{label:"4 Stars",value:4},{label:"5 Stars",value:5}],validations:[{type:"required",message:"Rating is required"}]},{type:"text",name:"title",label:"Review Title",placeholder:"Give your review a title",validations:[{type:"required",message:"Review title is required"},{type:"minLength",value:5,message:"Title must be at least 5 characters"}]},{type:"textarea",name:"comment",label:"Your Review",placeholder:"Share your experience",rows:6,validations:[{type:"required",message:"Review comment is required"},{type:"minLength",value:20,message:"Review must be at least 20 characters"}]}]},de={login:Ge,register:Ke,otp:Ze,contact:Je,"password-reset":Xe,"password-change":Qe,profile:et,checkout:tt,feedback:rt,subscription:at,booking:ot,review:st};function me(c){return c in de?de[c]:null}function it(){return Object.keys(de)}function ve(c,t){let e=me(c);if(!e)throw new Error(`Template "${c}" not found`);let a=e.fields||[],r=e.steps;if(r&&r.length>0){let o=r[r.length-1];return{...e,steps:[...r.slice(0,-1),{...o,fields:[...o.fields,...t]}]}}return{...e,fields:[...a,...t]}}var nt=typeof HTMLElement<"u"?HTMLElement:class{},ce=class extends nt{constructor(){if(typeof HTMLElement>"u")throw new Error("EasyForm can only be used in a browser environment");super();this.customComponents={};this.isRendering=!1;this.attemptsLock=null;this.lockCountdownInterval=null;this.slotTemplates=null;this.skipPreserveValuesOnNextRender=!1;this.dependencyRenderTimeout=null;this.stateManager=new P,this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["schema","template","template-extend","theme","colors","initialData","loading","disabled","max-attempts","block-duration-minutes","attempts-storage-key","submit-button","label-position","show-completed-indicator","form-direction"]}get schema(){let e=this.getAttribute("schema");return e?this.getAttribute("template")?(console.warn('EasyForm: Cannot use both "schema" and "template" attributes. "template" will be ignored.'),F(e)):F(e):null}set schema(e){e&&this.getAttribute("template")&&(console.warn('EasyForm: Setting "schema" will remove "template" attribute.'),this.removeAttribute("template"),this.removeAttribute("template-extend")),e?this.setAttribute("schema",A(e)):this.removeAttribute("schema")}get template(){let e=this.getAttribute("template");return e?(this.getAttribute("schema")&&console.warn('EasyForm: Cannot use both "template" and "schema" attributes. "schema" will be ignored.'),e):null}set template(e){e&&this.getAttribute("schema")&&(console.warn('EasyForm: Setting "template" will remove "schema" attribute.'),this.removeAttribute("schema")),e?this.setAttribute("template",e):(this.removeAttribute("template"),this.removeAttribute("template-extend"))}get templateExtend(){let e=this.getAttribute("template-extend");return e?F(e):null}set templateExtend(e){e?this.setAttribute("template-extend",A(e)):this.removeAttribute("template-extend")}get maxAttempts(){let e=this.getAttribute("max-attempts");if(!e)return null;let a=parseInt(e,10);return isNaN(a)?null:a}set maxAttempts(e){e!=null&&e>=1?this.setAttribute("max-attempts",String(e)):this.removeAttribute("max-attempts")}get blockDurationMinutes(){let e=this.getAttribute("block-duration-minutes");if(!e)return null;let a=parseInt(e,10);return isNaN(a)?null:a}set blockDurationMinutes(e){e!=null&&e>=1?this.setAttribute("block-duration-minutes",String(e)):this.removeAttribute("block-duration-minutes")}get attemptsStorageKey(){return this.getAttribute("attempts-storage-key")}set attemptsStorageKey(e){e?this.setAttribute("attempts-storage-key",e):this.removeAttribute("attempts-storage-key")}get submitButton(){let e=this.getAttribute("submit-button");if(e)try{return F(e)}catch{return null}return null}set submitButton(e){e&&typeof e=="object"?this.setAttribute("submit-button",A(e)):this.removeAttribute("submit-button")}getSubmitButtonConfig(e){let a=this.submitButton,o={...e?.submitButton,...a};return{visible:o.visible??!0,text:o.text??"Enviar",width:o.width??"auto",align:o.align??"left"}}connectedCallback(){this.setupAttemptsLock(),this.setupStyles(),this.render()}attributeChangedCallback(e,a,r){if(e==="schema"&&r!==a&&(this.getAttribute("template")&&(console.warn('EasyForm: "schema" and "template" cannot be used together. Removing "template".'),this.removeAttribute("template"),this.removeAttribute("template-extend")),this.handleSchemaChange()),e==="template"&&r!==a&&(this.getAttribute("schema")&&(console.warn('EasyForm: "template" and "schema" cannot be used together. Removing "schema".'),this.removeAttribute("schema")),this.handleSchemaChange()),e==="template-extend"&&r!==a&&this.handleSchemaChange(),e==="initialData"&&r!==a&&this.handleSchemaChange(),(e==="theme"||e==="colors")&&r!==a&&this.setupStyles(),e==="loading"&&r!==a){let o=this.shadow.querySelector("form");this.updateLoadingOverlay(o||void 0),o&&o.querySelectorAll("input, textarea, select, button").forEach(i=>{i instanceof HTMLElement&&"disabled"in i&&(i.disabled=this.loading)})}e==="disabled"&&r!==a&&this.render(),(e==="label-position"||e==="form-direction"||e==="show-completed-indicator")&&r!==a&&this.render(),(e==="max-attempts"||e==="block-duration-minutes"||e==="attempts-storage-key")&&r!==a&&(this.setupAttemptsLock(),this.updateLockOverlay()),e==="submit-button"&&r!==a&&this.render()}setupAttemptsLock(){let e=this.maxAttempts;if(e==null||e<1){this.attemptsLock=null;return}this.attemptsLock=new V({maxAttempts:e,blockDurationMinutes:this.blockDurationMinutes??5,storageKey:this.attemptsStorageKey??void 0,onLocked:()=>{this.updateLockOverlay()},onUnlocked:()=>{this.stopLockCountdown(),this.updateLockOverlay(),this.render()}})}handleSchemaChange(){let e=null,a=this.template;if(a?e=this.getSchemaFromTemplate(a):e=this.schema,e){let r=this.initialData;this.stateManager.initializeSchema(e,r||void 0),this.render()}}getSchemaFromTemplate(e){let a=me(e);if(!a)return console.error(`EasyForm: Template "${e}" not found`),null;let r=this.templateExtend;return r&&r.length>0?ve(e,r):a}async render(){if(!this.isRendering){this.isRendering=!0;try{let e=null,a=this.template;if(a?e=this.getSchemaFromTemplate(a):e=this.schema,!e){let k=this.shadow.querySelector("form");k&&k.parentNode===this.shadow&&k.remove();return}let r=this.skipPreserveValuesOnNextRender,o=r?{}:this.preserveCurrentValues();this.skipPreserveValuesOnNextRender=!1;let s=this.stateManager.getWizardState();if(o&&Object.keys(o).length>0)for(let[k,x]of Object.entries(o))this.stateManager.setValueWithoutValidation(k,x);let i=this.initialData,n=s!==null,l=e.steps&&e.steps.length>0;if(!r&&(!s||!n||!l||s&&e.steps&&s.totalSteps!==e.steps.length)&&(this.stateManager.initializeSchema(e,i||void 0),n&&l&&s)){let k=this.stateManager.getWizardState();if(k&&s.totalSteps===k.totalSteps){s.currentStep>=0&&s.currentStep<k.totalSteps&&this.stateManager.goToStep(s.currentStep);for(let x of s.completedSteps)x>=0&&x<k.totalSteps&&this.stateManager.completeStep(x)}}let m=this.stateManager.getWizardState(),p=document.createElement("form");p.addEventListener("submit",k=>this.handleSubmit(k)),(this.disabled||this.loading)&&p.classList.add("easy-form-disabled");let u=this.getAttribute("form-direction"),h=e.direction??(u==="vertical"||u==="horizontal"?u:"vertical");p.classList.add(`easy-form-direction-${h}`);let g=this.getAttribute("show-completed-indicator"),f=e.completedIndicator??(g!==null&&g!=="false"),b=typeof f=="object"&&f?.position?f.position:"top";if(m)this.renderWizard(p,e);else{this.renderFields(p,e.fields||[]);let k=this.getSubmitButtonConfig(e);if(k.visible){let x=document.createElement("div");x.className="easy-form-submit-wrapper",x.style.textAlign=k.align;let w=document.createElement("button");w.type="submit",w.textContent=k.text,w.className="easy-form-submit",w.style.width=k.width,(this.disabled||this.loading)&&(w.disabled=!0),x.appendChild(w),p.appendChild(x)}}let E=null;if(f){let{completed:k,total:x}=this.getCompletedRequiredProgress(e),w=document.createElement("div");w.className="easy-form-completed-indicator",w.setAttribute("role","progressbar"),w.setAttribute("aria-valuenow",String(k)),w.setAttribute("aria-valuemin","0"),w.setAttribute("aria-valuemax",String(x)),w.setAttribute("aria-label",`Campos obligatorios completados: ${k} de ${x}`);let S=document.createElement("div");S.className="easy-form-completed-track";let pe=document.createElement("div");pe.className="easy-form-completed-fill",pe.style.width=x>0?`${k/x*100}%`:"0%",S.appendChild(pe),w.appendChild(S),E=document.createElement("div"),E.className="easy-form-wrapper",b==="top"?(E.appendChild(w),E.appendChild(p)):(E.appendChild(p),E.appendChild(w))}let v=this.shadow.querySelector("form");if(v&&v.parentNode===this.shadow&&v!==p)try{v.remove()}catch(k){console.warn("Error al eliminar formulario anterior:",k)}let C=this.shadow.querySelector(".easy-form-wrapper");C&&C.remove(),this.shadow.appendChild(E||p),this.loading&&this.updateLoadingOverlay(p),this.updateLockOverlay(p)}finally{this.isRendering=!1}}}updateLockOverlay(e){let a=this.shadow.querySelector(".easy-form-lock-overlay");if(a&&a.remove(),this.stopLockCountdown(),!this.attemptsLock?.isLocked())return;let r=e||this.shadow.querySelector("form");if(!r)return;let o=document.createElement("div");o.className="easy-form-lock-overlay";let s=document.createElement("div");s.className="easy-form-lock-message",s.setAttribute("role","alert");let i=()=>{let n=this.attemptsLock.getRemainingBlockTimeMs();if(n<=0){this.stopLockCountdown();return}let l=Math.floor(n/6e4),d=Math.floor(n%6e4/1e3),m=l>0?`${l} min ${d} s`:`${d} segundos`;s.textContent=`Demasiados intentos. Intenta de nuevo en ${m}.`};i(),o.appendChild(s),r.appendChild(o),this.lockCountdownInterval=setInterval(i,1e3)}stopLockCountdown(){this.lockCountdownInterval&&(clearInterval(this.lockCountdownInterval),this.lockCountdownInterval=null)}updateLoadingOverlay(e){let a=this.shadow.querySelector(".easy-form-loading-overlay");if(a&&a.remove(),this.loading){let r=e||this.shadow.querySelector("form");if(r){let o=document.createElement("div");o.className="easy-form-loading-overlay";let s=document.createElement("div");s.className="easy-form-loading-spinner",o.appendChild(s),r.appendChild(o)}}}preserveCurrentValues(){let e=null,a=this.template;if(a?e=this.getSchemaFromTemplate(a):e=this.schema,!e)return{};let r=this.shadow.querySelector("form"),o={};if(!r)return o;let s=r.querySelectorAll("input, textarea, select");for(let i of s){let n=i.getAttribute("name");if(!n||!(this.findFieldInSchema(e,n)!==null))continue;let d;if(i instanceof HTMLInputElement)if(i.type==="checkbox")d=i.checked;else if(i.type==="radio")if(i.checked)d=i.value;else continue;else i.type==="number"?d=i.value===""?null:Number(i.value):d=i.value;else i instanceof HTMLTextAreaElement?d=i.value:i instanceof HTMLSelectElement&&(i.multiple?d=Array.from(i.selectedOptions).map(m=>m.value):d=i.value||null);d!==void 0&&(o[n]=d===""?null:d)}return o}initializeSlotTemplates(){if(this.slotTemplates!==null)return;let e=[];for(let a of Array.from(this.children))a instanceof HTMLElement&&e.push(a);if(e.length===0){this.slotTemplates=[];return}this.slotTemplates=e.map(a=>{let r=a.hasAttribute("row")?a.getAttribute("row"):null,o=r!=null&&r!==""?Number(r):NaN,s=Number.isFinite(o)?o:null;return{template:a.cloneNode(!0),row:s}})}getSlotClonesByRow(e){this.initializeSlotTemplates();let a=new Map;if(!this.slotTemplates||this.slotTemplates.length===0)return a;for(let{template:r,row:o}of this.slotTemplates){let s=typeof o=="number"?o:-1;Number.isFinite(s)||(s=-1),(s<0||s>=e)&&(s=-1);let i=r.cloneNode(!0),n=a.get(s)??[];n.push(i),a.set(s,n)}return a}applySlotDisabledState(e){if(!this.disabled&&!this.loading)return;e.classList.add("easy-form-slot-disabled"),e.querySelectorAll("input, textarea, select, button").forEach(r=>{"disabled"in r&&(r.disabled=!0)})}renderFields(e,a){if(a.length===0){let n=this.getSlotClonesByRow(0).get(-1);if(n&&n.length>0)for(let l of n)this.applySlotDisabledState(l),e.appendChild(l);return}let r=a.length,o=this.getSlotClonesByRow(r);for(let i=0;i<a.length;i++){let n=o.get(i);if(n&&n.length>0){for(let m of n)this.applySlotDisabledState(m),e.appendChild(m);o.delete(i)}let l=a[i],d=this.renderField(l);d&&e.appendChild(d)}let s=o.get(-1);if(s&&s.length>0)for(let i of s)this.applySlotDisabledState(i),e.appendChild(i)}renderField(e){let a=this.stateManager.getFieldVisibility(e.name),r=this.stateManager.getFieldEnabled(e.name);if(e.type==="group"){let f=this.renderGroup(e);return a||(f.style.display="none",f.classList.add("easy-form-field-hidden")),r||f.classList.add("easy-form-field-disabled"),f}if(e.type==="row"){let f=this.renderRow(e);return a||(f.style.display="none",f.classList.add("easy-form-field-hidden")),r||f.classList.add("easy-form-field-disabled"),f}if(e.type==="array"){let f=this.renderArray(e);return a||(f.style.display="none",f.classList.add("easy-form-field-hidden")),r||f.classList.add("easy-form-field-disabled"),f}if(e.type==="custom"){let f=this.renderCustom(e);return f&&(a||(f.style.display="none",f.classList.add("easy-form-field-hidden")),r||f.classList.add("easy-form-field-disabled")),f}let o=this.stateManager.getValue(e.name),s=this.stateManager.getErrors(e.name),i=s.length>0?s[0]:void 0,n=this.disabled||this.loading,l=this.getAttribute("label-position"),d=["up","down","left","right","none"],m=e.labelPosition??(l&&d.includes(l)?l:"up"),p={...e,disabled:n||!r||e.disabled,labelPosition:m},u=le(e.type);if(u){let f=u({field:p,value:o,error:i,onChange:b=>this.handleFieldChange(e.name,b),onBlur:()=>this.handleFieldBlur(e.name)});return f&&!a&&(f.style.display="none",f.classList.add("easy-form-field-hidden")),f}let h=ye(p,o,i,f=>this.handleFieldChange(e.name,f),()=>this.handleFieldBlur(e.name)),g=h.querySelector(".easy-form-field")||h;return g instanceof HTMLElement&&g.setAttribute("data-field-name",e.name),a||(h.style.display="none",h.classList.add("easy-form-field-hidden")),h}renderGroup(e){let a=e,r=a.direction??"vertical",o=a.collapsible===!0,s=a.defaultOpen!==!1,i=document.createElement("div");if(i.className=`easy-form-group easy-form-direction-${r}`,e.name&&i.setAttribute("data-field-name",e.name),o){i.classList.add("easy-form-group-collapsible"),s||i.classList.add("easy-form-group-collapsed");let n=document.createElement("button");n.type="button",n.className="easy-form-group-header",n.setAttribute("aria-expanded",String(s));let l=`easy-form-group-${(e.name||"group").replace(/[^a-z0-9]/gi,"-")}-content`;n.setAttribute("aria-controls",l);let d=document.createElement("span");d.textContent=e.label||"Grupo";let m=document.createElement("span");m.className="easy-form-group-chevron",m.setAttribute("aria-hidden","true"),m.textContent="\u25BC",n.appendChild(d),n.appendChild(m),i.appendChild(n);let p=document.createElement("div");if(p.id=l,p.className="easy-form-group-content","fields"in e&&e.fields)for(let h of e.fields){let g=h.name.startsWith(e.name+".")?h.name:`${e.name}.${h.name}`,f={...h,name:g},b=this.renderField(f);b&&p.appendChild(b)}i.appendChild(p);let u=h=>{h?p.style.maxHeight=p.scrollHeight+"px":p.style.maxHeight="0"};s?requestAnimationFrame(()=>u(!0)):p.style.maxHeight="0",n.addEventListener("click",()=>{i.classList.contains("easy-form-group-collapsed")?(i.classList.remove("easy-form-group-collapsed"),n.setAttribute("aria-expanded","true"),u(!0)):(p.style.maxHeight=p.scrollHeight+"px",requestAnimationFrame(()=>{i.classList.add("easy-form-group-collapsed"),n.setAttribute("aria-expanded","false"),u(!1)}))})}else{if(e.label){let n=document.createElement("h3");n.className="easy-form-group-label",n.textContent=e.label,i.appendChild(n)}if("fields"in e&&e.fields)for(let n of e.fields){let l=n.name.startsWith(e.name+".")?n.name:`${e.name}.${n.name}`,d={...n,name:l},m=this.renderField(d);m&&i.appendChild(m)}}return i}renderRow(e){let a=document.createElement("div");a.className="easy-form-row";let r=e;if(a.style.display="flex",a.style.flexWrap="wrap",a.style.alignItems=r.align||"stretch",r.gap!==void 0){let o=typeof r.gap=="number"?`${r.gap}px`:r.gap;a.style.gap=o}else a.style.gap="1rem";if("fields"in e&&e.fields)for(let o of e.fields){let s=this.renderField(o);if(s){let i=document.createElement("div");i.style.flex="1",i.style.minWidth="0",i.appendChild(s),a.appendChild(i)}}return a}renderArray(e){let a=document.createElement("div");if(a.className="easy-form-array",a.setAttribute("data-field-name",e.name),e.label){let m=document.createElement("label");m.className="easy-form-label",m.textContent=e.label,a.appendChild(m)}let r=this.stateManager.getValue(e.name)||[],o=e,s=o.minItems??0,i=o.maxItems??1/0,n=document.createElement("div");n.className="easy-form-array-items";for(let m=0;m<r.length;m++){let p=document.createElement("div");if(p.className="easy-form-array-item",o.itemSchema?.fields)for(let g of o.itemSchema.fields){let f={...g,name:`${e.name}.${m}.${g.name}`},b=this.renderField(f);b&&p.appendChild(b)}let u=document.createElement("button");u.type="button",u.textContent="Eliminar",u.className="easy-form-array-remove";let h=r.length<=s;this.disabled||this.loading||h?u.disabled=!0:u.addEventListener("click",()=>{let g=[...r];g.splice(m,1),this.handleFieldChange(e.name,g)}),p.appendChild(u),n.appendChild(p)}a.appendChild(n);let l=document.createElement("button");l.type="button",l.textContent="Agregar",l.className="easy-form-array-add";let d=r.length>=i;return this.disabled||this.loading||d?l.disabled=!0:l.addEventListener("click",()=>{let m=this.stateManager.createDefaultArrayItem(e),p=[...r,m];this.handleFieldChange(e.name,p)}),a.appendChild(l),a}renderCustom(e){let a=le("custom");if(!a){let i=document.createElement("div");return i.textContent=`Componente custom no registrado para: ${e.name}`,i}let r=this.stateManager.getValue(e.name),o=this.stateManager.getErrors(e.name),s=o.length>0?o[0]:void 0;return a({field:e,value:r,error:s,onChange:i=>this.handleFieldChange(e.name,i),onBlur:()=>this.handleFieldBlur(e.name)})}getCompletedRequiredProgress(e){let a=d=>{let m=[];for(let p of d)if(p.type==="array"&&"itemSchema"in p&&p.itemSchema?.fields){let u=this.stateManager.getValue(p.name),h=Array.isArray(u)?u.length:0;for(let g=0;g<h;g++)for(let f of p.itemSchema.fields)m.push({...f,name:`${p.name}.${g}.${f.name}`})}else(p.type==="group"||p.type==="row")&&"fields"in p&&p.fields?m.push(...a(p.fields)):m.push(p);return m},r=e.steps?this.stateManager.getCurrentStepFields()||[]:e.fields||[],i=a(r).filter(d=>d.validations?.some(m=>m.type==="required")).filter(d=>this.stateManager.getFieldVisibility(d.name)),n=i.length;return{completed:i.filter(d=>{if(this.stateManager.getErrors(d.name).length>0)return!1;let p=this.stateManager.getValue(d.name);return!(p==null||typeof p=="string"&&p.trim()===""||Array.isArray(p)&&p.length===0&&d.type==="array")}).length,total:n}}renderWizard(e,a){let r=this.stateManager.getWizardState();if(!r)return;let o=document.createElement("div");o.className="easy-form-wizard";let s=document.createElement("div");if(s.className="easy-form-wizard-steps",a?.steps)for(let m=0;m<a.steps.length;m++){let p=document.createElement("div");p.className="easy-form-wizard-step",m===r.currentStep&&p.classList.add("active"),r.completedSteps.includes(m)&&p.classList.add("completed"),p.textContent=a.steps[m].title,s.appendChild(p)}o.appendChild(s);let i=document.createElement("div");i.className="easy-form-wizard-fields";let n=this.stateManager.getCurrentStepFields();this.renderFields(i,n),o.appendChild(i);let l=document.createElement("div");if(l.className="easy-form-wizard-nav",r.currentStep>0){let m=document.createElement("button");m.type="button",m.textContent="Anterior",m.className="easy-form-wizard-prev",this.disabled||this.loading?m.disabled=!0:m.addEventListener("click",()=>{this.stateManager.getWizardState()&&this.stateManager.previousStep()&&(this.render(),this.emitStepChange())}),l.appendChild(m)}if(r.currentStep<r.totalSteps-1){let m=document.createElement("button");m.type="button",m.textContent="Siguiente",m.className="easy-form-wizard-next",this.disabled||this.loading?m.disabled=!0:m.addEventListener("click",async()=>{let p=this.stateManager.getWizardState();if(!p)return;let u=this.stateManager.getCurrentStepFields();for(let b of u)this.stateManager.getFieldVisibility(b.name)&&await this.stateManager.validateField(b.name);let h=this.stateManager.getAllErrors(),g={};for(let b of u)h[b.name]&&h[b.name].length>0&&(g[b.name]=h[b.name]);Object.keys(g).length>0?this.emitError(g):(this.stateManager.completeStep(p.currentStep),this.stateManager.nextStep()&&(this.render(),this.emitStepChange()))}),l.appendChild(m)}let d=this.getSubmitButtonConfig(a);if(r.currentStep===r.totalSteps-1&&d.visible){let m=document.createElement("button");m.type="button",m.textContent=d.text,m.className="easy-form-wizard-next",m.style.width=d.width,this.disabled||this.loading?m.disabled=!0:m.addEventListener("click",async()=>{let p=this.stateManager.getCurrentStepFields();for(let f of p)this.stateManager.getFieldVisibility(f.name)&&await this.stateManager.validateField(f.name);let u=this.stateManager.getAllErrors(),h={};for(let f of p)u[f.name]&&u[f.name].length>0&&(h[f.name]=u[f.name]);Object.keys(h).length>0?this.emitError(h):await this.handleSubmit(new Event("submit"))}),l.appendChild(m)}o.appendChild(l),e.appendChild(o)}async handleFieldChange(e,a){await this.stateManager.setValue(e,a);let r=this.schema;if(r){let i=this.findFieldInSchema(r,e);i?.type==="array"&&(this.rerenderArrayField(i)||(this.skipPreserveValuesOnNextRender=!0,requestAnimationFrame(()=>this.render())))}let o=this.stateManager.getDependentFields(e);o.length>0&&(this.dependencyRenderTimeout&&clearTimeout(this.dependencyRenderTimeout),this.dependencyRenderTimeout=setTimeout(()=>{this.renderDependentFields(o),this.emitDependencyChange(e,o)},10));let s=new CustomEvent("change",{detail:{field:e,value:a,values:this.stateManager.getState().values},bubbles:!0,composed:!0});this.dispatchEvent(s)}rerenderArrayField(e){let a=this.shadow.querySelector(`[data-field-name="${e.name}"].easy-form-array`);if(!a?.parentNode)return!1;let r=this.renderArray(e);return a.parentNode.replaceChild(r,a),!0}renderDependentFields(e){let a=this.shadow.querySelector("form");if(!a)return;let r=this.schema;if(r)for(let o of e){let s=a.querySelector(`.easy-form-field[name="${o}"], [data-field-name="${o}"]`)?.closest(".easy-form-field")??a.querySelector(`[data-field-name="${o}"]`);if(s){let i=this.findFieldInSchema(r,o);if(!i)continue;let n=this.renderField(i);n&&s.parentNode&&s.parentNode.replaceChild(n,s)}}}emitDependencyChange(e,a){let r=new CustomEvent("dependencyChange",{detail:{changedField:e,affectedFields:a},bubbles:!0,composed:!0});this.dispatchEvent(r)}async handleFieldBlur(e){this.stateManager.setTouched(e),await this.stateManager.validateField(e),this.updateSingleField(e)}updateSingleField(e){let a=this.schema;if(!a||!this.findFieldInSchema(a,e))return;let o=this.stateManager.getErrors(e),s=o.length>0?o[0]:void 0,i=this.shadow.querySelector(`[name="${e}"]`)?.closest(".easy-form-field");if(!i)return;let n=i.querySelector(".easy-form-error");if(s){if(n)n.textContent=s;else{let d=document.createElement("p");d.className="easy-form-error",d.textContent=s,i.appendChild(d)}i.querySelector("input, textarea, select")?.classList.add("easy-form-input-error")}else n?.remove(),i.querySelector("input, textarea, select")?.classList.remove("easy-form-input-error")}findFieldInSchema(e,a){let r=e.fields||[],o=a.indexOf(".");if(o>0){let s=a.slice(0,o),i=a.slice(o+1),n=r.find(l=>l.name===s);if(!n)return null;if((n.type==="group"||n.type==="row")&&"fields"in n&&n.fields){let l=this.findFieldInSchema({fields:n.fields},i);return l?{...l,name:a}:null}return null}for(let s of r){if(s.name===a)return s;if(s.type==="group"&&"fields"in s){let i=this.findFieldInSchema({fields:s.fields},a);if(i)return i}if(s.type==="row"&&"fields"in s){let i=this.findFieldInSchema({fields:s.fields},a);if(i)return i}}return null}async handleSubmit(e){if(e.preventDefault(),this.attemptsLock?.isLocked())return;let a=await this.stateManager.validateForm(),r=this.stateManager.getState();if(Object.keys(a).length>0){for(let s of Object.keys(a))this.updateSingleField(s);this.emitError(a);return}let o=new CustomEvent("submit",{detail:{values:r.values,isValid:!0,errors:{}},bubbles:!0,composed:!0});this.dispatchEvent(o)}emitError(e){let a=new CustomEvent("error",{detail:{errors:e},bubbles:!0,composed:!0});this.dispatchEvent(a)}emitStepChange(){let e=this.stateManager.getWizardState();if(!e)return;let a=new CustomEvent("stepChange",{detail:{currentStep:e.currentStep,previousStep:e.currentStep>0?e.currentStep-1:e.currentStep,totalSteps:e.totalSteps},bubbles:!0,composed:!0});this.dispatchEvent(a)}registerComponents(e){this.customComponents={...this.customComponents,...e},be(e)}reset(){this.stateManager.reset(),this.render()}incrementAttempts(){this.attemptsLock?.incrementAttempts(),this.attemptsLock?.isLocked()&&this.updateLockOverlay()}resetAttempts(){this.attemptsLock?.reset(),this.stopLockCountdown(),this.updateLockOverlay(),this.render()}isLocked(){return this.attemptsLock?.isLocked()??!1}getRemainingBlockTimeMs(){return this.attemptsLock?.getRemainingBlockTimeMs()??0}requestSubmit(){let e=this.shadow.querySelector("form");e&&typeof e.requestSubmit=="function"&&e.requestSubmit()}clear(){let e=this.schema,a=this.template,r=null;a?r=this.getSchemaFromTemplate(a):r=e,r&&(this.stateManager.initializeSchema(r,{}),this.render())}getValues(){return this.stateManager.getState().values}getValue(e){return this.stateManager.getValue(e)}async setValue(e,a){await this.stateManager.setValue(e,a),this.render()}async setValues(e){for(let[a,r]of Object.entries(e))await this.stateManager.setValue(a,r);this.render()}async validate(){let e=await this.stateManager.validateForm();if(Object.keys(e).length>0){for(let a of Object.keys(e))this.updateSingleField(a);this.emitError(e)}else this.shadow.querySelectorAll(".easy-form-error").forEach(o=>o.remove()),this.shadow.querySelectorAll(".easy-form-input-error").forEach(o=>o.classList.remove("easy-form-input-error"));return e}async validateField(e){return await this.stateManager.validateField(e),this.updateSingleField(e),this.stateManager.getErrors(e)}getErrors(){return this.stateManager.getAllErrors()}getFieldErrors(e){return this.stateManager.getErrors(e)}isValid(){return this.stateManager.getState().isValid}get theme(){let e=this.getAttribute("theme");return e&&["plano","tradicional","material","rounded-shadow","lines","shadcn","chakra","mantine","glass","bordered","minimal","efc"].includes(e)?e:"plano"}set theme(e){e?this.setAttribute("theme",e):this.removeAttribute("theme")}get colors(){let e=this.getAttribute("colors");return e?F(e):null}set colors(e){e?this.setAttribute("colors",A(e)):this.removeAttribute("colors")}get initialData(){let e=this.getAttribute("initialData");return e?F(e):null}set initialData(e){e?this.setAttribute("initialData",A(e)):this.removeAttribute("initialData")}get loading(){return this.hasAttribute("loading")}set loading(e){e?this.setAttribute("loading",""):this.removeAttribute("loading")}get disabled(){return this.hasAttribute("disabled")}set disabled(e){e?this.setAttribute("disabled",""):this.removeAttribute("disabled")}setupStyles(){let e=this.shadow.querySelector("style");e&&e.remove();let a=this.theme,r=N(this.colors||void 0),o=H(a,r),s=document.createElement("style");s.textContent=o,this.shadow.firstChild?this.shadow.insertBefore(s,this.shadow.firstChild):this.shadow.appendChild(s)}};typeof window<"u"&&typeof customElements<"u"&&!customElements.get("easy-form")&&customElements.define("easy-form",ce);export{V as AttemptsLock,L as ConditionEngine,ce as EasyForm,$ as INJECTION_VALIDATION_MESSAGE,M as MaskEngine,Ie as PREDEFINED_MASKS,I as SchemaParser,P as StateManager,R as ValidationEngine,A as attributeValue,Ne as containsInjection,ye as createInput,ve as extendTemplate,Bt as generateId,it as getAvailableTemplates,N as getColors,le as getCustomComponent,T as getNestedValue,fe as getPredefinedMask,me as getTemplate,H as getThemeStyles,q as isSafeFromInjection,qe as isValidEmail,F as parseAttributeValue,$e as registerComponent,be as registerComponents,Ot as sanitizeId,z as setNestedValue,de as templates};
|
|
2175
|
+
`;return}delete E.Icon.Default.prototype._getIconUrl,E.Icon.Default.mergeOptions({iconRetinaUrl:"https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png",iconUrl:"https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png",shadowUrl:"https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png"}),this.mapInstance=E.map(u,{preferCanvas:!1,zoomControl:!0}).setView([s,i],r);let v=E.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",{attribution:'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',maxZoom:19}).addTo(this.mapInstance);this.mapInstance.invalidateSize(),v.on("load",()=>{this.mapInstance&&this.mapInstance.invalidateSize()});let C=()=>{this.mapInstance&&this.mapInstance.invalidateSize()};setTimeout(C,100),setTimeout(C,300),setTimeout(C,500),new IntersectionObserver(x=>{x.forEach(w=>{w.isIntersecting&&this.mapInstance&&setTimeout(()=>{this.mapInstance?.invalidateSize()},100)})}).observe(u),this.markerInstance=E.marker([s,i],{draggable:!0}).addTo(this.mapInstance).on("dragend",()=>{let x=this.markerInstance.getLatLng();d.value=String(Number(x.lat.toFixed(6))),m.value=String(Number(x.lng.toFixed(6))),this.onChange({lat:x.lat,lng:x.lng}),this.onBlur()}),this.mapInstance.on("click",x=>{let{lat:w,lng:S}=x.latlng;this.markerInstance.setLatLng([w,S]),d.value=String(Number(w.toFixed(6))),m.value=String(Number(S.toFixed(6))),this.onChange({lat:w,lng:S}),this.onBlur()})})(),this.createFieldContainer(n)}syncMarkerPosition(e,a){this.mapInstance&&this.markerInstance&&(this.markerInstance.setLatLng([e,a]),this.mapInstance.setView([e,a]),setTimeout(()=>{this.mapInstance?.invalidateSize()},50))}};var De=c=>`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="${c?"currentColor":"none"}" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" role="img" aria-hidden="true"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>`,se=class extends y{render(){let t=this.field,e=t.max??5,a=t.half??!1,r=this.value!=null?Number(this.value):0,o=document.createElement("div");o.className="easy-form-rating",o.setAttribute("role","slider"),o.setAttribute("aria-valuemin","0"),o.setAttribute("aria-valuemax",String(e)),o.setAttribute("aria-valuenow",String(r)),o.setAttribute("aria-label",this.field.label||"Rating"),o.setAttribute("tabindex","0");let s=document.createElement("div");s.className="easy-form-rating-stars";for(let i=1;i<=e;i++){let n=document.createElement("button");n.type="button";let l=r>=i||a&&r>=i-.5;n.className=l?"easy-form-rating-star easy-form-rating-star-filled":"easy-form-rating-star",n.innerHTML=De(l),n.setAttribute("aria-label",`${i} de ${e}`),n.addEventListener("click",d=>{d.preventDefault();let m=d.target.closest("button")?.getBoundingClientRect(),p=i;if(a&&m){let u=m.left+m.width/2;p=d.clientX<u?i-.5:i}this.onChange(p),this.onBlur(),this.rerenderStars(o,e,p,a),o.setAttribute("aria-valuenow",String(p))}),s.appendChild(n)}return o.appendChild(s),o.addEventListener("keydown",i=>{let n=Number(o.getAttribute("aria-valuenow"))||0,l=n;i.key==="ArrowRight"||i.key==="ArrowUp"?(i.preventDefault(),l=Math.min(e,a?n+.5:n+1),this.onChange(l)):(i.key==="ArrowLeft"||i.key==="ArrowDown")&&(i.preventDefault(),l=Math.max(0,a?n-.5:n-1),this.onChange(l)),l!==n&&(this.rerenderStars(o,e,l,a),o.setAttribute("aria-valuenow",String(l)))}),this.createFieldContainer(o)}rerenderStars(t,e,a,r){t.querySelectorAll(".easy-form-rating-star").forEach((s,i)=>{let n=i+1,l=a>=n||r&&a>=n-.5;s.className=l?"easy-form-rating-star easy-form-rating-star-filled":"easy-form-rating-star",s.innerHTML=De(l)})}};var ie=class extends y{render(){let t=this.field,e=t.min??0,a=t.max??100,r=t.step??1,o=t.showValue??!1,s=document.createElement("input");s.type="range",s.min=String(e),s.max=String(a),s.step=String(r),s.value=this.value!=null?String(this.value):String(e),s.setAttribute("aria-valuemin",String(e)),s.setAttribute("aria-valuemax",String(a)),s.setAttribute("aria-valuenow",s.value),this.applyCommonProps(s),s.addEventListener("input",n=>{let l=n.target,d=r>=1?parseInt(l.value,10):parseFloat(l.value);this.onChange(isNaN(d)?e:d),i&&(i.textContent=l.value),s.setAttribute("aria-valuenow",l.value)}),s.addEventListener("change",()=>{this.onBlur()});let i=null;if(o){i=document.createElement("span"),i.className="easy-form-slider-value",i.textContent=s.value;let n=document.createElement("div");return n.className="easy-form-slider-wrapper",n.appendChild(s),n.appendChild(i),this.createFieldContainer(n)}return this.createFieldContainer(s)}};var Ue=/^#?([0-9A-Fa-f]{6})$/;function ge(c){let t=c.match(Ue);return t?`#${t[1].toLowerCase()}`:/^[0-9A-Fa-f]{6}$/.test(c)?`#${c.toLowerCase()}`:"#000000"}var ne=class extends y{render(){let e=this.field.defaultValue??"#000000",a=this.value!=null&&typeof this.value=="string"?ge(this.value):e,r=document.createElement("div");r.className="easy-form-color-wrapper";let o=document.createElement("input");o.type="color",o.value=a,o.setAttribute("value",a),o.setAttribute("aria-label",this.field.label||"Color"),o.id=`${this.getFieldId()}-picker`,this.field.disabled&&o.setAttribute("disabled","true");let s=document.createElement("input");s.type="text",s.value=a,s.setAttribute("aria-label",`${this.field.label||"Color"} (hex)`),s.placeholder="#000000",s.className="easy-form-color-text",this.applyCommonProps(s);let i=()=>{let l=o.value||"#000000",d=ge(l);s.value=d,this.onChange(d)},n=()=>{let l=s.value.trim(),d=l.startsWith("#")?l:`#${l}`;if(/^#[0-9A-Fa-f]{6}$/.test(d)){let m=ge(d);o.value=m,this.onChange(m)}};return o.addEventListener("input",i),o.addEventListener("change",()=>{i(),this.onBlur()}),s.addEventListener("input",n),s.addEventListener("blur",()=>{n(),this.onBlur()}),r.appendChild(o),r.appendChild(s),this.createFieldContainer(r)}};function ye(c,t,e,a,r){switch(c.type){case"text":case"email":return new O(c,t,e,a,r).render();case"password":return new re(c,t,e,a,r).render();case"number":return new j(c,t,e,a,r).render();case"textarea":return new W(c,t,e,a,r).render();case"select":return new _(c,t,e,a,r).render();case"checkbox":return new Y(c,t,e,a,r).render();case"radio":return new U(c,t,e,a,r).render();case"switch":return new G(c,t,e,a,r).render();case"date":return new K(c,t,e,a,r).render();case"file":return new Z(c,t,e,a,r).render();case"file-drop":return new ae(c,t,e,a,r).render();case"map":return new oe(c,t,e,a,r).render();case"rating":return new se(c,t,e,a,r).render();case"slider":return new ie(c,t,e,a,r).render();case"colorpicker":return new ne(c,t,e,a,r).render();case"quantity":return new J(c,t,e,a,r).render();case"accordion-select":return new X(c,t,e,a,r).render();case"image-grid-select":return new Q(c,t,e,a,r).render();case"otp":return new ee(c,t,e,a,r).render();default:let o=document.createElement("div");return o.textContent=`Tipo de campo no soportado: ${c.type}`,o}}var He=new Map;function $e(c,t){He.set(c,t)}function be(c){for(let[t,e]of Object.entries(c))$e(t,e)}function le(c){return He.get(c)}var Ge={fields:[{type:"email",name:"email",label:"Email",placeholder:"Enter your email",validations:[{type:"required",message:"Email is required"},{type:"email",message:"Please enter a valid email"}]},{type:"password",name:"password",label:"Password",placeholder:"Enter your password",validations:[{type:"required",message:"Password is required"},{type:"minLength",value:6,message:"Password must be at least 6 characters"}]},{type:"checkbox",name:"rememberMe",label:"Remember me",defaultValue:!1}]},Ke={fields:[{type:"text",name:"name",label:"Full Name",placeholder:"Enter your full name",validations:[{type:"required",message:"Name is required"},{type:"minLength",value:2,message:"Name must be at least 2 characters"}]},{type:"email",name:"email",label:"Email",placeholder:"Enter your email",validations:[{type:"required",message:"Email is required"},{type:"email",message:"Please enter a valid email"}]},{type:"password",name:"password",label:"Password",placeholder:"Create a password",validations:[{type:"required",message:"Password is required"},{type:"minLength",value:8,message:"Password must be at least 8 characters"}]},{type:"password",name:"confirmPassword",label:"Confirm Password",placeholder:"Confirm your password",validations:[{type:"required",message:"Please confirm your password"},{type:"custom",validator:c=>typeof c=="string"&&c.length>=8,message:"Password must be at least 8 characters"}]}]},Ze={fields:[{type:"otp",name:"code",label:"Verification Code",validations:[{type:"required",message:"Verification code is required"}]}]},Je={fields:[{type:"text",name:"name",label:"Name",placeholder:"Enter your name",validations:[{type:"required",message:"Name is required"}]},{type:"email",name:"email",label:"Email",placeholder:"Enter your email",validations:[{type:"required",message:"Email is required"},{type:"email",message:"Please enter a valid email"}]},{type:"text",name:"subject",label:"Subject",placeholder:"Enter the subject",validations:[{type:"required",message:"Subject is required"}]},{type:"textarea",name:"message",label:"Message",placeholder:"Enter your message",rows:5,validations:[{type:"required",message:"Message is required"},{type:"minLength",value:10,message:"Message must be at least 10 characters"}]}]},Xe={fields:[{type:"email",name:"email",label:"Email",placeholder:"Enter your email address",validations:[{type:"required",message:"Email is required"},{type:"email",message:"Please enter a valid email"}]}]},Qe={fields:[{type:"password",name:"currentPassword",label:"Current Password",placeholder:"Enter your current password",validations:[{type:"required",message:"Current password is required"}]},{type:"password",name:"newPassword",label:"New Password",placeholder:"Enter your new password",validations:[{type:"required",message:"New password is required"},{type:"minLength",value:8,message:"Password must be at least 8 characters"}]},{type:"password",name:"confirmPassword",label:"Confirm New Password",placeholder:"Confirm your new password",validations:[{type:"required",message:"Please confirm your new password"},{type:"custom",validator:c=>typeof c=="string"&&c.length>=8,message:"Password must be at least 8 characters"}]}]},et={fields:[{type:"text",name:"name",label:"Full Name",placeholder:"Enter your full name",validations:[{type:"required",message:"Name is required"}]},{type:"email",name:"email",label:"Email",placeholder:"Enter your email",validations:[{type:"required",message:"Email is required"},{type:"email",message:"Please enter a valid email"}]},{type:"text",name:"phone",label:"Phone",placeholder:"Enter your phone number",mask:{type:"phone"}},{type:"textarea",name:"bio",label:"Bio",placeholder:"Tell us about yourself",rows:4},{type:"file",name:"avatar",label:"Profile Picture",accept:"image/*"}]},tt={fields:[{type:"group",name:"billingAddress",label:"Billing Address",fields:[{type:"text",name:"street",label:"Street Address",placeholder:"Enter street address",validations:[{type:"required",message:"Street address is required"}]},{type:"row",name:"cityState",fields:[{type:"text",name:"city",label:"City",placeholder:"City",validations:[{type:"required",message:"City is required"}]},{type:"text",name:"state",label:"State",placeholder:"State",validations:[{type:"required",message:"State is required"}]}]},{type:"text",name:"zipCode",label:"ZIP Code",placeholder:"ZIP Code",validations:[{type:"required",message:"ZIP code is required"}]}]},{type:"select",name:"paymentMethod",label:"Payment Method",options:[{label:"Credit Card",value:"credit-card"},{label:"Debit Card",value:"debit-card"},{label:"PayPal",value:"paypal"},{label:"Bank Transfer",value:"bank-transfer"}],validations:[{type:"required",message:"Payment method is required"}]},{type:"select",name:"shipping",label:"Shipping Method",options:[{label:"Standard (5-7 days)",value:"standard"},{label:"Express (2-3 days)",value:"express"},{label:"Overnight",value:"overnight"}],validations:[{type:"required",message:"Shipping method is required"}]}]},rt={fields:[{type:"select",name:"rating",label:"Rating",options:[{label:"1 - Poor",value:1},{label:"2 - Fair",value:2},{label:"3 - Good",value:3},{label:"4 - Very Good",value:4},{label:"5 - Excellent",value:5}],validations:[{type:"required",message:"Rating is required"}]},{type:"textarea",name:"comment",label:"Comment",placeholder:"Share your feedback",rows:5,validations:[{type:"required",message:"Comment is required"}]},{type:"email",name:"email",label:"Email (optional)",placeholder:"Enter your email if you want a response"}]},at={fields:[{type:"email",name:"email",label:"Email",placeholder:"Enter your email",validations:[{type:"required",message:"Email is required"},{type:"email",message:"Please enter a valid email"}]},{type:"checkbox",name:"weeklyNewsletter",label:"Weekly Newsletter",defaultValue:!0},{type:"checkbox",name:"productUpdates",label:"Product Updates",defaultValue:!1},{type:"checkbox",name:"promotions",label:"Promotions and Special Offers",defaultValue:!1}]},ot={fields:[{type:"date",name:"date",label:"Date",validations:[{type:"required",message:"Date is required"}]},{type:"text",name:"time",label:"Time",placeholder:"HH:MM",mask:{type:"time"},validations:[{type:"required",message:"Time is required"}]},{type:"number",name:"guests",label:"Number of Guests",placeholder:"Enter number of guests",min:1,max:20,validations:[{type:"required",message:"Number of guests is required"},{type:"min",value:1,message:"At least 1 guest is required"}]},{type:"textarea",name:"specialRequests",label:"Special Requests",placeholder:"Any special requests or dietary restrictions?",rows:4}]},st={fields:[{type:"select",name:"rating",label:"Rating",options:[{label:"1 Star",value:1},{label:"2 Stars",value:2},{label:"3 Stars",value:3},{label:"4 Stars",value:4},{label:"5 Stars",value:5}],validations:[{type:"required",message:"Rating is required"}]},{type:"text",name:"title",label:"Review Title",placeholder:"Give your review a title",validations:[{type:"required",message:"Review title is required"},{type:"minLength",value:5,message:"Title must be at least 5 characters"}]},{type:"textarea",name:"comment",label:"Your Review",placeholder:"Share your experience",rows:6,validations:[{type:"required",message:"Review comment is required"},{type:"minLength",value:20,message:"Review must be at least 20 characters"}]}]},de={login:Ge,register:Ke,otp:Ze,contact:Je,"password-reset":Xe,"password-change":Qe,profile:et,checkout:tt,feedback:rt,subscription:at,booking:ot,review:st};function me(c){return c in de?de[c]:null}function it(){return Object.keys(de)}function ve(c,t){let e=me(c);if(!e)throw new Error(`Template "${c}" not found`);let a=e.fields||[],r=e.steps;if(r&&r.length>0){let o=r[r.length-1];return{...e,steps:[...r.slice(0,-1),{...o,fields:[...o.fields,...t]}]}}return{...e,fields:[...a,...t]}}var nt=typeof HTMLElement<"u"?HTMLElement:class{},ce=class extends nt{constructor(){if(typeof HTMLElement>"u")throw new Error("EasyForm can only be used in a browser environment");super();this.customComponents={};this.isRendering=!1;this.attemptsLock=null;this.lockCountdownInterval=null;this.slotTemplates=null;this.skipPreserveValuesOnNextRender=!1;this.persistenceConfig=null;this.persistenceDebounceTimer=null;this.pendingRestoreValues=null;this.isRestoringValues=!1;this.dependencyRenderTimeout=null;this.stateManager=new P,this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["schema","template","template-extend","theme","colors","initialData","loading","disabled","max-attempts","block-duration-minutes","attempts-storage-key","submit-button","label-position","show-completed-indicator","form-direction"]}get schema(){let e=this.getAttribute("schema");return e?this.getAttribute("template")?(console.warn('EasyForm: Cannot use both "schema" and "template" attributes. "template" will be ignored.'),F(e)):F(e):null}set schema(e){e&&this.getAttribute("template")&&(console.warn('EasyForm: Setting "schema" will remove "template" attribute.'),this.removeAttribute("template"),this.removeAttribute("template-extend")),e?this.setAttribute("schema",A(e)):this.removeAttribute("schema")}get template(){let e=this.getAttribute("template");return e?(this.getAttribute("schema")&&console.warn('EasyForm: Cannot use both "template" and "schema" attributes. "schema" will be ignored.'),e):null}set template(e){e&&this.getAttribute("schema")&&(console.warn('EasyForm: Setting "template" will remove "schema" attribute.'),this.removeAttribute("schema")),e?this.setAttribute("template",e):(this.removeAttribute("template"),this.removeAttribute("template-extend"))}get templateExtend(){let e=this.getAttribute("template-extend");return e?F(e):null}set templateExtend(e){e?this.setAttribute("template-extend",A(e)):this.removeAttribute("template-extend")}get maxAttempts(){let e=this.getAttribute("max-attempts");if(!e)return null;let a=parseInt(e,10);return isNaN(a)?null:a}set maxAttempts(e){e!=null&&e>=1?this.setAttribute("max-attempts",String(e)):this.removeAttribute("max-attempts")}get blockDurationMinutes(){let e=this.getAttribute("block-duration-minutes");if(!e)return null;let a=parseInt(e,10);return isNaN(a)?null:a}set blockDurationMinutes(e){e!=null&&e>=1?this.setAttribute("block-duration-minutes",String(e)):this.removeAttribute("block-duration-minutes")}get attemptsStorageKey(){return this.getAttribute("attempts-storage-key")}set attemptsStorageKey(e){e?this.setAttribute("attempts-storage-key",e):this.removeAttribute("attempts-storage-key")}get submitButton(){let e=this.getAttribute("submit-button");if(e)try{return F(e)}catch{return null}return null}set submitButton(e){e&&typeof e=="object"?this.setAttribute("submit-button",A(e)):this.removeAttribute("submit-button")}getSubmitButtonConfig(e){let a=this.submitButton,o={...e?.submitButton,...a};return{visible:o.visible??!0,text:o.text??"Enviar",width:o.width??"auto",align:o.align??"left"}}connectedCallback(){this.setupAttemptsLock(),this.setupStyles(),this.render()}attributeChangedCallback(e,a,r){if(e==="schema"&&r!==a&&(this.getAttribute("template")&&(console.warn('EasyForm: "schema" and "template" cannot be used together. Removing "template".'),this.removeAttribute("template"),this.removeAttribute("template-extend")),this.handleSchemaChange()),e==="template"&&r!==a&&(this.getAttribute("schema")&&(console.warn('EasyForm: "template" and "schema" cannot be used together. Removing "schema".'),this.removeAttribute("schema")),this.handleSchemaChange()),e==="template-extend"&&r!==a&&this.handleSchemaChange(),e==="initialData"&&r!==a&&this.handleSchemaChange(),(e==="theme"||e==="colors")&&r!==a&&this.setupStyles(),e==="loading"&&r!==a){let o=this.shadow.querySelector("form");this.updateLoadingOverlay(o||void 0),o&&o.querySelectorAll("input, textarea, select, button").forEach(i=>{i instanceof HTMLElement&&"disabled"in i&&(i.disabled=this.loading)})}e==="disabled"&&r!==a&&this.render(),(e==="label-position"||e==="form-direction"||e==="show-completed-indicator")&&r!==a&&this.render(),(e==="max-attempts"||e==="block-duration-minutes"||e==="attempts-storage-key")&&r!==a&&(this.setupAttemptsLock(),this.updateLockOverlay()),e==="submit-button"&&r!==a&&this.render()}setupAttemptsLock(){let e=this.maxAttempts;if(e==null||e<1){this.attemptsLock=null;return}this.attemptsLock=new V({maxAttempts:e,blockDurationMinutes:this.blockDurationMinutes??5,storageKey:this.attemptsStorageKey??void 0,onLocked:()=>{this.updateLockOverlay()},onUnlocked:()=>{this.stopLockCountdown(),this.updateLockOverlay(),this.render()}})}handleSchemaChange(){let e=null,a=this.template;if(a?e=this.getSchemaFromTemplate(a):e=this.schema,e){let r=this.initialData;this.stateManager.initializeSchema(e,r||void 0),this.initPersistence(e),this.render()}}getSchemaFromTemplate(e){let a=me(e);if(!a)return console.error(`EasyForm: Template "${e}" not found`),null;let r=this.templateExtend;return r&&r.length>0?ve(e,r):a}async render(){if(!this.isRendering){this.isRendering=!0;try{let e=null,a=this.template;if(a?e=this.getSchemaFromTemplate(a):e=this.schema,!e){let k=this.shadow.querySelector("form");k&&k.parentNode===this.shadow&&k.remove();return}let r=this.skipPreserveValuesOnNextRender,o=r?{}:this.preserveCurrentValues();this.skipPreserveValuesOnNextRender=!1;let s=this.stateManager.getWizardState();if(o&&Object.keys(o).length>0)for(let[k,x]of Object.entries(o))this.stateManager.setValueWithoutValidation(k,x);let i=this.initialData,n=s!==null,l=e.steps&&e.steps.length>0;if(!r&&(!s||!n||!l||s&&e.steps&&s.totalSteps!==e.steps.length)&&(this.stateManager.initializeSchema(e,i||void 0),n&&l&&s)){let k=this.stateManager.getWizardState();if(k&&s.totalSteps===k.totalSteps){s.currentStep>=0&&s.currentStep<k.totalSteps&&this.stateManager.goToStep(s.currentStep);for(let x of s.completedSteps)x>=0&&x<k.totalSteps&&this.stateManager.completeStep(x)}}let m=this.stateManager.getWizardState(),p=document.createElement("form");p.addEventListener("submit",k=>this.handleSubmit(k)),(this.disabled||this.loading)&&p.classList.add("easy-form-disabled");let u=this.getAttribute("form-direction"),h=e.direction??(u==="vertical"||u==="horizontal"?u:"vertical");p.classList.add(`easy-form-direction-${h}`);let g=this.getAttribute("show-completed-indicator"),f=e.completedIndicator??(g!==null&&g!=="false"),b=typeof f=="object"&&f?.position?f.position:"top";if(m)this.renderWizard(p,e);else{this.renderFields(p,e.fields||[]);let k=this.getSubmitButtonConfig(e);if(k.visible){let x=document.createElement("div");x.className="easy-form-submit-wrapper",x.style.textAlign=k.align;let w=document.createElement("button");w.type="submit",w.textContent=k.text,w.className="easy-form-submit",w.style.width=k.width,(this.disabled||this.loading)&&(w.disabled=!0),x.appendChild(w),p.appendChild(x)}}let E=null;if(f){let{completed:k,total:x}=this.getCompletedRequiredProgress(e),w=document.createElement("div");w.className="easy-form-completed-indicator",w.setAttribute("role","progressbar"),w.setAttribute("aria-valuenow",String(k)),w.setAttribute("aria-valuemin","0"),w.setAttribute("aria-valuemax",String(x)),w.setAttribute("aria-label",`Campos obligatorios completados: ${k} de ${x}`);let S=document.createElement("div");S.className="easy-form-completed-track";let pe=document.createElement("div");pe.className="easy-form-completed-fill",pe.style.width=x>0?`${k/x*100}%`:"0%",S.appendChild(pe),w.appendChild(S),E=document.createElement("div"),E.className="easy-form-wrapper",b==="top"?(E.appendChild(w),E.appendChild(p)):(E.appendChild(p),E.appendChild(w))}let v=this.shadow.querySelector("form");if(v&&v.parentNode===this.shadow&&v!==p)try{v.remove()}catch(k){console.warn("Error al eliminar formulario anterior:",k)}let C=this.shadow.querySelector(".easy-form-wrapper");C&&C.remove(),this.shadow.appendChild(E||p),this.loading&&this.updateLoadingOverlay(p),this.updateLockOverlay(p)}finally{this.isRendering=!1,this.pendingRestoreValues&&this.applyPendingRestoreValues()}}}updateLockOverlay(e){let a=this.shadow.querySelector(".easy-form-lock-overlay");if(a&&a.remove(),this.stopLockCountdown(),!this.attemptsLock?.isLocked())return;let r=e||this.shadow.querySelector("form");if(!r)return;let o=document.createElement("div");o.className="easy-form-lock-overlay";let s=document.createElement("div");s.className="easy-form-lock-message",s.setAttribute("role","alert");let i=()=>{let n=this.attemptsLock.getRemainingBlockTimeMs();if(n<=0){this.stopLockCountdown();return}let l=Math.floor(n/6e4),d=Math.floor(n%6e4/1e3),m=l>0?`${l} min ${d} s`:`${d} segundos`;s.textContent=`Demasiados intentos. Intenta de nuevo en ${m}.`};i(),o.appendChild(s),r.appendChild(o),this.lockCountdownInterval=setInterval(i,1e3)}stopLockCountdown(){this.lockCountdownInterval&&(clearInterval(this.lockCountdownInterval),this.lockCountdownInterval=null)}updateLoadingOverlay(e){let a=this.shadow.querySelector(".easy-form-loading-overlay");if(a&&a.remove(),this.loading){let r=e||this.shadow.querySelector("form");if(r){let o=document.createElement("div");o.className="easy-form-loading-overlay";let s=document.createElement("div");s.className="easy-form-loading-spinner",o.appendChild(s),r.appendChild(o)}}}preserveCurrentValues(){let e=null,a=this.template;if(a?e=this.getSchemaFromTemplate(a):e=this.schema,!e)return{};let r=this.shadow.querySelector("form"),o={};if(!r)return o;let s=r.querySelectorAll("input, textarea, select");for(let i of s){let n=i.getAttribute("name");if(!n||!(this.findFieldInSchema(e,n)!==null))continue;let d;if(i instanceof HTMLInputElement)if(i.type==="checkbox")d=i.checked;else if(i.type==="radio")if(i.checked)d=i.value;else continue;else i.type==="number"?d=i.value===""?null:Number(i.value):d=i.value;else i instanceof HTMLTextAreaElement?d=i.value:i instanceof HTMLSelectElement&&(i.multiple?d=Array.from(i.selectedOptions).map(m=>m.value):d=i.value||null);d!==void 0&&(o[n]=d===""?null:d)}return o}initializeSlotTemplates(){if(this.slotTemplates!==null)return;let e=[];for(let a of Array.from(this.children))a instanceof HTMLElement&&e.push(a);if(e.length===0){this.slotTemplates=[];return}this.slotTemplates=e.map(a=>{let r=a.hasAttribute("row")?a.getAttribute("row"):null,o=r!=null&&r!==""?Number(r):NaN,s=Number.isFinite(o)?o:null;return{template:a.cloneNode(!0),row:s}})}getSlotClonesByRow(e){this.initializeSlotTemplates();let a=new Map;if(!this.slotTemplates||this.slotTemplates.length===0)return a;for(let{template:r,row:o}of this.slotTemplates){let s=typeof o=="number"?o:-1;Number.isFinite(s)||(s=-1),(s<0||s>=e)&&(s=-1);let i=r.cloneNode(!0),n=a.get(s)??[];n.push(i),a.set(s,n)}return a}applySlotDisabledState(e){if(!this.disabled&&!this.loading)return;e.classList.add("easy-form-slot-disabled"),e.querySelectorAll("input, textarea, select, button").forEach(r=>{"disabled"in r&&(r.disabled=!0)})}renderFields(e,a){if(a.length===0){let n=this.getSlotClonesByRow(0).get(-1);if(n&&n.length>0)for(let l of n)this.applySlotDisabledState(l),e.appendChild(l);return}let r=a.length,o=this.getSlotClonesByRow(r);for(let i=0;i<a.length;i++){let n=o.get(i);if(n&&n.length>0){for(let m of n)this.applySlotDisabledState(m),e.appendChild(m);o.delete(i)}let l=a[i],d=this.renderField(l);d&&e.appendChild(d)}let s=o.get(-1);if(s&&s.length>0)for(let i of s)this.applySlotDisabledState(i),e.appendChild(i)}renderField(e){let a=this.stateManager.getFieldVisibility(e.name),r=this.stateManager.getFieldEnabled(e.name);if(e.type==="group"){let f=this.renderGroup(e);return a||(f.style.display="none",f.classList.add("easy-form-field-hidden")),r||f.classList.add("easy-form-field-disabled"),f}if(e.type==="row"){let f=this.renderRow(e);return a||(f.style.display="none",f.classList.add("easy-form-field-hidden")),r||f.classList.add("easy-form-field-disabled"),f}if(e.type==="array"){let f=this.renderArray(e);return a||(f.style.display="none",f.classList.add("easy-form-field-hidden")),r||f.classList.add("easy-form-field-disabled"),f}if(e.type==="custom"){let f=this.renderCustom(e);return f&&(a||(f.style.display="none",f.classList.add("easy-form-field-hidden")),r||f.classList.add("easy-form-field-disabled")),f}let o=this.stateManager.getValue(e.name),s=this.stateManager.getErrors(e.name),i=s.length>0?s[0]:void 0,n=this.disabled||this.loading,l=this.getAttribute("label-position"),d=["up","down","left","right","none"],m=e.labelPosition??(l&&d.includes(l)?l:"up"),p={...e,disabled:n||!r||e.disabled,labelPosition:m},u=le(e.type);if(u){let f=u({field:p,value:o,error:i,onChange:b=>this.handleFieldChange(e.name,b),onBlur:()=>this.handleFieldBlur(e.name)});return f&&!a&&(f.style.display="none",f.classList.add("easy-form-field-hidden")),f}let h=ye(p,o,i,f=>this.handleFieldChange(e.name,f),()=>this.handleFieldBlur(e.name)),g=h.querySelector(".easy-form-field")||h;return g instanceof HTMLElement&&g.setAttribute("data-field-name",e.name),a||(h.style.display="none",h.classList.add("easy-form-field-hidden")),h}renderGroup(e){let a=e,r=a.direction??"vertical",o=a.collapsible===!0,s=a.defaultOpen!==!1,i=document.createElement("div");if(i.className=`easy-form-group easy-form-direction-${r}`,e.name&&i.setAttribute("data-field-name",e.name),o){i.classList.add("easy-form-group-collapsible"),s||i.classList.add("easy-form-group-collapsed");let n=document.createElement("button");n.type="button",n.className="easy-form-group-header",n.setAttribute("aria-expanded",String(s));let l=`easy-form-group-${(e.name||"group").replace(/[^a-z0-9]/gi,"-")}-content`;n.setAttribute("aria-controls",l);let d=document.createElement("span");d.textContent=e.label||"Grupo";let m=document.createElement("span");m.className="easy-form-group-chevron",m.setAttribute("aria-hidden","true"),m.textContent="\u25BC",n.appendChild(d),n.appendChild(m),i.appendChild(n);let p=document.createElement("div");if(p.id=l,p.className="easy-form-group-content","fields"in e&&e.fields)for(let h of e.fields){let g=h.name.startsWith(e.name+".")?h.name:`${e.name}.${h.name}`,f={...h,name:g},b=this.renderField(f);b&&p.appendChild(b)}i.appendChild(p);let u=h=>{h?p.style.maxHeight=p.scrollHeight+"px":p.style.maxHeight="0"};s?requestAnimationFrame(()=>u(!0)):p.style.maxHeight="0",n.addEventListener("click",()=>{i.classList.contains("easy-form-group-collapsed")?(i.classList.remove("easy-form-group-collapsed"),n.setAttribute("aria-expanded","true"),u(!0)):(p.style.maxHeight=p.scrollHeight+"px",requestAnimationFrame(()=>{i.classList.add("easy-form-group-collapsed"),n.setAttribute("aria-expanded","false"),u(!1)}))})}else{if(e.label){let n=document.createElement("h3");n.className="easy-form-group-label",n.textContent=e.label,i.appendChild(n)}if("fields"in e&&e.fields)for(let n of e.fields){let l=n.name.startsWith(e.name+".")?n.name:`${e.name}.${n.name}`,d={...n,name:l},m=this.renderField(d);m&&i.appendChild(m)}}return i}renderRow(e){let a=document.createElement("div");a.className="easy-form-row";let r=e;if(a.style.display="flex",a.style.flexWrap="wrap",a.style.alignItems=r.align||"stretch",r.gap!==void 0){let o=typeof r.gap=="number"?`${r.gap}px`:r.gap;a.style.gap=o}else a.style.gap="1rem";if("fields"in e&&e.fields)for(let o of e.fields){let s=this.renderField(o);if(s){let i=document.createElement("div");i.style.flex="1",i.style.minWidth="0",i.appendChild(s),a.appendChild(i)}}return a}renderArray(e){let a=document.createElement("div");if(a.className="easy-form-array",a.setAttribute("data-field-name",e.name),e.label){let m=document.createElement("label");m.className="easy-form-label",m.textContent=e.label,a.appendChild(m)}let r=this.stateManager.getValue(e.name)||[],o=e,s=o.minItems??0,i=o.maxItems??1/0,n=document.createElement("div");n.className="easy-form-array-items";for(let m=0;m<r.length;m++){let p=document.createElement("div");if(p.className="easy-form-array-item",o.itemSchema?.fields)for(let g of o.itemSchema.fields){let f={...g,name:`${e.name}.${m}.${g.name}`},b=this.renderField(f);b&&p.appendChild(b)}let u=document.createElement("button");u.type="button",u.textContent="Eliminar",u.className="easy-form-array-remove";let h=r.length<=s;this.disabled||this.loading||h?u.disabled=!0:u.addEventListener("click",()=>{let g=[...r];g.splice(m,1),this.handleFieldChange(e.name,g)}),p.appendChild(u),n.appendChild(p)}a.appendChild(n);let l=document.createElement("button");l.type="button",l.textContent="Agregar",l.className="easy-form-array-add";let d=r.length>=i;return this.disabled||this.loading||d?l.disabled=!0:l.addEventListener("click",()=>{let m=this.stateManager.createDefaultArrayItem(e),p=[...r,m];this.handleFieldChange(e.name,p)}),a.appendChild(l),a}renderCustom(e){let a=le("custom");if(!a){let i=document.createElement("div");return i.textContent=`Componente custom no registrado para: ${e.name}`,i}let r=this.stateManager.getValue(e.name),o=this.stateManager.getErrors(e.name),s=o.length>0?o[0]:void 0;return a({field:e,value:r,error:s,onChange:i=>this.handleFieldChange(e.name,i),onBlur:()=>this.handleFieldBlur(e.name)})}getCompletedRequiredProgress(e){let a=d=>{let m=[];for(let p of d)if(p.type==="array"&&"itemSchema"in p&&p.itemSchema?.fields){let u=this.stateManager.getValue(p.name),h=Array.isArray(u)?u.length:0;for(let g=0;g<h;g++)for(let f of p.itemSchema.fields)m.push({...f,name:`${p.name}.${g}.${f.name}`})}else(p.type==="group"||p.type==="row")&&"fields"in p&&p.fields?m.push(...a(p.fields)):m.push(p);return m},r=e.steps?this.stateManager.getCurrentStepFields()||[]:e.fields||[],i=a(r).filter(d=>d.validations?.some(m=>m.type==="required")).filter(d=>this.stateManager.getFieldVisibility(d.name)),n=i.length;return{completed:i.filter(d=>{if(this.stateManager.getErrors(d.name).length>0)return!1;let p=this.stateManager.getValue(d.name);return!(p==null||typeof p=="string"&&p.trim()===""||Array.isArray(p)&&p.length===0&&d.type==="array")}).length,total:n}}renderWizard(e,a){let r=this.stateManager.getWizardState();if(!r)return;let o=document.createElement("div");o.className="easy-form-wizard";let s=document.createElement("div");if(s.className="easy-form-wizard-steps",a?.steps)for(let m=0;m<a.steps.length;m++){let p=document.createElement("div");p.className="easy-form-wizard-step",m===r.currentStep&&p.classList.add("active"),r.completedSteps.includes(m)&&p.classList.add("completed"),p.textContent=a.steps[m].title,s.appendChild(p)}o.appendChild(s);let i=document.createElement("div");i.className="easy-form-wizard-fields";let n=this.stateManager.getCurrentStepFields();this.renderFields(i,n),o.appendChild(i);let l=document.createElement("div");if(l.className="easy-form-wizard-nav",r.currentStep>0){let m=document.createElement("button");m.type="button",m.textContent="Anterior",m.className="easy-form-wizard-prev",this.disabled||this.loading?m.disabled=!0:m.addEventListener("click",()=>{this.stateManager.getWizardState()&&this.stateManager.previousStep()&&(this.render(),this.emitStepChange())}),l.appendChild(m)}if(r.currentStep<r.totalSteps-1){let m=document.createElement("button");m.type="button",m.textContent="Siguiente",m.className="easy-form-wizard-next",this.disabled||this.loading?m.disabled=!0:m.addEventListener("click",async()=>{let p=this.stateManager.getWizardState();if(!p)return;let u=this.stateManager.getCurrentStepFields();for(let b of u)this.stateManager.getFieldVisibility(b.name)&&await this.stateManager.validateField(b.name);let h=this.stateManager.getAllErrors(),g={};for(let b of u)h[b.name]&&h[b.name].length>0&&(g[b.name]=h[b.name]);Object.keys(g).length>0?this.emitError(g):(this.stateManager.completeStep(p.currentStep),this.stateManager.nextStep()&&(this.render(),this.emitStepChange()))}),l.appendChild(m)}let d=this.getSubmitButtonConfig(a);if(r.currentStep===r.totalSteps-1&&d.visible){let m=document.createElement("button");m.type="button",m.textContent=d.text,m.className="easy-form-wizard-next",m.style.width=d.width,this.disabled||this.loading?m.disabled=!0:m.addEventListener("click",async()=>{let p=this.stateManager.getCurrentStepFields();for(let f of p)this.stateManager.getFieldVisibility(f.name)&&await this.stateManager.validateField(f.name);let u=this.stateManager.getAllErrors(),h={};for(let f of p)u[f.name]&&u[f.name].length>0&&(h[f.name]=u[f.name]);Object.keys(h).length>0?this.emitError(h):await this.handleSubmit(new Event("submit"))}),l.appendChild(m)}o.appendChild(l),e.appendChild(o)}async handleFieldChange(e,a){await this.stateManager.setValue(e,a),this.scheduleSave();let r=this.schema;if(r){let i=this.findFieldInSchema(r,e);i?.type==="array"&&(this.rerenderArrayField(i)||(this.skipPreserveValuesOnNextRender=!0,requestAnimationFrame(()=>this.render())))}let o=this.stateManager.getDependentFields(e);o.length>0&&(this.dependencyRenderTimeout&&clearTimeout(this.dependencyRenderTimeout),this.dependencyRenderTimeout=setTimeout(()=>{this.renderDependentFields(o),this.emitDependencyChange(e,o)},10));let s=new CustomEvent("change",{detail:{field:e,value:a,values:this.stateManager.getState().values},bubbles:!0,composed:!0});this.dispatchEvent(s)}rerenderArrayField(e){let a=this.shadow.querySelector(`[data-field-name="${e.name}"].easy-form-array`);if(!a?.parentNode)return!1;let r=this.renderArray(e);return a.parentNode.replaceChild(r,a),!0}renderDependentFields(e){let a=this.shadow.querySelector("form");if(!a)return;let r=this.schema;if(r)for(let o of e){let s=a.querySelector(`.easy-form-field[name="${o}"], [data-field-name="${o}"]`)?.closest(".easy-form-field")??a.querySelector(`[data-field-name="${o}"]`);if(s){let i=this.findFieldInSchema(r,o);if(!i)continue;let n=this.renderField(i);n&&s.parentNode&&s.parentNode.replaceChild(n,s)}}}emitDependencyChange(e,a){let r=new CustomEvent("dependencyChange",{detail:{changedField:e,affectedFields:a},bubbles:!0,composed:!0});this.dispatchEvent(r)}async handleFieldBlur(e){this.stateManager.setTouched(e),await this.stateManager.validateField(e),this.updateSingleField(e)}updateSingleField(e){let a=this.schema;if(!a||!this.findFieldInSchema(a,e))return;let o=this.stateManager.getErrors(e),s=o.length>0?o[0]:void 0,i=this.shadow.querySelector(`[name="${e}"]`)?.closest(".easy-form-field");if(!i)return;let n=i.querySelector(".easy-form-error");if(s){if(n)n.textContent=s;else{let d=document.createElement("p");d.className="easy-form-error",d.textContent=s,i.appendChild(d)}i.querySelector("input, textarea, select")?.classList.add("easy-form-input-error")}else n?.remove(),i.querySelector("input, textarea, select")?.classList.remove("easy-form-input-error")}findFieldInSchema(e,a){let r=e.fields||[],o=a.indexOf(".");if(o>0){let s=a.slice(0,o),i=a.slice(o+1),n=r.find(l=>l.name===s);if(!n)return null;if((n.type==="group"||n.type==="row")&&"fields"in n&&n.fields){let l=this.findFieldInSchema({fields:n.fields},i);return l?{...l,name:a}:null}return null}for(let s of r){if(s.name===a)return s;if(s.type==="group"&&"fields"in s){let i=this.findFieldInSchema({fields:s.fields},a);if(i)return i}if(s.type==="row"&&"fields"in s){let i=this.findFieldInSchema({fields:s.fields},a);if(i)return i}}return null}async handleSubmit(e){if(e.preventDefault(),this.attemptsLock?.isLocked())return;let a=await this.stateManager.validateForm(),r=this.stateManager.getState();if(Object.keys(a).length>0){for(let s of Object.keys(a))this.updateSingleField(s);this.emitError(a);return}let o=new CustomEvent("submit",{detail:{values:r.values,isValid:!0,errors:{}},bubbles:!0,composed:!0});this.dispatchEvent(o),this.clearPersistence()}emitError(e){let a=new CustomEvent("error",{detail:{errors:e},bubbles:!0,composed:!0});this.dispatchEvent(a)}emitStepChange(){let e=this.stateManager.getWizardState();if(!e)return;let a=new CustomEvent("stepChange",{detail:{currentStep:e.currentStep,previousStep:e.currentStep>0?e.currentStep-1:e.currentStep,totalSteps:e.totalSteps},bubbles:!0,composed:!0});this.dispatchEvent(a)}registerComponents(e){this.customComponents={...this.customComponents,...e},be(e)}reset(){this.stateManager.reset(),this.render()}incrementAttempts(){this.attemptsLock?.incrementAttempts(),this.attemptsLock?.isLocked()&&this.updateLockOverlay()}resetAttempts(){this.attemptsLock?.reset(),this.stopLockCountdown(),this.updateLockOverlay(),this.render()}isLocked(){return this.attemptsLock?.isLocked()??!1}getRemainingBlockTimeMs(){return this.attemptsLock?.getRemainingBlockTimeMs()??0}requestSubmit(){let e=this.shadow.querySelector("form");e&&typeof e.requestSubmit=="function"&&e.requestSubmit()}clear(){let e=this.schema,a=this.template,r=null;a?r=this.getSchemaFromTemplate(a):r=e,r&&(this.stateManager.initializeSchema(r,{}),this.render())}getValues(){return this.stateManager.getState().values}getValue(e){return this.stateManager.getValue(e)}async setValue(e,a){await this.stateManager.setValue(e,a),this.render()}async setValues(e){for(let[a,r]of Object.entries(e))await this.stateManager.setValue(a,r);this.render()}async validate(){let e=await this.stateManager.validateForm();if(Object.keys(e).length>0){for(let a of Object.keys(e))this.updateSingleField(a);this.emitError(e)}else this.shadow.querySelectorAll(".easy-form-error").forEach(o=>o.remove()),this.shadow.querySelectorAll(".easy-form-input-error").forEach(o=>o.classList.remove("easy-form-input-error"));return e}async validateField(e){return await this.stateManager.validateField(e),this.updateSingleField(e),this.stateManager.getErrors(e)}getErrors(){return this.stateManager.getAllErrors()}getFieldErrors(e){return this.stateManager.getErrors(e)}isValid(){return this.stateManager.getState().isValid}get theme(){let e=this.getAttribute("theme");return e&&["plano","tradicional","material","rounded-shadow","lines","shadcn","chakra","mantine","glass","bordered","minimal","efc"].includes(e)?e:"plano"}set theme(e){e?this.setAttribute("theme",e):this.removeAttribute("theme")}get colors(){let e=this.getAttribute("colors");return e?F(e):null}set colors(e){e?this.setAttribute("colors",A(e)):this.removeAttribute("colors")}get initialData(){let e=this.getAttribute("initialData");return e?F(e):null}set initialData(e){e?this.setAttribute("initialData",A(e)):this.removeAttribute("initialData")}get loading(){return this.hasAttribute("loading")}set loading(e){e?this.setAttribute("loading",""):this.removeAttribute("loading")}get disabled(){return this.hasAttribute("disabled")}set disabled(e){e?this.setAttribute("disabled",""):this.removeAttribute("disabled")}setupStyles(){let e=this.shadow.querySelector("style");e&&e.remove();let a=this.theme,r=N(this.colors||void 0),o=H(a,r),s=document.createElement("style");s.textContent=o,this.shadow.firstChild?this.shadow.insertBefore(s,this.shadow.firstChild):this.shadow.appendChild(s)}initPersistence(e){if(!e.persistence||!e.persistence.enabled){this.persistenceConfig=null;return}this.persistenceConfig={enabled:!0,key:e.persistence.key,autoSave:e.persistence.autoSave??!0,debounce:e.persistence.debounce??500,onRestore:e.persistence.onRestore},this.restoreFromStorage()}restoreFromStorage(){if(!(!this.persistenceConfig||!this.persistenceConfig.enabled)&&this.persistenceConfig.key)try{let e=localStorage.getItem(this.persistenceConfig.key);if(e){let a=JSON.parse(e);a&&typeof a=="object"&&(this.pendingRestoreValues=a,this.persistenceConfig.onRestore&&this.persistenceConfig.onRestore(a))}}catch(e){console.warn("EasyForm: Error restoring from localStorage:",e)}}applyPendingRestoreValues(){if(!this.pendingRestoreValues||this.isRestoringValues)return;this.isRestoringValues=!0;let e={...this.pendingRestoreValues};this.pendingRestoreValues=null;for(let[a,r]of Object.entries(e))this.stateManager.setValueWithoutValidation(a,r);this.updateInputsWithValues(e),this.isRestoringValues=!1}updateInputsWithValues(e){for(let a of Object.keys(e)){let r=this.shadow.querySelector(`[name="${a}"]`);r&&(r.value=e[a]??"")}}saveToStorage(){if(!(!this.persistenceConfig||!this.persistenceConfig.enabled)&&this.persistenceConfig.key)try{let e=this.stateManager.getState().values;localStorage.setItem(this.persistenceConfig.key,JSON.stringify(e))}catch(e){console.warn("EasyForm: Error saving to localStorage:",e)}}scheduleSave(){!this.persistenceConfig||!this.persistenceConfig.enabled||this.persistenceConfig.autoSave&&(this.persistenceDebounceTimer&&clearTimeout(this.persistenceDebounceTimer),this.persistenceDebounceTimer=setTimeout(()=>{this.saveToStorage()},this.persistenceConfig.debounce))}clearPersistence(){if(!(!this.persistenceConfig||!this.persistenceConfig.key))try{localStorage.removeItem(this.persistenceConfig.key)}catch(e){console.warn("EasyForm: Error clearing localStorage:",e)}}};typeof window<"u"&&typeof customElements<"u"&&!customElements.get("easy-form")&&customElements.define("easy-form",ce);export{V as AttemptsLock,L as ConditionEngine,ce as EasyForm,$ as INJECTION_VALIDATION_MESSAGE,M as MaskEngine,Ie as PREDEFINED_MASKS,I as SchemaParser,P as StateManager,R as ValidationEngine,A as attributeValue,Ne as containsInjection,ye as createInput,ve as extendTemplate,Bt as generateId,it as getAvailableTemplates,N as getColors,le as getCustomComponent,T as getNestedValue,fe as getPredefinedMask,me as getTemplate,H as getThemeStyles,q as isSafeFromInjection,qe as isValidEmail,F as parseAttributeValue,$e as registerComponent,be as registerComponents,Ot as sanitizeId,z as setNestedValue,de as templates};
|
|
2176
2176
|
//# sourceMappingURL=index.js.map
|