UNPKG

form-functionality-library

Version:

A modular, flexible form functionality library for Webflow forms supporting single-step, multi-step, and branching forms

1 lines 33.3 kB
"use strict";var FormLib=(()=>{var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,a={};((t,i)=>{for(var n in i)e(t,n,{get:i[n],enumerable:!0})})(a,{FormState:()=>E,clearAllErrors:()=>M,clearError:()=>O,clearSummary:()=>ze,default:()=>De,getCurrentStepInfo:()=>Pe,getNextStep:()=>C,goToStep:()=>ke,initBranching:()=>A,initErrors:()=>V,initMultiStep:()=>Se,initSummary:()=>_e,initValidation:()=>U,resetBranching:()=>L,showError:()=>z,showStep:()=>Ie,updateSummary:()=>Le,validateAllVisibleFields:()=>W,validateField:()=>K,validateStep:()=>G});var r={MULTISTEP:'[data-form="multistep"]',LOGIC:"[data-logic]",STEP:'[data-form="step"]',ANSWER:"[data-answer]",NEXT_BTN:'[data-form="next-btn"]',BACK_BTN:'[data-form="back-btn"]',SUBMIT:'[data-form="submit"]',SKIP:"[data-skip]",ERROR_DISPLAY:'[data-form="error"]',SKIP_TO:"[data-skip-to]",SKIP_IF:"[data-skip-if]",SKIP_UNLESS:"[data-skip-unless]",SKIP_SECTION:"[data-skip-section]",ALLOW_SKIP_UNDO:"[data-allow-skip-undo]",SKIP_REASON:"[data-skip-reason]",GO_TO:"[data-go-to]",SHOW_IF:"[data-show-if]",SKIP_BTN:'[data-form="skip-btn"]',SUBMIT_BTN:'[data-form="submit-btn"]',STEP_TYPE:"[data-step-type]",STEP_SUBTYPE:"[data-step-subtype]",STEP_NUMBER:"[data-step-number]",STEP_FIELD_NAME:"[data-step-field-name]",SUMMARY_FIELD:"[data-summary-field]",SUMMARY_TYPE:"[data-summary-type]",SUMMARY_SUBTYPE:"[data-summary-subtype]",SUMMARY_NUMBER:"[data-summary-number]",JOIN:"[data-join]",REQUIRED:"[required]",ERROR_MESSAGE:"[data-error-message]",VALIDATE:"[data-validate]"},s={START_STEP:1,DEBUG:!0,LOG_PREFIX:"[FormLib]",VALIDATION_DELAY:300,ANIMATION_DURATION:300,JOIN_SEPARATOR:{space:" ",comma:", ",dash:" - ",pipe:" | ",newline:"\n"}},o={ACTIVE_STEP:"active-step",HIDDEN_STEP:"hidden-step",HIDDEN_STEP_ITEM:"hidden-step-item",ERROR_FIELD:"error-field",ACTIVE_ERROR:"active-error",DISABLED:"disabled",SKIPPED_STEP:"skipped-step",SKIP_AVAILABLE:"skip-available",SKIP_DISABLED:"skip-disabled"},l=new Map;function d(e,t){if(!s.DEBUG)return;const i=(new Date).toISOString().split("T")[1].split(".")[0],n=`${s.LOG_PREFIX} [${i}]`;void 0!==t?console.log(`${n} ${e}`,t):console.log(`${n} ${e}`)}function c(e,t=document){if(t===document){const i=`all:${e}`;if(l.has(i))return l.get(i);const n=t.querySelectorAll(e);return l.set(i,n),n}return t.querySelectorAll(e)}function p(e,t=document){if(t===document){const i=`single:${e}`;if(l.has(i))return l.get(i);const n=t.querySelector(e);return l.set(i,n),n}return t.querySelector(e)}function u(e,t){return e.getAttribute(t)}function f(e,t){e.classList.add(t)}function m(e,t){e.classList.remove(t)}function h(e){m(e,"hidden-step"),e.style.display="",d("Showing element:",e)}function S(e){f(e,"hidden-step"),e.style.display="none",d("Hiding element:",e)}function g(e){return"none"!==e.style.display&&!function(e,t){return e.classList.contains(t)}(e,"hidden-step")}function y(e){return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement}function v(e){return e instanceof HTMLInputElement?"checkbox"===e.type||"radio"===e.type?e.checked?e.value:"":e.value:e instanceof HTMLSelectElement&&e.multiple?Array.from(e.selectedOptions).map(e=>e.value):e.value}function b(e,t,i,n){const a=e=>{const t=e.target?.closest(i);t&&n(e,t)};return e.addEventListener(t,a),()=>{e.removeEventListener(t,a)}}var E=class e{constructor(){this.data={},this.steps={},this.branchPath={currentStep:"",previousSteps:[],skippedSteps:[],skipHistory:[],activeConditions:{}},d("FormState initialized")}static getInstance(){return e.instance||(e.instance=new e),e.instance}setField(e,t){const i=this.data[e];this.data[e]=t,d(`Field updated: ${e}`,{oldValue:i,newValue:t}),this.onFieldChange(e,t,i)}getField(e){return this.data[e]}getAll(){return{...this.data}}clear(){const e={...this.data};this.data={},this.steps={},this.branchPath={currentStep:"",previousSteps:[],skippedSteps:[],skipHistory:[],activeConditions:{}},d("FormState cleared",{oldData:e})}clearFields(e){const t={};e.forEach(e=>{void 0!==this.data[e]&&(t[e]=this.data[e],delete this.data[e])}),Object.keys(t).length>0&&d("Fields cleared due to branch change",t)}setStepInfo(e,t){this.steps[e]||(this.steps[e]={visible:!1,visited:!1}),Object.assign(this.steps[e],t),d(`Step info updated: ${e}`,this.steps[e])}getStepInfo(e){return this.steps[e]}getAllSteps(){return{...this.steps}}setStepVisibility(e,t){this.setStepInfo(e,{visible:t}),d(`Step visibility updated: ${e}`,{visible:t})}setCurrentStep(e){this.branchPath.currentStep&&this.branchPath.currentStep!==e&&this.branchPath.previousSteps.push(this.branchPath.currentStep),this.branchPath.currentStep=e,this.setStepInfo(e,{visited:!0}),d(`Current step changed to: ${e}`,this.branchPath)}getCurrentStep(){return this.branchPath.currentStep}getBranchPath(){return{...this.branchPath}}addSkippedStep(e,t,i=!0){if(!this.branchPath.skippedSteps.includes(e)){this.branchPath.skippedSteps.push(e);const n={stepId:e,reason:t,timestamp:Date.now(),canUndo:i,fieldsCleared:[]};this.branchPath.skipHistory.push(n),this.setStepInfo(e,{skipped:!0,skipReason:t,allowSkipUndo:i}),d(`Step skipped: ${e}`,{reason:t,canUndo:i,totalSkipped:this.branchPath.skippedSteps.length})}}undoSkipStep(e){const t=this.branchPath.skippedSteps.indexOf(e);if(-1===t)return d(`Cannot undo skip - step not in skipped list: ${e}`),!1;const i=this.getStepInfo(e);if(i&&!1===i.allowSkipUndo)return d(`Cannot undo skip - undo not allowed for step: ${e}`),!1;this.branchPath.skippedSteps.splice(t,1),this.setStepInfo(e,{skipped:!1,skipReason:void 0});const n=this.branchPath.skipHistory.find(t=>t.stepId===e);return n&&(n.canUndo=!1),d(`Skip undone for step: ${e}`,{remainingSkipped:this.branchPath.skippedSteps.length}),!0}isStepSkipped(e){return this.branchPath.skippedSteps.includes(e)}getSkipHistory(){return[...this.branchPath.skipHistory]}getSkippedSteps(){return[...this.branchPath.skippedSteps]}clearSkipHistory(){this.branchPath.skippedSteps=[],this.branchPath.skipHistory=[],Object.keys(this.steps).forEach(e=>{this.steps[e].skipped&&this.setStepInfo(e,{skipped:!1,skipReason:void 0})}),d("Skip history cleared")}getSkipStats(){const e={totalSkipped:this.branchPath.skippedSteps.length,canUndoCount:0,skipReasons:{}};return this.branchPath.skipHistory.forEach(t=>{t.canUndo&&e.canUndoCount++,t.reason&&(e.skipReasons[t.reason]=(e.skipReasons[t.reason]||0)+1)}),e}setActiveCondition(e,t){this.branchPath.activeConditions[e]=t,d(`Active condition set: ${e}`,t)}getActiveCondition(e){return this.branchPath.activeConditions[e]}getFieldsByStep(){const e={};return Object.entries(this.data).forEach(([t,i])=>{e[t]=i}),e}onFieldChange(e,t,i){t!==i&&d(`Field change detected: ${e}`,{from:i,to:t})}goToPreviousStep(){const e=this.branchPath.previousSteps.pop();return e?(this.branchPath.currentStep=e,d(`Went back to previous step: ${e}`,this.branchPath),e):null}wasStepVisited(e){return this.steps[e]?.visited||!1}isStepVisible(e){return this.steps[e]?.visible||!1}getDebugInfo(){return{data:this.data,steps:this.steps,branchPath:this.branchPath,fieldCount:Object.keys(this.data).length,stepCount:Object.keys(this.steps).length}}}.getInstance(),k=!1,I=[];function A(e=document){k&&(d("Branching already initialized, cleaning up first"),L()),d("Initializing branching logic"),function(e){const t=b(e,"change",r.GO_TO,T),i=b(e,"input",r.GO_TO,T),n=b(e,"click",r.GO_TO,T),a=b(e,"click","label.radio_field, .w-radio, .radio_button-skip-step, .w-form-formradioinput, .w-radio-input",P);I.push(t,i,n,a)}(e),k=!0,d("Branching initialization complete")}function P(e,t){let i=null;if(i=t.querySelector('input[type="radio"][data-go-to]'),!i){const e=t.closest("label");e&&(i=e.querySelector('input[type="radio"][data-go-to]'))}if(!i){const e=t.closest(".radio_field, .w-radio, .radio_component");e&&(i=e.querySelector('input[type="radio"][data-go-to]'))}if(i&&u(i,"data-go-to")){e.preventDefault(),e.stopPropagation(),i.checked=!0,$(i);const t=new Event("change",{bubbles:!0});Object.defineProperty(t,"target",{value:i}),T(t,i)}}function T(e,t){if(!y(t))return;const i=u(t,"data-go-to");if(i&&!function(e){return!!e&&(!!/^[a-zA-Z0-9_-]+$/.test(e)||(d("Invalid data-go-to value format",{goToValue:e}),!1))}(i))return void d("Skipping branch trigger due to invalid data-go-to value",{goToValue:i});const n=v(t);d("Branch trigger activated",{element:t,goTo:i,value:n,type:t.type||t.tagName});const a=t.name||u(t,"data-step-field-name");a&&E.setField(a,n);try{if(t instanceof HTMLInputElement)if("radio"===t.type&&t.checked){if(!i)return void d("Radio button has no data-go-to attribute, skipping navigation");!function(e){if(!e.name)return;document.querySelectorAll(`input[type="radio"][name="${e.name}"]`).forEach(t=>{const i=t,n=u(i,"data-go-to");var a;i!==e&&n&&(_(n),a=n,E.setStepVisibility(a,!1),d(`Set step item visibility to false in FormState: ${a}`))})}(t),$(t),w(i,t.value),function(e){if(!e)return void d("No stepItemId provided to triggerStepItemVisibility");d(`Triggering visibility for step_item: ${e}`),function(e){E.setStepVisibility(e,!0),d(`Set step item visibility to true in FormState: ${e}`)}(e)}(i)}else"checkbox"===t.type?i&&(t.checked?w(i,t.value):_(i)):"radio"!==t.type&&"checkbox"!==t.type&&i&&(n?w(i,n):_(i));else i&&(n?w(i,n):_(i))}catch(e){d("Error handling branch trigger",{error:e,element:t})}const r=E.getBranchPath().activeConditions;Object.keys(r).length>0&&F()}function $(e){const t=u(e,"fs-inputactive-class")||"is-active-inputactive";if(e.name){document.querySelectorAll(`input[type="radio"][name="${e.name}"]`).forEach(i=>{const n=i,a=n.closest("label");n!==e&&(n.classList.remove(t),a?.classList.remove(t))})}e.classList.add(t);const i=e.closest("label");i?.classList.add(t)}function w(e,t){e&&E.setActiveCondition(e,t)}function _(e){e&&(d(`Deactivating branch: ${e}`),E.setActiveCondition(e,null),function(e){const t=[];document.querySelectorAll(`[data-go-to="${e}"]`).forEach(e=>{y(e)&&e.name&&t.push(e.name)}),t.length>0&&E.clearFields(t)}(e),F())}function C(e){const t=E.getBranchPath().activeConditions;return Object.keys(t).find(e=>t[e])||null}function F(){const e=c(r.STEP),t=E.getBranchPath().activeConditions;e.forEach(e=>{const i=u(e,"data-answer"),n=function(e,t){if(!e)return!0;const i=p(`[data-answer="${e}"]`);if(i){const e=u(i,"data-show-if");if(e){const i=function(e,t){if(!e||"string"!=typeof e)return d("Invalid condition provided",{condition:e}),!1;try{const i=e.trim();return i.includes(",")?i.split(",").map(e=>e.trim()).some(e=>!!t[e]):i.includes("&")?i.split("&").map(e=>e.trim()).every(e=>!!t[e]):!!t[i]}catch(t){return d("Error evaluating condition",{condition:e,error:t}),!1}}(e,t);return i}}return!1}(i,t);i&&E.setStepVisibility(i,n)})}function L(){d("Resetting branching logic"),I.forEach(e=>e()),I=[];const e=E.getBranchPath().activeConditions;Object.keys(e).forEach(e=>{E.setActiveCondition(e,null)});c(r.ANSWER).forEach(e=>{const t=e;t.style.display="none",t.classList.add("hidden-step")}),k=!1,d("Branching reset complete")}var N=new Map,R=new Map;function V(e=document){d("Initializing error handling");e.querySelectorAll("input, select, textarea").forEach(e=>{const t=e.name||u(e,"data-step-field-name");t&&N.set(t,{fieldName:t,element:e,customMessage:u(e,"data-error-message")||void 0})}),d(`Error handling initialized for ${N.size} fields`)}function z(e,t){const i=N.get(e);if(!i)return void d(`Cannot show error for unknown field: ${e}`);const n=t||i.customMessage||"This field has an error";d(`Showing error for field: ${e}`,{message:n}),f(i.element,o.ERROR_FIELD);const a=function(e){if(!e||!e.element)return d("Cannot create error element - no config or element provided"),null;if(!e.element.parentElement)return d(`Cannot create error element for field: ${e.fieldName} - no parent element`,{element:e.element,parentElement:e.element.parentElement,nodeName:e.element.nodeName,id:e.element.id}),null;let t=null;try{t=e.element.parentElement.querySelector(`${r.ERROR_DISPLAY}[data-field="${e.fieldName}"]`)}catch(t){return d(`Error finding existing error element for field: ${e.fieldName}`,t),null}if(!t)try{t=document.createElement("div"),t.setAttribute("data-form","error"),t.setAttribute("data-field",e.fieldName);const i=e.element.parentElement,n=e.element.nextSibling;n?i.insertBefore(t,n):i.appendChild(t),d(`Created error element for field: ${e.fieldName}`)}catch(t){return d(`Error creating error element for field: ${e.fieldName}`,t),null}return t}(i);a&&(a.textContent=n,f(a,o.ACTIVE_ERROR),i.errorElement=a),function(e){const t=e.getBoundingClientRect();t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)||(e.scrollIntoView({behavior:"smooth",block:"center"}),d(`Scrolled to field with error: ${e.name||"unnamed"}`))}(i.element)}function O(e){const t=N.get(e);t?(d(`Clearing error for field: ${e}`),m(t.element,o.ERROR_FIELD),t.errorElement&&(t.errorElement.textContent="",m(t.errorElement,o.ACTIVE_ERROR))):d(`Cannot clear error for unknown field: ${e}`)}function M(){d("Clearing all field errors"),N.forEach((e,t)=>{O(t)})}function x(){const e={};return R.forEach((t,i)=>{e[i]={message:t.message}}),e}var D=!1,B=[],q=new Map;function U(e=document){D&&(d("Validation already initialized, cleaning up first"),d("Resetting validation"),B.forEach(e=>e()),B=[],d("Clearing all field validation"),q.forEach((e,t)=>{X(t)}),q.clear(),D=!1,d("Validation reset complete")),d("Initializing form validation");const t=c("input, select, textarea",e);d(`Found ${t.length} form inputs`),t.forEach(e=>{if(!y(e))return;const t=e,i=t.name||u(e,"data-step-field-name");if(!i)return void d("Skipping field validation setup - no field name",{element:e,name:t.name,dataStepFieldName:u(e,"data-step-field-name"),id:t.id,type:t.type});const n=function(e){const t=[];e.hasAttribute("required")&&t.push({type:"required",message:u(e,"data-error-message")||"This field is required"}),e instanceof HTMLInputElement&&"email"===e.type&&t.push({type:"email",message:"Please enter a valid email address"}),e instanceof HTMLInputElement&&"tel"===e.type&&t.push({type:"phone",message:"Please enter a valid phone number"});const i=u(e,"minlength");i&&t.push({type:"min",value:parseInt(i),message:`Minimum ${i} characters required`});const n=u(e,"maxlength");n&&t.push({type:"max",value:parseInt(n),message:`Maximum ${n} characters allowed`});const a=u(e,"pattern");return a&&t.push({type:"pattern",value:new RegExp(a),message:"Please enter a valid format"}),t}(e);0!==n.length?(q.set(i,{element:e,rules:n,isValid:!0}),d(`Validation rules set for field: ${i}`,{rules:n.map(e=>e.type),rulesCount:n.length})):d(`No validation rules found for field: ${i}`)}),function(e){const t=function(e,t){let i;return(...n)=>{clearTimeout(i),i=setTimeout(()=>e(...n),t)}}((...e)=>{H(e[0],e[1])},s.VALIDATION_DELAY),i=b(e,"input","input, select, textarea",t),n=b(e,"blur","input, select, textarea",H),a=b(e,"change","input, select, textarea",H);B.push(i,n,a)}(e),D=!0,d("Validation initialization complete")}function H(e,t){if(!y(t))return;const i=t,n=i.name||u(t,"data-step-field-name");if(!n)return void d("Skipping validation - no field name found",{element:t,name:i.name,dataStepFieldName:u(t,"data-step-field-name")});const a=t.closest(r.STEP);if(a){const e=u(a,"data-answer");if(e&&!E.isStepVisible(e))return void d(`Skipping validation for field in hidden step: ${n}`)}K(n)}function K(e){const t=q.get(e);if(!t)return d(`No validation rules found for field: ${e}`),!0;const i=t.element;if(!i)return d(`No element found for field: ${e}`),!0;const n=v(i);d(`Validating field: ${e}`,{value:n,elementExists:!!i});for(const a of t.rules){const{isValid:r,message:s}=Z(n,a);if(!r)return t.isValid=!1,t.errorMessage=s||"Invalid field",z(e,t.errorMessage),Y(i,!1,t.errorMessage),!1}return t.isValid=!0,O(e),Y(i,!0),!0}var j={email:/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,phone:/^[\+]?[1-9][\d]{0,15}$/,phoneUS:/^(\+1\s?)?(\([0-9]{3}\)|[0-9]{3})[\s\-]?[0-9]{3}[\s\-]?[0-9]{4}$/,url:/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/,zipCode:/^\d{5}(-\d{4})?$/,zipCodeCA:/^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$/,creditCard:/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|3[0-9]{13}|6(?:011|5[0-9]{2})[0-9]{12})$/,ssn:/^\d{3}-?\d{2}-?\d{4}$/,strongPassword:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/};function Z(e,t){switch(t.type){case"required":return{isValid:Array.isArray(e)?e.length>0:!!e&&""!==String(e).trim(),message:t.message};case"email":return{isValid:j.email.test(String(e)),message:t.message||"Please enter a valid email address"};case"phone":const i=String(e).replace(/[\s\-\(\)]/g,"");return{isValid:j.phone.test(i)||j.phoneUS.test(String(e)),message:t.message||"Please enter a valid phone number"};case"min":return"number"!=typeof t.value?{isValid:!0}:{isValid:String(e).length>=t.value,message:t.message||`Minimum ${t.value} characters required`};case"max":return"number"!=typeof t.value?{isValid:!0}:{isValid:String(e).length<=t.value,message:t.message||`Maximum ${t.value} characters allowed`};case"pattern":return t.value instanceof RegExp?{isValid:t.value.test(String(e)),message:t.message||"Please enter a valid format"}:{isValid:!0};case"custom":if(!t.validator)return{isValid:!0};try{return{isValid:t.validator(e),message:t.message||"Invalid value"}}catch(e){return d("Error in custom validator",{error:e,rule:t}),{isValid:!1,message:"Validation error occurred"}}default:return{isValid:!0}}}function Y(e,t,i){const n=e.name||u(e,"data-step-field-name");n&&(t?O(n):z(n,i))}function G(e){const t=p(`[data-answer="${e}"]`);if(!t)return d(`Step not found with data-answer="${e}"`),!0;if(!E.isStepVisible(e))return d(`Skipping validation for hidden step: ${e}`),!0;d(`Validating step: ${e}`);const i=t.querySelectorAll("input, select, textarea");let n=!0;return i.forEach(e=>{if(!y(e))return;const t=e.name||u(e,"data-step-field-name");if(t){K(t)||(n=!1)}}),d(`Step validation result: ${e}`,{isValid:n}),n}function W(){d("Validating all visible fields");let e=!0;const t={};for(const[i,n]of q){const a=n.element.closest(r.STEP);let s=!0;if(a){const e=u(a,"data-answer");e&&!E.isStepVisible(e)&&(s=!1)}if(s){const n=K(i);t[i]=n,n||(e=!1)}}return d("All visible fields validation complete",{allValid:e,results:t}),e}function X(e){const t=q.get(e);t&&(t.isValid=!0,t.errorMessage=void 0,Y(t.element,!0),d(`Cleared validation for field: ${e}`))}var J=!1,Q=[],ee=new Map,te=new Map;function ie(e=document){J&&(d("Skip module already initialized, cleaning up first"),ce()),d("Initializing enhanced skip functionality"),function(e){const t=c(r.STEP,e);t.forEach(e=>{const t=u(e,"data-answer");if(!t)return;const i=u(e,"data-skip-if"),n=u(e,"data-skip-unless"),a=u(e,"data-skip-to"),r=u(e,"data-skip-reason"),s="false"!==u(e,"data-allow-skip-undo");if(i||n){const e=i||`!(${n})`,o={stepId:t,condition:e,targetStep:a||void 0,reason:r||"Conditional skip",allowUndo:s,clearFields:!0};ee.set(t,o),d(`Skip rule configured for step: ${t}`,{condition:e,targetStep:a,reason:r})}})}(e),function(e){const t=c(r.SKIP_SECTION,e);t.forEach(e=>{const t=u(e,"data-skip-section");if(!t)return;const i=u(e,"data-skip-if"),n=u(e,"data-skip-reason"),a=e.querySelectorAll(r.STEP),s=[];if(a.forEach(e=>{const t=u(e,"data-answer");t&&s.push(t)}),s.length>0){const e={sectionId:t,steps:s,condition:i||void 0,reason:n||`Section skip: ${t}`};te.set(t,e),d(`Skip section configured: ${t}`,{steps:s.length,condition:i,reason:n})}})}(e),function(e){const t=b(e,"click",r.SKIP_BTN,ne),i=b(e,"click",r.SKIP_TO,ae);Q.push(t,i)}(e),J=!0,d("Skip initialization complete",{skipRules:ee.size,skipSections:te.size})}function ne(e,t){e.preventDefault();const i=E.getCurrentStep();if(!i)return void d("No current step found for skip operation");re(i,u(t,"data-skip-reason")||"User skipped","false"!==u(t,"data-allow-skip-undo"),u(t,"data-skip-to")||void 0)}function ae(e,t){e.preventDefault();const i=u(t,"data-skip-to");if(!i)return void d("No target step specified for skip-to operation");!function(e,t,i=!0){const n=E.getCurrentStep();if(!n)return d("No current step found for skip-to operation"),!1;const a=function(e,t){const i=Array.from(document.querySelectorAll(r.STEP)),n=[];let a=!1;return i.forEach(i=>{const r=u(i,"data-answer");r&&(r!==e?r!==t?a&&n.push(r):a=!1:a=!0)}),n}(n,e);if(0===a.length)return d(`No steps to skip between ${n} and ${e}`),!1;a.forEach(e=>{re(e,t,i)}),de(e),d(`Skipped to step: ${e}`,{stepsSkipped:a.length,skippedSteps:a})}(i,u(t,"data-skip-reason")||`Skipped to ${i}`,"false"!==u(t,"data-allow-skip-undo"))}function re(e,t,i=!0,n){if(d(`Attempting to skip step: ${e}`,{reason:t,allowUndo:i,targetStep:n}),E.isStepSkipped(e))return d(`Step already skipped: ${e}`),!1;const a=function(e){const t=document.querySelector(`[data-answer="${e}"]`);if(!t)return[];const i=[];return t.querySelectorAll("input, select, textarea").forEach(e=>{const t=e,n=t.name||u(e,"data-step-field-name");n&&(X(n),t instanceof HTMLInputElement&&("checkbox"===t.type||"radio"===t.type)?t.checked=!1:t.value="",E.setField(n,null),i.push(n))}),i}(e);E.addSkippedStep(e,t,i);const r=E.getSkipHistory(),s=r[r.length-1];return s&&s.stepId===e&&(s.fieldsCleared=a),oe(e,!0),n?de(n):d("Navigation requested to next available step"),d(`Step skipped successfully: ${e}`,{fieldsCleared:a.length,targetStep:n}),!0}function se(){const e=E.getBranchPath().activeConditions;ee.forEach((t,i)=>{if(!t.condition)return;const n=le(t.condition,e),a=E.isStepSkipped(i);n&&!a?re(i,t.reason,t.allowUndo,t.targetStep):!n&&a&&t.allowUndo&&function(e){if(!E.isStepSkipped(e))return d(`Step is not skipped, cannot undo: ${e}`),!1;const t=E.undoSkipStep(e);t&&(oe(e,!1),d(`Skip undone for step: ${e}`))}(i)}),te.forEach((t,i)=>{if(!t.condition)return;le(t.condition,e)&&function(e,t){const i=te.get(e);if(!i)return d(`Skip section not found: ${e}`),!1;const n=t||i.reason||`Section skipped: ${e}`;let a=0;i.steps.forEach(e=>{re(e,n,!0)&&a++}),d(`Section skipped: ${e}`,{totalSteps:i.steps.length,skippedCount:a})}(i,t.reason)})}function oe(e,t){const i=document.querySelector(`[data-answer="${e}"]`);i&&(t?(f(i,o.SKIPPED_STEP),m(i,o.SKIP_AVAILABLE)):(m(i,o.SKIPPED_STEP),f(i,o.SKIP_AVAILABLE)))}function le(e,t){try{const i=e.trim();if(i.startsWith("!")){return!le(i.substring(1).trim(),t)}if(i.includes(",")){return i.split(",").map(e=>e.trim()).some(e=>!!t[e])}if(i.includes("&")){return i.split("&").map(e=>e.trim()).every(e=>!!t[e])}return!!t[i]}catch(t){return d("Error evaluating skip condition",{condition:e,error:t}),!1}}function de(e){d(`Navigation requested to step: ${e}`)}function ce(){d("Resetting skip functionality"),Q.forEach(e=>e()),Q=[],ee.clear(),te.clear(),E.clearSkipHistory(),J=!1,d("Skip reset complete")}var pe=!1,ue=[],fe=[],me=[],he=0;function Se(e=document){pe&&(d("MultiStep already initialized, cleaning up first"),ue.forEach(e=>e()),ue=[],ce(),fe=[],me=[],he=0,pe=!1,d("Multi-step module reset")),d("Initializing multi-step navigation with step/step_item architecture");const t=c(r.STEP,e);d(`Found ${t.length} parent steps`),fe=Array.from(t).map((e,t)=>{const i=e,n=u(e,"data-answer")||`step-${t}`,a={element:i,id:n,index:t,type:u(e,"data-step-type")||void 0,subtype:u(e,"data-step-subtype")||void 0,number:u(e,"data-step-number")||void 0,isStepItem:!1};return E.setStepInfo(n,{type:a.type,subtype:a.subtype,number:a.number,visible:0===t,visited:!1}),a}),me=[],fe.forEach((e,t)=>{e.element.querySelectorAll(".step_item, .step-item").forEach(e=>{const i=e,n=u(e,"data-answer");if(!n)return void d(`Step item ${t} in parent step ${t} missing required data-answer attribute`);const a={element:i,id:n,index:me.length,type:u(e,"data-step-type")||void 0,subtype:u(e,"data-step-subtype")||void 0,number:u(e,"data-step-number")||void 0,isStepItem:!0,parentStepIndex:t};E.setStepInfo(n,{type:a.type,subtype:a.subtype,number:a.number,visible:!1,visited:!1}),me.push(a)})}),fe.forEach((e,t)=>{S(e.element)}),me.forEach((e,t)=>{S(e.element)}),function(e){const t=b(e,"click",r.NEXT_BTN,ge),i=b(e,"click",r.BACK_BTN,ye),n=b(e,"click",r.SKIP,ve),a=b(e,"click",r.SKIP_BTN,ve),s=b(e,"click",r.SUBMIT_BTN,be);ue.push(t,i,n,a,s);const o=e.querySelectorAll(r.SKIP),l=e.querySelectorAll(r.SKIP_BTN);d("Skip button setup complete",{dataSkipCount:o.length,dataFormSkipBtnCount:l.length,primarySelector:r.SKIP,fallbackSelector:r.SKIP_BTN})}(e),ie(e),fe.length>0&&ke(0),pe=!0,d("Multi-step initialization complete",{parentStepCount:fe.length,stepItemCount:me.length})}function ge(e){e.preventDefault(),function(){if(!Ae())return void d("No current step found");se();const e=he+1;e<fe.length?ke(e):d("Already at last step")}()}function ye(e){e.preventDefault(),function(){const e=E.goToPreviousStep();if(e){const i=(t=e,fe.findIndex(e=>e.id===t));if(-1!==i)return void ke(i)}var t;const i=he-1;i>=0?ke(i):d("Already at first step")}()}function ve(e){e.preventDefault(),d("Skip button clicked!",{target:e.target,currentTarget:e.currentTarget,currentStepIndex:he,totalSteps:fe.length});const t=E.getCurrentStep();if(!t)return void d("No current step found for skip operation");d("Processing skip for step",{stepId:t,stepIndex:he});const i=Ae()?.element;let n=0;if(i){Array.from(i.querySelectorAll("input, select, textarea")).forEach(e=>{e instanceof HTMLInputElement&&("checkbox"===e.type||"radio"===e.type)?e.checked=!1:e.value="",e.name&&(E.setField(e.name,null),n++)})}d("Fields cleared during skip",{fieldsCleared:n}),E.addSkippedStep(t,"User skipped step",!0);const a=he+1;d("Attempting to navigate to next step",{currentIndex:he,nextIndex:a,totalSteps:fe.length}),a<fe.length?(ke(a),d("Successfully navigated to next step",{newIndex:a})):d("Cannot skip - already at last step")}function be(e){if(!e.target.closest("form"))return void d("Form not found, preventing submission");if(!function(){for(const e of fe)if(E.isStepVisible(e.id)&&!Ee(e.element))return!1;return!0}())return e.preventDefault(),void d("Form validation failed, preventing submission");d("Form validation passed, allowing submission")}function Ee(e){const t=e.querySelectorAll("input[required], select[required], textarea[required]");for(const e of t){const t=e;if(g(t)){if(!t.value||""===t.value.trim())return d("Validation failed: empty required field",{element:t,name:t.name,id:t.id}),t.focus(),!1;if("email"===t.type&&t.value){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.value))return d("Validation failed: invalid email format"),t.focus(),!1}}}return!0}function ke(e){if(d(`Attempting to go to step index: ${e}`),e<0||e>=fe.length)return void d(`Invalid step index: ${e}`);-1!==he&&he<fe.length&&function(e){if(e<0||e>=fe.length)return;const t=fe[e];S(t.element),E.setStepVisibility(t.id,!1),me.forEach(t=>{t.parentStepIndex===e&&S(t.element)}),d(`Hiding step ${e} (${t.id})`)}(he),Ie(e),he=e;const t=fe[e];E.setCurrentStep(t.id),function(){const e=document.querySelector(r.NEXT_BTN),t=document.querySelector(r.BACK_BTN),i=document.querySelector(r.SUBMIT_BTN);if(!e||!t||!i)return;const n=0===he,a=he===fe.length-1;t.style.display=n?"none":"",a?(e.style.display="none",i.style.display=""):(e.style.display="",i.style.display="none")}()}function Ie(e){if(e<0||e>=fe.length)return;const t=fe[e];h(t.element),E.setStepVisibility(t.id,!0),me.forEach(t=>{t.parentStepIndex===e&&E.isStepVisible(t.id)&&h(t.element)}),d(`Showing step ${e} (${t.id})`)}function Ae(){return fe[he]||null}function Pe(){return{step:Ae(),index:he,totalSteps:fe.length,isFirstStep:0===he,isLastStep:he===fe.length-1}}var Te=!1,$e=[],we=[];function _e(e=document){Te&&(d("Summary already initialized, cleaning up first"),d("Resetting summary functionality"),$e.forEach(e=>e()),$e=[],we.forEach(e=>{Ve(e.element,"")}),we=[],Te=!1,d("Summary reset complete")),d("Initializing summary functionality");const t=c(r.SUMMARY_FIELD,e);d(`Found ${t.length} summary fields`),function(e){e.forEach(e=>{const t=u(e,"data-summary-field");if(!t)return;const i=t.split("|").map(e=>e.trim()),n=u(e,"data-join"),a=n&&n in s.JOIN_SEPARATOR?n:"space",r=u(e,"data-summary-type")||void 0,o=u(e,"data-summary-subtype")||void 0,l=u(e,"data-summary-number")||void 0,c={element:e,fieldNames:i,joinType:a,type:r,subtype:o,number:l};we.push(c),d("Summary field configured",{fieldNames:i,joinType:a,type:r,subtype:o,number:l})})}(t),function(e){const t=b(e,"input",r.STEP_FIELD_NAME,Ce),i=b(e,"change",r.STEP_FIELD_NAME,Ce),n=b(e,"blur",r.STEP_FIELD_NAME,Ce);$e.push(t,i,n)}(e),Ne(),Te=!0,d("Summary initialization complete")}function Ce(e,t){if(!y(t))return;const i=u(t,"data-step-field-name");if(!i)return;const n=v(t);d(`Summary field changed: ${i}`,{value:n}),E.setField(i,n),Fe(i)}function Fe(e){we.forEach(t=>{t.fieldNames.includes(e)&&Re(t)})}function Le(){d("Updating all summaries"),Ne()}function Ne(){we.forEach(e=>{Re(e)})}function Re(e){const t=[];e.fieldNames.forEach(e=>{const i=E.getField(e);null!=i&&""!==i&&(Array.isArray(i)?t.push(...i.filter(e=>""!==e)):t.push(String(i)))});const i=function(e,t){if(0===e.length)return"";const i=s.JOIN_SEPARATOR[t];return e.join(i)}(t,e.joinType);Ve(e.element,i),d("Summary field updated",{fieldNames:e.fieldNames,values:t,joinType:e.joinType,result:i})}function Ve(e,t){e.textContent=t,""===t?(e.classList.add("summary-empty"),e.classList.remove("summary-filled")):(e.classList.remove("summary-empty"),e.classList.add("summary-filled"))}function ze(e){e?(d("Clearing specific summary fields",e),E.clearFields(e),e.forEach(e=>{Fe(e)})):(d("Clearing all summaries"),E.clear(),Ne())}function Oe(){const e={};return we.forEach((t,i)=>{const n=t.type&&t.subtype&&t.number?`${t.type}-${t.subtype}-${t.number}`:`summary-${i}`;e[n]={hasContent:(t.element.textContent||"").trim().length>0}}),e}var Me,xe=class e{constructor(){this.initialized=!1,this.rootElement=document,d("FormLibrary instance created")}static getInstance(){return e.instance||(e.instance=new e),e.instance}init(e=document){this.initialized&&(d("FormLibrary already initialized, reinitializing..."),this.destroy()),this.rootElement=e,d("Initializing FormLibrary with enhanced skip functionality",{root:e===document?"document":"custom element"});const t=e.querySelectorAll(r.MULTISTEP),i=e.querySelectorAll(r.LOGIC),n=e.querySelectorAll(r.STEP);if(d("Form detection results",{multistepForms:t.length,logicForms:i.length,stepElements:n.length}),0!==t.length||0!==n.length)try{V(e),U(e),i.length>0&&A(e),(t.length>0||n.length>0)&&Se(e),_e(e),this.initialized=!0,d("FormLibrary initialization complete with enhanced skip functionality"),this.logCurrentState()}catch(e){throw d("FormLibrary initialization failed",e),e}else d("No compatible forms found, library will not initialize")}destroy(){if(this.initialized){d("Destroying FormLibrary");try{L(),ce()}catch(e){d("Error during FormLibrary destruction",e)}E.clear(),l.clear(),this.initialized=!1,d("FormLibrary destruction complete")}else d("FormLibrary not initialized, nothing to destroy")}isInitialized(){return this.initialized}getState(){return{initialized:this.initialized,formState:E.getDebugInfo(),branching:{initialized:k,activeConditions:E.getBranchPath().activeConditions,branchPath:E.getBranchPath()},multiStep:{initialized:pe,currentStepIndex:he,totalSteps:fe.length,steps:fe.map(e=>({id:e.id,index:e.index,visible:g(e.element),type:e.type,subtype:e.subtype,number:e.number}))},validation:{initialized:D,fieldValidations:Array.from(q.entries()).reduce((e,[t,i])=>(e[t]={isValid:i.isValid,errorMessage:i.errorMessage,rules:i.rules.map(e=>e.type)},e),{})},errors:x(),summary:Oe(),skip:{initialized:J,skipRules:Array.from(ee.entries()).map(([e,t])=>({stepId:e,condition:t.condition,targetStep:t.targetStep,reason:t.reason,allowUndo:t.allowUndo,clearFields:t.clearFields})),skipSections:Array.from(te.entries()).map(([e,t])=>({sectionId:e,steps:t.steps,condition:t.condition,reason:t.reason})),currentSkipStats:E.getSkipStats(),skippedSteps:E.getSkippedSteps(),skipHistory:E.getSkipHistory()}}}logCurrentState(){d("Current FormLibrary State",this.getState())}validateForm(){if(!this.initialized)return d("Cannot validate form - library not initialized"),!1;d("Validating entire form");const e=W();return d("Form validation result",{isValid:e}),e}resetForm(){if(this.initialized){d("Resetting form to initial state"),M(),E.clear(),ze();try{ke(0)}catch(e){d("Could not go to first step during reset",e)}d("Form reset complete")}else d("Cannot reset form - library not initialized")}getFormData(){return E.getAll()}setFormData(e){Object.entries(e).forEach(([e,t])=>{E.setField(e,t)}),Le(),d("Form data set",e)}}.getInstance(),De=xe;if("undefined"!=typeof window){const e=()=>{const e=document.querySelectorAll(r.MULTISTEP),t=document.querySelectorAll(r.STEP);(e.length>0||t.length>0)&&(d("Auto-initializing FormLibrary on DOM ready"),xe.init())};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}return"undefined"!=typeof window&&(window.FormLib=xe,d("FormLib attached to window for debugging")),Me=a,((a,r,s,o)=>{if(r&&"object"==typeof r||"function"==typeof r)for(let l of i(r))n.call(a,l)||l===s||e(a,l,{get:()=>r[l],enumerable:!(o=t(r,l))||o.enumerable});return a})(e({},"__esModule",{value:!0}),Me)})();