PageSourceSearch

https://www.westernsydney.edu.au/etc.clientlibs/core/fd/af-clientl…-1eac79b380cced1980781d350721f32d-lc.min.js

js westernsydney.edu.au collected 2026-09-24 07:51:10 UTC 615,347 bytes, 8,914 lines download raw bytes

1(()=>{"use strict";var e={5848:function(e,t,i){var n=this&&this.__decorate||function(e,t,i,n){var s,r=arguments.length,a=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(s=e[o])&&(a=(r<3?s(a):r>3?s(t,i,a):s(t,i))||a);return r>3&&a&&Object.defineProperty(t,i,a),a},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.BaseNode=t.exclude=t.include=t.dependencyTracked=t.qualifiedName=t.target=t.staticFields=t.dynamicProps=t.editableProperties=void 0;const r=i(9333),a=i(3332),o=i(8744),l=i(3820),u=s(i(8224)),d=i(4476);t.editableProperties=["value","label","description","visible","enabled","valid","errorMessage","readOnly","enum","enumNames","required","properties","exclusiveMinimum","exclusiveMaximum","maximum","maxItems","minimum","minItems","checked","placeholder"],t.dynamicProps=[...t.editableProperties,"index","activeChild"],t.staticFields=["plain-text","image"];class c{constructor(e,t){this._action=e,e.target?(this._currentTarget=t,this._target=e.target):(this._target=t,this._currentTarget=t)}get type(){return this._action.type}get payload(){return this._action.payload}get metadata(){return this._action.metadata}get target(){return this._target}get currentTarget(){return this._currentTarget}get isCustomEvent(){return this._action.isCustomEvent}get originalAction(){return this._action.originalAction}toString(){return this._action.toString()}}t.target=Symbol("target"),t.qualifiedName=Symbol("qualifiedName"),t.dependencyTracked=function(){return function(e,t,i){const n=i.get;null!=n&&(i.get=function(){return this.ruleEngine.trackDependency(this,t),n.call(this)})}};const h=e=>(...t)=>(i,n,s)=>{const r=s.get;null!=r&&(s.get=function(){if(t.indexOf(this.fieldType)>-1===e)return r.call(this)});const a=s.set;null!=a&&(s.set=function(i){this===this._ruleNode&&console.error(`Property '${n}' is being set through a proxy, which is not supported. Please use globals.functions.setProperty instead.`),t.indexOf(this.fieldType)>-1===e&&a.call(this,i)})};t.include=h(!0),t.exclude=h(!1);class p{constructor(e,i){var n,s;this._options=i,this._lang="",this._callbacks={},this._dependents=[],this._tokens=[],this._eventSource=r.EventSource.CODE,this._fragment="$form",this._idSet=this.createIdSet(),this[t.qualifiedName]=null,this._jsonModel=Object.assign(Object.assign({},e),{id:this.form.getUniqueId(null==e?void 0:e.id)}),(null===(n=this.parent)||void 0===n?void 0:n.isFragment)?this._fragment=this.parent.qualifiedName:(null===(s=this.parent)||void 0===s?void 0:s.fragment)&&(this._fragment=this.parent.fragment),this._propertiesManager=new o.PropertiesManager(this)}createIdSet(){return new Set}get isContainer(){return!1}get fragment(){return this._fragment}setupRuleNode(){const e=this;this._ruleNode=new Proxy(this.ruleNodeReference(),{get:(t,i)=>e.getFromRule(t,i)})}ruleNodeReference(){return this}getRuleNode(){return this._ruleNode}getFromRule(e,i){if(i===Symbol.toPrimitive||"valueOf"===i&&!e.hasOwnProperty("valueOf"))return this.valueOf;if(i===t.target)return this;if("string"==typeof i)if(i.startsWith("$")){if("function"!=typeof this[i=i.substr(1)]){const e=this[i];return e instanceof p?e.getRuleNode():e instanceof Array?e.map((e=>e instanceof p?e.getRuleNode():e)):e}}else{if(e.hasOwnProperty(i))return e[i];if("function"==typeof e[i])return e[i]}}get id(){return this._jsonModel.id}get index(){return this.parent?this.parent.indexOf(this):0}get parent(){return this._options.parent}get type(){return this._jsonModel.type}get repeatable(){var e;return null===(e=this.parent)||void 0===e?void 0:e.hasDynamicItems()}get fieldType(){return this._jsonModel.fieldType||"text-input"}get":type"(){return this._jsonModel[":type"]||this.fieldType}get name(){return this._jsonModel.name}get screenReaderText(){return this._jsonModel.screenReaderText}get description(){return this._jsonModel.description}set description(e){this._setProperty("description",e)}get dataRef(){return this._jsonModel.dataRef}get visible(){var e,t;return void 0!==(null===(e=this.parent)||void 0===e?void 0:e.visible)?!!(null===(t=this.parent)||void 0===t?void 0:t.visible)&&this._jsonModel.visible:this._jsonModel.visible}set visible(e){if(e!==this._jsonModel.visible){const t=(0,a.propertyChange)("visible",e,this._jsonModel.visible);this._jsonModel.visible=e,this.notifyDependents(t)}}get form(){return this._options.form}get ruleEngine(){return this.form.ruleEngine}get label(){return this._jsonModel.label}set label(e){if(!(null!==e&&null!==this._jsonModel.label&&"object"==typeof e&&"object"==typeof this._jsonModel.label?JSON.stringify(e)===JSON.stringify(this._jsonModel.label):e===this._jsonModel.label)){const t=(0,a.propertyChange)("label",e,this._jsonModel.label);this._jsonModel=Object.assign(Object.assign({},this._jsonModel),{label:e}),this.notifyDependents(t)}}get uniqueItems(){return this._jsonModel.uniqueItems}
1isTransparent(){var e,t;const i="array"===(null===(t=null===(e=this.parent)||void 0===e?void 0:e._jsonModel)||void 0===t?void 0:t.type);return!this._jsonModel.name&&!i}getDependents(){return this._dependents.map((e=>({id:e.node.id,propertyName:e.propertyName})))}getState(e=!1){return this.withDependencyTrackingControl(!0,(()=>Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this._jsonModel),{properties:this.properties,index:this.index,parent:void 0,qualifiedName:this.qualifiedName}),!0===this.repeatable?{repeatable:!0,minOccur:this.parent.minItems,maxOccur:this.parent.maxItems}:{}),{":type":this[":type"]}),e?{_dependents:this._dependents.length?this.getDependents():void 0,allowedComponents:void 0,columnClassNames:void 0,columnCount:void 0,gridClassNames:void 0}:{})))}subscribe(e,t="change",i="view"){this._callbacks[t]=this._callbacks[t]||[];const n={callback:e,dependentType:i};return this._callbacks[t].push(n),{unsubscribe:()=>{this._callbacks[t]=this._callbacks[t].filter((t=>t.callback!==e))}}}_addDependent(e,i){if(void 0===this._dependents.find((({node:t,propertyName:n})=>{let s=t===e;return s&&i&&i.startsWith("properties.")&&(s=n===i),s}))){const n=this.subscribe((n=>{const s=n.payload.changes,r=[...t.dynamicProps,"items"];s.findIndex((e=>{const t=e.propertyName;return r.includes(t)||t.startsWith("properties.")&&i===t}))>-1&&("deps"===this.form.changeEventBehaviour?e.dispatch(n):e.dispatch(new a.ExecuteRule))}),"change","model");this._dependents.push({node:e,propertyName:i,subscription:n})}}removeDependent(e){const t=this._dependents.findIndex((({node:t})=>t===e));t>-1&&(this._dependents[t].subscription.unsubscribe(),this._dependents.splice(t,1))}queueEvent(e){if(this._onlyViewNotify)return;const t=new c(e,this);this.form.getEventQueue().queue(this,t,["valid","invalid"].indexOf(t.type)>-1)}dispatch(e){this._onlyViewNotify?this.notifyDependents(new c(e,this)):(this.queueEvent(e),this.form.getEventQueue().runPendingQueue())}withDependencyTrackingControl(e,t){var i,n,s;const r=null===(i=this.form)||void 0===i?void 0:i.ruleEngine.getDependencyTracking();e&&(null===(n=this.form)||void 0===n||n.ruleEngine.setDependencyTracking(!1));try{return t()}finally{e&&(null===(s=this.form)||void 0===s||s.ruleEngine.setDependencyTracking(r))}}notifyDependents(e){const t=this._jsonModel._dependents;t&&(t.forEach((e=>{const t=this.form.getElement(e.id);t&&this._addDependent(t,e.propertyName)})),this._jsonModel._dependents=void 0);const i=this._onlyViewNotify,n=this._callbacks[e.type]||[];(i?n.filter((e=>
1"view"===e.dependentType||void 0===e.dependentType)):n).forEach((({callback:t})=>{this.withDependencyTrackingControl(!0,(()=>{t(new c(e,this))}))}))}isEmpty(e=this._jsonModel.value){return null==e||""===e}_setProperty(e,t,i=!0,n=(e=>{})){const s=this._jsonModel[e];let r=!1;if(r=null!==t&&null!==s&&"object"==typeof t&&"object"==typeof s?JSON.stringify(t)===JSON.stringify(s):s===t,!r){this._jsonModel[e]=t;const r=(0,a.propertyChange)(e,t,s);return i&&this.notifyDependents(r),n.call(this,r),d.validationConstraintsList.includes(e)&&(void 0===this.hasValueBeenSet||this.hasValueBeenSet)&&this.validate(),r.payload.changes}return[]}bindToDataModel(e){if("form"===this.fieldType||"$form"===this.id)return void(this._data=e);const i=this._jsonModel.dataRef;let n,s=e,r="";if(null===i)n=u.default;else if(void 0===i||this.repeatable){if(e!==u.default&&-1===t.staticFields.indexOf(this.fieldType)){s=e;const t=this._jsonModel.name||"",i="array"===e.$type?this.index:t;if(r=i,""!==i){const s=this.defaultDataModel(i);void 0!==s&&("function"==typeof e.$getDataNode?(n=e.$getDataNode(i),void 0===n&&(n=s,e.$addDataNode(i,n))):(console.error(`$getDataNode method is undefined for "${t}" with dataModel type "${e.$type}"`),n=void 0))}else n=void 0}}else try{0===this._tokens.length&&(this._tokens=(0,l.tokenize)(i));let t=e;if(this._tokens[0].type===l.TOK_GLOBAL)t=this.form.getDataNode();else if(this._tokens[0].type===l.TOK_REPEATABLE){let e=this.parent;for(;!e.repeatable&&e!==this.form;)e=e.parent;t=e.getDataNode()}if(void 0!==t){const e=this._tokens[this._tokens.length-1].value,i=this.defaultDataModel(e);n=(0,l.resolveData)(t,this._tokens,i),s=(0,l.resolveData)(t,this._tokens.slice(0,-1)),r=e}}catch(e){console.error(`Error parsing dataRef "${i}" for field "${this.id}". The data of this field will not be exported.`)}if(n){if(!this.isContainer&&s!==u.default&&n!==u.default){if(n.$isDataGroup&&n.$_fields.length>0)return console.error(`Data binding conflict: non-container field "${this._jsonModel.name||this.id}" with dataRef "${i}" points to a DataGroup already bound by a container. This would destroy existing child data. The data of this field will not be exported.`),this._data;n=null==n?void 0:n.$convertToDataValue(),s.$addDataNode(r,n,!0)}null==n||n.$bindToField(this),this._data=n}return this._data}getDataNode(){return this._data}get lang(){return this._jsonModel.lang&&(this._lang=this._jsonModel.lang),this._lang||(this.parent?this._lang=this.parent.lang:this._lang=Intl.DateTimeFormat().resolvedOptions().locale),this._lang}get properties(){return this._propertiesManager.properties}set properties(e){this._propertiesManager.properties=e}getPropertiesManager(){return this._propertiesManager}getNonTransparentParent(){let e=this.parent;for(;null!=e&&e.isTransparent();)e=e.parent;return e}_isAncestorRepeatable(){let e=this.parent;for(;e&&!e.repeatable;)e=e.parent;return Boolean(e)}_initialize(e){if(void 0===this._data){let e,t=this.parent;do{e=t.getDataNode(),t=t.parent}while(void 0===e);this.bindToDataModel(e)}}_applyUpdates(e,t){return e.reduce(((e,i)=>{const n=t[i],s=this._setProperty(i,n,!1);return s.length>0&&(e[i]=s[0]),e}),{})}get qualifiedName(){if(this.isTransparent())return null;if(null!==this[t.qualifiedName])return this[t.qualifiedName];const e=this.getNonTransparentParent();let i;return i=e&&"array"===e.type?`${e.qualifiedName}[${this.index}]`:`${e.qualifiedName}.${this.name}`,this.repeatable||this._isAncestorRepeatable()||(this[t.qualifiedName]=i),i}focus(){this.parent&&(this.parent.activeChild=this)}_getDefaults(){return{}}_applyDefaultsInModel(){Object.entries(this._getDefaults()).map((([e,t])=>{void 0===this._jsonModel[e]&&void 0!==t?this._jsonModel[e]=t:"object"!=typeof t||null===t||Array.isArray(t)||Object.keys(t).forEach((i=>{void 0===this._jsonModel[e][i]&&(this._jsonModel[e][i]=t[i])}))}))}}n([function(e,t,i){const n=i.get;null!=n&&(i.get=function(){return this.ruleEngine.trackDependency(this,t),n.call(this)})}],p.prototype,"index",null),n([function(e,t,i){const n=i.get;null!=n&&(i.get=function(){return this.ruleEngine.trackDependency(this,t),n.call(this)})}],p.prototype,"description",null),n([function(e,t,i){const n=i.get;null!=n&&(i.get=function(){return this.ruleEngine.trackDependency(this,t),n.call(this)})}],p.prototype,"visible",null),n([function(e,t,i){const n=i.get;null!=n&&(i.get=function(){return this.ruleEngine.trackDependency(this,t),n.call(this)})}],p.prototype,"label",null),t.BaseNode=p},3544:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esMo
1dule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=n(i(560)),r=i(3332);class a extends s.default{click(){var e;if(!(null===(e=this._events)||void 0===e?void 0:e.click)&&this._jsonModel.buttonType)return"submit"===this._jsonModel.buttonType?this.form.dispatch(new r.Submit({validate_form:!0})):"reset"===this._jsonModel.buttonType?this.form.dispatch(new r.Reset):void 0}}t.default=a},3968:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=n(i(560));class r extends s.default{constructor(e,t){super(e,t),this._captchaDisplayMode=e.captchaDisplayMode,this._captchaProvider=e.captchaProvider,this._captchaSiteKey=e.captchaSiteKey}getDataNode(){}custom_setProperty(e){this.applyUpdates(e.payload)}get captchaDisplayMode(){return this._captchaDisplayMode}get captchaProvider(){return this._captchaProvider}get captchaSiteKey(){return this._captchaSiteKey}}t.default=r},2716:function(e,t,i){var n=this&&this.__decorate||function(e,t,i,n){var s,r=arguments.length,a=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(s=e[o])&&(a=(r<3?s(a):r>3?s(t,i,a):s(t,i))||a);return r>3&&a&&Object.defineProperty(t,i,a),a},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=s(i(560)),a=i(4476),o=i(5848);class l extends r.default{offValue(){const e=this.enum;return e.length>1?e[1]:null}_getConstraintObject(){const e=Object.assign({},super._getConstraintObject());var t;return e.required=(t=this.offValue(),(e,i)=>({valid:a.Constraints.required(e,i).valid&&(!e||i!=t),value:i})),e}_applyDefaults(){var e,t;"boolean"==typeof this._jsonModel.checked&&(this._jsonModel.checked?this._jsonModel.default=null===(e=this._jsonModel.enum)||void 0===e?void 0:e[0]:this._jsonModel.default=null===(t=this._jsonModel.enum)||void 0===t?void 0:t[1]),super._applyDefaults()}_getDefaults(){return Object.assign(Object.assign({},super._getDefaults()),{enforceEnum:!0})}get enum(){return this._jsonModel.enum||[]}updateDataNodeAndTypedValue(e){var t,i;const n=super.updateDataNodeAndTypedValue(e),s=n.find((e=>"value"===e.propertyName));if(s){const e=s.prevValue===(null===(t=this._jsonModel.enum)||void 0===t?void 0:t[0]),r=s.currentValue===(null===(i=this._jsonModel.enum)||void 0===i?void 0:i[0]);e!==r&&n.push({propertyName:"checked",prevValue:e,currentValue:r})}return n}set checked(e){var t,i;this.value=e?null===(t=this._jsonModel.enum)||void 0===t?void 0:t[0]:null===(i=this._jsonModel.enum)||void 0===i?void 0:i[1]}get checked(){var e;return this.value===(null===(e=this._jsonModel.enum)||void 0===e?void 0:e[0])}getState(e=!1,t=!1){return Object.assign(Object.assign({},super.getState(e,t)),{checked:this.checked})}}n([(0,o.dependencyTracked)()],l.prototype,"checked",null),t.default=l},7288:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=n(i(560));class r extends s.default{constructor(e,t){super(e,t)}_getFallbackType(){const e=super._getFallbackType();return"string"==typeof e?`${e}[]`:"string[]"}_getDefaults(){return Object.assign(Object.assign({},super._getDefaults()),{enforceEnum:!0,enum:[]})}}t.default=r},5504:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FIELD_TYPE=void 0,t.FIELD_TYPE={TEXT_INPUT:"text-input",EMAIL:"email",CAPTCHA:"captcha",MULTILINE_INPUT:"multiline-input",NUMBER_INPUT:"number-input",DATE_INPUT:"date-input",FILE_INPUT:"file-input",DROP_DOWN:"drop-down",RADIO_GROUP:"radio-group",PLAIN_TEXT:"plain-text",CHECKBOX:"checkbox",BUTTON:"button",PANEL:"panel",FORM:"form",CHECKBOX_GROUP:"checkbox-group",IMAGE:"image",TELEPHONE:"tel",PASSWORD:"password"}},5716:function(e,t,i){var n=this&&this.__decorate||function(e,t,i,n){var s,r=arguments.length,a=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(s=e[o])&&(a=(r<3?s(a):r>3?s(t,i,a):s(t,i))||a);return r>3&&a&&Object.defineProperty(t,i,a),a}
1,s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(5088),a=s(i(5376)),o=i(3332),l=s(i(9576)),u=i(5848),d=["readOnly","enabled"];class c extends a.default{constructor(e,t){var i,n;super(e,{form:t.form,parent:t.parent,mode:t.mode}),this._children=[],this._itemTemplate=null,this._isFragment=!1,this._insideFragment=!1,this._activeChild=null,this._isFragment=!0===(null===(n=null===(i=this._jsonModel)||void 0===i?void 0:i.properties)||void 0===n?void 0:n["fd:fragment"]),this.fieldFactory=t.fieldFactory}_getDefaults(){return Object.assign(Object.assign({},super._getDefaults()),{enabled:!0,readOnly:!1})}ruleNodeReference(){return this._childrenReference}get items(){return this._children}get maxItems(){return this._jsonModel.maxItems}set maxItems(e){this._jsonModel.maxItems=e;const t=this._jsonModel.minItems||1,i=this._children.length,n=Math.min(i-e,i-t);if(n>0){for(let t=0;t<n;t++)this.getDataNode().$removeDataNode(e+t),this._childrenReference.pop();const t=this._children.splice(e,n);this.notifyDependents((0,o.propertyChange)("items",t,null))}}get minItems(){return this._jsonModel.minItems}set minItems(e){this._jsonModel.minItems=e;const t=this._children.length-e,i=Math.abs(t);if(t<0){const e=[];for(let t=0;t<i;t++)e.push(this._addChild(this._itemTemplate,null,!0));this.notifyDependents((0,o.propertyChange)("items",e,null))}}hasDynamicItems(){return null!=this._itemTemplate}get isContainer(){return!0}isSiteContainer(e){return(":items"in e||"cqItems"in e)&&!("fieldType"in e)}isAFormField(e){return"fieldType"in e||"id"in e||"name"in e||"dataRef"in e||"type"in e}_getFormAndSitesState(e=!1,t=!1){return this._jsonModel.items?this._jsonModel.items.map((i=>{if(this.isSiteContainer(i)){const e=Object.assign({},(null==i?void 0:i.id)?{id:this.form.getUniqueId()}:{});return Object.assign(Object.assign(Object.assign({},i),e),{":items":this.walkSiteContainerItems(i)})}return this.isAFormField(i)?Object.assign({},this.form.getElement(null==i?void 0:i.id).getState(e,t)):i})):[]}getItemsState(e=!1,t=!1){return"array"===this._jsonModel.type||(0,r.isRepeatable)(this._jsonModel)?this._children.map((e=>Object.assign({},e.getState(!0,t)))):this._getFormAndSitesState(e,t)}getState(e=!1,t=!1){return this.withDependencyTrackingControl(!0,(()=>Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},super.getState(t)),t?{":items":void 0,":itemsOrder":void 0}:{}),{items:this.getItemsState(e,t)}),("array"===this._jsonModel.type||(0,r.isRepeatable)(this._jsonModel))&&this._itemTemplate?{_itemTemplate:Object.assign({},this._itemTemplate)}:{}),{enabled:this.enabled,readOnly:this.readOnly})))}_createChild(e,t){return this.fieldFactory.createField(e,t)}walkSiteContainerItems(e){return Object.fromEntries(Object.entries(e[":items"]).map((([e,t])=>{if(this.isAFormField(t))return[e,this.form.getElement(null==t?void 0:t.id).getState()];if(this.isSiteContainer(t))return this.walkSiteContainerItems(t);if("object"==typeof t){const i=Object.assign({},(null==t?void 0:t.id)?{id:this.form.getUniqueId()}:{});return[e,Object.assign(Object.assign({},t),i)]}return[e,t]})))}_addChildToRuleNode(e,t){const i=this,{parent:n=this}=t,s="array"==n.type?n._children.length+"":e.name||"";s.length>0&&Object.defineProperty(n._childrenReference,s,{get:()=>(e.isContainer&&e.hasDynamicItems()&&i.ruleEngine.trackDependency(e,"items"),i.hasDynamicItems()?(i.ruleEngine.trackDependency(i,"items"),void 0!==this._children[s]?this._children[s].getRuleNode():void 0):e.getRuleNode()),configurable:!0,enumerable:!0})}_addChild(e,t,i=!1,n="create"){let s=this;for(;null!=s&&s.isTransparent();)s=s.parent;("number"!=typeof t||t>s._children.length)&&(t=this._children.length);const a=this.form,o=Object.assign({index:t},(0,r.deepClone)(e,i?()=>a.getUniqueId():void 0)),l=this._createChild(o,{parent:this,form:this.form,mode:n});return e.id=l.id,this.form.fieldAdded(l),this._addChildToRuleNode(l,{parent:s}),t===this._children.length?this._children.push(l):this._children.splice(t,0,l),l}indexOf(e){return this._children.indexOf(e)}defaultDataModel(e){const t=this._jsonModel.type||void 0;if(void 0!==t){const i="array"===t?[]:{};return new l.default(e,i,t)}}_canHaveRepeatingChildren(e="create"){const t=this._jsonModel.items;return"array"==this._jsonModel.type&&null!=this.getDataNode()&&(1===t.length||t.length>0&&1==t[0].repeatable&&"restore"===e)}get isFragment(){var e,t;return this._isFragment||(null===(t=null===(e=this._jsonModel)||void 0===e?void 0:e.properties)||void 0===t?void 0:t["fd:fragment"])}_initialize(e){super._initialize(e);const t=this._jsonModel.items||[];if(this._childrenReference="array"==this._jsonModel.type?[]:{},this._canHaveRepeatingChildren(e)){this._itemTemplate=this._jsonModel._itemTemplate||(0,r.deepClone)(t[0]),this._jsonModel._itemTemplate=void 0,"restore"===e&&(this._itemTemplate.repeatable=void 0),"number"!=typeof this._jsonModel.minItems&&(this._jsonModel.minItems=0),"number"!=typeof this._jsonModel.maxItems&&(this._jsonModel.maxItems=-1),"number"!=typeof this._jsonModel.initialItems&&(this._jsonModel.initialItems=Math.max(1,this._jsonModel.minItems));const i="restore"===e?this._jsonModel.items.length:this._jsonModel.initialItems;for(let n=0;n<i;n++){let i;if("restore"===e){let s=this._itemTemplate;n<this._jsonModel.items.length&&(s=(0,r.deepClone)(t[n]),s.repeatable=void 0),i=this._addChild(s,void 0,n>this._jsonModel.items.length-1,e)}else i=this._addChild(this._itemTemplate,void 0,n>this._jsonModel.items.length-1);"create"===e&&(t[0].id=i.id),i._initialize(e)}}else t.length>0?(t.forEach((t=>{this.isSiteContainer(t)?this._initializeSiteContainer(t):this.isAFormField(t)?this._addChild(t,void 0,!1,e)._initialize(e):this.form.logger.warn(`A container item was not initialized. ${t}`)})),this._jsonModel.minItems=this._children.length,this._jsonModel.maxItems=this._children.length,this._jsonModel.initialItems=this._children.length):this.form.logger.warn("A container exists with no items.");this.setupRuleNode()}
1_initializeSiteContainer(e){Object.entries(e[":items"]).forEach((([e,t])=>{if(this.isAFormField(t))this._addChild(t)._initialize();else if(this.isSiteContainer(t))return this._initializeSiteContainer(t)}))}addItem(e){if(("addItem"===e.type||"addInstance"==e.type)&&null!=this._itemTemplate&&(-1===this._jsonModel.maxItems||this._children.length<this._jsonModel.maxItems)){const t=this.getDataNode();let i=e.payload;const n=this._addChild(this._itemTemplate,e.payload,!0);("number"!=typeof i||i>this._children.length)&&(i=this._children.length);const s=n.defaultDataModel(i);s&&t.$addDataNode(i,s,!1,this),n._initialize("create"),this.notifyDependents((0,o.propertyChange)("items",n.getState(),null)),n.dispatch(new o.Initialize),n.dispatch(new o.ExecuteRule);for(let e=i+1;e<this._children.length;e++)this._children[e].dispatch(new o.ExecuteRule)}}removeItem(e){if(("removeItem"===e.type||"removeInstance"==e.type)&&null!=this._itemTemplate){if(0==this._children.length)return;let t=e.payload;"number"!=typeof t&&(t=this._children.length-1);const i=this._children[t].getState();if(this._children.length>this._jsonModel.minItems){this._childrenReference.pop(),this._children.splice(t,1),this.getDataNode().$removeDataNode(t,this);for(let e=t;e<this._children.length;e++)this._children[e].dispatch(new o.ExecuteRule);this.notifyDependents((0,o.propertyChange)("items",null,i))}}}queueEvent(e){var t;super.queueEvent(e),(null===(t=e.metadata)||void 0===t?void 0:t.dispatch)&&this.items.forEach((t=>{t.queueEvent(e)}))}reset(){if(("array"===this.type||(0,r.isRepeatable)(this._jsonModel))&&this.items.length>this._jsonModel.initialItems){const e=this.items.length-this._jsonModel.initialItems;for(let t=0;t<e;t++)this.dispatch(new o.RemoveItem)}this.items.forEach((e=>{e.reset()}))}get valid(){return this.items.every((e=>e.valid))}validate(){return this.items.flatMap((e=>e.validate())).filter((e=>""!==e.fieldName))}dispatch(e){super.dispatch(e)}importData(e){var t;if(void 0===this._data)return void console.warn(`Data node is null, hence importData did not work for panel "${this.name}". Check if parent has a dataRef set to null.`);const i="array"===this.type&&Array.isArray(e),n="object"===this.type&&"object"==typeof e&&null!==e&&!Array.isArray(e);if(!i&&!n)return;const s=new l.default(this._data.$name,e,this._data.$type,this._data.parent);try{null===(t=this._data.parent)||void 0===t||t.$addDataNode(s.$name,s,!0)}catch(e){return void this.form.logger.error(`unable to importData for ${this.qualifiedName} : ${e}`)}this._data=s,this.syncDataAndFormModel(s),this._children.forEach((e=>e.dispatch(new o.ExecuteRule)))}syncDataAndFormModel(e){const t={added:[],removed:[]};if("array"===(null==e?void 0:e.$type)&&null!=this._itemTemplate){const i=null==e?void 0:e.$value.length,n=this._children.length,s=-1===this._jsonModel.maxItems?i:this._jsonModel.maxItems,r=this._jsonModel.minItems;let a=Math.min(i-n,s-n);const l=Math.min(n-i,n-r);for(;a>0;){a--;const e=this._addChild(this._itemTemplate,this.items.length,!0);e._initialize("create"),t.added.push(e)}if(l>0)for(let e=0;e<l;e++)this._childrenReference.pop(),t.removed.push(this._children.pop());t.added.forEach((e=>{this.notifyDependents((0,o.propertyChange)("items",e.getState(),null)),e.dispatch(new o.Initialize)})),t.removed.forEach((e=>{this.notifyDependents((0,o.propertyChange)("items",null,e.getState()))}))}return this._children.forEach((t=>{let i=t.bindToDataModel(e);t.isContainer&&!i&&(i=e),t.syncDataAndFormModel(i)})),t}get activeChild(){return this._activeChild}set activeChild(e){var t;if(e!==this._activeChild){let i=this._activeChild;for(;i instanceof c;){const e=i.activeChild;i.activeChild=null,i=e}const n=(0,o.propertyChange)("activeChild",null==e?void 0:e.getState(),null===(t=this._activeChild)||void 0===t?void 0:t.getState());this._activeChild=e,this.parent&&null!==e&&(this.parent.activeChild=this),this._jsonModel.activeChild=null==e?void 0:e.id,this.notifyDependents(n)}}get enabled(){var e;const t=null===(e=this.parent)||void 0===e?void 0:e.enabled;return void 0!==t?!!t&&this._jsonModel.enabled:this._jsonModel.enabled}set enabled(e){this._setProperty("enabled",e,!0,this.notifyChildren)}get readOnly(){var e;return void 0!==(null===(e=this.parent)||void 0===e?void 0:e.readOnly)&&!!this.parent.readOnly||this._jsonModel.readOnly}set readOnly(e){this._setProperty("readOnly",e,!0,this.notifyChildren)}notifyChildren(e){if(void 0!==e.payload&&void 0!==e.payload.changes)for(const t of e.payload.changes)void 0!==t.propertyName&&d.includes(t.propertyName)&&this.items.forEac
1h((i=>{t.currentValue!==i._jsonModel[t.propertyName]&&(i._jsonModel[t.propertyName]=t.currentValue,this.notifyDependents.call(i,(0,o.propertyChange)(t.propertyName,i.getState()[t.propertyName],null))),"panel"===i.fieldType&&this.notifyChildren.call(i,e)}))}}n([(0,u.dependencyTracked)()],c.prototype,"maxItems",null),n([(0,u.dependencyTracked)()],c.prototype,"minItems",null),n([(0,u.dependencyTracked)()],c.prototype,"valid",null),n([(0,u.dependencyTracked)()],c.prototype,"activeChild",null),t.default=c},6884:function(e,t,i){var n,s,r=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=a(i(560)),l=i(6608),u=new Set;function d(e){if(!e||"string"!=typeof e)return e;const t=e.replace(/DD/g,"dd").replace(/YYYY/g,"yyyy");return t===e||u.has(e)||(u.add(e),console.warn(`[AEM Forms] Date field pattern "${e}" uses deprecated format. Auto-corrected to "${t}". Please update to use lowercase 'y' for year and 'd' for day.`)),t}class c extends o.default{constructor(){super(...arguments),n.add(this),this._dataFormat="yyyy-MM-dd"}_applyDefaults(){super._applyDefaults(),this.locale=(new Intl.DateTimeFormat).resolvedOptions().locale,this._jsonModel.editFormat||(this._jsonModel.editFormat="short"),this._jsonModel.editFormat=d(this._jsonModel.editFormat),this._jsonModel.displayFormat?this._jsonModel.displayFormat=d(this._jsonModel.displayFormat):this._jsonModel.displayFormat=this._jsonModel.editFormat,this._jsonModel.placeholder||(this._jsonModel.placeholder=(0,l.parseDateSkeleton)(this._jsonModel.editFormat,this.locale))}get value(){return super.value}set value(e){if("number"==typeof e){const t=r(this,n,"m",s).call(this,e);t&&(super.value=t)}else if("short"!==this._jsonModel.editFormat&&"date|short"!==this._jsonModel.editFormat){const t=(0,l.parseDate)(e,this.locale,this._jsonModel.editFormat)||(0,l.parseDate)(e,this.locale,"yyyy-MM-dd");t instanceof Date?super.value=(0,l.formatDate)(t,this.locale,this._dataFormat):super.value=e}else super.value=e}get minimum(){return super.minimum}set minimum(e){if("number"==typeof e){const t=r(this,n,"m",s).call(this,e);t&&(super.minimum=t)}else"string"==typeof e&&(super.minimum=e)}get maximum(){return super.maximum}set maximum(e){if("number"==typeof e){const t=r(this,n,"m",s).call(this,e);t&&(super.maximum=t)}else"string"==typeof e&&(super.maximum=e)}}n=new WeakSet,s=function(e){const t=(0,l.numberToDatetime)(e);return isNaN(t)?null:(0,l.formatDate)(t,this.locale,this._dataFormat)},t.default=c},3260:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=n(i(6884));class r extends s.default{constructor(){super(...arguments),this._dataFormat="yyyy-MM-ddTHH:mm"}_applyDefaults(){super._applyDefaults()}get value(){return super.value}set value(e){super.value=e}}t.default=r},6764:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=n(i(560));class r extends s.default{_getDefaults(){return Object.assign(Object.assign({},super._getDefaults()),{format:"email"})}}t.default=r},560:function(e,t,i){var n,s,r=this&&this.__decorate||function(e,t,i,n){var s,r=arguments.length,a=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(s=e[o])&&(a=(r<3?s(a):r>3?s(t,i,a):s(t,i))||a);return r>3&&a&&Object.defineProperty(t,i,a),a},a=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)}
1,o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const l=i(9333),u=i(4476),d=i(3332),c=o(i(5376)),h=i(9616),p=o(i(584)),f=i(5848),m=o(i(8224)),g=i(6608),_=i(1060),v=["string","number","integer","boolean","file","string[]","number[]","integer[]","boolean[]","file[]","array","object"];class y extends c.default{constructor(e,t){super(e,t),n.add(this),this._ruleNodeReference=[],this._hasValueBeenSet=!1,"restore"!==t.mode&&(this._applyDefaults(),this.queueEvent(new d.Initialize),"deps"===this.form.changeEventBehaviour?this.queueEvent(new d.Change({changes:[]})):this.queueEvent(new d.ExecuteRule))}get hasValueBeenSet(){return this._hasValueBeenSet}_initialize(){super._initialize(),this.setupRuleNode()}ruleNodeReference(){var e;return(null===(e=this.type)||void 0===e?void 0:e.endsWith("[]"))?this._ruleNodeReference=[]:this._ruleNodeReference=this,this._ruleNodeReference}_getDefaults(){return{readOnly:!1,enabled:!0,visible:!0,label:{visible:!0,richText:!1},required:!1,type:this._getFallbackType()}}_getFallbackType(){const e=this._jsonModel.type;let t=e;if("string"!=typeof e||-1===v.indexOf(e)){const e=this.enum;t=typeof(null==e?void 0:e[0]),"undefined"===t&&void 0!==this._jsonModel.default&&(t=this._jsonModel.default instanceof Array&&this._jsonModel.default.length>0?typeof this._jsonModel.default[0]+"[]":typeof this._jsonModel.default),0===t.indexOf("undefined")&&(t={"text-input":"string","multiline-input":"string","number-input":"number","date-input":"string","date-time":"string",email:"string","plain-text":"string",image:"string",checkbox:"boolean"}[this.fieldType])}return t}_applyDefaults(){var e,t,i;super._applyDefaultsInModel(),this.coerceParam("required","boolean"),this.coerceParam("readOnly","boolean"),this.coerceParam("enabled","boolean");const n=this._jsonModel.type;if("string"==typeof n&&-1!==v.indexOf(n)||(this._jsonModel.type=this._getFallbackType()),-1===["plain-text","image"].indexOf(this.fieldType)?this._jsonModel.value=void 0:"image"===this.fieldType?this._jsonModel.value=null!==(i=null===(t=null===(e=this._jsonModel)||void 0===e?void 0:e.properties)||void 0===t?void 0:t["fd:repoPath"])&&void 0!==i?i:this._jsonModel.value:this._jsonModel.default=this._jsonModel.default||this._jsonModel.value,void 0===this._jsonModel.value){const e=u.Constraints.type(this.getInternalType()||"string",this._jsonModel.default);this._jsonModel.value=e.value}if("string"!==this._jsonModel.type&&this.unset("emptyValue"),void 0===this._jsonModel.fieldType&&(this.form.logger.debug("fieldType property is mandatory. Please ensure all the fields have a fieldType"),this._jsonModel.viewType?(this._jsonModel.viewType.startsWith("custom:")?this.form.logger.error("viewType property has been removed. For custom types, use :type property"):this.form.logger.error("viewType property has been removed. Use fieldType property"),this._jsonModel.fieldType=this._jsonModel.viewType):this._jsonModel.fieldType=(0,h.defaultFieldTypes)(this._jsonModel)),void 0===this._jsonModel.enum)"boolean"===this._jsonModel.type&&(this._jsonModel.enum=[!0,!1]);else for(void 0===this._jsonModel.enumNames&&(this._jsonModel.enumNames=this._jsonModel.enum.map((e=>e.toString())));this._jsonModel.enumNames.length<this._jsonModel.enum.length;)this._jsonModel.enumNames.push(this._jsonModel.enum[this._jsonModel.enumNames.length].toString());const s=["minimum","maximum","exclusiveMinimum","exclusiveMaximum"];"string"!==this._jsonModel.type?"file-input"===this._jsonModel.fieldType?this.unset("pattern","minLength","maxLength"):this.unset("format","pattern","minLength","maxLength"):"date-input"===this._jsonModel.fieldType&&(this._jsonModel.format="date"),this.coerceParam("minLength","number"),this.coerceParam("maxLength","number"),"number"!==this._jsonModel.type&&"date"!==this._jsonModel.format&&"date-time"!==this._jsonModel.format&&"integer"!==this._jsonModel.type&&this.unset("step",...s),s.forEach((e=>{this.coerceParam(e,"integer"===this._jsonModel.type?"number":this._jsonModel.type)})),"number"!=typeof this._jsonModel.step&&this.coerceParam("step","number")}unset(...e){e.forEach((e=>this._jsonModel[e]=void 0))}coerceParam(e,t){const i=this._jsonModel[e];if(void 0!==i&&typeof i!==t){this.form.logger.info(`${e} is not of type ${t}. Trying to coerce.`);try{this._jsonModel[e]=(0,u.coerceType)(i,t)}catch(t){this.form.logger.warn(t),this.unset(e)}}}get editFormat(){return this.withCategory(this._jsonModel.editFormat)}get displayFormat(){return this.withCategory(this._jsonModel.displayFormat)}get displayValueExpression(){return this._jsonModel.displayValueExpression}get placeholder(){return this._jsonModel.placeholder}set placeholder(e){this._setProperty("placeholder",e)}get readOnly(){return void 0!==this.parent.readOnly&&!0===this.parent.readOnly||this._jsonModel.readOnly}set readOnly(e){this._setProperty("readOnly",e)}get enabled(){var e;const t=null===(e=this.parent)||void 0===e?void 0:e.enabled;return void 0!==t?!!t&&this._jsonModel.enabled:this._jsonModel.enabled}set enabled(e){this._setProperty("enabled",e)}get valid(){var e,t;return null===(t=null===(e=this._jsonModel)||void 0===e?void 0:e.validity)||void 0===t?void 0:t.valid}set valid(e){const t=Object.assign({valid:e},e?{}:{customConstraint:!0});this._setProperty("valid",e),this._setProperty("validity",t)}get validity(){return this._jsonModel.validity}get emptyValue(){return"null"===this._jsonModel.emptyValue?null:""===this._jsonModel.emptyValue&&"string"===this.type?"":void 0}get enum(){return this._jsonModel.enum}set enum(e){this._setProperty("enum",e)}get enumNames(){return this._jsonModel.enumNames}set enumNames(e){this._setProperty("enumNames",e)}get required(){return this._jsonModel.required||!1}set required(e){this._setProperty("required",e)}get maximum(){if("number"===this.type||"date"===this.format||"date-time"===this.format||"integer"===this.type)return this._jsonModel.maximum}set maximum(e){"number"!==this.type&&"date"!==this.format&&"date-time"!==this.format&&"integer"!==this.type||this._setProperty("maximum",e)}get minimum(){if("number"===this.type||"date"===this.format||"date-time"===this.format||"integer"===this.type)return this._jsonModel.minimum}set minimum(e){"number"!==this.type&&"date"!==this.format&&"date-time"!==this.format&&"integer"!==this.type||this._setProperty("minimum",e)}withCategory(e){return e&&null===(null==e?void 0:e.match(/^(?:date|num)\|/))?("date"===this.format?e=`date|${e}`:"number"!==this.type&&"integer"!==this.type||(e=`num|${e}`),e):e}get editValue(){var e;const t=this.editFormat;if(!t||!this.isNotEmpty(this.value)||!0===(null===(e=null==this?void 0:this.validity)||void 0===e?void 0:e.typeMismatch))return this.value;try{return(0,g.format)(this.value,this.lang,t)}catch(e){return this.value}}get displayValue(){var e,t;if(this.displayValueExpression&&"string"==typeof this.displayValueExpression&&0!==this.displayValueExpression.length)return this.executeExpression(this.displayValueExpression);const i=this.displayFormat;if(!i||!this.isNotEmpty(this.value)||!0===(null===(e=null==this?void 0:this.validity)||void 0===e?void 0:e.typeMismatch)||
1("date"===this.format||"date-time"===this.format)&&!0===(null===(t=null==this?void 0:this.validity)||void 0===t?void 0:t.formatMismatch))return this.value;try{return(0,g.format)(this.value,this.lang,i)}catch(e){return this.value}}getDataNodeValue(e){return this.isEmpty()?this.emptyValue:e}updateDataNodeAndTypedValue(e){const t=this.getDataNode();if(f.staticFields.indexOf(this.fieldType)>-1&&void 0!==t&&t!==m.default)return;const i=this._getConstraintObject().type(this.getInternalType()||"string",e),n=this._setProperty("value",i.value,!1);return n.length>0&&(this._hasValueBeenSet=!0,this._updateRuleNodeReference(i.value),void 0!==t&&t.setValue(this.getDataNodeValue(this._jsonModel.value),this._jsonModel.value,this)),n}get value(){return void 0===this._jsonModel.value?null:this._jsonModel.value}set value(e){const t=this.updateDataNodeAndTypedValue(e);let i={valid:!0},n="type";if((null==t?void 0:t.length)>0){let s={};const r=u.Constraints.type(this.getInternalType()||"string",e);if(this.parent.uniqueItems&&"array"===this.parent.type&&(i=u.Constraints.uniqueItems(this.parent.uniqueItems,this.parent.getDataNode().$value),n="uniqueItems"),r.valid&&i.valid)s=this.evaluateConstraints();else{const e=r.valid&&i.valid,t=Object.assign({valid:e,errorMessage:r.valid&&i.valid?"":this.getErrorMessage("type")},e?{}:{validationMessage:e?"":this.getErrorMessage(n),validity:{valid:e,[l.constraintKeys[n]]:!0}});s=this._applyUpdates(["valid","errorMessage","validationMessage","validity"],t)}s.valid&&this.triggerValidationEvent(s);const a=t.concat(Object.values(s)).map((e=>{const t="value"===e.propertyName?this._jsonModel.value:e.currentValue;return Object.assign(Object.assign({},e),{currentValue:t})})),o=new d.Change({changes:a,eventSource:this._eventSource});this.dispatch(o)}}uiChange(e){this._eventSource=l.EventSource.UI,"value"in e.payload?this.value=e.payload.value:"checked"in e.payload&&(this.checked=e.payload.checked),this._eventSource=l.EventSource.CODE}reset(){const e=this.updateDataNodeAndTypedValue(this.default);if(!e)return;const t=this._applyUpdates(["valid","errorMessage","validationMessage","validity"],{valid:void 0,errorMessage:"",validationMessage:"",validity:{valid:void 0}}),i=new d.Change({changes:e.concat(Object.values(t))});this.dispatch(i)}_updateRuleNodeReference(e){var t;if(null===(t=this.type)||void 0===t?void 0:t.endsWith("[]"))if(null!=e)for(e.forEach(((e,t)=>{this._ruleNodeReference[t]=e}));e.length!==this._ruleNodeReference.length;)this._ruleNodeReference.pop();else for(;0!==this._ruleNodeReference.length;)this._ruleNodeReference.pop()}getInternalType(){return this.type}valueOf(){const e=this[f.target],t=void 0===e?this:e;return t.ruleEngine.trackDependency(t,"value"),t._jsonModel.value||null}toString(){var e;const t=this[f.target];return(null===(e=(void 0===t?this:t)._jsonModel.value)||void 0===e?void 0:e.toString())||""}getErrorMessage(e){var t;const i=e,n=l.constraintKeys[i],s=(0,l.getConstraintTypeMessages)(),r=null===(t=this._jsonModel.constraintMessages)||void 0===t?void 0:t["exclusiveMaximum"===i?"maximum":"exclusiveMinimum"===i?"minimum":i];if(r){const t="step"===e?this._getStepMessageValues():[this._jsonModel[i]];return(0,_.replaceTemplatePlaceholders)(r,2===t.length?t:[this._jsonModel.step])}if("step"===e){const e=this._getStepMessageValues();return 2===e.length?(0,_.replaceTemplatePlaceholders)(s[n],e):"Please enter a valid value."}return(0,_.replaceTemplatePlaceholders)(s[n],[this._jsonModel[i]])}_getStepMessageValues(){const e=this.checkStep();return!e.valid&&null!=e.prev&&null!=e.next&&Number.isFinite(e.prev)&&Number.isFinite(e.next)?[e.prev,e.
1next]:[]}get errorMessage(){return this._jsonModel.errorMessage}set errorMessage(e){this._setProperty("errorMessage",e),this._setProperty("validationMessage",e)}set constraintMessage(e){if(Array.isArray(e)){const t=Object.assign({},this._jsonModel.constraintMessages);e.forEach((({type:e,message:i})=>{t[e]=i})),this._setProperty("constraintMessages",t)}else{const t=Object.assign(Object.assign({},this._jsonModel.constraintMessages),{[e.type]:e.message});this._setProperty("constraintMessages",t)}}_getConstraintObject(){return u.Constraints}isArrayType(){return!!this.type&&this.type.indexOf("[]")>-1}checkEnum(e,t){if(!0===this._jsonModel.enforceEnum&&null!=e){const i=t.enum;return e instanceof Array&&this.isArrayType()?e.every((e=>i(this._jsonModel.enum||[],e).valid)):i(this._jsonModel.enum||[],e).valid}return!0}checkStep(){var e,t;const i=this._jsonModel.value,n=this._jsonModel.step;if("number"==typeof n){const s=(null===(t=null===(e=n.toString().split("."))||void 0===e?void 0:e[1])||void 0===t?void 0:t.length)||0,r=Math.pow(10,s),a=n*r,o=i*r,l=(this._jsonModel.minimum||this._jsonModel.default||0)*r,u=(o-l)/a,d=Math.abs(o-l)%a<.001;let c,h;return d||(c=(Math.ceil(u)*a+l)/r,h=c-n),{valid:d,next:c,prev:h}}return{valid:!0}}checkValidationExpression(){const e=this._jsonModel.validationExpression;return"string"!=typeof e||0===e.length||this.executeExpression(e)}getConstraints(){switch(this.type){case"string":switch(this.format){case"date":return u.ValidConstraints.date;case"date-time":return u.ValidConstraints.datetime;case"email":return u.ValidConstraints.email;case"binary":case"data-url":return u.ValidConstraints.file;default:return u.ValidConstraints.string}case"file":return u.ValidConstraints.file;case"number":case"integer":return u.ValidConstraints.number}return this.isArrayType()?u.ValidConstraints.array:[]}get format(){if(void 0===this._jsonModel.format&&"string"===this.type)switch(this.fieldType){case"date-input":this._jsonModel.format="date";break;case"date-time":this._jsonModel.format="date-time"}return this._jsonModel.format}get enforceEnum(){return this._jsonModel.enforceEnum}get tooltip(){return this._jsonModel.tooltip}get maxLength(){return this._jsonModel.maxLength}get minLength(){return this._jsonModel.minLength}get pattern(){return this._jsonModel.pattern}get step(){if("number"===this.type||"date"===this.format)return this._jsonModel.step}get exclusiveMinimum(){if("number"===this.type||"date"===this.format||"integer"===this.type)return this._jsonModel.exclusiveMinimum}set exclusiveMinimum(e){"number"!==this.type&&"date"!==this.format&&"integer"!==this.type||(this._jsonModel.exclusiveMinimum=e)}get exclusiveMaximum(){if("number"===this.type||"date"===this.format||"integer"===this.type)return this._jsonModel.exclusiveMaximum}set exclusiveMaximum(e){"number"!==this.type&&"date"!==this.format&&"integer"!==this.type||(this._jsonModel.exclusiveMaximum=e)}get default(){return this._jsonModel.default}isNotEmpty(e){return null!=e&&""!==e}evaluateConstraints(){let e="type";const t=this._jsonModel,i=this._jsonModel.value,n=this._getConstraintObject(),s=this.getConstraints();let r=!0;if(r&&(r=n.required(this.required,i).valid&&(!this.isArrayType()||!this.required||i.length>0),e="required"),r&&this.isNotEmpty(i)){const a=s.find((e=>{if(e in t&&void 0!==t[e]){const s=t[e],r=n[e];return i instanceof Array&&this.isArrayType()?-1!==u.ValidConstraints.array.indexOf(e)?!r(s,i).valid:i.some((e=>!r(s,e).valid)):"function"==typeof r&&!r(s,i).valid}return!1}));null!=a?(r=!1,e=a):(r=this.checkEnum(i,n),e="enum",!r||"number"!==this.type&&"integer"!==this.type||(r=this.checkStep().valid,e="step"),r&&(r=this.checkValidationExpression(),e="validationExpression"))}r||this.form.logger.info(`${e} constraint evaluation failed ${this._jsonModel[e]}. Received ${this._jsonModel.value}`);const a=Object.assign({valid:r,errorMessage:r?"":this.getErrorMessage(e)},{validationMessage:r?"":this.getErrorMessage(e),validity:Object.assign({valid:r},r?{}:{[l.constraintKeys[e]]:!0})});return this._applyUpdates(["valid","errorMessage","validationMessage","validity"],a)}triggerValidationEvent(e){e.validity&&a(this,n,"m",s).call(this)}validate(){var e;if(!1===this.visible)return[];if(!1===this.valid&&this.errorMessage&&(null===(e=null==this?void 0:this.validity)||void 0===e?void 0:e.customConstraint))return[new l.ValidationError(this.id,[this._jsonModel.errorMessage])];const t=this.evaluateConstraints();return a(this,n,"m",s).call(this),t.validity&&this.notifyDependents(new d.Change({changes:Object.values(t)})),this.valid?[]:[new l.ValidationError(this.id,[this._jsonModel.errorMessage])]}syncDataAndFormModel(e){if(void 0!==e&&e!==m.default&&e.$value!==this._jsonModel.value){const t=(0,d.propertyChange)("value",e.$value,this._jsonModel.value);this._jsonModel.value=e.$value,this.queueEvent(t)}}defaultDataModel(e){const t=f.staticFields.indexOf(this.fieldType)>-1?void 0:this.getDataNodeValue(this._jsonModel.value);return new p.default(e,t,this.type||"string")}getState(e=!1,t=!1){return Object.assign(Object.assign({},super.getState(t)),{editFormat:this.editFormat,displayFormat:this.displayFormat,editV
1alue:this.editValue,displayValue:this.displayValue,enabled:this.enabled,readOnly:this.readOnly})}markAsInvalid(e,t=null){const i={valid:!1,errorMessage:e,validationMessage:e,validity:Object.assign({valid:!1},null!=t?{[l.constraintKeys[t]]:!0}:{customConstraint:!0})},n=this._applyUpdates(["valid","errorMessage","validationMessage","validity"],i),s=new d.Change({changes:[].concat(Object.values(n))});0!==s.payload.changes.length&&(this.triggerValidationEvent(n),this.dispatch(s))}}n=new WeakSet,s=function(){this.validity.valid?this.dispatch(new d.Valid):this.dispatch(new d.Invalid)},r([(0,f.dependencyTracked)(),(0,f.exclude)("button","image","plain-text")],y.prototype,"readOnly",null),r([(0,f.dependencyTracked)(),(0,f.exclude)("image","plain-text")],y.prototype,"enabled",null),r([(0,f.dependencyTracked)()],y.prototype,"valid",null),r([(0,f.dependencyTracked)()],y.prototype,"validity",null),r([(0,f.dependencyTracked)()],y.prototype,"enum",null),r([(0,f.dependencyTracked)()],y.prototype,"enumNames",null),r([(0,f.dependencyTracked)()],y.prototype,"required",null),r([(0,f.include)("date-input","number-input")],y.prototype,"editValue",null),r([(0,f.dependencyTracked)()],y.prototype,"value",null),r([(0,f.dependencyTracked)()],y.prototype,"errorMessage",null),r([(0,f.include)("text-input","date-input","file-input","email","datetime-input")],y.prototype,"format",null),r([(0,f.include)("text-input")],y.prototype,"maxLength",null),r([(0,f.include)("text-input")],y.prototype,"minLength",null),r([(0,f.include)("text-input")],y.prototype,"pattern",null),r([(0,f.dependencyTracked)()],y.prototype,"exclusiveMinimum",null),r([(0,f.dependencyTracked)()],y.prototype,"exclusiveMaximum",null),t.default=y},2692:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Fieldset=void 0;const s=n(i(5716)),r=i(3332);class a extends s.default{constructor(e,t){super(e,t),"restore"!==t.mode&&(this._applyDefaults(),this.queueEvent(new r.Initialize),this.queueEvent(new r.ExecuteRule))}_getDefaults(){return Object.assign(Object.assign({},super._getDefaults()),{visible:!0,required:!1,label:{visible:!0,richText:!1}})}_applyDefaults(){super._applyDefaultsInModel(),this._jsonModel.dataRef&&void 0===this._jsonModel.type&&(this._jsonModel.type="object")}get type(){const e=super.type;if("array"===e||"object"===e)return e}get items(){return super.items?super.items:[]}get value(){var e;return null===(e=this.getDataNode())||void 0===e?void 0:e.$value}get fieldType(){return"panel"}}t.Fieldset=a},6440:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FileObject=void 0,t.FileObject=class{constructor(e){this.mediaType="application/octet-stream",this.name="unknown",this.size=0,Object.assign(this,e)}get type(){return this.mediaType}set type(e){this.mediaType=e}toJSON(){return{name:this.name,size:this.size,mediaType:this.mediaType,data:this.data.toString()}}equals(e){return this.data===e.data&&this.mediaType===e.mediaType&&this.name===e.name&&this.size===e.size}}},5432:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(s,r){function a(e){try{l(n.next(e))}catch(e){r(e)}}function o(e){try{l(n.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(3332),a=s(i(560)),o=i(1060),l=i(6440),u=i(4476),d=s(i(8224));function c(e,t){return e.replace(";base64",`;name=${encodeURIComponent(t)};base64`)}function h(e){return n(this,void 0,void 0,(function*(){const{name:t,size:i,type:n}=e;return yield new Promise(((s,r)=>{const a=new FileReader;a.onload=e=>{s(new l.FileObject({data:c(e.target.result,t),type:n,name:t,size:i}))},a.readAsDataURL(e.data)}))}))}class p extends a.default{_getDefaults(){return Object.assign(Object.assign({},super._getDefaults()),{accept:["audio/*","video/*","image/*","text/*","application/pdf"],maxFileSize:"2MB"})}_getFallbackType(){return"file"}get maxFileSize(){return(0,o.getFileSizeInBytes)(this._jsonModel.maxFileSize)}get accept(){return this._jsonModel.accept}_applyUpdates(e,t){return e.reduce(((e,i)=>{const n=this._jsonModel[i],s=t[i];return s!==n&&(e[i]={propertyName:i,currentValue:s,prevValue:n},n instanceof l.FileObject&&"object"==typeof s&&"value"===i?this._jsonModel[i]=new l.FileObject(Object.assign(Object.assign({},n),{data:s.data})):this._jsonModel[i]=s),e}),{})}getInternalType(){var e;
1return(null===(e=this.type)||void 0===e?void 0:e.endsWith("[]"))?"file[]":"file"}getDataNodeValue(e){var t;let i=e;return null!=i&&("string"===this.type?i=null===(t=i.data)||void 0===t?void 0:t.toString():"string[]"===this.type&&(i=i instanceof Array?i:[i],i=i.map((e=>{var t;return null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.toString()})))),i}serialize(){return n(this,void 0,void 0,(function*(){const e=this._jsonModel.value;return void 0===e?null:yield(t=e instanceof Array?e:[e],Promise.all([].map.call(t,h)));var t}))}syncDataAndFormModel(e){if(void 0!==e&&e!==d.default){const t=null==e?void 0:e.$value;if(null!=t){const e=u.Constraints.type(this.getInternalType(),t);e.valid||this.form.logger.debug(`unable to bind ${this.name} to data`),this.form.getEventQueue().queue(this,(0,r.propertyChange)("value",e.value,this._jsonModel.value)),this._jsonModel.value=e.value}else this._jsonModel.value=null}}}t.default=p},3416:function(e,t,i){var n,s,r,a,o,l,u,d=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(s,r){function a(e){try{l(n.next(e))}catch(e){r(e)}}function o(e){try{l(n.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))},c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.currentVersion=void 0;const p=h(i(5716)),f=h(i(1316)),m=h(i(5840)),g=h(i(9712)),_=i(3332),v=i(2267),y=h(i(9576)),b=i(7279),E=i(9333),T=i(1060),M=i(7888),O=i(7177);t.currentVersion=new O.Version("0.13");const w=new O.Version("0.13");class I extends p.default{constructor(e,t,i,s=new g.default,r="off",a="create"){super(e,{fieldFactory:t,mode:a}),this._ruleEngine=i,this._eventQueue=s,n.add(this),this.additionalSubmitMetadata={},this._fields={},this._invalidFields=[],this._exportDataAttachmentMap={},this.promises=[],this._captcha=null,this.dataRefRegex=/("[^"]+?"|[^.]+?)(?:\.|$)/g,this._logger=new v.Logger(r),this._applyDefaultsInModel(),"create"===a&&(this.queueEvent(new _.Initialize),"deps"===this.changeEventBehaviour?this.queueEvent(new _.Change({changes:[]})):this.queueEvent(new _.ExecuteRule)),this._ids=(0,T.IdGenerator)(),this.bindToDataModel(new y.default("$form",{})),this._initialize(a),"create"===a&&this.queueEvent(new _.FormLoad)}addPromises(e){this.promises.push(e)}waitForPromises(){return d(this,void 0,void 0,(function*(){let e=0;for(;this.promises.length>e;)e=this.promises.length,yield Promise.all(this.promises);this.promises=[]}))}_applyDefaultsInModel(){const e=this.specVersion;this._jsonModel.properties=this._jsonModel.properties||{},this._jsonModel.fieldType=this._jsonModel.fieldType||"form",(e.lessThan(w)||"string"!=typeof this._jsonModel.properties["fd:changeEventBehaviour"])&&(this._jsonModel.properties["fd:changeEventBehaviour"]="self")}get activeField(){return this._findActiveField(this)}_findActiveField(e){return(null==e?void 0:e.isContainer)?this._findActiveField(null==e?void 0:e.activeChild):e}get logger(){return this._logger}get changeEventBehaviour(){return"deps"===this.properties["fd:changeEventBehaviour"]?"deps":"self"}get metaData(){const e=this._jsonModel.metadata||{};return new f.default(e)}get action(){return this._jsonModel.action}get isFragment(){return!1}importData(e){this.bindToDataModel(new y.default("$form",e)),this.syncDataAndFormModel(this.getDataNode()),this._eventQueue.runPendingQueue()}exportData(e={}){var t;this._exportDataAttachmentMap=e;const i=null===(t=this.getDataNode())||void 0===t?void 0:t.$value;return this._exportDataAttachmentMap={},i}setAdditionalSubmitMetadata(e){this.additionalSubmitMetadata=Object.assign(Object.assign({},this.additionalSubmitMetadata),e)}get specVersion(){if("string"!=typeof this._jsonModel.adaptiveform)return t.currentVersion;try{return new O.Version(this._jsonModel.adaptiveform)}catch(e){return console.log(e),console.log("Falling back to default version"+t.currentVersion.toString()),t.currentVersion}}
1resolveQualifiedName(e){if(this.qualifiedName===e)return this;let t=null;return this.visit((i=>{i.qualifiedName===e&&(t=i)})),t}exportSubmitMetaData(){return this.withDependencyTrackingControl(!0,(()=>{const e={};this.visit((t=>{"captcha"===t.fieldType&&(e[t.qualifiedName]=t.value)}));const t={},i=this.properties["fd:draftId"]||"";i&&(t["fd:draftId"]=i);const n=this.properties["fd:dor"];if(n&&"none"!==n.dorType){const e=n["fd:excludeFromDoRIfHidden"];let i=[];i=Object.values(this._fields).filter((t=>!1===t.enabled||e&&!1===t.visible)).map((e=>(0,M.transformFieldName)(e.qualifiedName))),i&&i.length>0&&(t.excludeFromDoR=i)}Object.keys(t).length>0&&this.setAdditionalSubmitMetadata(t);const s=Object.assign({lang:this.lang,captchaInfo:e},this.additionalSubmitMetadata);return new m.default(s)}))}setFocus(e,t){const i=this._ruleEngine.getDependencyTracking();this._ruleEngine.setDependencyTracking(!1);try{if(!t)return c(this,n,"m",u).call(this,e),void c(this,n,"m",a).call(this,e);const i=(null==e?void 0:e.isContainer)?e:e.parent,r=c(this,n,"m",s).call(this,i.items);let d=i.activeChild,h=null!==d?r.indexOf(d):-1;if(null===i.activeChild)return c(this,n,"m",a).call(this,r[0]),void(h=0);t===E.FocusOption.NEXT_ITEM?d=c(this,n,"m",o).call(this,h,r):t===E.FocusOption.PREVIOUS_ITEM&&(d=c(this,n,"m",l).call(this,h,r)),null!==d&&c(this,n,"m",a).call(this,d)}finally{this._ruleEngine.setDependencyTracking(i)}}getState(e=!1){const t=this,i=super.getState(!1,e);return i.id="$form",Object.defineProperty(i,"data",{get:function(){return t.exportData()}}),Object.defineProperty(i,"attachments",{get:function(){return(0,T.getAttachments)(t)}}),i}get type(){return"object"}isTransparent(){return!1}get form(){return this}get ruleEngine(){return this._ruleEngine}getUniqueId(e){var t,i,n;if(e&&!(null===(t=this._idSet)||void 0===t?void 0:t.has(e)))return null===(i=this._idSet)||void 0===i||i.add(e),e;if(null==this._ids)return"";const s=this._ids.next().value;return null===(n=this._idSet)||void 0===n||n.add(s),s}clearIdRegistry(){var e;null===(e=this._idSet)||void 0===e||e.clear()}fieldAdded(e){"captcha"!==e.fieldType||this._captcha||(this._captcha=e),this._fields[e.id]=e,e.subscribe((e=>{-1===this._invalidFields.indexOf(e.target.id)&&this._invalidFields.push(e.target.id)}),"invalid","model"),e.subscribe((e=>{const t=this._invalidFields.indexOf(e.target.id);t>-1&&this._invalidFields.splice(t,1)}),"valid","model"),e.subscribe((e=>{const t=e.target.getState();if(e.payload.changes.length>0&&t){const i=e=>e&&"object"==typeof e?Array.isArray(e)?e.map(i):Object.assign({},e):e,n=e.payload.changes.map((({propertyName:e,currentValue:t,prevValue:n})=>({propertyName:e,currentValue:i(t),prevValue:i(n)}))),s=new _.FieldChanged(n,t,e.payload.eventSource);this.notifyDependents(s)}}),"change","model")}visit(e){this.traverseChild(this,e)}traverseChild(e,t){e.items.forEach((e=>{e.isContainer&&this.traverseChild(e,t),t(e)}))}validate(){const e=super.validate();return this.dispatch(new _.ValidationComplete(e)),e}isValid(){return 0===this._invalidFields.length}dispatch(e){"submit"===e.type?(super.queueEvent(e),this._eventQueue.runPendingQueue()):super.dispatch(e)}submit(e,t){var i;if(!1===(null===(i=null==e?void 0:e.payload)||void 0===i?void 0:i.validate_form)||0===this.validate().length){const i=(null==e?void 0:e.payload)||{},n=(null==i?void 0:i.success)?null==i?void 0:i.success:"submitSuccess",s=(null==i?void 0:i.error)?null==i?void 0:i.error:"submitError",r=i.action||this.action,a=i.metadata||{submitMetadata:this.exportSubmitMetaData()},o=(null==i?void 0:i.save_as)||(null==i?void 0:i.submit_as);(0,b.submit)(t,n,s,o,null==i?void 0:i.data,r,a)}}save(e,t){const i=(null==e?void 0:e.payload)||{};i.save_as="multipart/form-data",i.metadata={draftMetadata:{lang:this.lang,"fd:draftId":this.properties["fd:draftId"]||""}},i.success="custom:saveSuccess",i.error="custom:saveError",this.submit(e,t),this.subscribe((e=>{this._saveSuccess(e)}),"saveSuccess")}_saveSuccess(e){var t,i;const n=(null===(i=null===(t=null==e?void 0:e.payload)||void 0===t?void 0:t.body)||void 0===i?void 0:i.draftId)||"",s=this.properties;n&&s&&(s["fd:draftId"]=n)}reset(){super.reset(),this._invalidFields=[]}getElement(e){return e==this.id?this:this._fields[e]}get qualifiedName(){return"$form"}getEventQueue(){return this._eventQueue}get name(){return"$form"}get value(){return null}get id(){return this._jsonModel.id||"$form"}get title(){return this._jsonModel.title||""}get captcha(){return this._captcha}}n=new WeakSet,s=function(e){return e.filter((e=>!0===e.visible))},r=function(e){const t=c(this,n,"m",s).call(this,e.items);return t&&t.length>0?t[0]:null},a=function e(t){if(!t.isContainer)return void(t.parent.activeChild=t);c(this,n,"m",u).call(this,t);const i=t.activeChild||c(this,n,"m",r).call(this,t);null!==i?c(this,n,"m",e).call(this,i):t.parent.activeChild=t},o=function(e,t){return e<t.length-1?t[e+1]:null},l=function(e,t){return e>0?t[e-1]:null},u=function(e){const t=e.parent;null!=t&&null!=t.activeChild&&(t.activeChild=null)},t.default=I},9916:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var s=Object.getOwnPropertyDescriptor(t,i);
1s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,s)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return s(t,e),t},a=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(s,r){function a(e){try{l(n.next(e))}catch(e){r(e)}}function o(e){try{l(n.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.registerFunctions=t.fetchForm=t.validateFormData=t.validateFormInstance=t.restoreFormInstance=t.createFormInstanceSync=t.createFormInstance=void 0;const l=r(i(3416)),u=i(5088),d=i(372),c=o(i(6552)),h=o(i(9712)),p=i(2267),f=i(8608),m=i(7279),g=i(1060),_=o(i(9576)),v=(e,t,i)=>{let n=i;null==n&&(e=(0,g.sitesModelToFormModel)(e),n=new l.default(Object.assign({},e),f.FormFieldFactory,new c.default,new h.default(new p.Logger(t)),t));const s=null==e?void 0:e.data;return s&&n.importData(s),n};t.createFormInstance=(e,t,i="error",n=void 0)=>{try{const s=v(e,i,n);return"function"==typeof t&&t(s),s.getEventQueue().runPendingQueue(),s}catch(e){throw console.error(`Unable to create an instance of the Form ${e}`),new Error(e)}},t.createFormInstanceSync=(e,t,i="error",n=void 0)=>a(void 0,void 0,void 0,(function*(){try{const s=v(e,i,n);return"function"==typeof t&&t(s),s.getEventQueue().runPendingQueue(),yield s.waitForPromises(),s}catch(e){throw console.error(`Unable to create an instance of the Form ${e}`),new Error(e)}})),t.createFormInstance.currentVersion=l.currentVersion;const y={logLevel:"error"};t.restoreFormInstance=(e,t=null,{logLevel:i}=y)=>{try{const n=new l.default(Object.assign({},e),f.FormFieldFactory,new c.default,new h.default(new p.Logger(i)),i,"restore");return t&&(n.bindToDataModel(new _.default("$form",t)),n.syncDataAndFormModel(n.getDataNode())),n.getEventQueue().empty(),n}catch(e){throw console.error(`Unable to restore an instance of the Form ${e}`),new Error(e)}},t.validateFormInstance=(e,t)=>{try{const i=new l.default(Object.assign({},e),f.FormFieldFactory,new c.default);return t&&i.importData(t),0===i.validate().length}catch(e){throw new Error(e)}},t.validateFormData=(e,t)=>{try{const i=new l.default(Object.assign({},e),f.FormFieldFactory,new c.default);t&&i.importData(t);const n=i.validate();return{messages:n,valid:0===n.length}}catch(e){throw new Error(e)}},t.fetchForm=(e,t={})=>{const i=new Headers;return Object.entries(t).forEach((([e,t])=>{i.append(e,t)})),new Promise(((i,n)=>{(0,d.request)(`${e}.model.json`,null,{headers:t}).then((e=>{if(200!==e.status)n("Not Found");else{let t=e.body;if("model"in t){const{model:e}=t;t=e}i((0,u.jsonString)(t))}})).catch((e=>{n(`Network error: ${e.message||e}`)}))}))},t.registerFunctions=e=>{m.FunctionRuntime.registerFunctions(e)}},1316:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=n(i(140));class r extends s.default{get version(){return this.getP("version","")}get grammar(){return this.getP("grammar","")}}t.default=r},3336:function(e,t,i){var n=this&&this.__decorate||function(e,t,i,n){var s,r=arguments.length,a=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(s=e[o])&&(a=(r<3?s(a):r>3?s(t,i,a):s(t,i))||a);return r>3&&a&&Object.defineProperty(t,i,a),a};Object.defineProperty(t,"__esModule",{value:!0}),t.InstanceManager=void 0;const s=i(2692),r=i(5848);class a extends s.Fieldset{get maxOccur(){return this._jsonModel.maxItems}set maxOccur(e){this.maxItems=e}get minOccur(){return this.minItems}addInstance(e){return this.addItem(e)}removeInstance(e){return this.removeItem(e)}}n([(0,r.dependencyTracked)()],a.prototype,"maxOccur",null),n([(0,r.dependencyTracked)()],a.prototype,"minOccur",null),t.InstanceManager=a},140:(e,t,i)=>
1{Object.defineProperty(t,"__esModule",{value:!0});const n=i(5088);t.default=class{constructor(e){this._jsonModel=Object.assign({},e)}getP(e,t){return(0,n.getProperty)(this._jsonModel,e,t)}get isContainer(){return!1}}},8744:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PropertiesManager=void 0;const n=i(3332);t.PropertiesManager=class{constructor(e){this.host=e,this._definedProperties=new Set,this._propertiesWrapper={},this._initialized=!1}get properties(){return this._initialized||(this._setupInitialProperties(),this._initialized=!0),this._propertiesWrapper}set properties(e){const t=this.host._jsonModel.properties||{},i=Object.assign({},e);this.host._jsonModel.properties=i,Object.keys(i).forEach((e=>{this._ensurePropertyDescriptor(e)})),Object.keys(Object.assign(Object.assign({},t),i)).forEach((e=>{if(t[e]!==i[e]){const s=(0,n.propertyChange)(`properties.${e}`,i[e],t[e]);this.host.notifyDependents(s)}}))}ensurePropertyDescriptor(e){this._ensurePropertyDescriptor(e)}_setupInitialProperties(){const e=this.host._jsonModel.properties||{};Object.keys(e).forEach((e=>{this._ensurePropertyDescriptor(e)})),this.host._jsonModel.properties||(this.host._jsonModel.properties={})}_ensurePropertyDescriptor(e){this._definedProperties.has(e)||(Object.defineProperty(this._propertiesWrapper,e,{get:()=>(e.startsWith("fd:")||this.host.ruleEngine.trackDependency(this.host,`properties.${e}`),(this.host._jsonModel.properties||{})[e]),set:t=>{const i=this.host._jsonModel.properties||{},s=i[e];if(s!==t){const r=Object.assign(Object.assign({},i),{[e]:t});this.host._jsonModel.properties=r;const a=(0,n.propertyChange)(`properties.${e}`,t,s);this.host.notifyDependents(a)}},enumerable:!0,configurable:!0}),this._definedProperties.add(e))}updateNestedProperty(e,t){const i=e.split("."),s=i[0];this._ensurePropertyDescriptor(s);const r=this.host._jsonModel.properties||{},a=JSON.parse(JSON.stringify(r)),o=a[s]||{};a[s]=o;let l=o;for(let e=1;e<i.length-1;e++)l[i[e]]?"object"!=typeof l[i[e]]&&(l[i[e]]={}):l[i[e]]={},l=l[i[e]];const u=i[i.length-1],d=l[u];l[u]=t,this.host._jsonModel.properties=a;const c=(0,n.propertyChange)(`properties.${e}`,t,d);this.host.notifyDependents(c)}updateSimpleProperty(e,t){this._ensurePropertyDescriptor(e),this._propertiesWrapper[e]=t}}},5376:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0});const n=i(5848),s=i(1060),r=i(3332);class a extends n.BaseNode{constructor(){super(...arguments),this._events={},this._rules={}}getRules(){return"object"!=typeof this._jsonModel.rules?{}:this._jsonModel.rules}getCompiledRule(e,t){if(!(e in this._rules)){const i=t||this.getRules()[e];if(!("string"==typeof i&&i.length>0))throw new Error(`only expression strings are supported. ${typeof i} types are not supported`);{let t=i;try{if("$form"!==this.fragment){const e=(0,s.sanitizeName)(this.fragment);t=i.replaceAll("$form",e)}this._rules[e]=this.ruleEngine.compileRule(t,this.lang)}catch(i){const n=`Unable to compile rule \`"${e}" : "${t}"\` Exception : ${i}`;this.form.logger.error(n);const s={name:this.name,error:n,event:e,rule:t,stack:i instanceof Error?i.stack:void 0};this.form.dispatch(new r.ScriptError(s,!1))}}}return this._rules[e]}getCompiledEvent(e){var t;if(!(e in this._events)){let i=null===(t=this._jsonModel.events)||void 0===t?void 0:t[e];"custom:setProperty"===e&&void 0===i&&(i=["$event.payload"]),"string"==typeof i&&i.length>0&&(i=[i]),void 0!==i&&i.length>0&&(this._events[e]=i.map((t=>{let i=t;try{if("$form"!==this.fragment){const e=(0,s.sanitizeName)(this.fragment);i=t.replaceAll("$form",e)}return this.ruleEngine.compileRule(i,this.lang)}catch(t){const n=`Unable to compile expression \`"${e}" : "${i}"\` Exception : ${t}`;this.form.logger.error(n);const s={name:this.name,error:n,event:e,rule:i,stack:t instanceof Error?t.stack:void 0};this.form.dispatch(new r.ScriptError(s,!1))}return null})).filter((e=>null!==e)))}return this._events[e]||[]}getState(e=!1){const t=super.getState(e);return t.events=t.events||{},t}applyUpdates(e){"object"==typeof e?null!==e&&Object.entries(e).forEach((([e,t])=>{if(e in n.editableProperties||e in this&&"function"!=typeof this[e])try{this[e]=t}catch(e){console.error(e)}})):void 0!==e&&(this.value=e)}executeAllRules(e){const t=Object.entries(this.getRules());if(t.length>0){const i=this.getExpressionScope();t.forEach((([t,s])=>{const r=this.getCompiledRule(t,s);if(r){const a=this.ruleEngine.execute(r,i,e,!0,s);n.editableProperties.indexOf(t)>-1?this.isEmpty()&&this.isEmpty(a)&&"value"===t||(this[t]=a):this.form.logger.warn(`${t} is not a valid editable property.`)}}))}}getExpressionScope(){const e=this.getNonTransparentParent(),t={self:this.getRuleNode(),siblings:(null==e?void 0:e.ruleNodeReference())||{}},i=new Proxy(t,{get:(e,t)=>{if(t===Symbol.toStringTag)return"Object";if("string"==typeof t&&t.startsWith("$")){const i=e.self[t];return i instanceof n.BaseNode?i.getRuleNode():i instanceof Array?i.map((e=>e instanceof n.BaseNode?e.getRuleNode():e)):i}return t in e.siblings?e.siblings[t]:e.self[t]},has:(e,t)=>{const i=e.self[t],n=e.siblings[t];return void 0!==i||void 0!==n}});return i}executeEvent(e,t,i){let n;t&&(n=this.ruleEngine.execute(t,this.getExpressionScope(),e,!1,i),n instanceof Promise&&this.form.addPromises(n)),void 0!==n&&null!=n&&this.applyUpdates(n)}executeRule(e,t){void 0===e.payload.ruleName&&this.executeAllRules(t)}executeExpression(e){const t={form:this.form,$form:this.form.getRuleNode(),$field:this.getRuleNode(),field:this},i=this.ruleEngine.compileRule(e,this.lang);return this.ruleEngine.execute(i,this.getExpressionScope(),t,!1,e)}change(e,t){"deps"===this.form.changeEventBehaviour&&this.executeAllRules(t)}executeAction(e){var t;const i={form:this.form,$form:this.form.getRuleNode(),$field:this.getRuleNode(),field:this,$event:{type:e.type,payload:e.payload,target:this.getRuleNode()}};this.ruleEngine.setDependencyTracking(["change","executeRule"].includes(e.type));const n=e.isCustomEvent?`custom:${e.type}`:e.type,s=e.isCustomEvent?`custom_${e.type}`:e.type,r=this.getCompiledEvent(n),a=null===(t=this._jsonModel.events)||void 0===t?void 0:t[n];s in this&&"function"==typeof this[s]&&this[s](e,i),r.forEach(((e,t)=>{let n="";Array.isArray(a)?n=a[t]:"string"==typeof a&&(n=a),this.executeEvent(i,e,n)})),e.target===this&&this.notifyDependents(e)}}t.default=a},5840:(e,t)=>
1{Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e={}){this.lang=e.lang||"en",this.captchaInfo=e.captchaInfo||{},Object.keys(e).forEach((t=>{"lang"!==t&&"captchaInfo"!==t&&(this[t]=e[t])}))}}},9712:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0});const n=i(2267);class s{constructor(e,t){this._node=e,this._event=t}get node(){return this._node}get event(){return this._event}isEqual(e){return null!=e&&this._node==e._node&&this._event.type==e._event.type}toString(){var e;const t=this._node.id+"__"+this._event.type;return"change"===this._event.type&&(null===(e=this._event.payload)||void 0===e?void 0:e.changes)?t+"__"+this._event.payload.changes.map((e=>e.propertyName)).sort().join(","):t}valueOf(){return this.toString()}}class r{constructor(e=new n.Logger("off")){this.logger=e,this._isProcessing=!1,this._pendingEvents=[],this._runningEventCount={}}get length(){return this._pendingEvents.length}get isProcessing(){return this._isProcessing}isQueued(e,t){const i=new s(e,t);return void 0!==this._pendingEvents.find((e=>i.isEqual(e)))}queue(e,t,i=!1){e&&t&&(t instanceof Array||(t=[t]),t.forEach((t=>{var n;const a=new s(e,t),o=this._runningEventCount[a.valueOf()]||0;if(o<r.MAX_EVENT_CYCLE_COUNT){let s="";if("change"!==(null==t?void 0:t.type)||(null===(n=null==t?void 0:t.payload)||void 0===n?void 0:n.changes.map((e=>e.propertyName)).includes("activeChild"))?(null==t?void 0:t.type.includes("setProperty"))&&(s=JSON.stringify(t.payload,null,2)):s=JSON.stringify(t.payload.changes,null,2),this.logger.isLevelEnabled("info")&&e.withDependencyTrackingControl(!0,(()=>{this.logger.info(`Queued event : ${t.type} node: ${e.id} - ${e.qualifiedName} - ${s}`)})),i){const e=this._isProcessing?1:0;this._pendingEvents.splice(e,0,a)}else this._pendingEvents.push(a);this._runningEventCount[a.valueOf()]=o+1}else this.logger.info(`Skipped queueing event : ${t.type} node: ${e.id} - ${e.name} with count=${o}`)})))}empty(){this._pendingEvents=[]}runPendingQueue(){if(!this._isProcessing){for(this._isProcessing=!0;this._pendingEvents.length>0;
1){const e=this._pendingEvents[0];this.logger.info(`Dequeued event : ${e.event.type} node: ${e.node.id} - ${e.node.name}`),e.node.executeAction(e.event),this._pendingEvents.shift()}this._runningEventCount={},this._isProcessing=!1}}}r.MAX_EVENT_CYCLE_COUNT=10,t.default=r},3332:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.ScriptError=t.RequestFailure=t.RequestSuccess=t.RemoveInstance=t.AddInstance=t.RemoveItem=t.AddItem=t.CustomEvent=t.FieldChanged=t.Reset=t.SubmitError=t.SubmitFailure=t.SubmitSuccess=t.Save=t.Submit=t.Focus=t.ValidationComplete=t.Blur=t.Click=t.FormLoad=t.Initialize=t.propertyChange=t.ExecuteRule=t.Valid=t.Invalid=t.UIChange=t.Change=void 0,function(e){e.CODE="code",e.UI="ui"}(i||(i={}));class n{constructor(e,t,i){this._metadata=i,this._payload=e,this._type=t}get type(){return this._type}get payload(){return this._payload}get metadata(){return this._metadata}get target(){return this._target}get currentTarget(){return this._currentTarget}get isCustomEvent(){return!1}payloadToJson(){return this.payload}
1toJson(){return{payload:this.payloadToJson(),type:this.type,isCustomEvent:this.isCustomEvent}}toString(){return JSON.stringify(this.toJson())}}class s extends n{constructor(e,t=!1){super(e,"change",{dispatch:t})}withAdditionalChange(e){return new s(this.payload.changes.concat(e.payload.changes),this.metadata)}}t.Change=s,t.UIChange=class extends n{constructor(e,t=!1){super(e,"uiChange",{dispatch:t})}},t.Invalid=class extends n{constructor(e={}){super(e,"invalid",{})}},t.Valid=class extends n{constructor(e={}){super(e,"valid",{})}},t.ExecuteRule=class extends n{constructor(e={},t=!1){super(e,"executeRule",{dispatch:t})}},t.propertyChange=(e,t,i)=>new s({changes:[{propertyName:e,currentValue:t,prevValue:i}]}),t.Initialize=class extends n{constructor(e,t=!1){super(e,"initialize",{dispatch:t})}},t.FormLoad=class extends n{constructor(){super({},"load",{dispatch:!1})}},t.Click=class extends n{constructor(e,t=!1){super(e,"click",{dispatch:t})}},t.Blur=class extends n{constructor(e,t=!1){super(e,"blur",{dispatch:t})}},t.ValidationComplete=class extends n{constructor(e,t=!1){super(e,"validationComplete",{dispatch:t})}},t.Focus=class extends n{constructor(e,t=!1){super(e,"focus",{dispatch:t})}},t.Submit=class extends n{constructor(e,t=!1){super(e,"submit",{dispatch:t})}},t.Save=class extends n{constructor(e,t=!1){super(e,"save",{dispatch:t})}},t.SubmitSuccess=class extends n{constructor(e,t=!1){super(e,"submitSuccess",{dispatch:t})}},t.SubmitFailure=class extends n{constructor(e,t=!1){super(e,"submitFailure",{dispatch:t})}},t.SubmitError=class extends n{constructor(e,t=!1){super(e,"submitError",{dispatch:t})}},t.Reset=class extends n{constructor(e,t=!1){super(e,"reset",{dispatch:t})}},t.FieldChanged=class extends n{constructor(e,t,n=i.CODE){super({field:t,changes:e,eventSource:n},"fieldChanged")}},t.CustomEvent=class extends n{constructor(e,t={},i=!1){super(t,e,{dispatch:i})}get isCustomEvent(){return!0}},t.AddItem=class extends n{constructor(e){super(e,"addItem")}},t.RemoveItem=class extends n{constructor(e){super(e,"removeItem")}},t.AddInstance=class extends n{constructor(e){super(e,"addInstance")}},t.RemoveInstance=class extends n{constructor(e){super(e,"removeInstance")}},t.RequestSuccess=class extends n{constructor(e,t=!1){super(e,"requestSuccess",{dispatch:t})}},t.RequestFailure=class extends n{constructor(e,t=!1){super(e,"requestFailure",{dispatch:t})}},t.ScriptError=class extends n{constructor(e,t=!1){super(e,"scriptError",{dispatch:t})}}},2267:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Logger=void 0;const i={off:0,debug:1,info:2,warn:3,error:4};t.Logger=class{constructor(e="off"){this.logLevel=i[e]}debug(e){this.log(e,"debug")}info(e){this.log(e,"info")}warn(e){this.log(e,"warn")}error(e){this.log(e,"error")}log(e,t){0!==this.logLevel&&this.logLevel<=i[t]&&console[t](e)}isLevelEnabled(e){return 0!==this.logLevel&&this.logLevel<=i[e]}}},9576:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=n(i(584)),r=n(i(8224));class a extends s.default{constructor(e,t,i=typeof t,n){super(e,t,i,n),this.$_items=t instanceof Array?t.map(((e,t)=>this.createEntry(t,e,this))):Object.fromEntries(Object.entries(t).map((([e,t])=>[e,this.createEntry(e,t,this)])))}createEntry(e,t,i){const n=Array.isArray(t)?"array":typeof t;return"object"==typeof t&&null!=t?new a(e,t,n,i):new s.default(e,t,n,i)}get $value(){return"array"===this.$type?Object.values(this.$_items).filter((e=>void 0!==e&&!e.disabled)).map((e=>e.$value)):Object.fromEntries(Object.values(this.$_items).filter((e=>void 0!==e&&!e.disabled)).map((e=>[e.$name,e.$value])))}get $length(){return Object.entries(this.$_items).length}$convertToDataValue(){return new s.default(this.$name,this.$value,this.$type,this.parent)}syncDataAndFormModel(e){this.$_fields.forEach((t=>{e&&e!==t&&t.syncDataAndFormModel(this)}))}
1$addDataNode(e,t,i=!1,n=null){if(t!==r.default){if("array"===this.$type){const s=e;i?this.$_items[e]=t:this.$_items.splice(s,0,t),this.syncDataAndFormModel(n)}else this.$_items[e]=t;t.parent=this}}$removeDataNode(e,t=null){"array"===this.$type?(this.$_items.splice(e,1),this.syncDataAndFormModel(t)):this.$_items[e]=void 0}$getDataNode(e){if(this.$_items.hasOwnProperty(e))return this.$_items[e]}$containsDataNode(e){return this.$_items.hasOwnProperty(e)&&void 0!==this.$_items[e]}get $isDataGroup(){return!0}}t.default=a},584:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0});const n=i(5088);t.default=class{constructor(e,t,i=typeof t,n){this.$_name=e,this.$_value=t,this.$_type=i,this.$_fields=[],this.parent=n}valueOf(){return this.$_value}get $name(){return this.$_name}get disabled(){return!this.$_fields.find((e=>!1!==e.enabled))&&this.$_fields.length}get $value(){const e=this.$_fields.find((e=>{if((0,n.isFile)(e))return e}));if(e&&this.$_fields.every((e=>["string","string[]"].includes(e.type)))){const t=e.form._exportDataAttachmentMap;if(t&&t[e.id]){const i=t[e.id];return Array.isArray(i)?i.map((e=>e.data)):i.data}}return this.$_value}setValue(e,t,i){this.$_value=e,this.$_fields.forEach((e=>{i!==e&&(e.value=t)}))}get $type(){return this.$_type}$bindToField(e){-1===this.$_fields.indexOf(e)&&(this.$_fields.push(e),this._checkForTypeConflicts(e))}_checkForTypeConflicts(e){if(this.$_fields.length<=1)return;const t=e.type,i=this.$_fields.filter((i=>i&&i!==e&&i.type!==t));if(i.length>0){const n=i.map((e=>`Field "${e.id}" (${e.type})`)).join(", ");console.error(`Type conflict detected: Multiple fields with same dataRef have different types. New field '${e.id}' (${t}) conflicts with: ${n}. DataRef: ${this.$name}`)}}$convertToDataValue(){return this}get $isDataGroup(){return!1}$addDataNode(e,t,i=!1){throw"add Data Node is called on a data value"}}},8224:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=n(i(584)),r=Symbol("NullValue");class a extends s.default{constructor(){super("",r,"null")}setValue(){}$bindToField(){}$length(){return 0}$convertToDataValue(){return this}$addDataNode(){}$removeDataNode(){}$getDataNode(){return this}$containsDataNode(){return!1}}const o=new a;t.default=o},5444:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,s)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),s=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sanitizeName=t.Captcha=t.EmailInput=t.SubmitMetaData=t.isEmpty=t.request=t.FunctionRuntime=t.readAttachments=t.extractFileInfo=t.getFileSizeInBytes=t.Scriptable=t.Node=t.FormMetaData=t.FileUpload=t.FileObject=t.Fieldset=t.Field=t.Container=t.CheckboxGroup=t.Checkbox=t.BaseNode=t.Form=void 0,s(i(9916),t),s(i(9333),t),s(i(3332),t),s(i(712),t),s(i(5088),t),s(i(9616),t),s(i(5504),t);const a=i(1060);Object.defineProperty(t,"getFileSizeInBytes",{enumerable:!0,get:function(){return a.getFileSizeInBytes}}),Object.defineProperty(t,"extractFileInfo",{enumerable:!0,get:function(){return a.extractFileInfo}}),Object.defineProperty(t,"isEmpty",{enumerable:!0,get:function(){return a.isEmpty}}),Object.defineProperty(t,"readAttachments",{enumerable:!0,get:function(){return a.readAttachments}}),Object.defineProperty(t,"sanitizeName",{enumerable:!0,get:function(){return a.sanitizeName}});const o=i(5848);Object.defineProperty(t,"BaseNode",{enumerable:!0,get:function(){return o.BaseNode}});const l=r(i(2716));t.Checkbox=l.default;const u=r(i(7288));t.CheckboxGroup=u.default;const d=r(i(6764));t.EmailInput=d.default;const c=r(i(3968));t.Captcha=c.default;const h=r(i(5716));t.Container=h.default;const p=r(i(560));t.Field=p.default;const f=i(2692);Object.defineProperty(t,"Fieldset",{enumerable:!0,get:function(){return f.Fieldset}});const m=i(6440);Object.defineProperty(t,"FileObject",{enumerable:!0,get:function(){return m.FileObject}});const g=r(i(5432));t.FileUpload=g.default;const _=r(i(1316));t.FormMetaData=_.default;const v=r(i(5840));t.SubmitMetaData=v.default;const y=r(i(140));t.Node=y.default;const b=r(i(5376));t.Scriptable=b.default;const E=r(i(3416));t.Form=E.default;const T=i(7279);Object.defineProperty(t,"FunctionRuntime",{enumerable:!0,get:function(){return T.FunctionRuntime}}),Object.defineProperty(t,"request",{enumerable:!0,get:function(){return T.request}})},7279:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Prom
1ise))((function(s,r){function a(e){try{l(n.next(e))}catch(e){r(e)}}function o(e){try{l(n.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.FunctionRuntime=t.submit=t.request=void 0;const s=i(3332),r=i(372),a=i(6440),o=i(1060),l=i(5088),u=i(9333),d=e=>{const t=e;return t.length>0&&t.startsWith("custom:")?t.substring(7):t};t.request=(e,t,i,o,l,u,p)=>n(void 0,void 0,void 0,(function*(){var n;const f=t,m={method:i};let g,_={},v=null;try{o instanceof Promise&&(o=yield o)}catch(e){throw console.error("Error resolving payload Promise:",e),e}if(o.body&&o.headers&&(_=Object.assign({},o),p=Object.assign({},o.headers),o.options&&"object"==typeof o.options&&Object.assign(m,o.options),v=(o=o.body).cryptoMetadata,g=o),o&&o instanceof a.FileObject&&o.data instanceof File){const e=new FormData;e.append(o.name,o.data),g=e}else if(o instanceof FormData)g=o;else if(o&&("string"==typeof o||"object"==typeof o&&Object.keys(o).length>0)){const e=Object.keys(p);e.length>0?m.headers=Object.assign(Object.assign({},p),-1===e.indexOf("Content-Type")?{"Content-Type":"application/json"}:{}):m.headers={"Content-Type":"application/json"};const t=(null===(n=null==m?void 0:m.headers)||void 0===n?void 0:n["Content-Type"])||"application/json";"object"==typeof o&&("application/json"===t?g=JSON.stringify(o):t.indexOf("multipart/form-data")>-1?g=h(o):t.indexOf("application/x-www-form-urlencoded")>-1&&(g=c(o))),"text/plain"===t&&(g=String(o))}const y=(t,i,n)=>{const r=d(i);"submitError"===i?(e.form.dispatch(new s.SubmitError(t,!0)),e.form.dispatch(new s.SubmitFailure(t,!0))):e.field?e.field.dispatch(new s.CustomEvent(r,t,!0)):e.form.dispatch(new s.CustomEvent(r,t,!0)),e.form.dispatch(new s.RequestFailure(n,!1))},b=e.$field||null,E={request:Object.assign({url:f,method:i},_),targetField:b,targetEvent:e.$event||null};try{const t=yield(0,r.request)(f,g,m);t.originalRequest=Object.assign(Object.assign({url:f,method:i},v&&{cryptoMetadata:v}),_),t.submitter=b;const n=Object.assign(Object.assign({},E),{response:t,request:t.originalRequest});if((null==t?void 0:t.status)>=200&&(null==t?void 0:t.status)<=299){const i=d(l);"submitSuccess"===l?e.form.dispatch(new s.SubmitSuccess(t,!0)):e.field?e.field.dispatch(new s.CustomEvent(i,t,!0)):e.form.dispatch(new s.CustomEvent(i,t,!0)),e.form.dispatch(new s.RequestSuccess(n,!1))}else e.form.logger.error("Error invoking a rest API"),y(t,u,n);return t}catch(t){e.form.logger.error("Network error while invoking a rest API:",t);const i={body:null,headers:{},error:t instanceof Error?t.message:String(t)},n=Object.assign(Object.assign({},E),{response:i});y(i,u,n),e.form.dispatch(new s.RequestFailure(n,!1))}}));const c=e=>{const t=new URLSearchParams;return Object.entries(e).forEach((([e,i])=>{null!=i&&"object"==typeof i?t.append(e,(0,l.jsonString)(i)):t.append(e,i)})),t};t.submit=(e,i,s,r="multipart/form-data",a=null,l="",u=null)=>n(void 0,void 0,void 0,(function*(){const n=l||e.form.action;let d=a;const c=yield(0,o.readAttachments)(e.form,!0);"object"==typeof d&&null!=d||(d=e.form.exportData(c));let p=r;const f=Object.assign({data:d},u);let m=f;(Object.keys(c).length>0||"multipart/form-data"===r)&&(m=h(f,c),p="multipart/form-data"),yield(0,t.request)(e,n,"POST",m,i,s,{"Content-Type":p})}));const h=(e,t)=>{const i=new FormData;Object.entries(e).forEach((([e,t])=>{null!=t&&"object"==typeof t?i.append(e,(0,l.jsonString)(t)):i.append(e,t)}));const n=(e,t)=>{if((null==e?void 0:e.data)instanceof File){let i=`${null==e?void 0:e.dataRef}/${null==e?void 0:e.name}`;i.startsWith("/")||(i=`/${i}`),t.append(i,e.data)}};return t&&Object.keys(t).reduce(((e,s)=>{const r=t[s];return r&&r instanceof Array?[...e,...r.map((e=>n(e,i)))]:[...e,n(r,i)]}),[]),i},p=(e,t={},i=!1)=>{switch(e){case"change":return new s.Change(t);case"submit":return new s.Submit(t);case"save":return new s.Save(t);case"click":return new s.Click(t);case"addItem":return new s.AddItem(t);case"removeItem":return new s.RemoveItem(t);case"reset":return new s.Reset(t);case"addInstance":return new s.AddInstance(t);case"removeInstance":return new s.RemoveInstance(t);
1case"invalid":return new s.Invalid(t);case"valid":return new s.Valid(t);case"initialize":return new s.Initialize(t);case"focus":return new s.Focus(t);default:console.error("invalid action")}};class f{constructor(){this.customFunctions={}}static getInstance(){return f.instance||(f.instance=new f),f.instance}registerFunctions(e){Object.entries(e).forEach((([e,t])=>{let i=t;"function"==typeof t&&(i={_func:(e,i,s)=>{const r={form:s.globals.$form,field:s.globals.$field,event:s.globals.$event,functions:{setProperty:(e,t)=>{const n=[e,"custom:setProperty",t];return f.getInstance().getFunctions().dispatchEvent._func.call(void 0,n,i,s)},reset:e=>{const t=[e=e||"reset","reset"];return s.globals.form.logger.warn("This usage of reset is deprecated. Please see the documentation and update."),f.getInstance().getFunctions().dispatchEvent._func.call(void 0,t,i,s)},validate:e=>{const t=[e];return f.getInstance().getFunctions().validate._func.call(void 0,t,i,s)},importData:(e,t)=>{const n=[e,t];return f.getInstance().getFunctions().importData._func.call(void 0,n,i,s)},exportData:()=>f.getInstance().getFunctions().exportData._func.call(void 0,e,i,s),submitForm:(e,t,n)=>{const r=[e,t,n||"multipart/form-data"];return f.getInstance().getFunctions().submitForm._func.call(void 0,r,i,s)},markFieldAsInvalid:(e,t,i)=>{var n,r;!i||i.useId?null===(n=s.globals.form.getElement(e))||void 0===n||n.markAsInvalid(t):i&&i.useDataRef?s.globals.form.visit((function(i){i.dataRef===e&&i.markAsInvalid(t)})):i&&i.useQualifiedName&&(null===(r=s.globals.form.resolveQualifiedName(e))||void 0===r||r.markAsInvalid(t))},setFocus:(e,t)=>{const n=[e,t];return f.getInstance().getFunctions().setFocus._func.call(void 0,n,i,s)},dispatchEvent:(e,t,n,r)=>{const a=[e,t,n,r];return f.getInstance().getFunctions().dispatchEvent._func.call(void 0,a,i,s)},getFiles:e=>{const t={};e||s.globals.form.visit((function(e){"file-input"===e.fieldType&&e.value&&(t[e.qualifiedName]=e.serialize())}));const i=s.globals.form.resolveQualifiedName(e);return"file-input"===(null==i?void 0:i.fieldType)&&(null==i?void 0:i.value)&&(t[e]=i.serialize()),t},setVariable:(e,t,n)=>{const r=[e,t,n];return f.getInstance().getFunctions().setVariable._func.call(void 0,r,i,s)},getVariable:(e,t)=>
1{const n=[e,t];return f.getInstance().getFunctions().getVariable._func.call(void 0,n,i,s)},request:e=>n(this,void 0,void 0,(function*(){const{url:t,method:n="GET",body:r={},headers:a={"Content-Type":"application/json"},options:o}=e,l=f.getInstance().getFunctions(),u=l.externalize._func.call(void 0,[t],i,s),d=Math.floor(1e6*Math.random()),c=Date.now(),h=`custom:__internalSuccess_${d}_${c}`,p=`custom:__internalError_${d}_${c}`,m={body:r,headers:a};o&&(m.options=o);const g=[u,n,yield l.encrypt._func.call(void 0,[m],i,s),h,p],_=l.requestWithRetry._func.call(void 0,g,i,s),v=yield l.retryHandler._func.call(void 0,[_],i,s),y=(null==v?void 0:v.status)>=200&&(null==v?void 0:v.status)<=299;if(y&&(null==v?void 0:v.body)){const e=yield l.decrypt._func.call(void 0,[v.body,v.originalRequest],i,s);return{ok:!0,status:v.status,body:e,headers:v.headers}}return{ok:y,status:null==v?void 0:v.status,body:null==v?void 0:v.body,headers:null==v?void 0:v.headers}}))}};return t(...e,r)},_signature:[]}),i.hasOwnProperty("_func")?f.getInstance().customFunctions[e]=i:console.warn(`Unable to register function with name ${e}.`)}))}unregisterFunctions(...e){e.forEach((e=>{e in f.getInstance().customFunctions&&(null==f||delete f.getInstance().customFunctions[e])}))}getFunctions(){function e(t){return null==t?t:null!==(i=t)&&"[object Array]"===Object.prototype.toString.call(i)?t.map((t=>e(t))):t.valueOf();var i}function i(e){return null==e?"":e.toString()}const r={validate:{_func:(e,t,i)=>{const n=e[0];let s;return s="string"==typeof n||void 0===n?i.globals.form.validate():i.globals.form.getElement(n.$id).validate(),Array.isArray(s)&&s.length&&i.globals.form.logger.warn("Form Validation Error"),s},_signature:[]},setFocus:{_func:(e,t,i)=>{const n=e[0],s=e[1];try{const e=i.globals.form.getElement(null==n?void 0:n.$id)||i.globals.field;i.globals.form.setFocus(e,s)}catch(e){i.globals.form.logger.error("An error has occurred within the setFocus API.")}},_signature:[]},getData:{_func:(e,t,i)=>(i.globals.form.logger.warn("The `getData` function is depricated. Use `exportData` instead."),i.globals.form.withDependencyTrackingControl(!0,(()=>i.globals.form.exportData()))),_signature:[]},exportData:{_func:(e,t,i)=>i.globals.form.withDependencyTrackingControl(!0,(()=>i.globals.form.exportData())),_signature:[]},importData:{_func:(e,t,i)=>i.globals.form.withDependencyTrackingControl(!0,(()=>{const t=e[0],n=e[1];if("object"!=typeof t||null===t||n){const e=i.globals.form.resolveQualifiedName(n);(null==e?void 0:e.isContainer)?e.importData(t,n):i.globals.form.logger.error("Invalid argument passed in importData. A container is expected")}else i.globals.form.importData(t);return{}})),_signature:[]},submitForm:{_func:(t,r,a)=>n(this,void 0,void 0,(function*(){var n,o,l,d,c;let h,p,f,m=null,g=null;t.length>0&&"object"==typeof e(t[0])?(h=t.length>0?e(t[0]):null,p=!(t.length>1)||e(t[1]),f=t.length>2?i(t[2]):"multipart/form-data"):(a.globals.form.logger.warn("This usage of submitForm is deprecated. Please see the documentation and update"),m=i(t[0]),g=i(t[1]),f=t.length>2?i(t[2]):"multipart/form-data",h=t.length>3?e(t[3]):null,p=!(t.length>4)||e(t[4]));const _=a.globals.form;if(_.captcha&&(_.captcha.captchaDisplayMode===u.CaptchaDisplayMode.INVISIBLE||"enterprise"===(null===(o=null===(n=_.captcha.properties["fd:captcha"])||void 0===n?void 0:n.config)||void 0===o?void 0:o.version)&&"score"===(null===(d=null===(l=_.captcha.properties["fd:captcha"])||void 0===l?void 0:l.config)||void 0===d?void 0:d.keyType))){if("function"!=typeof(null===(c=a.runtime.functionTable.fetchCaptchaToken)||void 0===c?void 0:c._func))return a.globals.form.logger.error("fetchCaptchaToken is not defined"),a.globals.form.dispatch(new s.SubmitError({type:"FetchCaptchaTokenNotDefined"})),{};try{const e=yield a.runtime.functionTable.fetchCaptchaToken._func([],r,a);_.captcha.value=e}catch(e){return a.globals.form.logger.error("Error while fetching captcha token"),a.globals.form.dispatch(new s.SubmitError({type:"FetchCaptchaTokenFailed"})),{}}}return a.globals.form.dispatch(new s.Submit({success:m,error:g,submit_as:f,validate_form:p,data:h}
1)),{}})),_signature:[]},saveForm:{_func:(e,t,n)=>{const r=i(e[0]),a=e[2]||!1;return n.globals.form.dispatch(new s.Save({action:r,validate_form:a})),{}},_signature:[]},setVariable:{_func:(e,t,n)=>{const s=i(e[0]);let r=e[1];const a=e[2]||n.globals.form;return r&&"object"==typeof r&&r.$qualifiedName&&(r=n.globals.form.getElement(r.$id)._jsonModel.value),(a.$id?n.globals.form.getElement(a.$id):n.globals.form).getPropertiesManager().updateSimpleProperty(s,r),{}},_signature:[]},getVariable:{_func:(e,t,n)=>{const s=i(e[0]),r=e[1]||n.globals.form;if(!s)return;const a=(r.$id?n.globals.form.getElement(r.$id):n.globals.form).getPropertiesManager();if(s.includes(".")){const e=s.replace(/\[/g,".").replace(/\]/g,"").split(".").filter(Boolean);let t=a.properties;for(const i of e){if(null==t)return;t=t[i]}return t}return a.ensurePropertyDescriptor(s),a.properties[s]},_signature:[]},request:{_func:(n,s,r)=>{const a=i(n[0]),o=i(n[1]);let l,u,d,c={};if(n[2]&&"object"==typeof n[2]&&!n[2].then&&("data"in n[2]||"headers"in n[2])){const t=e(n[2]);l=t.data,c=t.headers||{},u=e(n[3]),d=e(n[4])}else l=e(n[2]),"string"==typeof n[3]?(r.globals.form.logger.warn("This usage of request is deprecated. Please see the documentation and update"),u=e(n[3]),d=e(n[4])):(c=e(n[3]),u=e(n[4]),d=e(n[5]));return(0,t.request)(r.globals,a,o,l,u,d,c)},_signature:[]},requestWithRetry:{_func:(s,r,a)=>{const o=i(s[0]),l=i(s[1]);let u,d,c=e(s[2]);return"string"==typeof s[3]&&5===s.length?(u=e(s[3]),d=e(s[4])):"string"==typeof s[4]&&6===s.length&&(u=e(s[4]),d=e(s[5])),e=>n(this,void 0,void 0,(function*(){try{c instanceof Promise&&(c=yield c)}catch(e){throw console.error("Error resolving payload Promise:",e),e}let i={},n={},r=null;5===s.length?(n=c.body||{},i=c.headers||{},r=c.cryptoMetadata):(n=c||{},i=s[3]||{}),e&&(e.body&&(n=Object.assign(Object.assign({},n),e.body)),e.headers&&(i=Object.assign(Object.assign({},i),e.headers)));const h=Object.assign({body:n,headers:i},r&&{cryptoMetadata:r});try{return yield(0,t.request)(a.globals,o,l,h,u,d,i)}catch(e){if(e&&"object"==typeof e&&"status"in e&&e.status>=400)throw e;throw new Error("Request failed")}}))},_signature:[]},retryHandler:{_func:(t,i,n)=>e(t[0])(),_signature:[]},externalize:{_func:(e,t,n)=>i(e[0]),_signature:[]},awaitFn:{_func:(e,t,i)=>n(this,void 0,void 0,(function*(){const n=e[1],s=i.globals.$field;try{const a=yield e[0];r.dispatchEvent._func([s,n,a],t,i)}catch(n){const a=e[2];a&&r.dispatchEvent._func([s,a,n],t,i)}return{}})),_signature:[]},addInstance:{_func:(t,i,n)=>{const s=t[0],r=t.length>1?e(t[1]):void 0;try{const e=n.globals.form.getElement(s.$id),t=p("addInstance",r);e.addItem(t)}catch(e){n.globals.form.logger.error("Invalid argument passed in addInstance. An element is expected")}},_signature:[]},removeInstance:{_func:(t,i,n)=>{const s=t[0],r=t.length>1?e(t[1]):void 0;try{const e=n.globals.form.getElement(s.$id),t=p("removeInstance",r);e.removeItem(t)}catch(e){n.globals.form.logger.error("Invalid argument passed in removeInstance. An element is expected")}},_signature:[]},dispatchEvent:{_func:(t,i,n)=>{const r=t[0];if(null===r&&"string"!=typeof n)return n.debug.push("Invalid argument passed in dispatchEvent. An element is expected"),{};let a,o=e(t[1]),l=t.length>2?e(t[2]):void 0,u=t.length>3&&e(t[3]);if("string"==typeof r&&(l=o,o=r,u=!0),a=o.startsWith("custom:")?new s.CustomEvent(o.substring(7),l,u):p(o,l,u),null!=a)if("string"==typeof r)n.globals.form.dispatch(a);else{const e=(e,t,i)=>{i.globals.form.getElement(e.$id).dispatch(t)};Array.isArray(r)&&r.length>0&&void 0===r.$id?r.forEach((t=>{e(t,a,n)})):e(r,a,n)}return{}},_signature:[]},encrypt:{_func:(t,i,s)=>n(this,void 0,void 0,(function*(){return e(t[0])})),_signature:[]},decrypt:{_func:(t,i,s)=>n(this,void 0,void 0,(function*(){return e(t[0])})),_signature:[]},getQueryParameter:{_func:(e,t,n)=>{var s,r,a,o;const l=i(e[0]);if(!l)return n.globals.form.logger.error("Argument is missing in getQueryParameter. A parameter is expected"),"";const u=null===(r=null===(s=n.globals.form)||void 0===s?void 0:s.properties)||void 0===r?void 0:r.queryParams;if(u){if(void 0!==u[l])return u[l];const e=l.toLowerCase();for(const[t,i]of Object.entries(u))if(t.toLowerCase()===e)return i}try{const e=new URLSearchParams((null===(a=null===window||void 0===window?void 0:window.location)||void 0===a?void 0:a.search)||""),t=e.get(l)||(null===(o=Array.from(e.entries()).find((([e])=>e.toLowerCase()===l.toLowerCase())))||void 0===o?void 0:o[1]);if(null!=t)return t}catch(e){n.globals.form.logger.warn("Error reading URL parameters:",e)}return""},_signature:[]}
1,getBrowserDetail:{_func:(e,t,n)=>{var s,r,a;const o=i(e[0]);return o?(null===(a=null===(r=null===(s=n.globals.form)||void 0===s?void 0:s.properties)||void 0===r?void 0:r.browserDetails)||void 0===a?void 0:a[o])?n.globals.form.properties.browserDetails[o]:"undefined"!=typeof navigator&&o in navigator?navigator[o]||"":(n.globals.form.logger.warn(`Invalid or unsupported browser detail requested: "${o}"`),""):(n.globals.form.logger.error("Argument is missing in getBrowserDetail. A parameter is expected"),"")},_signature:[]},getURLDetail:{_func:(e,t,n)=>{var s,r,a;const o=i(e[0]);return o?(null===(a=null===(r=null===(s=n.globals.form)||void 0===s?void 0:s.properties)||void 0===r?void 0:r.urlDetails)||void 0===a?void 0:a[o])?n.globals.form.properties.urlDetails[o]:"undefined"!=typeof window&&void 0!==window.location&&o in window.location?window.location[o]||"":(n.globals.form.logger.warn(`Invalid or unsupported url parameter requested: "${o}"`),""):(n.globals.form.logger.error("Argument is missing in getURLDetail. A parameter is expected"),"")},_signature:[]},getRelativeInstanceIndex:{_func:(t,i,n)=>{if(!Array.isArray(t[0])||0===t[0].length)return-1;const s=e(t[0])[0].$parent,r=n.globals.$field,a=s.$qualifiedName,o=r.$qualifiedName;if(o.startsWith(a+"[")){const e=a.length+1,t=o.indexOf("]",e);if(-1!==t){const i=Number(o.slice(e,t));if(!Number.isNaN(i))return i}}return s.length-1},_signature:[]},today:{_func:()=>{const e=new Date(Date.now());return new Date(e.getFullYear(),e.getMonth(),e.getDate())/864e5},_signature:[]},formatInput:{_func:e=>{const t=e[0],i=e[1];if(!t||!i)return t;const n=String(t).replace(/\D/g,"");switch(String(i).toLowerCase()){case"phonenumber":return n.length>=10?`(${n.substring(0,3)}) ${n.substring(3,6)}-${n.substring(6,10)}`:n.length>=7?`(${n.substring(0,3)}) ${n.substring(3,7)}`:n;case"socialsecuritynumber":return n.length>=9?`${n.substring(0,3)}-${n.substring(3,5)}-${n.substring(5,9)}`:n;case"email-alphanumeric":{const e=String(t).replace(/[^a-zA-Z0-9]/g,"");return e.length>0?`${e}@example.com`:t}case"zipcode":return n.length>=5?n.substring(0,5):n;default:return t}},_signature:[]}};return Object.assign(Object.assign({},r),f.getInstance().customFunctions)}}f.instance=null,t.FunctionRuntime=f.getInstance()},6552:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=n(i(3548)),r=i(7279),a=i(8416),o=i(3332);t.default=class{constructor(){this._globalNames=["$form","$field","$event"],this.debugInfo=[],this.dependencyTracking=!0,this.customFunctions=r.FunctionRuntime.getFunctions()}compileRule(e,t){const i=new s.default(this.customFunctions,function(e){if(null==e){const t=(new Intl.DateTimeFormat).resolvedOptions();e=t.locale}return t=>(0,a.stringToNumber)(t,e)}(t),this.debugInfo);return{formula:i,ast:i.compile(e,this._globalNames)}}execute(e,t,i,n=!1,s){var r,a,l,u,d,c,h,p,f,m,g,_,v,y,b,E,T,M,O,w;const{formula:I,ast:A}=e,C=this._context;let N;this._context=i;try{null===(l=null===(a=null===(r=this._context)||void 0===r?void 0:r.form)||void 0===a?void 0:a.logger)||void 0===l||l.info({message:"Executing rule",expression:s,fieldName:null===(u=this._context.field)||void 0===u?void 0:u.name,fieldId:null===(d=this._context.field)||void 0===d?void 0:d.id,eventType:null===(h=null===(c=this._context)||void 0===c?void 0:c.$event)||void 0===h?void 0:h.type}),N=I.run(A,t,"en-US",i)}catch(e){if(null===(m=null===(f=null===(p=this._context)||void 0===p?void 0:p.form)||void 0===f?void 0:f.logger)||void 0===m||m.error(e),null===(g=this._context)||void 0===g?void 0:g.form){const t=null===(_=this._context)||void 0===_?void 0:_.field,i=null==t?void 0:t.name,n=e instanceof Error?e.message:String(e),r={name:i,error:i?`Script execution error in field "${i}": ${n}. Expression: ${s}`:`Script execution error: ${n}. Expression: ${s}`,event:null===(y=null===(v=this._context)||void 0===v?void 0:v.$event)||void 0===y?void 0:y.type,rule:s,stack:e instanceof Error?e.stack:void 0};this._context.form.dispatch(new o.ScriptError(r,!1))}}if(this.debugInfo.length)for(null===(T=null===(E=null===(b=this._context)||void 0===b?void 0:b.form)||void 0===E?void 0:E.logger)||void 0===T||T.warn(`Form rule expression string: ${s}`);this.debugInfo.length>0;)null===(w=null===(O=null===(M=this._context)||void 0===M?void 0:M.form)||void 0===O?void 0:O.logger)||void 0===w||w.warn(this.debugInfo.pop());let S=N;return n&&"object"==typeof N&&null!==N&&(S=Object.getPrototypeOf(N).valueOf.call(N)),this._context=C,S}trackDependency(e,t){this.dependencyTracking&&this._context&&void 0!==this._context.field&&this._context.field!==e&&e._addDependent(this._context.field,t)}
1setDependencyTracking(e){this.dependencyTracking=e}getDependencyTracking(){return this.dependencyTracking}}},9136:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getConstraintTypeMessages=t.setCustomDefaultConstraintTypeMessages=t.constraintKeys=t.ConstraintType=t.constraintProps=t.translationProps=void 0,t.translationProps=["description","placeholder","enum","enumNames","label.value","constraintMessages.accept","constraintMessages.enum","constraintMessages.exclusiveMinimum","constraintMessages.exclusiveMaximum","constraintMessages.format","constraintMessages.maxFileSize","constraintMessages.maxLength","constraintMessages.maximum","constraintMessages.maxItems","constraintMessages.minLength","constraintMessages.minimum","constraintMessages.minItems","constraintMessages.pattern","constraintMessages.required","constraintMessages.step","constraintMessages.type","constraintMessages.validationExpression"],t.constraintProps=["accept","enum","exclusiveMinimum","exclusiveMaximum","format","maxFileSize","maxLength","maximum","maxItems","minLength","minimum","minItems","pattern","required","step","validationExpression","enumNames"],t.ConstraintType=Object.freeze({PATTERN_MISMATCH:"patternMismatch",TOO_SHORT:"tooShort",TOO_LONG:"tooLong",RANGE_OVERFLOW:"rangeOverflow",RANGE_UNDERFLOW:"rangeUnderflow",TYPE_MISMATCH:"typeMismatch",VALUE_MISSING:"valueMissing",STEP_MISMATCH:"stepMismatch",FORMAT_MISMATCH:"formatMismatch",ACCEPT_MISMATCH:"acceptMismatch",FILE_SIZE_MISMATCH:"fileSizeMismatch",UNIQUE_ITEMS_MISMATCH:"uniqueItemsMismatch",MIN_ITEMS_MISMATCH:"minItemsMismatch",MAX_ITEMS_MISMATCH:"maxItemsMismatch",EXPRESSION_MISMATCH:"expressionMismatch",EXCLUSIVE_MAXIMUM_MISMATCH:"exclusiveMaximumMismatch",EXCLUSIVE_MINIMUM_MISMATCH:"exclusiveMinimumMismatch",ENUM_MISMATCH:"enumMismatch"}),t.constraintKeys=Object.freeze({pattern:t.ConstraintType.PATTERN_MISMATCH,minLength:t.ConstraintType.TOO_SHORT,maxLength:t.ConstraintType.TOO_LONG,maximum:t.ConstraintType.RANGE_OVERFLOW,minimum:t.ConstraintType.RANGE_UNDERFLOW,type:t.ConstraintType.TYPE_MISMATCH,required:t.ConstraintType.VALUE_MISSING,step:t.ConstraintType.STEP_MISMATCH,format:t.ConstraintType.FORMAT_MISMATCH,accept:t.ConstraintType.ACCEPT_MISMATCH,maxFileSize:t.ConstraintType.FILE_SIZE_MISMATCH,uniqueItems:t.ConstraintType.UNIQUE_ITEMS_MISMATCH,minItems:t.ConstraintType.MIN_ITEMS_MISMATCH,maxItems:t.ConstraintType.MAX_ITEMS_MISMATCH,validationExpression:t.ConstraintType.EXPRESSION_MISMATCH,exclusiveMinimum:t.ConstraintType.EXCLUSIVE_MINIMUM_MISMATCH,exclusiveMaximum:t.ConstraintType.EXCLUSIVE_MAXIMUM_MISMATCH,enum:t.ConstraintType.ENUM_MISMATCH});const i=Object.freeze({[t.ConstraintType.PATTERN_MISMATCH]:"Please match the format requested.",[t.ConstraintType.TOO_SHORT]:"Please lengthen this text to ${0} characters or more.",[t.ConstraintType.TOO_LONG]:"Please shorten this text to ${0} characters or less.",[t.ConstraintType.RANGE_OVERFLOW]:"Value must be less than or equal to ${0}.",[t.ConstraintType.RANGE_UNDERFLOW]:"Value must be greater than or equal to ${0}.",[t.ConstraintType.TYPE_MISMATCH]:"Please enter a valid value.",[t.ConstraintType.VALUE_MISSING]:"Please fill in this field.",[t.ConstraintType.STEP_MISMATCH]:"Please enter a valid value. The two nearest valid values are ${0} and ${1}.",[t.ConstraintType.FORMAT_MISMATCH]:"Specify the value in allowed format : ${0}.",[t.ConstraintType.ACCEPT_MISMATCH]:"The specified file type not supported.",[t.ConstraintType.FILE_SIZE_MISMATCH]:"File too large. Reduce size and try again.",[t.ConstraintType.UNIQUE_ITEMS_MISMATCH]:"All the items must be unique.",[t.ConstraintType.MIN_ITEMS_MISMATCH]:"Specify a number of items equal to or greater than ${0}.",[t.ConstraintType.MAX_ITEMS_MISMATCH]:"Specify a number of items equal to or less than ${0}.",[t.ConstraintType.EXPRESSION_MISMATCH]:"Please enter a valid value.",[t.ConstraintType.EXCLUSIVE_MINIMUM_MISMATCH]:"Value must be greater than ${0}.",[t.ConstraintType.EXCLUSIVE_MAXIMUM_MISMATCH]:"Value must be less than ${0}.",[t.ConstraintType.ENUM_MISMATCH]:"Please select a value from the allowed options."}),n=(e,t)=>"object"!=typeof e||null===e?e:Array.isArray(e)?e.map((e=>n(e,t))):Object.keys(e).reduce(((i,s)=>{const r=t(s),a=e[s];return i[r]=n(a,t),i}),{});let s={};t.setCustomDefaultConstraintTypeMessages=e=>{const i=Object.entries(e).reduce(((e,[i,n])=>(void 0!==t.constraintKeys[i]&&(e[i]=n),e)),{});s=n(i,(e=>t.constraintKeys[e]))},t.getConstraintTypeMessages=()=>Object.assign(Object.assign({},i),s)},9048:(e,t)=>
1{var i,n,s;Object.defineProperty(t,"__esModule",{value:!0}),t.CaptchaDisplayMode=t.FocusOption=t.ValidationError=t.EventSource=void 0,(i=t.EventSource||(t.EventSource={})).CODE="code",i.UI="ui",t.ValidationError=class{constructor(e="",t=[]){this.errorMessages=t,this.fieldName=e}},(s=t.FocusOption||(t.FocusOption={})).NEXT_ITEM="nextItem",s.PREVIOUS_ITEM="previousItem",(n=t.CaptchaDisplayMode||(t.CaptchaDisplayMode={})).INVISIBLE="invisible",n.VISIBLE="visible"},9333:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,s)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),s=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0}),s(i(9136),t),s(i(9048),t)},8416:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stringToNumber=void 0;const n=i(6608);t.stringToNumber=function(e,t){if(null===e)return 0;const i=+e;if(!isNaN(i))return i;if(t){const i=(0,n.parseDefaultDate)(e,t,!0);if(i!==e)return(0,n.datetimeToNumber)(i)}return 0}},3820:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolveData=t.tokenize=t.repeatable=t.global$=t.bracket=t.identifier=t.TOK_REPEATABLE=t.TOK_GLOBAL=void 0;const s=n(i(9576)),r="Identifier";t.TOK_GLOBAL="Global",t.TOK_REPEATABLE="Repeatable";const a="bracket";t.identifier=(e,t)=>({type:r,value:e,start:t}),t.bracket=(e,t)=>({type:a,value:e,start:t}),t.global$=()=>({type:t.TOK_GLOBAL,start:0,value:"$"}),t.repeatable=()=>({type:t.TOK_REPEATABLE,start:0,value:"#"});const o=function(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e>="0"&&e<="9"||"_"===e||"-"===e},l=(e,t,i)=>null===e&&"$"===t[i],u=(e,t,i)=>null===e&&"#"===t[i],d=(e,t)=>{const i=e[t];return"$"===i?e.length>t&&o(e[t+1]):i>="a"&&i<="z"||i>="A"&&i<="Z"||"_"===i||"-"===i},c=e=>e>="0"&&e<="9";class h{constructor(e){this.stream=e,this._tokens=[],this._result_tokens=[],this._current=0}_consumeGlobal(){return this._current+=1,(0,t.global$)()}_consumeRepeatable(){return this._current+=1,(0,t.repeatable)()}_consumeUnquotedIdentifier(e){const i=this._current;for(this._current+=1;this._current<e.length&&o(e[this._current]);)this._current+=1;return(0,t.identifier)(e.slice(i,this._current),i)}_consumeQuotedIdentifier(e){const i=this._current;this._current+=1;const n=e.length;for(;'"'!==e[this._current]&&this._current<n;){let t=this._current;"\\"!==e[t]||"\\"!==e[t+1]&&'"'!==e[t+1]?t+=1:t+=2,this._current=t}return this._current+=1,(0,t.identifier)(JSON.parse(e.slice(i,this._current)),i)}_consumeNumber(e){const t=this._current;this._current+=1;const i=e.length;for(;c(e[this._current])&&this._current<i;)this._current+=1;const n=e.slice(t,this._current);return{type:"Number",value:parseInt(n,10),start:t}}_consumeBracket(e){const i=this._current;let n;if(this._current+=1,!c(e[this._current]))throw new Error(`unexpected exception at position ${this._current}. Must be a character`);if(n=this._consumeNumber(e).value,this._current<this.stream.length&&"]"!==e[this._current])throw new Error(`unexpected exception at position ${this._current}. Must be a character`);return this._current++,(0,t.bracket)(n,i)}tokenize(){const e=this.stream;for(;this._current<e.length;){const t=this._tokens.length?this._tokens.slice(-1)[0]:null;if(l(t,e,this._current)){const e=this._consumeGlobal();this._tokens.push(e),this._result_tokens.push(e)}else if(u(t,e,this._current)){const e=this._consumeRepeatable();this._tokens.push(e),this._result_tokens.push(e)}else if(d(e,this._current)){const t=this._consumeUnquotedIdentifier(e);this._tokens.push(t),this._result_tokens.push(t)}else if("."===e[this._current]&&null!=t&&"DOT"!==t.type)this._tokens.push({type:"DOT",value:".",start:this._current}),this._current+=1;else if("["===e[this._current]){const t=this._consumeBracket(e);this._tokens.push(t),this._result_tokens.push(t)}else{if('"'!==e[this._current]){const e=Math.max(0,this._current-2),t=Math.min(this.stream.length,this._current+2);throw new Error(`Exception at parsing stream ${this.stream.slice(e,t)}`)}{const t=this._consumeQuotedIdentifier(e);this._tokens.push(t),this._result_tokens.push(t)}}}return this._result_tokens}}t.tokenize=e=>new h(e).tokenize(),t.resolveData=(e,i,n)=>{let o;o="string"==typeof i?(0,t.tokenize)(i):i;let l=e,u=0;const d=(e,t,i)=>null===t?i:t.type===a?new s.default(e.value,[],"array"):new s.default(e.value,{});for(;u<o.length&&null!=l;){const i=o[u];if(i.type===t.TOK_GLOBAL)l=e;else if(i.type===r){if(!(l instanceof s.default&&"object"===l.$type))throw new Error(`Looking for ${i.value} in ${l.$value}`);if(l.$containsDataNode(i.value)&&null!==l.$getDataNode(i.value).$value)l=l.$getDataNode(i.value);else if(n){const e=d(i,u<o.length-1?o[u+1]:null,n);l.$addDataNode(i.value,e),l=e}else l=void 0}else if(i.type===a){if(!(l instanceof s.default&&"array"===l.$type))throw new Error(`Looking for index ${i.value} in non array${l.$value}`);{const e=i.value;if(e<l.$length)l=l.$getDataNode(e);else if(n){const t=d(i,u<o.length-1?o[u+1]:null,n);l.$addDataNode(e,t),l=t}else l=void 0}}u+=1}return l}},7888:(e,t)=>
1{Object.defineProperty(t,"__esModule",{value:!0}),t.transformFieldName=void 0,t.transformFieldName=e=>e.split(".").slice(1).map((e=>e.match(/\[\d+\]$/)?e:""!==e?`${e}[0]`:e)).join(".")},372:function(e,t){var i=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(s,r){function a(e){try{l(n.next(e))}catch(e){r(e)}}function o(e){try{l(n.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.convertQueryString=t.request=void 0,t.request=(e,s=null,r={})=>{const a=Object.assign(Object.assign({},n),r),o="GET"===a.method&&s?(0,t.convertQueryString)(e,s):e;return"GET"!==a.method&&(a.body=s),fetch(o,Object.assign({},a)).then((t=>i(void 0,void 0,void 0,(function*(){var i,n,s;let r;t.ok||console.error(`Error while fetching response from ${e} : ${t.statusText}`),r=(null===(n=null===(i=null==t?void 0:t.headers)||void 0===i?void 0:i.get("Content-Type"))||void 0===n?void 0:n.includes("application/json"))?yield t.json():yield t.text();const a={};return null===(s=null==t?void 0:t.headers)||void 0===s||s.forEach(((e,t)=>{a[t]=e})),{status:t.status,body:r,headers:a}})))).catch((t=>{throw console.error(`Network error while fetching from ${e}:`,t),t}))};const n={method:"GET"};t.convertQueryString=(e,t)=>{if(!t)return e;let i={};try{i=JSON.parse(t)}catch(e){console.log("Query params invalid")}const n=[];
1return Object.keys(i).forEach((e=>{Array.isArray(i[e])?n.push(`${encodeURIComponent(e)}=${encodeURIComponent(JSON.stringify(i[e]))}`):n.push(`${encodeURIComponent(e)}=${encodeURIComponent(i[e])}`)})),n.length?e.includes("?")?`${e}&${n.join("&")}`:`${e}?${n.join("&")}`:e}},8608:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FormFieldFactory=void 0;const s=i(3336),r=i(2692),a=i(5088),o=n(i(5432)),l=n(i(2716)),u=n(i(7288)),d=n(i(6884)),c=n(i(3260)),h=n(i(560)),p=n(i(6764)),f=n(i(3968)),m=n(i(3544)),g={text:"text-input",number:"number-input",email:"email",file:"file-input",range:"range",textarea:"multiline-input"};t.FormFieldFactory=new class{createField(e,t){let i;const n=Object.assign(Object.assign({},t),{fieldFactory:this});if(e.fieldType=e.fieldType?e.fieldType in g?g[e.fieldType]:e.fieldType:"text-input",(0,a.isRepeatable)(e)){const t=Object.assign(Object.assign(Object.assign({},e),"items"in e&&{type:"object"}),{minOccur:void 0,maxOccur:void 0,repeatable:void 0,name:void 0}),r=Object.assign({minItems:e.minOccur||0,maxItems:e.maxOccur||-1,fieldType:e.fieldType,type:"array",name:e.name,dataRef:e.dataRef,events:{"custom:setProperty":"$event.payload"}},{items:[t]});i=new s.InstanceManager(r,n)}else i="items"in e||"panel"===e.fieldType?new r.Fieldset(e,n):(0,a.isFile)(e)||"file-input"===e.fieldType?new o.default(e,n):(0,a.isCheckbox)(e)?new l.default(e,n):(0,a.isCheckboxGroup)(e)?new u.default(e,n):(0,a.isEmailInput)(e)?new p.default(e,n):(0,a.isDateField)(e)?new d.default(e,n):(0,a.isDateTimeField)(e)?new c.default(e,n):(0,a.isCaptcha)(e)?new f.default(e,n):(0,a.isButton)(e)?new m.default(e,n):new h.default(e,n);return i}}},1060:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(s,r){function a(e){try{l(n.next(e))}catch(e){r(e)}}function o(e){try{l(n.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.sanitizeName=t.replaceTemplatePlaceholders=t.sitesModelToFormModel=t.dataURItoBlob=t.extractFileInfo=t.isDataUrl=t.IdGenerator=t.getFileSizeInBytes=t.getAttachments=t.readAttachments=t.isEmpty=t.randomWord=void 0;const s=i(5088),r=i(6440),a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_".split(""),o=/^(\d*\.?\d+)(\\?(?=[KMGT])([KMGT])(?:i?B)?|B?)$/i;t.randomWord=e=>{const t=[];for(let i=0;i<=e;i++){let e;e=0===i?Math.floor(Math.random()*(a.length-11)):Math.floor(Math.random()*a.length),t.push(a[e])}return t.join("")},t.isEmpty=e=>""===e||null==e;const l=(e,i,n)=>{if(i&&null===e.dataRef)return n?Promise.resolve(null):null;let r=null;if(e.isContainer)return n?(0,t.readAttachments)(e,i).then((e=>e)):(0,t.getAttachments)(e,i);if((0,s.isFile)(e.getState())){r={};const t=e.name||"",i=null!=e.dataRef?e.dataRef:t.length>0?e.name:void 0;if(e.value instanceof Array)if("string[]"===e.type&&"data-url"===(null==e?void 0:e.format)){if(n)return e.serialize().then((t=>(r[e.id]=t.map((e=>Object.assign(Object.assign({},e),{dataRef:i}))),r)));r[e.id]=e.value.map((e=>Object.assign(Object.assign({},e),{dataRef:i})))}else r[e.id]=e.value.map((e=>Object.assign(Object.assign({},e),{dataRef:i})));else if(null!=e.value)if("string"===e.type&&"data-url"===(null==e?void 0:e.format)){if(n)return e.serialize().then((t=>(r[e.id]=Object.assign(Object.assign({},t[0]),{dataRef:i}),r)));r[e.id]=Object.assign(Object.assign({},e.value),{dataRef:i})}else r[e.id]=Object.assign(Object.assign({},e.value),{dataRef:i})}return n?Promise.resolve(r):r};t.readAttachments=(e,t=!1)=>n(void 0,void 0,void 0,(function*(){return(e.items||[]).reduce(((e,i)=>n(void 0,void 0,void 0,(function*(){const n=yield e,s=yield l(i,t,!0);return Object.assign(n,s)}))),Promise.resolve({}))})),t.getAttachments=(e,t=!1)=>(e.items||[]).reduce(((e,i)=>{const n=l(i,t,!1);return Object.assign(e,n)}),{}),t.getFileSizeInBytes=e=>{let t=0;if("string"==typeof e){const i=o.exec(e.trim());null!=i&&(t=u(parseFloat(i[1]),(i[2]||"kb").toUpperCase()))}return t};const u=(e,t)=>
1{const i=Math.pow(1024,{KB:1,MB:2,GB:3,TB:4}[t]);return Math.round(e*i)};t.IdGenerator=function*(e=50){const i=function(){const i=[];for(let n=0;n<e;n++)i.push((0,t.randomWord)(10));return i},n={};let s=i();do{let e=s.pop();for(;e in n;)0===s.length&&(s=i()),e=s.pop();n[e]=!0,yield s.pop(),0===s.length&&(s=i())}while(s.length>0)},t.isDataUrl=e=>null!=/^data:([a-z]+\/[a-z0-9-+.]+)?;(?:name=(.*);)?base64,(.*)$/.exec(e.trim()),t.extractFileInfo=e=>{if(null!==e){let i=null;if(e instanceof r.FileObject)i=e;else if("undefined"!=typeof File&&e instanceof File)i={name:e.name,mediaType:e.type,size:e.size,data:e};else if("string"==typeof e&&(0,t.isDataUrl)(e)){const n=(0,t.dataURItoBlob)(e);if(null!==n){const{blob:e,name:t}=n;i={name:t,mediaType:e.type,size:e.size,data:e}}}else{let n=e;try{n=JSON.parse(e),i=n,i.mediaType||(i.mediaType=i.type)}catch(e){}if("string"==typeof(null==n?void 0:n.data)&&(0,t.isDataUrl)(null==n?void 0:n.data)){const e=(0,t.dataURItoBlob)(null==n?void 0:n.data);if(null!==e){const t=e.blob;i={name:null==n?void 0:n.name,mediaType:(null==n?void 0:n.type)||(null==n?void 0:n.mediaType),size:t.size,data:t}}}else"string"==typeof n?i={name:n.split("/").pop(),mediaType:"application/octet-stream",size:0,data:n}:"object"==typeof n&&(i={name:null==n?void 0:n.name,mediaType:(null==n?void 0:n.type)||(null==n?void 0:n.mediaType),size:null==n?void 0:n.size,data:null==n?void 0:n.data})}return null!==i&&null!=i.data?new r.FileObject(i):null}return null},t.dataURItoBlob=e=>{const t=/^data:([a-z]+\/[a-z0-9-+.]+)?(?:;name=([^;]+))?(;base64)?,(.+)$/.exec(e);if(null!==t){const e=t[1]||"",i=t[2]||"unknown";if("string"==typeof t[3]){const n=atob(t[4]),s=[];for(let e=0;e<n.length;e++)s.push(n.charCodeAt(e));return{name:i,blob:new window.Blob([new Uint8Array(s)],{type:e})}}return{name:i,blob:new window.Blob([t[4]],{type:e})}}return null},t.sitesModelToFormModel=e=>{if(!e||!Object.keys(e).length)return e;if((":items"in(i=e)||"cqItems"in i)&&(":itemsOrder"in i||"cqItemsOrder"in i)){const i=[],n=e[":itemsOrder"]||e.cqItemsOrder,s=e[":items"]||e.cqItems;n.forEach((e=>{i.push((0,t.sitesModelToFormModel)(s[e]))})),e.items=i}var i;return e},t.replaceTemplatePlaceholders=(e,t=[])=>null==e?void 0:e.replace(/\${(\d+)}/g,((e,i)=>{const n=t[i];return void 0!==n?n:e})),t.sanitizeName=e=>{const t=/^[A-Za-z0-9_$][A-Za-z0-9_.[\]]*$/;return e.includes(".")?e.split(".").map((e=>{if(e.includes("[")){const i=e.indexOf("["),n=e.substring(0,i),s=e.substring(i);return t.test(n)?e:`"${n}"${s}`}return t.test(e)?e:`"${e}"`})).join("."):t.test(e)?e:`"${e}"`}},5088:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isRepeatable=t.jsonString=t.checkIfKeyAdded=t.deepClone=t.isButton=t.isCaptcha=t.isDateField=t.isDateTimeField=t.isEmailInput=t.isCheckboxGroup=t.isCheckbox=t.checkIfConstraintsArePresent=t.isFile=t.getProperty=void 0;const n=i(9333),s=i(9616);t.getProperty=(e,t,i)=>{if(t in e)return e[t];if(!t.startsWith(":")){const i=`:${t}`;if(i in e)return e[i]}return i},t.isFile=function(e){return"file"===(null==e?void 0:e.type)||"file[]"===(null==e?void 0:e.type)||("string"===(null==e?void 0:e.type)||"string[]"===(null==e?void 0:e.type))&&("binary"===(null==e?void 0:e.format)||"data-url"===(null==e?void 0:e.format))||"file-input"===(null==e?void 0:e.fieldType)},t.checkIfConstraintsArePresent=function(e){return n.constraintProps.some((t=>void 0!==e[t]))},t.isCheckbox=function(e){return"checkbox"===((null==e?void 0:e.fieldType)||(0,s.defaultFieldTypes)(e))},t.isCheckboxGroup=function(e){return"checkbox-group"===((null==e?void 0:e.fieldType)||(0,s.defaultFieldTypes)(e))},t.isEmailInput=function(e){const t=(null==e?void 0:e.fieldType)||(0,s.defaultFieldTypes)(e);return"text-input"===t&&"email"===(null==e?void 0:e.format)||"email"===t},t.isDateTimeField=function(e){const t=(null==e?void 0:e.fieldType)||(0,s.defaultFieldTypes)(e);return"text-input"===t&&"date-time"===(null==e?void 0:e.format)||"datetime-input"===t},t.isDateField=function(e){const t=(null==e?void 0:e.fieldType)||(0,s.defaultFieldTypes)(e);return"text-input"===t&&"date"===(null==e?void 0:e.format)||"date-input"===t},t.isCaptcha=function(e){return"captcha"===((null==e?void 0:e.fieldType)||(0,s.defaultFieldTypes)(e))},t.isButton=function(e){return"button"===(null==e?void 0:e.fieldType)},t.deepClone=function e(t,i){if(null===t||"object"!=typeof t)return t;let n;if(Array.isArray(t)){n=new Array(t.length);for(let s=0;s<t.length;s++)n[s]=e(t[s],i)}else{n={};for(const s of Object.keys(t))n[s]=e(t[s],i)}return i&&n&&n.id&&(n.id=i()),n},t.checkIfKeyAdded=function(e,i,n){if(null!=e&&null!=i){const s=Object.assign({},i);return s[n]=e[n],""===(0,t.jsonString)(e).replace((0,t.jsonString)(s),"")}return!1},t.jsonString=e=>JSON.stringify(e,null,2),t.isRepeatable=e=>e.repeatable&&(void 0===e.minOccur&&void 0===e.maxOccur||void 0!==e.minOccur&&void 0!==e.maxOccur&&0!==e.maxOccur||void 0!==e.minOccur&&void 0!==e.maxOccur&&0!==e.minOccur&&0!==e.maxOccur||void 0!==e.minOccur&&e.minOccur>=0||void 0!==e.maxOccur&&0!==e.maxOccur)||!1},9616:(e,t)=>
1{Object.defineProperty(t,"__esModule",{value:!0}),t.exportDataSchema=t.defaultFieldTypes=void 0;const i=e=>new Map(Object.entries(e)),n=i({date:"date-input","data-url":"file-input",binary:"file-input"}),s=i({number:"number-input",boolean:"checkbox",object:"panel",array:"panel",file:"file-input","file[]":"file-input"}),r=["string[]","boolean[]","number[]","array"];t.defaultFieldTypes=e=>{const t=e.type||"string";return"enum"in e?e.enum.length>2||r.indexOf(t)>-1?"drop-down":"checkbox":"string"===t||"string[]"===t?n.get(e.format)||"text-input":s.get(t)||"text-input"};const a=e=>{var t;if("items"in e){const t=e,i=t.items;if("array"===t.type)return{type:"array",items:a(i[0]),minItems:null==t?void 0:t.minItems,maxItems:null==t?void 0:t.maxItems};{const e=i.filter((e=>null!=e.name));return{type:"object",properties:Object.fromEntries(e.map((e=>[e.name,a(e)]))),required:e.filter((e=>e.required)).map((e=>e.name))}}}{const i=e,n=["type","maxLength","minLength","minimum","maximum","format","pattern","step","enum"].reduce(((e,t)=>{const n=t;return t in i&&null!=i[n]&&(e[t]=i[n]),e}),{});if("none"===i.dataRef||0==Object.keys(n).length)return;return Object.assign({title:null===(t=i.label)||void 0===t?void 0:t.value,description:i.description},n)}};t.exportDataSchema=e=>a(e)},712:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createTranslationObject=t.createTranslationObj=t.getOrElse=t.addTranslationId=t.invalidateTranslation=t.CUSTOM_PROPS_KEY=t.TRANSLATION_ID=t.TRANSLATION_TOKEN=void 0;const n=i(9333);t.TRANSLATION_TOKEN="##",t.TRANSLATION_ID="afs:translationIds",t.CUSTOM_PROPS_KEY="properties";const s=["de-DE","en-US","es-ES","fr-FR","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-TW"];t.invalidateTranslation=(e,i)=>{n.translationProps.forEach((n=>{var s,r,a,o;n in i&&(null===(r=null===(s=null==e?void 0:e[t.CUSTOM_PROPS_KEY])||void 0===s?void 0:s[t.TRANSLATION_ID])||void 0===r?void 0:r[n])&&(null===(o=null===(a=null==e?void 0:e[t.CUSTOM_PROPS_KEY])||void 0===a?void 0:a[t.TRANSLATION_ID])||void 0===o||delete o[n])}))},t.addTranslationId=(e,t=[])=>{const i=e,s=[...n.translationProps,...t];return r(i,"",s),i};const r=(e,i,n)=>{Object.entries(e).forEach((([s,a])=>{if("object"==typeof a)e instanceof Array?a&&"name"in a&&r(a,`${""===i?i:i+t.TRANSLATION_TOKEN}${a.name}`,n):r(a,"items"===s?i:`${""===i?i:i+t.TRANSLATION_TOKEN}${s}`,n);else if(":type"in e||"type"in e||"fieldType"in e)for(const s of n)null!=(0,t.getOrElse)(e,s)&&(t.CUSTOM_PROPS_KEY in e||(e[t.CUSTOM_PROPS_KEY]={}),t.TRANSLATION_ID in e[t.CUSTOM_PROPS_KEY]||(e[t.CUSTOM_PROPS_KEY][t.TRANSLATION_ID]={}),s in e[t.CUSTOM_PROPS_KEY][t.TRANSLATION_ID]||(e[t.CUSTOM_PROPS_KEY][t.TRANSLATION_ID][s]=`${i}${t.TRANSLATION_TOKEN}${s}${t.TRANSLATION_TOKEN}${Math.floor(1e4*Math.random())+1}`))}))},a=(e,i,n)=>{Object.values(e).forEach((s=>{var r,o;if("object"==typeof s)a(s,i,n);else for(const s of n){const n=(0,t.getOrElse)(e,s);n&&(null===(o=null===(r=null==e?void 0:e[t.CUSTOM_PROPS_KEY])||void 0===r?void 0:r[t.TRANSLATION_ID])||void 0===o?void 0:o[s])&&(n instanceof Array?n.forEach(((n,r)=>{"string"==typeof n&&(i[`${e[t.CUSTOM_PROPS_KEY][t.TRANSLATION_ID][s]}${t.TRANSLATION_TOKEN}${r}`]=n)})):i[`${e[t.CUSTOM_PROPS_KEY][t.TRANSLATION_ID][s]}`]=n)}}))};t.getOrElse=(e,t,i=null)=>{if(!t)return i;const n=Array.isArray(t)?t:t.split(".");let s=e,r=0;for(;r<n.length&&s.hasOwnProperty(n[r]);)s=s[n[r]],r++;return r==n.length?s:i},t.createTranslationObj=(e,t=[])=>{const i={},s=[...n.translationProps,...t];return a(e,i,s),i},t.createTranslationObject=(e,i=[],r=[])=>{const a=[...n.translationProps,...i],o=JSON.parse(JSON.stringify(e)),l=(0,t.createTranslationObj)((0,t.addTranslationId)(o,i),a),u=[...s,...r],d={};for(const e of u)d[e]=JSON.parse(JSON.stringify(l));return[o,d]}},4476:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Constraints=t.validationConstraintsList=t.ValidConstraints=t.coerceType=void 0;const n=i(1060),s=i(6440),r=/^(\d{4})-(\d{1,2})-(\d{1,2})$/,a=/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,o=[31,28,31,30,31,30,31,31,30,31,30,31];t.coerceType=(e,t)=>{let i;switch(t){case"string":return e+"";case"number":if(i=+e,!isNaN(i))return i;break;case"boolean":if("string"==typeof e)return"true"===e;if("number"==typeof e)return 0!==e}throw`${e}
1 has invalid type. Expected : ${t}, Actual ${typeof e}`};const l=e=>{if(""===e||null==e)return{value:"",valid:!0};let t=parseFloat(e);const i=!isNaN(t);return i||(t=e),{value:t,valid:i}},u=e=>{if(""===e||null==e)return{value:"",valid:!0};let t=parseFloat(e);const i=!isNaN(t)&&Math.round(t)===t;return i||(t=e),{value:t,valid:i}},d=e=>null==e||e instanceof Array?e:[e],c=e=>{const t="boolean"==typeof e||"true"===e||"false"===e;return{valid:t,value:"boolean"==typeof e?e:t?"true"===e:e}},h=e=>{const t=(0,n.extractFileInfo)(e),i=null!==t;return{value:i?t:e,valid:i}},p=(e,t)=>{const i=d(e);return null==i?[[],[i]]:i.reduce(((e,i)=>{if(0==e[1].length){const n=t(i);e[n.valid?0:1].push(n.value)}return e}),[[],[]])};t.ValidConstraints={date:["minimum","maximum","exclusiveMinimum","exclusiveMaximum","format"],string:["minLength","maxLength","pattern"],number:["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],array:["minItems","maxItems","uniqueItems"],file:["accept","maxFileSize"],email:["minLength","maxLength","format","pattern"],datetime:["minimum","maximum"]},t.validationConstraintsList=["type","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","minItems","maxItems","uniqueItems","minLength","maxLength","pattern","required","enum","accept","maxFileSize"],t.Constraints={type:(e,t)=>{let i=t;if(null==t)return{valid:!0,value:t};let n,s=!0;switch(e){case"string":s=!0,i=t.toString();break;case"string[]":i=d(t);break;case"number":n=l(t),i=n.value,s=n.valid;break;case"boolean":n=c(t),s=n.valid,i=n.value;break;case"integer":n=u(t),s=n.valid,i=n.value;break;case"integer[]":n=p(t,u),s=0===n[1].length,i=s?n[0]:t;break;case"file":n=h(t instanceof Array?t[0]:t),s=n.valid,i=n.value;break;case"file[]":n=p(t,h),s=0===n[1].length,i=s?n[0]:t;break;case"number[]":n=p(t,l),s=0===n[1].length,i=s?n[0]:t;break;case"boolean[]":n=p(t,c),s=0===n[1].length,i=s?n[0]:t}return{valid:s,value:i}},format:(e,t)=>{let i=!0;const n=t;if(null===t)return{value:n,valid:i};let s;switch(e){case"date":if(s=r.exec((t||"").trim()),null!=s){const[e,t,n,r]=s,[a,l]=[+n,+r],u=(e=>e%400==0||e%4==0&&e%100!=0)(+t);i=a>=1&&a<=12&&l>=1&&l<=((e,t)=>e&&2==t?29:o[t-1])(u,a)}else i=!1;break;case"email":i=new RegExp(a).test((t||"").trim());break;case"data-url":i=!0}return{valid:i,value:n}},minimum:(e,t)=>
1({valid:t>=e,value:t}),maximum:(e,t)=>({valid:t<=e,value:t}),exclusiveMinimum:(e,t)=>({valid:t>e,value:t}),exclusiveMaximum:(e,t)=>({valid:t<e,value:t}),minItems:(e,t)=>({valid:t instanceof Array&&t.length>=e,value:t}),maxItems:(e,t)=>({valid:t instanceof Array&&t.length<=e,value:t}),uniqueItems:(e,t)=>({valid:!e||t instanceof Array&&t.length===new Set(t).size,value:t}),minLength:(e,i)=>Object.assign(Object.assign({},t.Constraints.minimum(e,"string"==typeof i?i.length:0)),{value:i}),maxLength:(e,i)=>Object.assign(Object.assign({},t.Constraints.maximum(e,"string"==typeof i?i.length:0)),{value:i}),pattern:(e,t)=>{let i;return i="string"==typeof e?new RegExp(e):e,{valid:i.test(t),value:t}},required:(e,t)=>({valid:!e||null!=t&&""!==t,value:t}),enum:(e,t)=>({valid:e.indexOf(t)>-1,value:t}),accept:(e,t)=>e&&0!==e.length&&null!=t?{valid:!(t instanceof Array?t:[t]).some((t=>{return!(""!==(i=t.type)&&(!i||e.some((e=>{const t=e.trim(),n=t.split("/")[0],s=t.split(".")[1];return t.includes("*")&&i.startsWith(n)||t.includes(".")&&i.endsWith(s)||t===i}))));var i})),value:t}:{valid:!0,value:t},maxFileSize:(e,t)=>{const i="string"==typeof e?(0,n.getFileSizeInBytes)(e):e;return{valid:!(t instanceof s.FileObject)||t.size<=i,value:t}}}},7177:function(e,t){var i,n,s,r,a=this&&this.__classPrivateFieldSet||function(e,t,i,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,i):s?s.value=i:t.set(e,i),i},o=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Version=void 0,t.Version=class{constructor(e){i.set(this,void 0),n.set(this,void 0),s.set(this,void 0),r.set(this,!0);const t=e.match(/([^.]+)\.([^.]+)(?:\.(.+))?/);if(!t)throw new Error("Invalid version string "+e);if(a(this,n,+t[1],"f"),a(this,i,+t[2],"f"),a(this,s,t[3]?+t[3]:0,"f"),isNaN(o(this,n,"f"))||isNaN(o(this,i,"f"))||isNaN(o(this,s,"f")))throw new Error("Invalid version string "+e)}get major(){return o(this,n,"f")}get minor(){return o(this,i,"f")}get subversion(){return o(this,s,"f")}completeMatch(e){return this.major===e.major&&this.minor===e.minor&&o(this,s,"f")===e.subversion}lessThan(e){return this.major<e.major||this.major===e.major&&this.minor<e.minor||this.major===e.major&&this.minor===e.minor&&o(this,s,"f")<e.subversion}toString(){return`${this.major}.${this.minor}.${this.subversion}`}valueOf(){return this.toString()}},i=new WeakMap,n=new WeakMap,s=new WeakMap,r=new WeakMap},2435:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.adjustTimeZone=o,t.datetimeToNumber=function(e){return null===e?0:e.getTime()/864e5},t.formatDate=function(e,t,i,s){if(i.startsWith("date|")&&(i=i.split("|")[1]),n.ShorthandStyles.find((e=>i.includes(e)))){const r={timeZone:s},a=i.split(/\s/).filter((e=>e.length));return n.ShorthandStyles.indexOf(a[0])>-1&&(r.dateStyle=a[0]),a.length>1&&n.ShorthandStyles.indexOf(a[1])>-1&&(r.timeStyle=a[1]),new Intl.DateTimeFormat(t,r).format(e)}return function(e,t,i,s){const r=(0,n.parseDateTimeSkeleton)(i,t);r.push(["timeZone",s]);const a=r.filter((e=>!e[0].startsWith("x-"))),o=r.filter((e=>e[0].startsWith("x-"))),l=Object.fromEntries(a);delete l.literal;const u=new Intl.DateTimeFormat(t,l).formatToParts(e);return function(e,t){["hour","minute","second"].forEach((i=>{const n=e.find((e=>e.type===i));if(!n)return;const s=t.find((e=>e[0]===i))[1];"2-digit"===s&&1===n.value.length&&(n.value=`0${n.value}`),"numeric"===s&&2===n.value.length&&"0"===n.value.charAt(0)&&(n.value=n.value.slice(1))}))}(u,r),function(e,t){const i=e.find((e=>"year"===e.type));if(!i)return;const n=t.find((e=>"year"===e[0]))[2];for(;i.value.length<n;)i.value=`0${i.value}`}(u,a),a.reduce(((e,t)=>
1{if("literal"===t[0])e.push(t);else{const i=u.find((e=>{return e.type===({hour12:"dayPeriod",fractionalSecondDigits:"fractionalSecond"}[i=t[0]]||i);var i}));if(i&&"timeZoneName"===i.type){const e=o.find((e=>"x-timeZoneName"===e[0]))[1],t=e[0];"Z"===t&&(e.length<4?(i.value=i.value.replace(/(GMT|:)/g,""),""===i.value&&(i.value="+0000")):5===e.length&&("GMT"===i.value?i.value="Z":i.value=i.value.replace(/GMT/,""))),"X"===t||"x"===t?(1===e.length&&(i.value=i.value.replace(/(GMT|:(00)?)/g,"")),2===e.length&&(i.value=i.value.replace(/(GMT|:)/g,"")),3===e.length&&(i.value=i.value.replace(/GMT/g,"")),"X"===t&&""===i.value&&(i.value="Z")):"O"===e&&(i.value=i.value.replace(/GMT/g,"").replace(/0(\d+):/,"$1:").replace(/:00/,""),""===i.value&&(i.value="+0"))}i&&e.push([i.type,i.value])}return e}),[])}(e,t,i,s).map((e=>e[1])).join("")},t.numberToDatetime=function(e){return new Date(Math.round(1e3*e*60*60*24))},t.offsetMS=r,t.offsetMSFallback=a,t.parseDate=l,t.parseDefaultDate=function(e,t,i){return l(e,t,"yyyy-MM-dd",null,i)};var n=i(8880);const s=[0,1,2,3,4,5,6,7,8,9,10,11].map((e=>new Date(2e3,e,1)));function r(e,t){let i;try{i=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"longOffset"}).format(e)}catch(e){return a(0,t)}const n=/GMT([+\-−])?(\d{1,2}):?(\d{0,2})?/.exec(i);if(!n)return 0;const[s,r,o]=n.slice(1),l=60*(60*(isNaN(parseInt(r))?0:parseInt(r))+(isNaN(parseInt(o))?0:parseInt(o)))*1e3;return"-"===s?-l:l}function a(e,t){return 60*function(e){var t=new Date;function i(e){var t=e.replace(":"," ").split(" ");return{day:parseInt(t[0]),hour:parseInt(t[1]),minute:parseInt(t[2])}}var n=t.toLocaleString("en-US",{timeZone:e,day:"numeric",hour:"numeric",minute:"numeric",hourCycle:"h23"}),s=i(n),r=i(n=t.toLocaleString("en-US",{day:"numeric",hour:"numeric",minute:"numeric",hourCycle:"h23"}));return 24*s.day*60+60*s.hour+s.minute-(24*r.day*60+60*r.hour+r.minute)-t.getTimezoneOffset()}(t)*1e3}function o(e,t){if(null===e)return null;let i=e.getTime()-60*e.getTimezoneOffset()*1e3;const n=r(e,t);return a(0,t),i+=-n,new Date(i)}function l(e,t,i,r){let a=arguments.length>4&&void 0!==arguments[4]&&arguments[4];i.startsWith("date|")&&(i=i.split("|")[1]);const l=[],u=[],d=(c=t,"هـ"===(null===(h=new Intl.DateTimeFormat(c,{era:"short"}).formatToParts(new Date).find((e=>"era"===e.type)))||void 0===h?void 0:h.value)?"islamic":"gregory");var c,h;const p=function(e){return new Intl.NumberFormat(e,{style:"decimal",useGrouping:!1}).format(9876543210).split("").reverse()}(t),f=`([${p[0]}-${p[9]}]{1,2})`,m=`([${p[0]}-${p[9]}]{1,3})`,g=`([${p[0]}-${p[9]}]{1,4})`;let _="h12",v=a,y=!1;const b=e=>E(e)-1,E=e=>e.split("").reduce(((e,t)=>10*e+p.indexOf(t)),0),T=(0,n.parseDateTimeSkeleton)(i,t),M=function(e,t){return s.map((i=>{const n=new Intl.DateTimeFormat(e,t).formatToParts(i).find((e=>"month"===e.type));return n&&n.value}))}(t,Object.fromEntries(T));T.forEach((e=>{let[i,n,s]=e;if("literal"===i)u.push(n);else if("month"===i&&["numeric","2-digit"].includes(n))u.push(f),l.push(["month",b]);else if("month"===i&&["formatted","long","short","narrow"].includes(n))u.push(`(${M.join("|")})`),l.push(["month",(a=M,e=>a.indexOf(e))]);else if(["day","minute","second"].includes(i))"minute"!==i&&"second"!==i||(v=!1),u.push(f),l.push([i,E]);else if("fractionalSecondDigits"===i)v=!1,u.push(m),l.push([i,(e,t)=>t.fractionalSecondDigits+E(e)]);else if("hour"===i)v=!1,u.push(f),l.push([i,(e,t)=>t.hour+E(e)]);else if("year"===i)u.push("numeric"===n?g:f),l.push(["year",(r=s,e=>{let t=E(e);return t=t<100&&2===r?t+2e3:t,"islamic"===d&&(t=Math.ceil(.97*t+622)),r>2&&t<100&&(y=!0),t})]);else if("dayPeriod"===i){v=!1;const e=function(e){const t=new Date(2e3,1,1,1,1,1),i=new Date(2e3,1,1,16,1,1),n=new Intl.DateTimeFormat(e,{dateStyle:"full",timeStyle:"full"}),s=n.formatToParts(t).find((e=>"dayPeriod"===e.type)),r=n.formatToParts(i).find((e=>"dayPeriod"===e.type));return s&&r?{regex:`(${s.value}|${r.value})`,fn:(e,t)=>t.hour+=e===r.value?12:0}:null}(t);e&&(u.push(e.regex),l.push(["hour",e.fn]))}else"hourCycle"===i?(v=!1,_=n):"x-timeZoneName"===i?(v=!1,u.push("(?:GMT|UTC|Z)?([+\\-−0-9]{0,3}:?[0-9]{0,2})"),l.push([i,(e,t)=>{if(v=!0,!e)return;const i=e.replace(/−/,"-").match(/([+\-\d]{2,3}):?(\d{0,2})/),n=1*i[1];t.hour-=n;const s=i.length>2?1*i[2]:0;t.minute-=n<0?-s:s}])):"timeZoneName"!==i&&(v=!1,u.push(".+?"));var r,a;return u}),[]);const O=new RegExp(`^${u.join("")}$`),w=e.match(O);if(null===w)return null;const I={year:1972,month:0,day:1,hour:0,minute:0,second:0,fractionalSecondDigits:0};
1if(w.slice(1).forEach(((e,t)=>{const[i,n]=l[t];I[i]=n(e,I)})),"h24"===_&&24===I.hour&&(I.hour=0),"h12"===_&&12===I.hour&&(I.hour=0),v){const e=new Date(Date.UTC(I.year,I.month,I.day,I.hour,I.minute,I.second,I.fractionalSecondDigits));return y&&e.setUTCFullYear(I.year),e}const A=new Date(I.year,I.month,I.day,I.hour,I.minute,I.second,I.fractionalSecondDigits);return y&&A.setFullYear(I.year),((e,t,i)=>"gregory"!==i||e.getMonth()===t.month&&e.getDate()===t.day&&e.getFullYear()===t.year)(A,I,d)?null==r?A:o(A,r):null}},8880:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShorthandStyles=void 0,t.getSkeleton=function(e,t){if(n.find((t=>e.includes(t)))){const i=s(e,t),n=[],r={month:"M",year:"Y",day:"d"};return i.forEach((e=>{let[t,i,s]=e;t in r?n.push(Array(s).fill(r[t]).join("")):"literal"===t&&n.push(i)})),n.join("")}return e},t.parseDateTimeSkeleton=function(e,t){if(n.find((t=>e.includes(t))))return s(e,t);const r=[];return e.replace(i,(e=>{const t=e.length;switch(e[0]){case"G":r.push(["era",4===t?"long":5===t?"narrow":"short",t]);break;case"y":r.push(["year",2===t?"2-digit":"numeric",t]);break;case"Y":case"u":case"U":case"r":throw new RangeError("`Y/u/U/r` (year) patterns are not supported, use `y` instead");case"q":case"Q":throw new RangeError("`q/Q` (quarter) patterns are not supported");case"M":case"L":r.push(["month",["numeric","2-digit","short","long","narrow"][t-1],t]);break;case"w":case"W":throw new RangeError("`w/W` (week) patterns are not supported");case"d":r.push(["day",["numeric","2-digit"][t-1],t]);break;case"D":case"F":case"g":throw new RangeError("`D/F/g` (day) patterns are not supported, use `d` instead");case"E":r.push(["weekday",["short","short","short","long","narrow","narrow"][t-1],t]);break;case"e":if(t<4)throw new RangeError("`e..eee` (weekday) patterns are not supported");r.push(["weekday",["short","long","narrow","short"][t-4],t]);break;case"c":if(t<3||t>5)throw new RangeError("`c, cc, cccccc` (weekday) patterns are not supported");r.push(["weekday",["short","long","narrow","short"][t-3],t]);break;case"a":r.push(["hour12",!0,1]);break;case"b":case"B":throw new RangeError("`b/B` (period) patterns are not supported, use `a` instead");case"h":r.push(["hourCycle","h12"]),r.push(["hour",["numeric","2-digit"][t-1],t]);break;case"H":r.push(["hourCycle","h23",1]),r.push(["hour",["numeric","2-digit"][t-1],t]);break;case"K":r.push(["hourCycle","h11",1]),r.push(["hour",["numeric","2-digit"][t-1],t]);break;case"k":r.push(["hourCycle","h24",1]),r.push(["hour",["numeric","2-digit"][t-1],t]);break;case"j":case"J":case"C":throw new RangeError("`j/J/C` (hour) patterns are not supported, use `h/H/K/k` instead");case"m":r.push(["minute",["numeric","2-digit"][t-1],t]);break;case"s":r.push(["second",["numeric","2-digit"][t-1],t]);break;case"S":r.push(["fractionalSecondDigits",t,t]);break;case"A":throw new RangeError("`S/A` (millisecond) patterns are not supported, use `s` instead");case"O":r.push(["timeZoneName",t<4?"shortOffset":"longOffset",t]),r.push(["x-timeZoneName",t<4?"O":"OOOO",t]);break;case"X":case"x":case"Z":r.push(["timeZoneName","longOffset",1]),r.push(["x-timeZoneName",e,1]);break;case"z":case"v":case"V":throw new RangeError("z/v/V` (timeZone) patterns are not supported, use `X/x/Z/O` instead");case"'":r.push(["literal",e.slice(1,-1).replace(/''/g,"'"),-1]);break;default:r.push(["literal",e,-1])}return""})),r};const i=/(?:[Eec]{1,6}|G{1,5}|[Qq]{1,5}|(?:[yYur]+|U{1,5})|[ML]{1,5}|d{1,2}|D{1,3}|F{1}|[abB]{1,5}|[hkHK]{1,2}|w{1,2}|W{1}|m{1,2}|s{1,2}|[zZOvV]{1,5}|[zZOvVxX]{1,3}|S{1,3}|'(?:[^']|'')*')|[^a-zA-Z']+/g,n=["full","long","medium","short"];function s(e,t){const i={},n=e.split(/\s/).filter((e=>e.length));i.dateStyle=n[0],n.length>1&&(i.timeStyle=n[1]);const s=new Date(2e3,2,1,2,3,4),r=new Intl.DateTimeFormat(t,i).formatToParts(s),a=r.find((e=>"month"===e.type)).value,o=new Intl.DateTimeFormat(t,{month:"long"}).formatToParts(s)[0].value,l=new Intl.DateTimeFormat(t,{month:"short"}).formatToParts(s)[0].value,u=[];return r.forEach((t=>{let i,{type:n,value:s}=t;"month"===n&&(i={[a]:"medium"===e?"short":"long",[o]:"long",[l]:"short","03":"2-digit",3:"numeric"}[s]),"year"===n&&(i={2e3:"numeric","00":"2-digit"}[s]),["day","hour","minute","second"].includes(n)&&(i=2===s.length?"2-digit":"numeric"),"literal"
1===n&&(i=s),"dayPeriod"===n&&(i="short"),u.push([n,i,s.length])})),u}t.ShorthandStyles=n,new Date(2e3,2,1,2,3,4)},9704:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"datetimeToNumber",{enumerable:!0,get:function(){return n.datetimeToNumber}}),Object.defineProperty(t,"formatDate",{enumerable:!0,get:function(){return n.formatDate}}),Object.defineProperty(t,"getSkeleton",{enumerable:!0,get:function(){return s.getSkeleton}}),Object.defineProperty(t,"numberToDatetime",{enumerable:!0,get:function(){return n.numberToDatetime}}),Object.defineProperty(t,"parseDate",{enumerable:!0,get:function(){return n.parseDate}}),Object.defineProperty(t,"parseDefaultDate",{enumerable:!0,get:function(){return n.parseDefaultDate}});var n=i(2435),s=i(8880)},6608:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"datetimeToNumber",{enumerable:!0,get:function(){return n.datetimeToNumber}}),t.format=void 0,Object.defineProperty(t,"formatDate",{enumerable:!0,get:function(){return n.formatDate}}),Object.defineProperty(t,"formatNumber",{enumerable:!0,get:function(){return s.formatNumber}}),Object.defineProperty(t,"numberToDatetime",{enumerable:!0,get:function(){return n.numberToDatetime}}),t.parse=void 0,Object.defineProperty(t,"parseDate",{enumerable:!0,get:function(){return n.parseDate}}),Object.defineProperty(t,"parseDateSkeleton",{enumerable:!0,get:function(){return n.getSkeleton}}),Object.defineProperty(t,"parseDefaultDate",{enumerable:!0,get:function(){return n.parseDefaultDate}}),Object.defineProperty(t,"parseNumber",{enumerable:!0,get:function(){return s.parseNumber}});var n=i(9704),s=i(1960);const r=function(e){const t=null==e?void 0:e.match(/^(?:(num|date)\|)?(.+)/);return[null==t?void 0:t[1],null==t?void 0:t[2]]};t.format=function(e,t,i,a){const[o,l]=r(i);switch(o){case"date":return e instanceof Date||(e=new Date(e.replace(/-/g,"/").replace(/T.+/,""))),(0,n.formatDate)(e,t,l,a);case"num":return(0,s.formatNumber)(e,t,l);default:throw"unable to deduce the format. The skeleton should be date|<format> for date formats and num|<format> for numbers"}},t.parse=function(e,t,i,a){const[o,l]=r(i);switch(o){case"date":return(0,n.parseDate)(e,t,l,a);case"number":return(0,s.parseNumber)(e,t,l);default:throw"unable to deduce the format. The skeleton should be date|<format> for date formats and num|<format> for numbers"}}},1960:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.formatNumber=function(e,t,i){if(i.startsWith("num|")&&(i=i.split("|")[1]),!i)return e;t=t||"en";const{options:s,order:r}=(0,n.parseNumberSkeleton)(i,t);return new Intl.NumberFormat(t,s).format(e)},t.parseDefaultNumber=function(e,t){return s(e,t,`currency/${currencies[t]||"USD"}`)},t.parseNumber=s;var n=i(1764);function s(e,t,i){try{i.startsWith("num|")&&(i=i.split("|")[1]);let s=1,r=e;const a=function(e,t){const i={};let s=new Intl.NumberFormat(e,{style:"decimal",useGrouping:!1}
1).formatToParts(9876543210.1);i.digits=s.find((e=>"integer"===e.type)).value.split("").reverse(),i.decimal=s.find((e=>"decimal"===e.type)).value;const r=e=>{const t=s.find((t=>t.type===e));t&&(i[e]=t.value)},a=(0,n.parseNumberSkeleton)(t),o=new Intl.NumberFormat(e,a);return s=o.formatToParts(-987654321),r("group"),r("minusSign"),r("percentSign"),i.currency=s.filter((e=>"currency"===e.type)).map((e=>e.value)),i.literal=s.filter((e=>"literal"===e.type)).map((e=>e.value)),s=o.formatToParts(987654321),r("plusSign"),r("exponentSeparator"),r("unit"),i}(t,i);if(a.group&&(r=r.replaceAll(a.group,"")),r=r.replace(a.decimal,"."),a.unit&&(r=r.replaceAll(a.unit,"")),a.minusSign&&r.includes(a.minusSign)&&(r=r.replace(a.minusSign,""),s*=-1),a.percentSign&&r.includes(a.percentSign)&&(s/=100,r=r.replace(a.percentSign,"")),a.currency.forEach((e=>r=r.replace(e,""))),a.literal.forEach((e=>{r.includes(e)&&("("===e&&(s*=-1),r=r.replace(e,""))})),a.plusSign&&(r=r.replace(a.plusSign,"")),a.exponentSeparator){let e;[r,e]=r.split(a.exponentSeparator),s*=Math.pow(10,e)}const o=s*r;return isNaN(o)?e:o}catch(t){return console.dir(t),e}}},1764:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShorthandStyles=void 0,t.parseNumberSkeleton=function(e,t){const i={},r=[];let o,l;for(l=0;l<a.length&&null==o;l++)o=a[l].exec(e);if(o){switch(l){case 1:i.style="currency",i.currencyDisplay="narrowSymbol",o[1]?i.currency=o[1]:i.currency=(0,n.getCurrency)(t);break;case 2:new Intl.NumberFormat(t,{}).resolvedOptions(),i.minimumFractionDigits=i.minimumFractionDigits||2;break;case 3:i.minimumFractionDigits=0,i.maximumFractionDigits=0;break;case 4:i.style="percent",i.maximumFractionDigits=2;break;case 5:i.style="unit",i.unitDisplay="long",i.unit=o[1]}return{options:i,order:r}}return i.useGrouping=!1,i.minimumIntegerDigits=1,i.maximumFractionDigits=0,i.minimumFractionDigits=0,e.replace(s,((s,a,o,l)=>{const u=s.length;switch(s[0]){case"#":r.push(["digit",u]),!0===(null==i?void 0:i.decimal)&&(i.maximumFractionDigits=i.minimumFractionDigits+u);break;case"@":if(null!=i&&i.minimumSignificantDigits)throw"@ symbol should occur together";const d=a||"";r.push(["@",u-d.length]),i.minimumSignificantDigits=u-d.length,i.maximumSignificantDigits=u,r.push(["digit",d.length]);break;case",":if(!0===(null==i?void 0:i.decimal))throw"grouping character not supporting for fractions";r.push(["group",1]),i.useGrouping="auto";break;case".":null!=i&&i.decimal?console.error("only one decimal symbol is allowed"):(r.push(["decimal",1]),i.decimal=!0);break;case"0":if(r.push("0",u),i.minimumSignificantDigits||i.maximumSignificantDigits)throw"0 is not supported with @";!0===(null==i?void 0:i.decimal)?(i.minimumFractionDigits=u,i.maximumFractionDigits||(i.maximumFractionDigits=u)):i.minimumIntegerDigits=u;break;case"-":0!==l&&console.error("sign display is always in the beginning"),i.signDisplay="negative",r.push(["signDisplay",1,"-"]);break;case"+":0!==l&&"E"===r[r.length-1][0]&&console.error("sign display is always in the beginning"),0===l&&(i.signDisplay="always"),r.push(["signDisplay",1,"+"]);break;case"¤":0!==l&&l!==e.length-1?console.error("currency display should be either in the beginning or at the end"):(i.style="currency",i.currencyDisplay=["symbol","code","name","narrowSymbol"][u-1],i.currency=o||(0,n.getCurrency)(t),r.push(["currency",u]));break;case"%":0!==l&&l!==e.length-1?console.error("percent display should be either in the beginning or at the end"):(r.push(["%",1]),i.style="percent");break;case"E":r.push(["E",u]),i.style=["scientific","engineering"](u-1);break;default:console.error("unknown chars"+s)}})),{options:i,order:r}};var n=i(8763);const s=/(?:[#]+|[@]+(#+)?|[0]+|[,]|[.]|[-]|[+]|[%]|[¤]{1,4}(?:\/([a-zA-Z]{3}))?|[;]|[K]{1,2}|E{1,2}[+]?|'(?:[^']|'')*')|[^a-zA-Z']+/g,r=["acre","bit","byte","celsius","centimeter","day","degree","fahrenheit","fluid-ounce","foot","gallon","gigabit","gigabyte","gram","hectare","hour","inch","kilobit","kilobyte","kilogram","kilometer","liter","megabit","megabyte","meter","mile","mile-scandinavian","milliliter","millimeter","millisecond","minute","month","ounce","percent","petabyte","pound","second","stone","terabit","terabyte","
1week","yard","year"].join("|"),a=[/^currency(?:\/([a-zA-Z]{3}))?$/,/^decimal$/,/^integer$/,/^percent$/,new RegExp(`^unit/(${r})$`)];t.ShorthandStyles=a},8763:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getCurrency=void 0;const i={"da-DK":"DKK","de-DE":"EUR","en-US":"USD","en-GB":"GBP","es-ES":"EUR","fi-FI":"EUR","fr-FR":"EUR","it-IT":"EUR","ja-JP":"JPY","nb-NO":"NOK","nl-NL":"EUR","pt-BR":"BRL","sv-SE":"SEK","zh-CN":"CNY","zh-TW":"TWD","ko-KR":"KRW","cs-CZ":"CZK","pl-PL":"PLN","ru-RU":"RUB","tr-TR":"TRY"},n=Object.keys(i);t.getCurrency=function(e){if(n.indexOf(e)>-1)return i[e];{const t=n.find((t=>t.startsWith(e)));if(t)return i[t]}return""}},3548:(e,t,i)=>{i.r(t),i.d(t,{default:()=>At,jsonFormula:()=>Ct});const n={TYPE_NUMBER:0,TYPE_ANY:1,TYPE_STRING:2,TYPE_ARRAY:3,TYPE_OBJECT:4,TYPE_BOOLEAN:5,TYPE_EXPREF:6,TYPE_NULL:7,TYPE_ARRAY_NUMBER:8,TYPE_ARRAY_STRING:9,TYPE_CLASS:10,TYPE_ARRAY_ARRAY:11},s={TOK_EOF:"EOF",TOK_UNQUOTEDIDENTIFIER:"UnquotedIdentifier",TOK_QUOTEDIDENTIFIER:"QuotedIdentifier",TOK_RBRACKET:"Rbracket",TOK_RPAREN:"Rparen",TOK_COMMA:"Comma",TOK_COLON:"Colon",TOK_CONCATENATE:"Concatenate",TOK_RBRACE:"Rbrace",TOK_NUMBER:"Number",TOK_CURRENT:"Current",TOK_GLOBAL:"Global",TOK_FIELD:"Field",TOK_EXPREF:"Expref",TOK_PIPE:"Pipe",TOK_OR:"Or",TOK_AND:"And",TOK_ADD:"Add",TOK_SUBTRACT:"Subtract",TOK_UNARY_MINUS:"UnaryMinus",TOK_MULTIPLY:"Multiply",TOK_POWER:"Power",TOK_UNION:"Union",TOK_DIVIDE:"Divide",TOK_EQ:"EQ",TOK_GT:"GT",TOK_LT:"LT",TOK_GTE:"GTE",TOK_LTE:"LTE",TOK_NE:"NE",TOK_FLATTEN:"Flatten",TOK_STAR:"Star",TOK_FILTER:"Filter",TOK_DOT:"Dot",TOK_NOT:"Not",TOK_LBRACE:"Lbrace",TOK_LBRACKET:"Lbracket",TOK_LPAREN:"Lparen",TOK_LITERAL:"Literal"},{TYPE_NUMBER:r,TYPE_ANY:a,TYPE_STRING:o,TYPE_ARRAY:l,TYPE_OBJECT:u,TYPE_BOOLEAN:d,TYPE_EXPREF:c,TYPE_NULL:h,TYPE_ARRAY_NUMBER:p,TYPE_ARRAY_STRING:f,TYPE_CLASS:m,TYPE_ARRAY_ARRAY:g}=n,{TOK_EXPREF:_}=s,v={[r]:"number",[a]:"any",[o]:"string",[l]:"array",[u]:"object",[d]:"boolean",[c]:"expression",[h]:"null",[p]:"Array<number>",[f]:"Array<string>",[m]:"class",[g]:"Array<array>"};function y(e,t=!0){if(null===e)return h;let i=e;if(t){if("function"!=typeof e.valueOf)return u;i=e.valueOf.call(e)}switch(Object.prototype.toString.call(i)){case"[object String]":return o;case"[object Number]":return r;case"[object Array]":return l;case"[object Boolean]":return d;case"[object Null]":return h;case"[object Object]":return i.jmespathType===_?c:u;default:return u}}function b(e){return[y(e),y(e,!1)]}function E(e,t,i,n,s,c){const _=e[0];if(-1!==t.findIndex((e=>e===a||_===e)))return i;let y=!1;if((_===u||1===t.length&&t[0]===m)&&(y=!0),_===l&&1===t.length&&t[0]===u&&(y=!0),t.includes(g)){if(_===l&&(i.forEach((e=>{e instanceof Array||(y=!0)})),!y))return i;y=!0}if(y)throw new Error(`TypeError: ${n} expected argument to be type ${v[t[0]]} but received type ${v[_]} instead.`);let T=-1;if(_===l&&t.includes(f)&&t.includes(p)&&(T=i.length>0&&"string"==typeof i[0]?f:p),-1===T&&[f,p,l].includes(_)&&(T=t.find((e=>[f,p,l].includes(e)))),-1===T&&([T]=t),T===a)return i;if(T===f||T===p||T===l){if(T===l)return _===p||_===f?i:null===i?[]:[i];const t=T===p?r:o;if(_===l){const e=i.slice();for(let i=0;i<e.length;i+=1){const r=b(e[i]);e[i]=E(r,[t],e[i],n,s,c)}return e}if([r,o,h,d].includes(t))return[E(e,[t],i,n,s,c)]}else{if(T===r)return[o,d,h].includes(_)?s(i):0;if(T===o)return _===h||_===u?"":c(i);if(T===d)return!!i;if(T===u&&e[1]===u)return i}throw new Error(`TypeError: ${n} expected argument to be type ${v[t[0]]} but received type ${v[_]} instead.`)}function T(e){return null!==e&&"[object Array]"===Object.prototype.toString.call(e)}function M(e){return null!==e&&"[object Object]"===Object.prototype.toString.call(e)}function O(e){return null==e?e:T(e)?e.map((e=>O(e))):"function"!=typeof e.valueOf?e:e.valueOf()}function w(e,t){const i=O(e),n=O(t);if(i===n)return!0;if(Object.prototype.toString.call(i)!==Object.prototype.toString.call(n))return!1;if(!0===T(i)){if(i.length!==n.length)return!1;for(let e=0;e<i.length;e+=1)if(!1===w(i[e],n[e]))return!1;return!0}if(!0===M(i)){const e={};for(const t in i)if(hasOwnProperty.call(i,t)){if(!1===w(i[t],n[t]))return!1;e[t]=!0}for(const t in n)if(hasOwnProperty.call(n,t)&&!0!==e[t])return!1;return!0}return!1}const{TOK_CURRENT:I,TOK_GLOBAL:A,TOK_EXPREF:C,TOK_PIPE:N,TOK_EQ:S,TOK_GT:j,TOK_LT:x,TOK_GTE:R,TOK_LTE:D,TOK_NE:P,TOK_FLATTEN:F}=s,{TYPE_STRING:L,TYPE_ARRAY_STRING:k,TYPE_ARRAY:$}=n;function U(e){if(null===e)return!0;const t=O(e);if(""===t||!1===t||null===t)return!0;
1if(T(t)&&0===t.length)return!0;if(M(t)){for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!1;return!0}return!t}class V{constructor(e,t,i,n,s,r){this.runtime=e,this.globals=t,this.toNumber=i,this.toString=n,this.debug=s,this.language=r}search(e,t){return this.visit(e,t)}visit(e,t){const i=e&&{Field:(e,t)=>{if(null!==t&&(M(t)||T(t))){let i=t[e.name];if("function"==typeof i&&(i=void 0),void 0===i){try{this.debug.push(`Failed to find: '${e.name}'`);const i=Object.keys(t).map((e=>`'${e}'`)).toString();i.length&&this.debug.push(`Available fields: ${i}`)}catch(e){}return null}return i}return null},Subexpression:(e,t)=>{let i=this.visit(e.children[0],t);for(let t=1;t<e.children.length;t+=1)if(i=this.visit(e.children[1],i),null===i)return null;return i},IndexExpression:(e,t)=>{const i=this.visit(e.children[0],t);return this.visit(e.children[1],i)},Index:(e,t)=>{if(T(t)){let i=this.toNumber(this.visit(e.value,t));i<0&&(i=t.length+i);const n=t[i];return void 0===n?(this.debug.push(`Index ${i} out of range`),null):n}if(M(t)){const i=this.toString(this.visit(e.value,t)),n=t[i];return void 0===n?(this.debug.push(`Key ${i} does not exist`),null):n}return this.debug.push(`left side of index expression ${t} is not an array or object.`),null},Slice:(e,t)=>{if(!T(t))return null;const i=e.children.slice(0).map((e=>null!=e?this.toNumber(this.visit(e,t)):null)),n=this.computeSliceParams(t.length,i),[s,r,a]=n,o=[];if(a>0)for(let e=s;e<r;e+=a)o.push(t[e]);else for(let e=s;e>r;e+=a)o.push(t[e]);return o},Projection:(e,t)=>{const i=this.visit(e.children[0],t);if(!T(i))return null;const n=[];return i.forEach((t=>{const i=this.visit(e.children[1],t);null!==i&&n.push(i)})),n},ValueProjection:(e,t)=>{const i=this.visit(e.children[0],t);if(!M(O(i)))return null;const n=[];var s;return(s=i,Object.values(s)).forEach((t=>{const i=this.visit(e.children[1],t);null!==i&&n.push(i)})),n},FilterProjection:(e,t)=>{const i=this.visit(e.children[0],t);if(!T(i))return null;const n=i.filter((t=>!U(this.visit(e.children[2],t)))),s=[];return n.forEach((t=>{const i=this.visit(e.children[1],t);null!==i&&s.push(i)})),s},Comparator:(e,t)=>{const i=this.visit(e.children[0],t),n=this.visit(e.children[1],t);if(e.name===S)return w(i,n);if(e.name===P)return!w(i,n);if(e.name===j)return i>n;if(e.name===R)return i>=n;if(e.name===x)return i<n;if(e.name===D)return i<=n;throw new Error(`Unknown comparator: ${e.name}`)},[F]:(e,t)=>{const i=this.visit(e.children[0],t);if(!T(i))return null;const n=[];return i.forEach((e=>{T(e)?n.push(...e):n.push(e)})),n},Identity:(e,t)=>t,MultiSelectList:(e,t)=>null===t?null:e.children.map((e=>this.visit(e,t))),MultiSelectHash:(e,t)=>{if(null===t)return null;const i={};return e.children.forEach((e=>{i[e.name]=this.visit(e.value,t)})),i},OrExpression:(e,t)=>{let i=this.visit(e.children[0],t);return U(i)&&(i=this.visit(e.children[1],t)),i},AndExpression:(e,t)=>{const i=this.visit(e.children[0],t);return!0===U(i)?i:this.visit(e.children[1],t)},AddExpression:(e,t)=>{const i=this.visit(e.children[0],t),n=this.visit(e.children[1],t);return this.applyOperator(i,n,"+")},ConcatenateExpression:(e,t)=>{let i=this.visit(e.children[0],t),n=this.visit(e.children[1],t);return i=E(b(i),[L,k],i,"concatenate",this.toNumber,this.toString),n=E(b(n),[L,k],n,"concatenate",this.toNumber,this.toString),this.applyOperator(i,n,"&")},UnionExpression:(e,t)=>{let i=this.visit(e.children[0],t),n=this.visit(e.children[1],t);return i=E(b(i),[$],i,"union",this.toNumber,this.toString),n=E(b(n),[$],n,"union",this.toNumber,this.toString),i.concat(n)},SubtractExpression:(e,t)=>{const i=this.visit(e.children[0],t),n=this.visit(e.children[1],t);return this.applyOperator(i,n,"-")},MultiplyExpression:(e,t)=>{const i=this.visit(e.children[0],t),n=this.visit(e.children[1],t);return this.applyOperator(i,n,"*")},DivideExpression:(e,t)=>{const i=this.visit(e.children[0],t),n=this.visit(e.children[1],t);return this.applyOperator(i,n,"/")},PowerExpression:(e,t)=>{const i=this.visit(e.children[0],t),n=this.visit(e.children[1],t);return this.applyOperator(i,n,"^")},NotExpression:(e,t)=>U(this.visit(e.children[0],t)),UnaryMinusExpression:(e,t)=>
1-1*this.visit(e.children[0],t),Literal:e=>e.value,Number:e=>e.value,[N]:(e,t)=>{const i=this.visit(e.children[0],t);return this.visit(e.children[1],i)},[I]:(e,t)=>t,[A]:e=>{const t=this.globals[e.name];return void 0===t?null:t},Function:(e,t)=>{if("if"===e.name)return this.runtime.callFunction(e.name,e.children,t,this,!1);const i=e.children.map((e=>this.visit(e,t)));return this.runtime.callFunction(e.name,i,t,this)},ExpressionReference:e=>{const[t]=e.children;return t.jmespathType=C,t}}[e.type];if(!i)throw new Error(`Unknown/missing node type ${e&&e.type||""}`);return i(e,t)}computeSliceParams(e,t){function i(e,t,i){let n=t;return n<0?(n+=e,n<0&&(n=i<0?-1:0)):n>=e&&(n=i<0?e-1:e),n}let[n,s,r]=t;if(null===r)r=1;else if(0===r){const e=new Error("Invalid slice, step cannot be 0");throw e.name="RuntimeError",e}const a=r<0;return n=null===n?a?e-1:0:i(e,n,r),s=null===s?a?-1:e:i(e,s,r),[n,s,r]}applyOperator(e,t,i){if(T(e)&&T(t)){const n=e.length<t.length?e:t,s=Math.abs(e.length-t.length);n.length+=s,n.fill(null,n.length-s);const r=[];for(let n=0;n<e.length;n+=1)r.push(this.applyOperator(e[n],t[n],i));return r}if(T(e))return e.map((e=>this.applyOperator(e,t,i)));if(T(t))return t.map((t=>this.applyOperator(e,t,i)));if("*"===i)return this.toNumber(e)*this.toNumber(t);if("&"===i)return e+t;if("+"===i)return this.toNumber(e)+this.toNumber(t);if("-"===i)return this.toNumber(e)-this.toNumber(t);if("/"===i){const i=e/t;return Number.isFinite(i)?i:null}if("^"===i)return e**t;throw new Error(`Unknown operator: ${i}`)}}const{TOK_UNQUOTEDIDENTIFIER:B,TOK_QUOTEDIDENTIFIER:Y,TOK_RBRACKET:H,TOK_RPAREN:K,TOK_COMMA:q,TOK_COLON:G,TOK_CONCATENATE:z,TOK_RBRACE:W,TOK_NUMBER:J,TOK_CURRENT:Q,TOK_GLOBAL:X,TOK_EXPREF:Z,TOK_PIPE:ee,TOK_OR:te,TOK_AND:ie,TOK_ADD:ne,TOK_SUBTRACT:se,TOK_UNARY_MINUS:re,TOK_MULTIPLY:ae,TOK_POWER:oe,TOK_DIVIDE:le,TOK_UNION:ue,TOK_EQ:de,TOK_GT:ce,TOK_LT:he,TOK_GTE:pe,TOK_LTE:fe,TOK_NE:me,TOK_FLATTEN:ge,TOK_STAR:_e,TOK_FILTER:ve,TOK_DOT:ye,TOK_NOT:be,TOK_LBRACE:Ee,TOK_LBRACKET:Te,TOK_LPAREN:Me,TOK_LITERAL:Oe}=s,we={".":ye,",":q,":":G,"{":Ee,"}":W,"]":H,"(":Me,")":K,"@":Q},Ie={"<":!0,">":!0,"=":!0,"!":!0},Ae={" ":!0,"\t":!0,"\n":!0};function Ce(e){return e>="0"&&e<="9"||"."===e}function Ne(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e>="0"&&e<="9"||"_"===e}function Se(e,t){const i=e[t];return"$"===i?e.length>t&&Ne(e[t+1]):i>="a"&&i<="z"||i>="A"&&i<="Z"||"_"===i}class je{constructor(e=[],t=[]){this._allowedGlobalNames=e,this.debug=t}tokenize(e){const t=[];let i,n,s;for(this._current=0;this._current<e.length;){const r=t.length?t.slice(-1)[0].type:null;if(this._isGlobal(r,e,this._current))t.push(this._consumeGlobal(e));else if(Se(e,this._current))i=this._current,n=this._consumeUnquotedIdentifier(e),t.push({type:B,value:n,start:i});else if(void 0!==we[e[this._current]])t.push({type:we[e[this._current]],value:e[this._current],start:this._current}),this._current+=1;else if("-"!==e[this._current]||[X,Q,J,K,B,Y,H].includes(r))if(Ce(e[this._current]))s=this._consumeNumber(e),t.pu
1sh(s);else if("["===e[this._current])s=this._consumeLBracket(e),t.push(s);else if('"'===e[this._current])i=this._current,n=this._consumeQuotedIdentifier(e),t.push({type:Y,value:n,start:i});else if("'"===e[this._current])i=this._current,n=this._consumeRawStringLiteral(e),t.push({type:Oe,value:n,start:i});else if("`"===e[this._current]){i=this._current;const n=this._consumeLiteral(e);t.push({type:Oe,value:n,start:i})}else if(void 0!==Ie[e[this._current]])t.push(this._consumeOperator(e));else if(void 0!==Ae[e[this._current]])this._current+=1;else if("&"===e[this._current])i=this._current,this._current+=1,"&"===e[this._current]?(this._current+=1,t.push({type:ie,value:"&&",start:i})):r===q||r===Me?t.push({type:Z,value:"&",start:i}):t.push({type:z,value:"&",start:i});else if("~"===e[this._current])i=this._current,this._current+=1,t.push({type:ue,value:"~",start:i});else if("+"===e[this._current])i=this._current,this._current+=1,t.push({type:ne,value:"+",start:i});else if("-"===e[this._current])i=this._current,this._current+=1,t.push({type:se,value:"-",start:i});else if("*"===e[this._current]){i=this._current,this._current+=1;const e=t.length&&t.slice(-1)[0].type;0===t.length||[Te,ye,ee,ie,te,q,G].includes(e)?t.push({type:_e,value:"*",start:i}):t.push({type:ae,value:"*",start:i})}else if("/"===e[this._current])i=this._current,this._current+=1,t.push({type:le,value:"/",start:i});else if("^"===e[this._current])i=this._current,this._current+=1,t.push({type:oe,value:"^",start:i});else{if("|"!==e[this._current]){const t=new Error(`Unknown character:${e[this._current]}`);throw t.name="LexerError",t}i=this._current,this._current+=1,"|"===e[this._current]?(this._current+=1,t.push({type:te,value:"||",start:i})):t.push({type:ee,value:"|",start:i})}else s=this._consumeUnaryMinus(e),t.push(s)}return t}_consumeUnquotedIdentifier(e){const t=this._current;for(this._current+=1;this._current<e.length&&Ne(e[this._current]);)this._current+=1;return e.slice(t,this._current)}_consumeQuotedIdentifier(e){const t=this._current;this._current+=1;const i=e.length;let n=!Se(e,t+1);for(;'"'!==e[this._current]&&this._current<i;){let t=this._current;Ne(e[t])||(n=!0),"\\"!==e[t]||"\\"!==e[t+1]&&'"'!==e[t+1]?t+=1:t+=2,this._current=t}this._current+=1;const s=e.slice(t,this._current);try{n&&!s.includes(" ")||(this.debug.push(`Suspicious quotes: ${s}`),this.debug.push(`Did you intend a literal? '${s.replace(/"/g,"")}'?`))}catch(e){}return JSON.parse(s)}_consumeRawStringLiteral(e){const t=this._current;this._current+=1;const i=e.length;for(;"'"!==e[this._current]&&this._current<i;){let t=this._current;"\\"!==e[t]||"\\"!==e[t+1]&&"'"!==e[t+1]?t+=1:t+=2,this._current=t}return this._current+=1,e.slice(t+1,this._current-1).replaceAll("\\'","'")}_consumeNumber(e){const t=this._current;this._current+=1;const i=e.length;for(;Ce(e[this._current])&&this._current<i;)this._current+=1;const n=e.slice(t,this._current);let s;return s=n.includes(".")?parseFloat(n):parseInt(n,10),{type:J,value:s,start:t}}_consumeUnaryMinus(){const e=this._current;return this._current+=1,{type:re,value:"-",start:e}}_consumeLBracket(e){const t=this._current;return this._current+=1,"?"===e[this._current]?(this._current+=1,{type:ve,value:"[?",start:t}):"]"===e[this._current]?(this._current+=1,{type:ge,value:"[]",start:t}):{type:Te,value:"[",start:t}}_isGlobal(e,t,i){if(null!==e&&e===ye)return!1;if("$"!==t[i])return!1;let n=i+1;for(;n<t.length&&Ne(t[n]);)n+=1;const s=t.slice(i,n);return this._allowedGlobalNames.includes(s)}_consumeGlobal(e){const t=this._current;for(this._current+=1;this._current<e.length&&Ne(e[this._current]);)this._current+=1;const i=e.slice(t,this._current);return{type:X,name:i,start:t}}_consumeOperator(e){const t=this._current,i=e[t];return this._current+=1,"!"===i?"="===e[this._current]?(this._current+=1,{type:me,value:"!=",start:t}):{type:be,value:"!",start:t}:"<"===i?"="===e[this._current]?(this._current+=1,{type:fe,value:"<=",start:t}):{type:he,value:"<",start:t}:">"===i?"="===e[this._current]?(this._current+=1,{type:pe,value:">=",start:t}):{type:ce,value:">",start:t}:"="===e[this._current]?(this._current+=1,{type:de,value:"==",start:t}):{type:de,value:"=",start:t}}_consumeLiteral(e){this._current+=1;const t=this._current,i=e.length;let n,s=!1;for(;(s||"`"!==e[this._current])&&this._current<i;){let t=this._current;s&&"\\"===e[t]&&'"'===e[t+1]?t+=2:('"'===e[t]&&(s=!s),s&&"`"===e[t+1]?t+=2:"\\"!==e[t]||"\\"!==e[t+1]&&"`"!==e[t+1]?t+=1:t+=2),this._current=t}let r=e.slice(t,this._current).trimStart();return r=r.replaceAll("\\`","`"),n=function(e){if(""===e)return!1;if('[{"'.includes(e[0]))return!0;
1if(["true","false","null"].includes(e))return!0;if(!"-0123456789".includes(e[0]))return!1;try{return JSON.parse(e),!0}catch(e){return!1}}(r)?JSON.parse(r):JSON.parse(`"${r}"`),this._current+=1,n}}const{TOK_LITERAL:xe,TOK_COLON:Re,TOK_EOF:De,TOK_UNQUOTEDIDENTIFIER:Pe,TOK_QUOTEDIDENTIFIER:Fe,TOK_RBRACKET:Le,TOK_RPAREN:ke,TOK_COMMA:$e,TOK_CONCATENATE:Ue,TOK_RBRACE:Ve,TOK_NUMBER:Be,TOK_CURRENT:Ye,TOK_GLOBAL:He,TOK_FIELD:Ke,TOK_EXPREF:qe,TOK_PIPE:Ge,TOK_OR:ze,TOK_AND:We,TOK_ADD:Je,TOK_SUBTRACT:Qe,TOK_UNARY_MINUS:Xe,TOK_MULTIPLY:Ze,TOK_POWER:et,TOK_DIVIDE:tt,TOK_UNION:it,TOK_EQ:nt,TOK_GT:st,TOK_LT:rt,TOK_GTE:at,TOK_LTE:ot,TOK_NE:lt,TOK_FLATTEN:ut,TOK_STAR:dt,TOK_FILTER:ct,TOK_DOT:ht,TOK_NOT:pt,TOK_LBRACE:ft,TOK_LBRACKET:mt,TOK_LPAREN:gt}=s,_t={[De]:0,[Pe]:0,[Fe]:0,[Le]:0,[ke]:0,[$e]:0,[Ve]:0,[Be]:0,[Ye]:0,[He]:0,[Ke]:0,[qe]:0,[Ge]:1,[ze]:2,[We]:3,[Ue]:5,[Je]:6,[Qe]:6,[Ze]:7,[tt]:7,[et]:7,[it]:7,[nt]:5,[st]:5,[rt]:5,[at]:5,[ot]:5,[lt]:5,[ut]:9,[dt]:20,[ct]:21,[ht]:40,[pt]:30,[Xe]:30,[ft]:50,[mt]:55,[gt]:60};class vt{constructor(e=[]){this._allowedGlobalNames=e}parse(e,t){this._loadTokens(e,t),this.index=0;const i=this.expression(0);if(this._lookahead(0)!==De){const e=this._lookaheadToken(0),t=new Error(`Unexpected token type: ${e.type}, value: ${e.value}`);throw t.name="ParserError",t}return i}_loadTokens(e,t){const i=new je(this._allowedGlobalNames,t).tokenize(e);i.push({type:De,value:"",start:e.length}),this.tokens=i}expression(e){const t=this._lookaheadToken(0);this._advance();let i=this.nud(t),n=this._lookahead(0);for(;e<_t[n];)this._advance(),i=this.led(n,i),n=this._lookahead(0);return i}_lookahead(e){return this.tokens[this.index+e].type}_lookaheadToken(e){return this.tokens[this.index+e]}_advance(){this.index+=1}_getIndex(){return this.index}_setIndex(e){this.index=e}nud(e){let t,i,n,s,r;switch(e.type){case xe:return{type:"Literal",value:e.value};case Be:return{type:"Number",value:e.value};case Pe:return{type:"Field",name:e.value};case Fe:if(s={type:"Field",name:e.value},this._lookahead(0)===gt)throw new Error("Quoted identifier not allowed for function names.");return s;case pt:return i=this.expression(_t.Not),{type:"NotExpression",children:[i]};case Xe:return i=this.expression(_t.UnaryMinus),{type:"UnaryMinusExpression",children:[i]};case dt:return t={type:"Identity"},i=this._lookahead(0)===Le?{type:"Identity"}:this._parseProjectionRHS(_t.Star),{type:"ValueProjection",children:[t,i]};case ct:return this.led(e.type,{type:"Identity"});case ft:return this._parseMultiselectHash();case ut:return t={type:ut,children:[{type:"Identity"}]},i=this._parseProjectionRHS(_t.Flatten),{type:"Projection",children:[t,i]};case mt:return this._lookahead(0)===dt&&this._lookahead(1)===Le?(this._advance(),this._advance(),i=this._parseProjectionRHS(_t.Star),{type:"Projection",children:[{type:"Identity"},i]}):this._parseUnchainedIndexExpression();case Ye:return{type:Ye};case He:return{type:He,name:e.name};case Ke:return{type:Ke};case qe:return n=this.expression(_t.Expref),{type:"ExpressionReference",children:[n]};case gt:for(r=[];this._lookahead(0)!==ke;)n=this.expression(0),r.push(n);return this._match(ke),r[0];default:this._errorToken(e)}}led(e,t){let i,n,s,r,a,o,l,u,d;switch(e){case Ue:return n=this.expression(_t.Concatenate),{type:"ConcatenateExpression",children:[t,n]};case ht:return l=_t.Dot,this._lookahead(0)!==dt?(n=this._parseDotRHS(l),{type:"Subexpression",children:[t,n]}):(this._advance(),n=this._parseProjectionRHS(l),{type:"ValueProjection",children:[t,n]});case Ge:return n=this.expression(_t.Pipe),{type:Ge,children:[t,n]};case ze:return n=this.expression(_t.Or),{type:"OrExpression",children:[t,n]};case We:return n=this.expression(_t.And),{type:"AndExpression",children:[t,n]};case Je:return n=this.expression(_t.Add),{type:"AddExpression",children:[t,n]};case Qe:return n=this.expression(_t.Subtract),{type:"SubtractExpression",children:[t,n]};case Ze:return n=this.expression(_t.Multiply),{type:"MultiplyExpression",children:[t,n]};case tt:return n=this.expression(_t.Divide),{type:"DivideExpression",children:[t,n]};case et:return n=this.expression(_t.Power),{type:"PowerExpression",children:[t,n]};case it:return n=this.expression(_t.Power),{type:"UnionExpression",children:[t,n]};case gt:for(s=t.name,r=[];this._lookahead(0)!==ke;)a=this.expression(0),this._lookahead(0)===$e&&this._match($e),r.push(a);return this._match(ke),o={type:"Function",name:s,children:r},o;case ct:return i=this.expression(0),this._match(Le),n=this._lookahead(0)===ut?{type:"Identity"}:this._parseProjectionRHS(_t.Filter),{type:"FilterProjection",children:[t,n,i]};case ut:return u={type:ut,children:[t]},d=this._parseProjectionRHS(_t.Flatten),{type:"Projection",children:[u,d]};case nt:case lt:case st:case at:case rt:case ot:return this._parseComparator(t,e);case mt:return this._lookahead(0)===dt&&this._lookahead(1)===Le?(this._advance(),this._advance(),n=this._parseProjectionRHS(_t.Star),{type:"Projection",children:[t,n]}):(n=this._parseChainedIndexExpression(),this._projectIfSlice(t,n));default:this._errorToken(this._lookaheadToken(0))}}_match(e){if(this._lookahead(0)!==e){const t=this._lookaheadToken(0),i=new Error(`Expected ${e}, got: ${t.type}`);throw i.name="ParserError",i}this._advance()}_errorToken(e){const t=new Error(`Invalid token (${e.type}): "${e.value}"`);throw t.name="ParserError",t}_parseChainedIndexExpression(){const e=this._getIndex();if(this._lookahead(0)===Re)return this._parseSliceExpression();const t=this.expression(0);return this._lookahead(0)===Re?(this._setIndex(e),this._parseSliceExpression()):(this._match(Le),{type:"Index",value:t})}
1_parseUnchainedIndexExpression(){const e=this._getIndex(),t=this._lookahead(0);if(t===Re){const e=this._parseSliceExpression();return this._projectIfSlice({type:"Identity"},e)}const i=this.expression(0),n=this._lookahead(0);if(n===$e)return this._setIndex(e),this._parseMultiselectList();if(n===Re){this._setIndex(e);const t=this._parseSliceExpression();return this._projectIfSlice({type:"Identity"},t)}return t===Be||t===Xe?(this._match(Le),{type:"Index",value:i}):(this._setIndex(e),this._parseMultiselectList())}_projectIfSlice(e,t){const i={type:"IndexExpression",children:[e,t]};return"Slice"===t.type?{type:"Projection",children:[i,this._parseProjectionRHS(_t.Star)]}:i}_parseSliceExpression(){const e=[null,null,null];let t=0,i=this._lookahead(0);for(;i!==Le&&t<3;){if(i===Re&&t<2)t+=1,this._advance();else{e[t]=this.expression(0);const i=this._lookahead(0);if(i!==Re&&i!==Le){const e=new Error(`Syntax error, unexpected token: ${i.value}(${i.type})`);throw e.name="Parsererror",e}}i=this._lookahead(0)}return this._match(Le),{type:"Slice",children:e}}_parseComparator(e,t){return{type:"Comparator",name:t,children:[e,this.expression(_t[t])]}}_parseDotRHS(e){const t=this._lookahead(0);return[Pe,Fe,dt].indexOf(t)>=0?this.expression(e):t===mt?(this._match(mt),this._parseMultiselectList()):t===ft?(this._match(ft),this._parseMultiselectHash()):void 0}_parseProjectionRHS(e){let t;if(_t[this._lookahead(0)]<10)t={type:"Identity"};else if(this._lookahead(0)===mt)t=this.expression(e);else if(this._lookahead(0)===ct)t=this.expression(e);else{if(this._lookahead(0)!==ht){const e=this._lookaheadToken(0),t=new Error(`Sytanx error, unexpected token: ${e.value}(${e.type})`);throw t.name="ParserError",t}this._match(ht),t=this._parseDotRHS(e)}return t}_parseMultiselectList(){const e=[];for(;this._lookahead(0)!==Le;){const t=this.expression(0);if(e.push(t),this._lookahead(0)===$e&&(this._match($e),this._lookahead(0)===Le))throw new Error("Unexpected token Rbracket")}return this._match(Le),{type:"MultiSelectList",children:e}}_parseMultiselectHash(){const e=[],t=[Pe,Fe];let i,n,s,r;if(this._lookahead(0)===Ve)return this._advance(),{type:"MultiSelectHash",children:[]};for(;;){if(i=this._lookaheadToken(0),t.indexOf(i.type)<0)throw new Error(`Expecting an identifier token, got: ${i.type}`);if(n=i.value,this._advance(),this._match(Re),s=this.expression(0),r={type:"KeyValuePair",name:n,value:s},e.push(r),this._lookahead(0)===$e)this._match($e);else if(this._lookahead(0)===Ve){this._match(Ve);break}}return{type:"MultiSelectHash",children:e}}}function yt(e,t){const i=10**t;return Math.round(e*i)/i}const bt=864e5;const{TYPE_CLASS:Et,TYPE_ANY:Tt}=n;function Mt(e){return null==e?"":e.toString()}const Ot=e=>{const t=+e;return Number.isNaN(t)?0:t};class wt{constructor(e,t,i={}){this.strictDeepEqual=w,this.toNumber=t,this.functionTable=function(e,t,i,s,r,a,o,l){const{TYPE_NUMBER:u,TYPE_ANY:d,TYPE_STRING:c,TYPE_ARRAY:h,TYPE_OBJECT:p,TYPE_BOOLEAN:f,TYPE_EXPREF:m,TYPE_NULL:g,TYPE_ARRAY_NUMBER:_,TYPE_ARRAY_STRING:v}=n;function y(t,i){return n=>{const s=e.interpreter.visit(t,n);if(i.indexOf(r(s))<0){const e=`TypeError: expected one of ${i}, received ${r(s)}`;throw new Error(e)}return s}}const b={abs:{_func:e=>Math.abs(e[0]),_signature:[{types:[u]}]},avg:{_func:e=>{let t=0;const i=e[0];return i.forEach((e=>{t+=e})),t/i.length},_signature:[{types:[_]}]},ceil:{_func:e=>Math.ceil(e[0]),_signature:[{types:[u]}]},contains:{_func:e=>a(e[0]).indexOf(a(e[1]))>=0,_signature:[{types:[c,h]},{types:[d]}]},endsWith:{_func:e=>{const t=a(e[0]),i=a(e[1]);return-1!==t.indexOf(i,t.length-i.length)},_signature:[{types:[c]},{types:[c]}]},floor:{_func:e=>Math.floor(e[0]),_signature:[{types:[u]}]},join:{_func:e=>{const t=e[0];return e[1].join(t)},_signature:[{types:[c]},{types:[v]}]},keys:{_func:e=>null===e[0]?[]:Object.keys(e[0]),_signature:[{types:[d]}]},length:{_func:e=>{const n=a(e[0]);return t(n)?Object.keys(n).length:i(n)?n.length:o(n).length},_signature:[{types:[c,h,p]}]},map:{_func:t=>{const i=t[0];return t[1].map((t=>e.interpreter.visit(i,t)))},_signature:[{types:[m]},{types:[h]}]},max:{_func:e=>{const t=e.reduce(((e,t)=>(Array.isArray(t)?e.push(...t):e.push(t),e)),[]),i=t.find((e=>null!==e));if(0===t.length||void 0===i)return null;const n=r(i,!0)===u,a=n?(e,t)=>{const i=s(t);return e<=i?i:e}:(e,t)=>{const i=o(t);return 1===e.localeCompare(i)?e:i};return t.reduce(a,n?s(i):o(i))},_signature:[{types:[h,_,v],variadic:!0}]},maxBy:{_func:e=>{const t=e[1],i=e[0],n=y(t,[u,c]);let s,r,a=-1/0;
1return i.forEach((e=>{r=n(e),r>a&&(a=r,s=e)})),s},_signature:[{types:[h]},{types:[m]}]},merge:{_func:e=>{const t={};return e.forEach((e=>{Object.entries(e||{}).forEach((([e,i])=>{t[e]=i}))})),t},_signature:[{types:[p],variadic:!0}]},min:{_func:e=>{const t=e.reduce(((e,t)=>(Array.isArray(t)?e.push(...t):e.push(t),e)),[]),i=t.find((e=>null!==e));if(0===t.length||void 0===i)return null;const n=r(i,!0)===u,a=n?(e,t)=>{const i=s(t);return e<=i?e:i}:(e,t)=>{const i=o(t);return 1===e.localeCompare(i)?i:e};return t.reduce(a,n?s(i):o(i))},_signature:[{types:[h,_,v],variadic:!0}]},minBy:{_func:e=>{const t=e[1],i=e[0],n=y(t,[u,c]);let s,r,a=1/0;return i.forEach((e=>{r=n(e),r<a&&(a=r,s=e)})),s},_signature:[{types:[h]},{types:[m]}]},notNull:{_func:e=>e.find((e=>r(e)!==g))||null,_signature:[{types:[d],variadic:!0}]},reduce:{_func:t=>{const i=t[0];return t[1].reduce(((t,n,s,r)=>e.interpreter.visit(i,{accumulated:t,current:n,index:s,array:r})),3===t.length?t[2]:null)},_signature:[{types:[m]},{types:[h]},{types:[d],optional:!0}]},register:{_func:t=>{const i=t[0],n=t[1];return b[i]?(l.push(`Cannot re-register '${i}'`),{}):(b[i]={_func:t=>e.interpreter.visit(n,...t),_signature:[{types:[d],optional:!0}]},{})},_signature:[{types:[c]},{types:[m]}]},reverse:{_func:e=>{const t=a(e[0]);if(r(t)===c){let e="";for(let i=t.length-1;i>=0;i-=1)e+=t[i];return e}const i=e[0].slice(0);return i.reverse(),i},_signature:[{types:[c,h]}]},sort:{_func:e=>{const t=e[0].slice(0);if(t.length>0){const i=r(e[0][0])===u?s:o;t.sort(((e,t)=>{const n=i(e),s=i(t);return n<s?-1:n>s?1:0}))}return t},_signature:[{types:[h,v,_]}]},sortBy:{_func:t=>{const i=t[0].slice(0);if(0===i.length)return i;const n=t[1],s=r(e.interpreter.visit(n,i[0]));if([u,c].indexOf(s)<0)throw new Error("TypeError");const a=[];for(let e=0;e<i.length;e+=1)a.push([e,i[e]]);a.sort(((t,i)=>{const a=e.interpreter.visit(n,t[1]),o=e.interpreter.visit(n,i[1]);if(r(a)!==s)throw new Error(`TypeError: expected ${s}, received ${r(a)}`);if(r(o)!==s)throw new Error(`TypeError: expected ${s}, received ${r(o)}`);return a>o?1:a<o?-1:t[0]-i[0]}));for(let e=0;e<a.length;e+=1)[,i[e]]=a[e];return i},_signature:[{types:[h]},{types:[m]}]},startsWith:{_func:e=>a(e[0]).startsWith(a(e[1])),_signature:[{types:[c]},{types:[c]}]},sum:{_func:e=>{let t=0;
1return e[0].forEach((e=>{t+=1*e})),t},_signature:[{types:[_]}]},toArray:{_func:e=>r(e[0])===h?e[0]:[e[0]],_signature:[{types:[d]}]},toNumber:{_func:e=>{const t=r(e[0]);return t===u?e[0]:t===c?s(e[0]):null},_signature:[{types:[d]}]},toString:{_func:e=>r(e[0])===c?e[0]:JSON.stringify(e[0]),_signature:[{types:[d]}]},type:{_func:e=>({[u]:"number",[c]:"string",[h]:"array",[p]:"object",[f]:"boolean",[m]:"expref",[g]:"null"}[r(e[0])]),_signature:[{types:[d]}]},values:{_func:e=>{const t=a(e[0]);return null===t?[]:Object.values(t)},_signature:[{types:[d]}]},zip:{_func:e=>{const t=e.reduce(((e,t)=>Math.min(e,t.length)),e[0].length),i=new Array(t);for(let n=0;n<t;n+=1)i[n]=[],e.forEach((e=>{i[n].push(e[n])}));return i},_signature:[{types:[h],variadic:!0}]}};return b}(this,M,T,t,y,O,Mt,e),Object.entries(function(e,t,i,s=[]){return{and:{_func:t=>{let i=!!e(t[0]);return t.slice(1).forEach((t=>{i=i&&!!e(t)})),i},_signature:[{types:[n.TYPE_ANY],variadic:!0}]},casefold:{_func:(e,i,n)=>t(e[0]).toLocaleUpperCase(n.language).toLocaleLowerCase(n.language),_signature:[{types:[n.TYPE_STRING]}]},datedif:{_func:e=>{const n=i(e[0]),s=i(e[1]),r=t(e[2]).toLowerCase();if(s===n)return 0;if(s<n)return null;if("d"===r)return Math.floor(s-n);const a=new Date(n*bt),o=new Date(s*bt),l=o.getFullYear()-a.getFullYear();let u=o.getMonth()-a.getMonth();const d=o.getDate()-a.getDate();if("y"===r){let e=l;return u<0&&(e-=1),0===u&&d<0&&(e-=1),e}if("m"===r)return 12*l+u+(d<0?-1:0);if("ym"===r)return d<0&&(u-=1),u<=0&&l>0?12+u:u;if("yd"===r)return d<0&&(u-=1),u<0?o.setFullYear(a.getFullYear()+1):o.setFullYear(a.getFullYear()),Math.floor((o.getTime()-a.getTime())/bt);throw new TypeError(`Unrecognized unit parameter "${r}" for datedif()`)},_signature:[{types:[n.TYPE_NUMBER]},{types:[n.TYPE_NUMBER]},{types:[n.TYPE_STRING]}]},datetime:{_func:e=>{const n=i(e[0]),s=i(e[1]),r=i(e[2]),a=e.length>3?i(e[3]):0,o=e.length>4?i(e[4]):0,l=e.length>5?i(e[5]):0,u=e.length>6?i(e[6]):0,d=e.length>7?t(e[7]):null;let c=new Date(n,s-1,r,a,o,l,u);return d&&(c=function(e,t){if(null===e)return null;let i=Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds());return i+=function(e,t){const i=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"longOffset"}).format(e),n=/GMT([+\-−])?(\d{1,2}):?(\d{0,2})?/.exec(i);if(!n)return 0;const[s,r,a]=n.slice(1),o=60*(60*(r||0)+1*(a||0))*1e3;return"-"===s?-1*o:o}(e,t),new Date(i)}(c,d)),c.getTime()/bt},_signature:[{types:[n.TYPE_NUMBER]},{types:[n.TYPE_NUMBER]},{types:[n.TYPE_NUMBER]},{types:[n.TYPE_NUMBER],optional:!0},{types:[n.TYPE_NUMBER],optional:!0},{types:[n.TYPE_NUMBER],optional:!0},{types:[n.TYPE_NUMBER],optional:!0},{types:[n.TYPE_STRING],optional:!0}]},day:{_func:e=>{const t=i(e[0]);return new Date(t*bt).getDate()},_signature:[{types:[n.TYPE_NUMBER]}]},deepScan:{_func:e=>{const[t,i]=e,n=i.toString(),s=[];return null===t||function e(t){Object.entries(t).forEach((([t,i])=>{t===n&&s.push(i),"object"==typeof i&&e(i)}))}(t),s},_signature:[{types:[n.TYPE_OBJECT,n.TYPE_ARRAY,n.TYPE_NULL]},{types:[n.TYPE_STRING,n.TYPE_NUMBER]}]},entries:{_func:t=>{const i=e(t[0]);return Object.entries(i)},_signature:[{types:[n.TYPE_NUMBER,n.TYPE_STRING,n.TYPE_ARRAY,n.TYPE_OBJECT,n.TYPE_BOOLEAN]}]},eomonth:{_func:e=>{const t=i(e[0]),n=i(e[1]),s=new Date(t*bt);return new Date(s.getFullYear(),s.getMonth()+n+1,0).getTime()/bt},_signature:[{types:[n.TYPE_NUMBER]},{types:[n.TYPE_NUMBER]}]},exp:{_func:e=>{const t=i(e[0]);return Math.exp(t)},_signature:[{types:[n.TYPE_NUMBER]}]},false:{_func:()=>!1,_signature:[]},find:{_func:e=>{const n=t(e[0]),s=t(e[1]),r=e.length>2?i(e[2]):0,a=s.indexOf(n,r);return-1===a?null:a},_signature:[{types:[n.TYPE_STRING]},{types:[n.TYPE_STRING]},{types:[n.TYPE_NUMBER],optional:!0}]},fromEntries:{_func:e=>{const t=e[0];return Object.fromEntries(t)},_signature:[{types:[n.TYPE_ARRAY_ARRAY]}]},hour:{_func:e=>{const t=i(e[0])%1;if(t<0)return null;const n=yt(24*t,14);return Math.floor(n%24)},_signature:[{types:[n.TYPE_NUMBER]}]},if:{_func:(t,i,n)=>{const s=t[0],r=t[1],a=t[2],o=n.visit(s,i);return e(o)?n.visit(r,i):n.visit(a,i)},_signature:[{types:[n.TYPE_ANY]},{types:[n.TYPE_ANY]},{types:[n.TYPE_ANY]}]},left:{_func:e=>{const n=e.length>1?i(e[1]):1;return n<0?null:e[0]instanceof Array?e[0].slice(0,n):t(e[0]).substr(0,n)},_signature:[{types:[n.TYPE_STRING,n.TYPE_ARRAY]}
1,{types:[n.TYPE_NUMBER],optional:!0}]},lower:{_func:e=>t(e[0]).toLowerCase(),_signature:[{types:[n.TYPE_STRING]}]},mid:{_func:e=>{const n=i(e[1]),s=i(e[2]);return n<0?null:e[0]instanceof Array?e[0].slice(n,n+s):t(e[0]).substr(n,s)},_signature:[{types:[n.TYPE_STRING,n.TYPE_ARRAY]},{types:[n.TYPE_NUMBER]},{types:[n.TYPE_NUMBER]}]},minute:{_func:e=>{const t=i(e[0])%1;if(t<0)return null;const n=Math.round(1440*t,10);return Math.floor(n%60)},_signature:[{types:[n.TYPE_NUMBER]}]},mod:{_func:e=>i(e[0])%i(e[1]),_signature:[{types:[n.TYPE_NUMBER]},{types:[n.TYPE_NUMBER]}]},month:{_func:e=>{const t=i(e[0]);return new Date(t*bt).getMonth()+1},_signature:[{types:[n.TYPE_NUMBER]}]},not:{_func:t=>!e(t[0]),_signature:[{types:[n.TYPE_ANY]}]},now:{_func:()=>Date.now()/bt,_signature:[]},null:{_func:()=>null,_signature:[]},or:{_func:t=>{let i=!!e(t[0]);return t.slice(1).forEach((t=>{i=i||!!e(t)})),i},_signature:[{types:[n.TYPE_ANY],variadic:!0}]},power:{_func:e=>i(e[0])**i(e[1]),_signature:[{types:[n.TYPE_NUMBER]},{types:[n.TYPE_NUMBER]}]},proper:{_func:e=>t(e[0]).split(" ").map((e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())).join(" "),_signature:[{types:[n.TYPE_STRING]}]},replace:{_func:e=>{const n=t(e[0]),s=i(e[1]),r=i(e[2]),a=t(e[3]);return s<0?null:n.substr(0,s)+a+n.substr(s+r)},_signature:[{types:[n.TYPE_STRING]},{types:[n.TYPE_NUMBER]},{types:[n.TYPE_NUMBER]},{types:[n.TYPE_STRING]}]},rept:{_func:e=>{const n=t(e[0]),s=i(e[1]);return s<0?null:n.repeat(s)},_signature:[{types:[n.TYPE_STRING]},{types:[n.TYPE_NUMBER]}]},right:{_func:e=>{const n=e.length>1?i(e[1]):1;if(n<0)return null;if(e[0]instanceof Array)return 0===n?[]:e[0].slice(-1*n);const s=t(e[0]),r=s.length-n;return s.substr(r,n)},_signature:[{types:[n.TYPE_STRING,n.TYPE_ARRAY]},{types:[n.TYPE_NUMBER],optional:!0}]},round:{_func:e=>yt(i(e[0]),i(e[1])),_signature:[{types:[n.TYPE_NUMBER]},{types:[n.TYPE_NUMBER]}]},search:{_func:e=>{const n=t(e[0]),s=t(e[1]),r=i(e[2]);if(null===n||null===s||0===s.length)return[];const a=n.replace(/([[.\\^$()+{])/g,"\\$1").replace(/~?\?/g,(e=>"~?"===e?"\\?":".")).replace(/~?\*/g,(e=>"~*"===e?"\\*":".*?")).replace(/~~/g,"~"),o=new RegExp(a),l=s.substring(r).match(o);return null===l?[]:[l.index+r,l[0]]},_signature:[{types:[n.TYPE_STRING]},{types:[n.TYPE_STRING]},{types:[n.TYPE_NUMBER],optional:!0}]},second:{_func:e=>{const t=i(e[0])%1;if(t<0)return null;const n=yt(86400*t,10);return Math.floor(n%60)},_signature:[{types:[n.TYPE_NUMBER]}]},split:{_func:e=>{const i=t(e[0]),n=t(e[1]);return i.split(n)},_signature:[{types:[n.TYPE_STRING]},{types:[n.TYPE_STRING]}]},sqrt:{_func:e=>{const t=Math.sqrt(i(e[0]));return Number.isNaN(t)?null:t},_signature:[{types:[n.TYPE_NUMBER]}]},stdev:{_func:e=>{const t=e[0]||[];if(t.length<=1)return null;const n=t.map((e=>i(e))),s=n.reduce(((e,t)=>e+t),0)/t.length,r=n.reduce(((e,t)=>e+t*t),0),a=Math.sqrt((r-t.length*s*s)/(t.length-1));return Number.isNaN(a)?null:a},_signature:[{types:[n.TYPE_ARRAY_NUMBER]}]},stdevp:{_func:e=>{const t=e[0]||[];if(0===t.length)return null;const n=t.map((e=>i(e))),s=n.reduce(((e,t)=>e+t),0)/t.length,r=n.reduce(((e,t)=>e+t*t),0)/t.length,a=Math.sqrt(r-s*s);return Number.isNaN(a)?null:a},_signature:[{types:[n.TYPE_ARRAY_NUMBER]}]},substitute:{_func:e=>{const n=t(e[0]),s=t(e[1]),r=t(e[2]);if(e.length<=3)return n.replaceAll(s,r);const a=i(e[3]);if(a<1)return n;let o=-1;for(let e=0;e<a;e+=1){o+=1;const e=n.slice(o).indexOf(s);if(-1===e)return n;o+=e}return n.slice(0,o)+n.slice(o).replace(s,r)},_signature:[{types:[n.TYPE_STRING]},{types:[n.TYPE_STRING]},{types:[n.TYPE_STRING]},{types:[n.TYPE_NUMBER],optional:!0}]},time:{_func:e=>{const t=(3600*i(e[0])+60*i(e[1])+i(e[2]))/86400;return t<0?null:t-Math.floor(t)},_signature:[{types:[n.TYPE_NUMBER]},{types:[n.TYPE_NUMBER]},{types:[n.TYPE_NUMBER]}]},today:{_func:()=>Math.floor(Date.now()/bt),_signature:[]},trim:{_func:e=>t(e[0]).split(" ").filter((e=>e)).join(" "),_signature:[{types:[n.TYPE_STRING]}]},true:{_func:()=>!0,_signature:[]},trunc:{_func:e=>{const t=i(e[0]),n=e.length>1?i(e[1]):0;return(t>=0?Math.floor:Math.ceil)(t*10**n)/10**n}
1,_signature:[{types:[n.TYPE_NUMBER]},{types:[n.TYPE_NUMBER],optional:!0}]},unique:{_func:t=>{const i=t[0].map((t=>e(t)));return t[0].filter(((t,n)=>i.indexOf(e(t))===n))},_signature:[{types:[n.TYPE_ARRAY]}]},upper:{_func:e=>t(e[0]).toUpperCase(),_signature:[{types:[n.TYPE_STRING]}]},value:{_func:e=>{const t=e[0]||{},i=e[1],n=t[i];if(void 0===n){s.push(`Failed to find: '${i}'`);const e=Object.keys(t).map((e=>`'${e}'`)).toString();return e.length&&s.push(`Available fields: ${e}`),null}return n},_signature:[{types:[n.TYPE_OBJECT,n.TYPE_ARRAY,n.TYPE_NULL]},{types:[n.TYPE_STRING,n.TYPE_NUMBER]}]},weekday:{_func:e=>{const t=i(e[0]),n=e.length>1?i(e[1]):1,s=new Date(t*bt).getDay();switch(n){case 1:return s+1;case 2:return(s+6)%7+1;case 3:return(s+6)%7;default:return null}},_signature:[{types:[n.TYPE_NUMBER]},{types:[n.TYPE_NUMBER],optional:!0}]},year:{_func:e=>{const t=i(e[0]);return new Date(t*bt).getFullYear()},_signature:[{types:[n.TYPE_NUMBER]}]},charCode:{_func:e=>{const t=i(e[0]);return Number.isInteger(t)?String.fromCharCode(t):null},_signature:[{types:[n.TYPE_NUMBER]}]},codePoint:{_func:e=>{const i=t(e[0]);return 0===i.length?null:i.codePointAt(0)},_signature:[{types:[n.TYPE_STRING]}]},encodeUrlComponent:{_func:e=>encodeURIComponent(e[0]),_signature:[{types:[n.TYPE_STRING]}]},encodeUrl:{_func:e=>encodeURI(e[0]),_signature:[{types:[n.TYPE_STRING]}]},decodeUrlComponent:{_func:e=>decodeURIComponent(e[0]),_signature:[{types:[n.TYPE_STRING]}]},decodeUrl:{_func:e=>decodeURI(e[0]),_signature:[{types:[n.TYPE_STRING]}]}}}(O,Mt,t,e)).forEach((([e,t])=>{this.functionTable[e]=t})),Object.entries(i).forEach((([e,t])=>{this.functionTable[e]=t}))}_validateArgs(e,t,i,n){if(0===i.length)return;let s;const r=i.filter((e=>!e.optional)).length;if(i[i.length-1].variadic){if(t.length<i.length)throw s=1===i.length?" argument":" arguments",new Error(`ArgumentError: ${e}() takes at least${i.length}${s} but received ${t.length}`)}else if(t.length<r||t.length>i.length)throw s=1===i.length?" argument":" arguments",new Error(`ArgumentError: ${e}() takes ${i.length}${s} but received ${t.length}`);if(!n)return;let a,o;const l=Math.min(i.length,t.length);for(let n=0;n<l;n+=1)a=i[n].types,u=t[n],d=void 0,a.includes(Et)&&null!==(d=u)&&!Array.isArray(d)&&"Object"!==d.constructor.name||a.includes(Tt)||(o=b(t[n]),t[n]=E(o,a,t[n],e,this.toNumber,Mt));var u,d}callFunction(e,t,i,n,s=!0){if(!Object.prototype.hasOwnProperty.call(this.functionTable,e))throw new Error(`Unknown function: ${e}()`);const r=this.functionTable[e];return this._validateArgs(e,t,r._signature,s),r._func.call(this,t,i,n)}}class It{constructor(e,t,i){this.debug=e,this.toNumber=function(e,t=[]){return i=>{const n=O(i);if(null===n)return null;if(n instanceof Array)return t.push("Converted array to zero"),0;const s=typeof n;return"number"===s?n:"string"===s?e(n,t):"boolean"===s?n?1:0:(t.push("Converted object to zero"),0)}}(i||Ot,e),this.runtime=new wt(e,this.toNumber,t)}compile(e,t=[]){let i;try{i=new vt(t).parse(e,this.debug)}catch(e){throw this.debug.push(e.toString()),e}return i}search(e,t,i={},n="en-US"){this.runtime.interpreter=new V(this.runtime,i,this.toNumber,Mt,this.debug,n);try{return this.runtime.interpreter.search(e,t)}catch(e){throw this.debug.push(e.message||e.toString()),e}}}class At{constructor(e={},t=null,i=[]){this.customFunctions={...e},this.stringToNumber=t,this.debug=i,this.formula=new It(i,e,t)}search(e,t,i={},n="en-US"){const s=this.compile(e,Object.keys(i));return this.run(s,t,n,i)}run(e,t,i,n){return this.formula.search(e,t,n,i)}compile(e,t=[]){return this.debug.length=0,this.formula.compile(e,t)}}function Ct(e,t,i,n={},s=null,r=[],a="en-US"){return new At(n,s,r).search(i,e,t,a)}}},t={};function i(n){var s=t[n];if(void 0!==s)return s.exports;var r=t[n]={exports:{}};return e[n].call(r.exports,r,r.exports,i),r.exports}i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}
1),Object.defineProperty(e,"__esModule",{value:!0})};var n={};(()=>{i.r(n),i.d(n,{Actions:()=>C,Constants:()=>t,FileAttachmentUtils:()=>S,FormCheckBox:()=>b,FormContainer:()=>p,FormField:()=>f,FormFieldBase:()=>m,FormFileInput:()=>E,FormFileInputWidget:()=>O,FormFileInputWidgetBase:()=>T,FormOptionFieldBase:()=>M,FormPanel:()=>_,FormTabs:()=>y,Formatters:()=>N,FunctionRuntime:()=>e.FunctionRuntime,HTTPAPILayer:()=>s,LanguageUtils:()=>h,Utils:()=>c,createFormInstance:()=>e.createFormInstance,customFunctions:()=>o});var e=i(5444);const t={NS:"cmp",FORM_CONTAINER_INITIALISED:"AF_FormContainerInitialised",PANEL_INSTANCE_ADDED:"AF_PanelInstanceAdded",PANEL_INSTANCE_REMOVED:"AF_PanelInstanceRemoved",FORM_LANGUAGE_INITIALIZED:"AF_LanguageInitialised",ELEMENT_FOCUS_CHANGED:"elementFocusChanged",ELEMENT_HELP_SHOWN:"elementHelpShown",ELEMENT_ERROR_SHOWN:"elementErrorShown",ELEMENT_VALUE_CHANGED:"elementValueChanged",FORM_CONTAINER_DATA_ATTRIBUTE:"adaptiveformcontainerPath",DATA_HOOK_ADD_INSTANCE:"data-cmp-hook-add-instance",DATA_HOOK_REMOVE_INSTANCE:"data-cmp-hook-remove-instance",DATA_ATTRIBUTE_VALID:"data-cmp-valid",DATA_ATTRIBUTE_ENABLED:"data-cmp-enabled",DATA_ATTRIBUTE_VISIBLE:"data-cmp-visible",DATA_ATTRIBUTE_REQUIRED:"data-cmp-required",DATA_ATTRIBUTE_READONLY:"data-cmp-readonly",DATA_ATTRIBUTE_ACTIVE:"data-cmp-active",ARIA_DISABLED:"aria-disabled",ARIA_HIDDEN:"aria-hidden",ARIA_INVALID:"aria-invalid",ARIA_CHECKED:"aria-checked",ARIA_SELECTED:"aria-selected",GUIDE_BRIDGE_INITIALIZE_START:"bridgeInitializeStart",HTML_ATTRS:{DISABLED:"disabled",CHECKED:"checked"},TABINDEX:"tabindex",ARIA_CURRENT:"aria-current",API_PATH_PREFIX:"/adobe/forms/af",FIELD_TYPE:e.FIELD_TYPE,LOCALE_SELECTOR_PATTERN:/^[a-z]{2}(?:[-_][a-z0-9]{2,8})?$/i},s=class{static REQ_PARAMETER_DATA_REF="dataRef";static async getForm(e){const t=e.indexOf("/jcr:content/guideContainer");let i=e;-1!==t&&(i=e.substring(0,t));const n=await this.#e();if(n)return await this.#t(i,n);console.debug("Error in fetching form")}static async getFormDefinition(e,i){const n=new URLSearchParams(window.location.search),s=Object.fromEntries(n.entries());let r=null;if("afAcceptLang"in s)r=`${s.afAcceptLang}`;else{const e=(window.location.pathname||"").match(/\/([^/]+)\.html(?=\/|$)/);if(e&&e.length>1){const i=e[1].split(".");if(i.length>=2){const e=i[i.length-1];t.LOCALE_SELECTOR_PATTERN.test(e)&&(r=e)}}}return null===r&&null!=i&&(r=i),await this.getJson(`${e}.model.${null!==r?`${r}.`:""}json${this.REQ_PARAMETER_DATA_REF in s?`?${this.REQ_PARAMETER_DATA_REF}=${s[this.REQ_PARAMETER_DATA_REF]}`:""}`)}static async#t(e,t){const i=t.items.find((t=>t.path===e));if(i)return i;if(t.cursor){const i=await this.#e(t.cursor);return await this.#t(e,i)}console.debug("Form at "+e+" Not Found")}static async#e(e=""){return await this.getJson(`${t.API_PATH_PREFIX}/listforms?cursor=${e}`)}static async getPrefillData(e,i){return await this.getJson(t.API_PATH_PREFIX+"/data/"+e+"?"+Object.keys(i).map((e=>e+"="+i[e])).join("&"))}static async getJson(e){let t=`${c.getContextPath()}${e}`;return new Promise((e=>{let i=new XMLHttpRequest;i.open("GET",t,!0),i.responseType="json",i.onload=function(){let t=i.status;e(200===t?i.response:null)},i.send()}))}static async getCustomFunctionConfig(e){return await this.getJson(t.API_PATH_PREFIX+"/customfunctions/"+e)}};function r(e){try{const t=new URL(e,window.location.href);return"http:"===t.protocol||"https:"===t.protocol}catch(e){return!1}}function a(e){return window?.Granite?.HTTP&&"function"==typeof window.Granite.HTTP.externalize?window.Granite.HTTP.externalize(e):e}const o={toObject:function(e){if("string"==typeof e)try{return JSON.parse(e)}catch(e){return{}}return e},externalize:a,validateURL:r,navigateTo:(e,t)=>function(e,t){let i=null,n=window,s=null;"_newwindow"===t&&(i="_blank",s="width=1000,height=800"),i||(i=t||"_blank"),r(e)&&n.open(e,i,s)}(o.externalize(e),t),defaultErrorHandler:function(e,t,i){e&&e.validationErrors&&e.validationErrors?.forEach((function(e){e.details&&(e.fieldName?i.functions.markFieldAsInvalid(e.fieldName,e.details.join("\n"),{useQualifiedName:!0}):e.dataRef&&i.functions.markFieldAsInvalid(e.dataRef,e.details.join("\n"),{useDataRef:!0}))}))},defaultSubmitSuccessHandler:function(e){const t=e.event,i=t?.payload?.body,n=e.form;if(i)if(i.redirectUrl)window.location.href=encodeURI(i.redirectUrl);else if(i.thankYouMessage){let e=document.getElementById(`${n.$id}`),t=document.createElement("div");t.setAttribute("class","tyMessage"),t.setAttribute("tabindex","-1"),t.setAttribute("role","alertdialog"),t.innerHTML=i.thankYouMessage,e.replaceWith(t),t.focu
1s()}},defaultSubmitErrorHandler:function(e,t){var i=t&&t.event&&t.event.payload,n=i&&i.body;if(n&&"SSV_VALIDATION_ERROR"===n.errorType&&Array.isArray(n.errors)&&n.errors.length>0){var s=n.errors.filter((function(e){return e.qualifiedName})),r=n.errors.filter((function(e){return!e.qualifiedName})),a=t.formModel;s.forEach((function(e){var t=a&&"function"==typeof a.resolveQualifiedName?a.resolveQualifiedName(e.qualifiedName):null;t?t.markAsInvalid(e.message):console.warn('[SSV] No field found for qualifiedName "'+e.qualifiedName+'" — error not shown inline: '+e.message)})),r.length>0&&window.alert(r.map((function(e){return e.message})).join("\n"))}else!function(e,t){window.alert(e)}(e)},fetchCaptchaToken:async function(e){return new Promise(((t,i)=>{const n=function(e){t(e)},s=function(e){i(e)};try{const r=e.form.$captcha;if("turnstile"===r.$captchaProvider){const e=document.getElementsByClassName("cmp-adaptiveform-turnstile__widget")[0],t={sitekey:r.$captchaSiteKey,callback:n,"error-callback":s};if(null!=turnstile){const n=turnstile.render(e,t);n?turnstile.execute(n):i({error:"Failed to render turnstile captcha"})}else i({error:"Turnstile captcha not loaded"})}else{const e=r?.$properties["fd:captcha"]?.config?.siteKey,n=r.$name.replaceAll("-","_");let s=r?.$properties["fd:path"];const a=s.indexOf("/jcr:content");let o="";a>0&&(s=s.substring(0,a),o=s.substring(s.lastIndexOf("/")+1).replaceAll("-","_"));let l=`submit_${o}_${n}`;grecaptcha.enterprise.ready((()=>{grecaptcha.enterprise.execute(e,{action:l}).then((e=>t(e))).catch((e=>i(e)))}))}}catch(e){i(e)}}))},dateToDaysSinceEpoch:function(e){let t;if("string"==typeof e)t=new Date(e);else{if("number"==typeof e)return Math.floor(e);if(!(e instanceof Date))throw new Error("Invalid date input");t=e}if(isNaN(t.getTime()))throw new Error("Invalid date input");return Math.floor(t.getTime()/864e5)},downloadDoR:function(e,t){const i=t.form.$lang,n=new URLSearchParams({locale:i}).toString();let s=a("/adobe/forms/af/dor/"+t.form.$id+"?"+n);const r=new FormData;var o=JSON.stringify(t.functions.exportData());r.append("data",o),t.form.$id;var l=new XMLHttpRequest;l.open("POST",s,!0),l.responseType="arraybuffer",l.onreadystatechange=function(){if(4===l.readyState)if(200===l.status){const t=new Blob([l.response],{type:"application/pdf"}),i=URL.createObjectURL(t),n=document.createElement("a");n.href=i,n.download=e||"Downloaded_DoR.pdf",document.body.appendChild(n),n.click(),URL.revokeObjectURL(i),document.body.removeChild(n)}else console.error("Error while generating pdf")},l.send(r)},exportFormData:function(e,t,i){null==e&&(e=!0);const n=i.functions.exportData();if(!n)return;if(null==t)return e&&"object"==typeof n?JSON.stringify(n):n;const s=t.replace(/\[/g,".").replace(/\]/g,"").split(".").filter(Boolean);let r=n;for(const e of s){if(null==r)return;r=r[e]}return r&&"object"==typeof r&&e?JSON.stringify(r):r}};function l(e,t){if(window.xfalib){formBridge.registerConfig("disabledServerScripts",["initialize","$formready","$layoutready"]);const i=JSON.parse(JSON.parse(JSON.stringify(e)));return xfalib.runtime.renderContext=JSON.parse(JSON.parse(JSON.stringify(t))),xfalib.script.XfaModelRegistry.prototype.createModel(i),new xfalib.acrobat.Acrobat,function(e){e._syncXfaProps(),xfalib.runtime.xfa.form._initialize(!0),$(window).trigger("XfaInitialized")}}}const u=class{static async registerCustomFunctions(t){const i=await s.getCustomFunctionConfig(t);if(console.debug("Fetched custom functions: "+JSON.stringify(i)),i&&i.customFunction){const t=i.customFunction.reduce(((e,t)=>(window[t.id]&&(e[t.id]=window[t.id]),e)),{});e.FunctionRuntime.registerFunctions(t)}}static async registerCustomFunctionsV2(t){const i=this.extractFunctionNames(t).reduce(((e,t)=>(Object.prototype.hasOwnProperty.call(window,t.id)&&"function"==typeof window[t.id]&&(e[t.id]=window[t.id]),e)),{});console.debug("Registering custom functions:",i),e.FunctionRuntime.registerFunctions(i)}static extractFunctionNames=e=>{const t=new Set,i=e=>{const i=/(\w+)\s*\(/g;let n;for(;null!==(n=i.exec(e));)t.add(n[1])};
1e.events&&Object.values(e.events).forEach((e=>{e.forEach((e=>{i(e)}))})),e.rules&&Object.values(e.rules).forEach((e=>{i(e)}));const n=e=>{e&&Object.values(e).forEach((e=>{e.validationExpression&&i(e.validationExpression),e.displayValueExpression&&i(e.displayValueExpression),e.events&&Object.values(e.events).forEach((e=>{e.forEach((e=>{i(e)}))})),e.rules&&Object.values(e.rules).forEach((e=>{i(e)})),e[":items"]&&n(e[":items"])}))};return e[":items"]&&n(e[":items"]),console.debug("Extracted function names from form JSON:",t),Array.from(t).map((e=>({id:e})))};static async registerCustomFunctionsByUrl(t){try{if(null!=t&&t.trim().length>0){const i=await import(t),n=Object.keys(i),s=[];for(const e of n){const t=i[e];"function"==typeof t&&(s[e]=t)}e.FunctionRuntime.registerFunctions(s)}}catch(e){window.console&&console.error("error in loading custom functions from url "+t+" with message "+e.message)}}};class d{static#i="";static#n={};static#s=[];static readData(e,i){const n=e.dataset;let s={};const r=["is"];if(i){const e=i.charAt(0).toUpperCase()+i.substring(1);r.push("hook"+e)}for(let e in n)if(Object.prototype.hasOwnProperty.call(n,e)){let i=n[e];0===e.indexOf(t.NS)&&(e=e.slice(t.NS.length),e=e.charAt(0).toLowerCase()+e.substring(1),-1===r.indexOf(e)&&(s[e]=i))}return s}static registerMutationObserver(e,t,i,n){let s=new(window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver)((function(n){n.forEach((function(n){var s=[].slice.call(n.addedNodes);s.length>0&&s.forEach((function(n){if(n.querySelectorAll){var s=[].slice.call(n.querySelectorAll(i));d.#r(s,t,e)}}))}))}));const r='[data-cmp-path="'+e.getPath()+'"]',a=document.querySelector(r);s.observe(a,{subtree:!0,childList:!0,characterData:!0}),e._addMutationObserver&&e._addMutationObserver(s)}static#r(e,t,i){for(let n=0;n<e.length;n++){const s=e[n].id,r=e[n].getAttribute("data-cmp-adaptiveformcontainer-path"),a=i.getFormElement().getAttribute("data-cmp-path");if(null==i.getField(s)&&r==a){let s=t({element:e[n],formContainer:i});i.addField(s)}}}static createFieldsForAddedElement(e,t){Object.values(d.#s).forEach((function(i){let n=d.#n[i];const s=Array.from(e.querySelectorAll(n.fieldSelector));e.matches&&e.matches(n.fieldSelector)&&s.unshift(e),d.#r(s,n.fieldCreator,t)}))}static setupField(e,t,i){t in d.#n||d.#s.push(t),d.#n[t]={fieldCreator:e,fieldSelector:t,fieldClass:i}}static initializeAllFields(e){console.debug("Initializing field views ",e),Object.values(d.#s).forEach((function(t){const{fieldSelector:i,fieldCreator:n,fieldClass:s}=d.#n[t];console.debug("Initializing all fields of field selector ",i);let r=document.querySelectorAll(i);d.#r(r,n,e),d.registerMutationObserver(e,n,i,s)}))}static#a(e,t){e&&e.getAllFields()&&delete e.getAllFields()[t]}static#o(e,t){if(!e)return;let i=e.children;if(i)for(let e=0;e<i.length;e++)d.#o(i[e],t);e.getInstanceManager&&e.getInstanceManager()&&d.#a(t,e.getInstanceManager().id),d.#a(t,e.id)}static removeFieldReferences(e,t){if(!e)return;let i=e.children;if(i)for(let e=0;e<i.length;e++)d.#o(i[e],t);d.#a(t,e.id)}static updateId(e,t,i){if(e.id===t)return void(e.id=i);let n=e.querySelectorAll("#"+t)[0];n&&(n.id=i)}static setContextPath(e){null!=d.#i&&0!==d.#i.length||(d.#i=e)}static getContextPath(){return d.#i}static _clearState(){d.#i="",d.#n={},d.#s=[]}static registerClickHandler(e,t,i){const n="["+t+"]";e.querySelectorAll(n).forEach((e=>e.addEventListener("click",i)))}static async setupFormContainer(i,n,r){e.FunctionRuntime.registerFunctions(o);let a=document.querySelectorAll(n);for(let e=0;e<a.length;e++){const n=d.readData(a[e],r),o=n.customFunctionsModuleUrl,c=n.path,h=n.pageLang;if("contextPath"in n&&d.setContextPath(n.contextPath),null==c)console.error(`data-${t.NS}-${r}-path attribute is not present in the HTML element. Form cannot be initialized`);else{if(a[e].dataset.cmpAdaptiveformcontainerInitialized)continue;{let n,r;a[e].dataset.cmpAdaptiveformcontainerInitialized="true";const p=a[e].parentElement?.querySelector("[data-cmp-adaptiveform-container-loader]"),f=a[e].getAttribute("data-cmp-schema-type");if(p&&f&&("XDP"===f||"FORM_TEMPLATES"===f)){const e=p.getAttribute("data-cmp-adaptiveform-container-loader"),t=await fetch(`/adobe/forms/af/${e}`);n=(await t.json()).afModelDefinition,n.id=e,r=l(n.formdom,n.xfaRenderContext)}else n=await s.getFormDefinition(c,h);console.debug("fetched model json",n),await u.registerCustomFunctionsV2(n),await u.registerCustomFunctionsByUrl(o);const m=new URLSearchParams(window.location.search),g=Object.fromEntries(m.entries());let _={};!0===n?.properties?.["fd:formDataEnabled"]&&(_=await s.getJson(n.properties["fd:dataUrl"]+"?"+Object.keys(g).map((e=>e+"="+g[e])).join("&")),_=_||{},_=d.stripIfWrapped(_),window.formBridge&&window.formBridge.restoreFormState({formState:{xfaDom:_.data.xfaDom,xfaRenderContext:_.data.xfaRenderContext},context:this,error:function(){},success:function(){}}));const v=await i({_formJson:n,_prefillData:_,_path:c,_element:a[e]});"function"==typeof r&&r(v.getModel()),d.initializeAllFields(v);const y=new CustomEvent(t.FORM_CONTAINER_INITIALISED,{detail:v});document.dispatchEvent(y)}}}}static stripIfWrapped(e){if(e&&e.hasOwnProperty("data")){const t=e.data;if(t&&t.hasOwnProperty("afData")){const e=t.afData;if(e&&e.hasOwnProperty("afBoundData"))return e.afBoundData}}return e}static isUserAgent(e){if(navigator.userAgent)return new RegExp("^((?!chrome|android).)*"+e,"i").test(navigator.userAgent)}}const c=d,h=class{static#l={};static async loadLang(i,n,r=!1){const a=await s.getJson(n);if(a&&(console.debug("fetched language data",a),this.#l[i]=a,(0,e.setCustomDefaultConstraintTypeMessages)(a)),r){await this.#u(i);const e=new CustomEvent(t.FORM_LANGUAGE_INITIALIZED,{detail:i});document.dispatchEvent(e)}}static async#u(e){let t=guideBridge.getConfigsForKey(guideBridge.ConfigKeys.LOCALE_CONFIG)||[];t=t.map((e=>e.fn)).filter((e=>"function"==typeof e));for(const i of t)await i(e)}static getTranslatedString(e,t,i){let n="";return e in this.#l&&(n=this.#l[e][t],i&&(n=n.replace(/\${(\d+)}/g,(function(e,t){return void 0!==i[t]?i[t]:e})))),n}},p=class{constructor(t){let i=t._prefillData.data&&0===Object.keys(t._prefillData.data).length?null:t._prefillData.data;this._model=(0,e.createFormInstance)({...t._formJson,data:i}),this._path=t._path,this._fields={},this._deferredParents={},this._element=t._element,this._mutationObservers=[],this.#d()}#d(){this._element&&this._element.addEventListener("keydown",(e=>{if("Enter"!==e.key)return;const t=e.target;"INPUT"===t.tagName&&["text","password","email","url","search","tel","number"].includes(t.type)&&e.preventDefault()}))}_addMutationObserver(e){this._mutationObservers.push(e)}
1_disconnectMutationObservers(){this._mutationObservers.forEach((e=>e.disconnect())),this._mutationObservers=[]}addInstanceManager(e){this._fields[e.id]=e}getField(e){return this._fields.hasOwnProperty(e)?this._fields[e]:null}getModel(e){return e?this._model.getElement(e):this._model}getLang(){return this._model.lang||"en"}getParentFormElementId(e){const t=e.fieldType&&e.repeatable?e.parent.parent:e.parent;return"form"===t.fieldType?"$form":t.id}addField(e){if(e.getFormContainerPath()===this._path){let t=e.getId();this._fields[t]=e;let i=this.getModel(t);e.setModel(i),e.syncMarkupWithModel();const n=this.getParentFormElementId(i);if("$form"!=n){let t=this._fields[n];t?e.setParent(t):(this._deferredParents[n]||(this._deferredParents[n]=[]),this._deferredParents[n].push(e))}else e.setParent(this);if(this._deferredParents[t]){let i=this._deferredParents[t];for(let t=0;t<i.length;t++)i[t].setParent(e);delete this._deferredParents[t]}e.subscribe()}}setFocus(e){if(e){let t=this._fields[e];t&&t.setFocus?t.setFocus():console.log("View on which focus is to be set, not initialized.")}}getFormId(){return this._model._jsonModel.id}getFormTitle(){return this._model._jsonModel.title}getPath(){return this._path}getFormElement(){return this._element}getAllFields(){return this._fields}updateActiveChild(e){this.setFocus(e?._activeChild?.id||e?.id)}#c(e){const t=e[0].fieldName;this.setFocus(t)}subscribe(){this._model.subscribe((e=>{let t=e.target.getState();
1e.payload.changes.forEach((e=>{const i=`update${(n=e.propertyName)[0].toUpperCase()+n.slice(1)}`;var n;"function"==typeof this[i]?this[i](e.currentValue,t):console.warn(`changes to ${e.propertyName} are not supported at form. Please raise an issue`)}))})),this._model.subscribe((e=>{e.payload.length>0&&this.#c(e.payload)}),"validationComplete")}},f=class{constructor(e){this.formContainer=e.formContainer,this.element=e.element,this.options=c.readData(this.element,this.getClass()),this.setId(this.element.id),this.active=!1}setId(e){this.id=e}setParent(e){this.parentView=e,this.parentView.addChild&&this.parentView.addChild(this),this.getInstanceManager()&&!this.getInstanceManager().getRepeatableParentView()&&this.getInstanceManager().setRepeatableParentView(e)}setInstanceManager(e){this.instanceManager=e}setActive(){this.isActive()||(this.element.setAttribute(t.DATA_ATTRIBUTE_ACTIVE,!0),this.parentView&&this.parentView?._model?.activeChild!==this._model&&(this.parentView._model.activeChild=this._model),this.active=!0)}setInactive(){this.isActive()&&this.element.setAttribute(t.DATA_ATTRIBUTE_ACTIVE,!1)}isActive(){return"true"===this.element.getAttribute(t.DATA_ATTRIBUTE_ACTIVE)}triggerExit(){this._model.dispatch(new FormView.Actions.CustomEvent("xfaexit"))}triggerEnter(){this._model.dispatch(new FormView.Actions.CustomEvent("xfaenter"))}getFormContainerPath(){return this.options.adaptiveformcontainerPath}getId(){return this.id}setModel(e){if(void 0!==this._model&&null!==this._model)throw"Re-initializing model is not permitted";this._model=e}setModelValue(e){this._model.dispatch(new FormView.Actions.UIChange({value:e}))}syncMarkupWithModel(){throw"method not implemented"}toggle(e,t,i){this.toggleAttribute(this.element,e,t,i)}toggleAttribute(e,t,i,n){e&&(!1===t?e.setAttribute(i,n):e.removeAttribute(i))}getLayoutProperties(){let e={};const t=this.getModel().getState();return t&&t.properties&&t.properties["afs:layout"]&&(e=t.properties["afs:layout"]),e}getModel(){return this._model}subscribe(){throw"the field does not subscribe to the model"}initializeHelpContent(e){throw"method not implemented"}getInstanceManager(){return this.instanceManager}},m=class extends f{constructor(e){super(e),this.widget=this.getWidget(),this.description=this.getDescription(),this.label=this.getLabel(),this.errorDiv=this.getErrorDiv(),this.qm=this.getQuestionMarkDiv(),this.tooltip=this.getTooltipDiv(),this.updateEmptyStatus()}ELEMENT_FOCUS_CHANGED=t.ELEMENT_FOCUS_CHANGED;ELEMENT_HELP_SHOWN=t.ELEMENT_HELP_SHOWN;ELEMENT_ERROR_SHOWN=t.ELEMENT_ERROR_SHOWN;ELEMENT_VALUE_CHANGED=t.ELEMENT_VALUE_CHANGED;getWidget(){throw"method not implemented"}getDescription(){throw"method not implemented"}getLabel(){throw"method not implemented"}getErrorDiv(){throw"method not implemented"}getTooltipDiv(){throw"method not implemented"}getQuestionMarkDiv(){throw"method not implemented"}getClass(){return this.constructor.IS}setModel(e){super.setModel(e);const t=this._model.getState();this.applyState(t),this.#h()}getWidgetId(){return this.getId()+"-widget"}#p(){let e="function"==typeof this.getWidget?this.getWidget():null;e=("function"==typeof this.getWidgets?this.getWidgets():null)||e,e&&e.setAttribute("id",this.getWidgetId())}#f(){let e="function"==typeof this.getLabel?this.getLabel():null;e&&"LABEL"===e.tagName?.toUpperCase()?e.setAttribute("for",this.getWidgetId()):e&&e.removeAttribute("for")}#m(){let e="function"==typeof this.getErrorDiv?this.getErrorDiv():null;e&&e.setAttribute("id",`${this.getId()}__errormessage`)}#g(){let e="function"==typeof this.getTooltipDiv?this.getTooltipDiv():null;e&&e.setAttribute("id",`${this.getId()}__shortdescription`)}#_(){let e="function"==typeof this.getDescription?this.getDescription():null;e&&e.setAttribute("id",`${this.getId()}__longdescription`)}#v(){let e="",t="function"==typeof this.getWidget?this.getWidget():null;function i(t,i){e?e+=` ${i}__${t}`:e=`${i}__${t}`}if(t=("function"==typeof this.getWidgets?this.getWidgets():null)||t,t){if(this.getDescription()){const e=this.getDescription();""!==e.innerHTML.trim()&&0!==e.children.length&&i("longdescription",this.getId())}this.getTooltipDiv()&&i("shortdescription",this.getId()),this.getErrorDiv()&&this.getErrorDiv().innerHTML&&i("errormessage",this.getId()),t.setAttribute("aria-describedby",e)}}#y(){let e="function"==typeof this.getWidget?this.getWidget():null;e=("function"==typeof this.getWidgets?this.getWidgets():null)||e;const t=this.getModel?.();if(e&&t?.screenReaderText){const i=window.DOMPurify?window.DOMPurify.sanitize(t.screenReaderText,{ALLOWED_TAGS:[]}):t.screenReaderText;e.setAttribute("aria-label",i)}}syncMarkupWithModel(){this.#f(),this.#p(),this.#g(),this.#_(),this.#v(),this.#m(),this.#y()}setFocus(e){const t=this.parentView?.getModel()?.fieldType;"form"!==t&&this.parentView?.setFocus&&this.parentView.setFocus(this.getId()),this.isActive()||(this.widget=this.getWidget(),this.widget instanceof NodeList?this.widget[0].focus():"adaptiveFormFileInput"===this.getClass()?this.getAttachButtonLabel().focus():this.widget.focus())}
1applyState(e){e.value&&this.updateValue(e.value),this.updateVisible(e.visible,e),this.updateReadOnly(e.readOnly),this.updateEnabled(e.enabled,e),this.initializeHelpContent(e),this.updateLabel(e.label),this.updateRequired(e.required,e),this.updateDescription(e.description)}initializeHelpContent(e){this.#b(!1),this.getDescription()&&this.#E(e)}#h(){this.#T(),this.#M()}#M(){const e=this.qm;e&&e.addEventListener("click",(()=>{this.#O(this.ELEMENT_HELP_SHOWN)}))}#T(){const e=this.getWidget();if(e)if(e.length&&e.length>1)for(let t of e)t.onfocus=()=>{this.#O(this.ELEMENT_FOCUS_CHANGED)};else e.onfocus=()=>{this.#O(this.ELEMENT_FOCUS_CHANGED)}}#O(e,t){const i=this.formContainer.getFormId(),n=this.formContainer.getFormTitle(),s=this.#w(),r={formId:i,formTitle:n,fieldName:this._model.name,fieldId:this._model.id,panelName:s,fieldQualifiedName:this._model.qualifiedName,...void 0!==t?.prevValue?{prevText:t?.prevValue}:{},...void 0!==t?.currentValue?{newText:t?.currentValue}:{},..."object"==typeof t&&null!==t?t:{}},a=this.formContainer.getPath();window.guideBridge.trigger(e,r,a)}#w(){return this.parentView?.getModel()?.name}setWidgetValueToDisplayValue(){this._model.displayValueExpression&&this._model.displayValue&&(this.widget.value=this._model.displayValue)}setWidgetValueToModelValue(){this._model.displayValueExpression&&this._model.displayValue&&(this.widget.value=this._model.value)}#I(e){this.tooltip&&this.toggleAttribute(this.getTooltipDiv(),e,t.DATA_ATTRIBUTE_VISIBLE,!1)}#b(e){this.getDescription()&&this.toggleAttribute(this.getDescription(),e,t.DATA_ATTRIBUTE_VISIBLE,!1)}#A(){return!!this.getLayoutProperties().tooltipVisible}updateVisible(e,i){this.toggle(e,t.ARIA_HIDDEN,!0),this.element.setAttribute(t.DATA_ATTRIBUTE_VISIBLE,e),null!=this.parentView&&"panel"===this.parentView.getModel().fieldType&&this.parentView.updateChildVisibility(e,i)}updateEnabled(e,i){this.widget&&(this.element.setAttribute(t.DATA_ATTRIBUTE_ENABLED,e),!1===e?this.widget.setAttribute("disabled","disabled"):this.widget.removeAttribute("disabled"))}updateReadOnly(e){this.widget&&(this.element.setAttribute(t.DATA_ATTRIBUTE_READONLY,e),!0===e?this.widget.setAttribute("readonly","readonly"):this.widget.removeAttribute("readonly"))}updateRequired(e,i){this.widget&&(this.element.toggleAttribute("required",e),this.element.setAttribute(t.DATA_ATTRIBUTE_REQUIRED,e),!0===e?this.widget.setAttribute("required","required"):this.widget.removeAttribute("required"))}updateValid(e,t){}updateValidity(e,i){const n=e.valid;this.errorDiv&&(this.element.setAttribute(t.DATA_ATTRIBUTE_VALID,n),this.widget.setAttribute(t.ARIA_INVALID,!n),this.updateValidationMessage(i.validationMessage,i))}updateErrorMessage(e,t){}updateValidationMessage(e,t){if(this.errorDiv&&this.errorDiv.innerHTML!==t.validationMessage){if(this.errorDiv.innerHTML=t.validationMessage,!1===t.validity.valid){const e=Object.keys(t.validity).find((e=>"valid"!==e&&!0===t.validity[e]));this.#O(this.ELEMENT_ERROR_SHOWN,{validationMessage:t.validationMessage,validationType:e}),t.validationMessage||(this.errorDiv.innerHTML=h.getTranslatedString(this.formContainer.getModel().lang,"defaultError"))}this.#v()}}updateValue(e){let t=void 0===e?null:e;this.widget&&(this.widget.value=t,this.updateEmptyStatus())}updateEmptyStatus(){if(!this.getWidget())return;let e="";const t=["radio","checkbox"];e=this.widget instanceof NodeList?Array.from(this.widget).map((e=>t.includes(e.type)?e.checked:e.value)).find((e=>e)):t.includes(this.widget.type)?this.widget.checked:this.widget.value;const i=Array.from(this.element.classList).filter((e=>!e.includes("--")))[0],n=`${i}--filled`,s=`${i}--empty`;this.element.classList.add(e?n:s),this.element.classList.remove(e?s:n)}updateLabel(e){this.label&&(e.hasOwnProperty("value")&&(this.label.innerHTML=e.value),e.hasOwnProperty("visible")&&(this.toggleAttribute(this.label,e.visible,t.ARIA_HIDDEN,!0),this.label.setAttribute(t.DATA_ATTRIBUTE_VISIBLE,e.visible)))}updateActiveChild(e){this.formContainer.setFocus(e?._activeChild?.id||e?.id)}updateDescription(e){if(void 0!==e){const t=window.DOMPurify?window.DOMPurify.sanitize(e,{ALLOWED_TAGS:[]}).trim():e;let i=this.getDescription();if(i){if(i.innerText.trim()===t)return;let e=i.querySelectorAll("p");e||(e=document.createElement("p"),i.innerHTML="",i.appendChild(pElement)),1===e.length&&(e[0].innerHTML=t)}else this.#C(t)}}#C(e){const t=Array.from(this.element.classList).filter((e=>!e.includes("--")))[0],i=this.element.querySelector(`.${t}__label-container`);if(!i)return void console.error("label container not found");{const e=document.createElement("button");e.className=`${t}__questionmark`,e.title="Help text",i.appendChild(e)}const n=document.createElement("div");n.className=`${t}__longdescription`,n.id=`${this.getId()}__longdescription`,n.setAttribute("aria-live","polite"),n.setAttribute("data-cmp-visible",!1);const s=document.createElement("p");s.textContent=e,n.appendChild(s);var r=this.getErrorDiv();r?(this.element.insertBefore(n,r),this.#E()):console.log("error div not found")}#E(e){const i=this.getQuestionMarkDiv(),n=this.getDescription(),s=this.#A(),r=this;i&&n&&i.addEventListener("click",(e=>{e.preventDefault(),"false"===n.getAttribute(t.DATA_ATTRIBUTE_VISIBLE)?(r.#b(!0),s&&r.#I(!1),i.setAttribute("aria-expanded",!0)):(r.#b(!1),s&&r.#I(!0),i.setAttribute("aria-expanded",!1))}))}subscribe(){this._model.subscribe((e=>{let t=e.target.getState();
1e.payload.changes.forEach((e=>{const i=`update${(n=e.propertyName)[0].toUpperCase()+n.slice(1)}`;var n;"value"===e.propertyName&&this.#O(this.ELEMENT_VALUE_CHANGED,e),"function"==typeof this[i]?this[i](e.currentValue,t):console.warn(`changes to ${e.propertyName} are not supported. Please raise an issue`)}))}))}},g=class{constructor(e){this.formContainer=e.formContainer,this._model=e.model,this.parentElement=e.parentElement,this.id=this._model.id,this.children=[],this.subscribe()}#N(e,t,i){let n=null;return null==e?n=this.#S(t,i):null==t?this.#j(e.getModel()):e.getId()!=t.id&&(n=this.#S(t,i),this.#j(e.getModel())),n}#x(){const e=this.children,t=this._model.items,i=e.length,n=t.length,s=i>n?i:n;let r=null;for(let a=0;a<s;a++){const s=a<i?e[a]:null,o=a<n?t[a]:null;r=this.#N(s,o,r)}}#R(e,t,i){if("array"!=t.type&&c.updateId(e,t.id,i),"panel"==t.fieldType&&t.items)for(let n=0;n<t.items.length;n++)this.#R(e,t.items[n],i+"_"+n)}updateCloneIds(e,t,i){if("array"!=i.type&&c.updateId(e,t,i.id),"panel"==i.fieldType&&i.items)for(let n=0;n<i.items.length;n++)this.updateCloneIds(e,t+"_"+n,i.items[n])}updateTemplate(e){const t=e.element.parentElement,i="function"==typeof e.getRepeatableDomWrapper?e.getRepeatableDomWrapper():t;this._templateHTML=i.cloneNode(!0);let n=e.getModel();n||(n=this.formContainer.getModel(e.getId())),this.#R(this._templateHTML,n,"temp_0")}#D(e,t,i){const n=new CustomEvent(t);i&&(n.payload=i),this.getModel().dispatch(n)}#S(e,t){if(!this._templateHTML)return void console.error("Panel needs to have templateHTML to support repeatability.");const i=this.handleAddition(e,t);return i&&c.createFieldsForAddedElement(i,this.formContainer),i}#j(e){if(!e||!e.id)return;let i=this.children.find((t=>t&&t.getId()===e.id));if(!i&&"number"==typeof e.index&&e.index>=0&&e.index<this.children.length&&(i=this.children[e.index]),i||(i=this.formContainer.getField(e.id)),!i)return void console.warn("InstanceManager: no view for removed instance",e.id);const n=this.children.indexOf(i);c.removeFieldReferences(i,this.formContainer),this.handleRemoval(i),n>=0&&this.children.splice(n,1);const s=new CustomEvent(t.PANEL_INSTANCE_REMOVED,{detail:i});this.formContainer.getFormElement().dispatchEvent(s)}addInstance(e,t){this.#D(e,"addInstance",t)}removeInstance(e,t){this.#D(e,"removeInstance",t)}#P(e,t,i,n){const s=this.formContainer.getModel(e),r=new CustomEvent(t);r.payload=s.index+i,s.parent.dispatch(r),n.stopPropagation()}#F(e){if("function"==typeof this?.repeatableParentView?.getRepeatableRootElement){const i=this.repeatableParentView.getRepeatableRootElement(e);c.registerClickHandler(i,t.DATA_HOOK_ADD_INSTANCE,(e=>{const i=e.currentTarget.getAttribute(t.DATA_HOOK_ADD_INSTANCE);i?this.#P(i,"addInstance",1,e):this.addInstance(e)})),c.registerClickHandler(i,t.DATA_HOOK_REMOVE_INSTANCE,(e=>{const i=e.currentTarget.getAttribute(t.DATA_HOOK_REMOVE_INSTANCE);i?this.#P(i,"removeInstance",0,e):this.removeInstance(e)}))}}handleAddition(e,t){const i=e.index;let n=this._templateHTML.cloneNode(!0),s=this.formContainer.getModel(e.id);if(this.updateCloneIds(n,"temp_0",s),this.repeatableParentView&&"function"==typeof this.repeatableParentView.addRepeatableMarkup)n=this.repeatableParentView.addRepeatableMarkup(this,s,n);else if(0==this.children.length)this.parentElement.append(n);else if(0==s.index){let e=this.children[0].element.parentElement;this.parentElement.insertBefore(n,e)}else this.getElementAt(i-1).after(n);return n}getElementAt(e){let t=this._model.items.find((t=>t.index===e)),i=this.parentElement.querySelector(`#${t.id}`);if(i)for(;i.parentElement!==this.parentElement;)i=i.parentElement;return i}handleRemoval(e){let t;this.repeatableParentView&&"function"==typeof this.repeatableParentView.handleChildRemoval&&this.repeatableParentView.handleChildRemoval(e),t="function"==typeof e.getRepeatableDomWrapper?e.getRepeatableDomWrapper():e.element.parentElement,t&&t.parentElement&&t.remove()}addChild(e){this._templateHTML||this.updateTemplate(e),this.children.splice(e.getModel().index,0,e),this.#F(e);const i=new CustomEvent(t.PANEL_INSTANCE_ADDED,{detail:e});this.repeatableParentView&&"function"==typeof this.repeatableParentView.handleChildAddition&&this.repeatableParentView.handleChildAddition(e),this.formContainer.getFormElement().dispatchEvent(i)}updateItems(e,t,i){e?this.#j(e):t&&this.#S(t)}
1subscribe(){this.getModel().subscribe((e=>{let t=e.target.getState();e.payload.changes.forEach((e=>{"items"===e.propertyName?this.updateItems(e.prevValue,e.currentValue,t):console.warn(`changes to ${e.propertyName} are not supported. Please raise an issue`)}))}))}getId(){return this.id}getModel(){return this._model}setRepeatableParentView(e){this.repeatableParentView=e,this.#x(),this.children.length>0&&this.#F(this.children[0])}getRepeatableParentView(){return this.repeatableParentView}},_=class extends m{constructor(e){super(e),this.children=[]}getRepeatableInstancesContainerElement(){return this.element.parentElement?.parentElement}getRepeatableDomWrapper(){return this.element.parentElement}instantiateInstanceManager(){return new g({formContainer:this.formContainer,model:this._model.parent,parentElement:this.getRepeatableInstancesContainerElement()})}setModel(e){if(super.setModel(e),e.repeatable){let t=this.formContainer.getField(e.parent.id);null==t&&(t=this.instantiateInstanceManager(),this.formContainer.addInstanceManager(t)),this.setInstanceManager(t),t.addChild(this)}}setFocus(e){const t=this.parentView?.getModel()?.fieldType;"form"!==t&&this.parentView?.setFocus&&this.parentView.setFocus(this.getId())}getActiveRepeatableNonRepeatableTabId(e,t){for(const i of e){if(i.id===t)return t;if("panel"===i.fieldType&&"array"===i.type){const e=this.formContainer.getModel().getElement(i.id).getState(),n=this.getActiveRepeatableNonRepeatableTabId(e.items,t);if(n)return n}}return null}focusToFirstVisibleField(e){const t=this.formContainer.getModel(),i=this.getActiveRepeatableNonRepeatableTabId(this.getModel().getState().items,e),n=t.getElement(i);if(!n)return;const s=e=>{if(!e.visible||!e.enabled)return null;if(e.fieldType&&"panel"!==e.fieldType)return e;for(const t of e.items){const e=s(t);if(e)return e}return null},r=s(n);r&&setTimeout((()=>{this.formContainer.setFocus(r.id)}),0)}addChild(e){this.children.push(e)}getCountOfAllChildrenInModel(){var e=0;for(let i in this.getModel()._children){var t=this.getModel()._children[i];null!=t.minOccur&&null!=t.maxOccur&&null!=t._children?e+=0==t._children.length?1:t._children.length:e+=1}return e}getChild(e){for(let t in this.children)if(this.children[t].id===e)return this.children[t]}handleChildAddition(e){}handleChildRemoval(e){}applyState(e){this.updateVisible(e.visible),this.updateEnabled(e.enabled),this.initializeHelpContent(e),this.updateLabel(e.label)}updateEnabled(e){this.toggle(e,t.ARIA_DISABLED,!0),this.element.setAttribute(t.DATA_ATTRIBUTE_ENABLED,e)}updateValid(e,t){}updateValidity(e,i){const n=e.valid;this.toggle(n,t.ARIA_INVALID,!0),this.element.setAttribute(t.DATA_ATTRIBUTE_VALID,n)}getChildViewByIndex(e){}#L(e){var t={closestRepeatableFieldInstanceManagerIds:[]};for(let n=e-1;n>=0;n--){var i=this.getChildViewByIndex(n);if(null==i.getInstanceManager()){t.closestNonRepeatableFieldId=i.getId();break}if(t.closestRepeatableFieldInstanceManagerIds.push(i.getInstanceManager().getId()),0!=i.getInstanceManager().getModel().minOccur)break}return t}cacheClosestFieldsInView(){for(let n=0;n<this.children.length;n++){var e=this.getChildViewByIndex(n);if(null!=e.getInstanceManager()&&0==e.getInstanceManager().getModel().minOccur){var t=e.getInstanceManager().getId();if(null==this._templateHTML[t]&&(this._templateHTML[t]={}),null==this._templateHTML[t].closestNonRepeatableFieldId&&null==this._templateHTML[t].closestRepeatableFieldInstanceManagerIds){var i=this.#L(n);this._templateHTML[t].closestNonRepeatableFieldId=i.closestNonRepeatableFieldId,this._templateHTML[t].closestRepeatableFieldInstanceManagerIds=i.closestRepeatableFieldInstanceManagerIds}}}}getIndexToInsert(e,t){var i=-1;for(let s=this.children.length-1;s>=0;s--){var n=this.getChildViewByIndex(s);if(e===n.getId()){i=s;break}if(null!=n.getInstanceManager()&&t.includes(n.getInstanceManager().getId())){i=s;break}}return i+1}getRepeatableRootElement(e){return"function"==typeof e.getRepeatableDomWrapper?e.getRepeatableDomWrapper():e.element.parentElement}updateChildVisibility(e,t){}handleHiddenChildrenVisibility(){for(let e=0;e<this.children.length;e++)"false"===this.children[e].element.getAttribute(t.DATA_ATTRIBUTE_VISIBLE)&&this.updateChildVisibility(!1,this.children[e].getModel().getState())}findFirstVisibleChild(e){for(let i=0;i<e.length;i++)if("false"!=e[i].getAttribute(t.DATA_ATTRIBUTE_VISIBLE))return e[i]}updateVisibilityOfNavigationElement(e,i){e&&(!1===i?e.setAttribute(t.ARIA_HIDDEN,!0):e.removeAttribute(t.ARIA_HIDDEN),e.setAttribute(t.DATA_ATTRIBUTE_VISIBLE,i))}updateEmptyStatus(){}};class v extends _{static keyCodes={END:35,HOME:36,ARROW_LEFT:37,ARROW_UP:38,ARROW_RIGHT:39,ARROW_DOWN:40};#k;#$;#U;#V;#B="__tab";#Y="__tabpanel";_templateHTML={};constructor(e,t,i,n){super(e),this.#U=t,this.#$=i,this.#V=n;const{element:s}=e;this.#H(s),this.#k=this.getActiveTabId(this.#K()),this.#q(),this.#G()}#q(){var e=this.#z(),i=this.#K();if(e)for(var n=0;n<e.length;n++)i[n]&&(i[n].id===this.#k?(e[n].classList.add(this.#V.active.tabpanel),e[n].removeAttribute(t.ARIA_HIDDEN),i[n].classList.add(this.#V.active.tab),i[n].setAttribute(t.ARIA_SELECTED,!0),i[n].setAttribute(t.TABINDEX,"0"),i[n].setAttribute(t.ARIA_CURRENT,"true"),i[n].setAttribute("state","selected")):(e[n].classList.remove(this.#V.active.tabpanel),e[n].setAttribute(t.ARIA_HIDDEN,!0),i[n].classList.remove(this.#V.active.tab),i[n].setAttribute(t.ARIA_SELECTED,!1),i[n].setAttribute(t.TABINDEX,"-1"),i[n].setAttribute(t.ARIA_CURRENT,"false"),i[n].removeAttribute("state")))}#G(){var e=this.#K();if(e)for(var t=0;t<e.length;t++){var i=this;!function(t){e[t].addEventListener("click",(function(n){n?.target?.id===e[t].id&&i.navigateAndFocusTab(e[t].id)}))}(t),e[t].addEventListener("keydown",(function(e){i.#W(e)}))}}#H(e){this._elements={},this._elements.self=e;for(var t=this._elements.self.querySelectorAll("[data-"+this.#U+"-hook-"+this.#$+"]"),i=0;i<t.length;i++){var n=t[i];if(n.closest("[data-cmp-is="+this.#$+"]")===this._elements.self){var s=this.#$.toLowerCase(),r=s.charAt(0).toUpperCase()+s.slice(1),a=n.dataset[this.#U+"Hook"+r];if(this._elements[a]){if(!Array.isArray(this._elements[a])){var o=this._elements[a];this._elements[a]=[o]}this._elements[a].push(n)}else this._elements[a]=[n]}}}#W(e){var t=this.#J(this.#k),i=this.#K(),n=i.length-1;switch(e.keyCode){case v.keyCodes.ARROW_LEFT:case v.keyCodes.ARROW_UP:e.preventDefault(),t>0&&this.navigateAndFocusTab(i[t-1].id);break;case v.keyCodes.ARROW_RIGHT:case v.keyCodes.ARROW_DOWN:e.preventDefault(),t<n&&this.navigateAndFocusTab(i[t+1].id);break;case v.keyCodes.HOME:e.preventDefault(),this.navigateAndFocusTab(i[0].id);break;case v.keyCodes.END:e.preventDefault(),this.navigateAndFocusTab(i[n].id);break;default:return}}#J(e){var t=this.#K();if(t)for(var i=0;i<t.length;i++)if(t[i].id===e)return i;return-1}navigateAndFocusTab(e){if(this.setActive(),this.#k!==e){this.navigate(e),this.focusWithoutScroll(this.#Q(e));const t=this.getActiveTabId(this.#K()).replace(this.#B,"");this.focusToFirstVisibleField(t)}}#Q(e){var t=this.#K();if(t)for(var i=0;i<t.length;i++)if(t[i].id===e)return t[i]}focusWithoutScroll(e){if(e){var t=window.scrollX||window.pageXOffset,i=window.scrollY||window.pageYOffset;e.focus(),window.scrollTo(t,i)}}navigate(e){this.#k=e,this.addSteppedClass(e),this.#q()}addSteppedClass(e){var t=this.#K(),i=this.#z();const n=this.getActiveTabId(t),s=this.#Q(n);if(s.classList.contains(this.#V.active.tab)){s.classList.add(this.#V.stepped.tab);const e=Array.from(i).find((e=>
1e.getAttribute("aria-labelledby")===s.id));e&&e.classList.add(this.#V.stepped.tabpanel)}}getActiveTabId(e){if(e){for(var t=e[0].id,i=0;i<e.length;i++)if(e[i].classList.contains(this.#V.active.tab)){t=e[i].id;break}return t}}#X(){var e=this.#K(),t=this.#z();if(t)for(var i=0;i<t.length;i++){var n=t[i].querySelectorAll("[data-cmp-is]")[0].id;e[i].id=n+this.#B,e[i].setAttribute("aria-controls",n+this.#Y)}}#Z(){var e=this.#z();if(e)for(var t=0;t<e.length;t++){var i=e[t].querySelectorAll("[data-cmp-is]")[0].id;e[t].id=i+this.#Y,e[t].setAttribute("aria-labelledby",i+this.#B)}}syncMarkupWithModel(){super.syncMarkupWithModel(),this.#X(),this.#Z()}handleChildAddition(e){if(null!=e.getInstanceManager()&&null!=this._templateHTML[e.getInstanceManager().getId()]){var t=this._templateHTML[e.getInstanceManager().getId()].navigationTab.cloneNode(!0);t.id=e.id+this.#B,t.setAttribute("aria-controls",e.id+this.#Y);var i=e.getModel().index,n=e.getInstanceManager().getId();if(0==i){var s=this._templateHTML[n].closestNonRepeatableFieldId,r=this._templateHTML[n].closestRepeatableFieldInstanceManagerIds,a=this.getIndexToInsert(s,r);if(0==a){var o=this.#ee();o.insertBefore(t,o.firstChild)}else this.#K()[a-1].after(t)}else{var l=e.getInstanceManager().children[i-1].element.id+this.#B;this.#Q(l).after(t)}this.#H(this._elements.self);var u=this.#te(e.id+this.#Y);u.setAttribute("aria-labelledby",e.id+this.#B);const d=Array.from(t.classList).find((e=>e.includes("--stepped")));d&&t.classList.remove(d);const c=Array.from(u.classList).find((e=>e.includes("--stepped")));c&&u.classList.remove(c),this.#ie(t.id),this.#q(),null!=e.getInstanceManager().getModel().minOccur&&e.getInstanceManager().children.length>e.getInstanceManager().getModel().minOccur?this.navigateAndFocusTab(t.id):this.navigateAndFocusTab(this.findFirstVisibleChild(this.#K()).id)}}handleChildRemoval(e){var t=e.element.id+this.#Y,i=e.element.id+this.#B,n=this.#te(t),s=this.#Q(i);const r=this.#K(),a=Array.from(r).findIndex((e=>e.id===i));let o=null;if(0===a)o=r[1];else for(let e=a-1;e>=0;e--){o=r[e];break}s.remove(),n.remove(),this.children.splice(this.children.indexOf(e),1),this.#H(this._elements.self),this.#q(),o&&this.navigateAndFocusTab(o.id)}addChild(e){super.addChild(e),this.#ne(e),this.getCountOfAllChildrenInModel()===this.children.length&&(this.cacheClosestFieldsInView(),this.handleHiddenChildrenVisibility())}#ne(e){if(null!=e.getInstanceManager()&&(null==this._templateHTML||null==this._templateHTML[e.getInstanceManager().getId()])){var t=e.element.id+this.#B,i=e.element.id+this.#Y,n=e.getInstanceManager().getId(),s=this.#Q(t),r=this.#te(i);this._templateHTML[n]={},this._templateHTML[n].navigationTab=s,this._templateHTML[n].targetTabPanel=r}}#te(e){var t=this.#z();if(t)for(var i=0;i<t.length;i++)if(t[i].id===e)return t[i]}#ie(e){var t=this,i=this.#K(),n=this.#J(e);i[n].addEventListener("click",(function(i){i?.target?.id===e&&t.navigateAndFocusTab(e)})),i[n].addEventListener("keydown",(function(e){t.#W(e)}))}#ee(){return this.element.querySelector(this.#V.olTabList)}#z(){return this._elements.tabpanel}#K(){return this._elements.tab}addRepeatableMarkup(e,t,i){let n=this._templateHTML[e.getId()].targetTabPanel.cloneNode(!1);return n.id=t.id+this.#Y,this.#se(e,t.index).beforeViewElement.after(n),n.append(i),n}#se(e,t){var i={},n=e.getId();if(0==t){var s=this._templateHTML[n].closestNonRepeatableFieldId,r=this._templateHTML[n].closestRepeatableFieldInstanceManagerIds,a=this.getIndexToInsert(s,r);i.beforeViewElement=a>0?this.#z()[a-1]:this.#ee()}else{let n=this.#re(e,t-1);i.beforeViewElement=n}return i}#re(e,t){let i=e._model.items.find((e=>e.index===t))?.id;return this.element.querySelector(`#${i}${this.#Y}`)}getChildViewByIndex(e){var t=this.#z(),i=t[e].id.substring(0,t[e].id.lastIndexOf("__"));return this.getChild(i)}updateChildVisibility(e,t){this.updateVisibilityOfNavigationElement(this.#Q(t.id+this.#B),e);var i=this.getActiveTabId(this._elements.tab);if(!e&&i===t.id+this.#B){let e=this.findFirstVisibleChild(this.#K());e&&this.navigateAndFocusTab(e.id)}}}const y=v,b=class extends m{constructor(e){super(e)}updateValue(e){e===this._model._jsonModel.enum[0]?(this.widget.checked=!0,this.widget.setAttribute(FormView.Constants.HTML_ATTRS.CHECKED,FormView.Constants.HTML_ATTRS.CHECKED)):(this.widget.checked=!1,this.widget.removeAttribute(FormView.Constants.HTML_ATTRS.CHECKED)),this.widget.value=e,super.updateEmptyStatus()}setModel(e){super.setModel(e),this._onValue=this._model._jsonModel.enum[0],this._offValue=this._model._jsonModel.enum[1],this.widget.addEventListener("change",(e=>{const t=this.widget.checked?this._onValue:this._offValue;this._model.dispatch(new FormView.Actions.UIChange({value:t}))})),this.widget.addEventListener("focus",(e=>{this.setActive(),this.triggerEnter()})),this.widget.addEventListener("blur",(e=>{this.setInactive(),this.triggerExit()}))}},E=class extends m{constructor(e){super(e)}setModel(e){super.setModel(e),null==this.widgetObject&&(this.widgetObject=ne
1w FileInputWidget(this.widgetFields))}updateValue(e){null==this.widgetObject&&(this.widgetObject=new FileInputWidget(this.widgetFields)),this.widgetObject.setValue(e),super.updateEmptyStatus()}syncWidget(){let e=this.getWidget?this.getWidget():null;e&&(e.id=this.getId()+"__widget",this.getAttachButtonLabel().setAttribute("for",this.getId()+"__widget"))}syncLabel(){let e="function"==typeof this.getLabel?this.getLabel():null;e&&e.setAttribute("for",this.getId())}syncMarkupWithModel(){super.syncMarkupWithModel(),this.syncWidget(),this.syncLabel()}},T=class{fileItemSelector=".cmp-adaptiveform-fileinput__fileitem";widget=null;fileArr=[];fileList=null;lang="en";model=null;isFileUpdate=!1;options=null;regexMimeTypeList=[];values=[];invalidFeature={SIZE:1,NAME:2,MIMETYPE:3};extensionToMimeTypeMap={bat:"application/x-msdownload",com:"application/x-msdownload",dll:"application/x-msdownload",exe:"application/x-msdownload",msi:"application/x-msdownload",msg:"application/vnd.ms-outlook",dwg:"image/vnd.dwg",jxr:"image/vnd.ms-photo",psd:"image/vnd.adobe.photoshop",ico:"image/vnd.microsoft.icon",cab:"application/vnd.ms-cab-compressed",deb:"application/vnd.debian.binary-package",sqlite:"application/vnd.sqlite3",inf2:"image/vnd.cns.inf2",djv:"image/vnd.djvu",djvu:"image/vnd.djvu",dxf:"image/vnd.dxf",fbs:"image/vnd.fastbidsheet",fpx:"image/vnd.fpx",fst:"image/vnd.fst",mmr:"image/vnd.fujixerox.edmics-mmr",rlc:"image/vnd.fujixerox.edmics-rlc",pgb:"image/vnd.globalgraphics.pgb",mix:"image/vnd.mix",mdi:"image/vnd.ms-modi",npx:"image/vnd.net-fpx",radiance:"image/vnd.radiance","sealed.png":"image/vnd.sealed.png","softseal.gif":"image/vnd.sealedmedia.softseal.gif","softseal.jpg":"image/vnd.sealedmedia.softseal.jpg",svf:"image/vnd.svf"};initialFileValueFileNameMap;constructor(e){this.widget=e.widget,this.model=e.model(),this.fileList=e.fileListDiv,this.lang=this.model.lang,this.options=Object.assign({},{contextPath:""},this.model._jsonModel),this.attachEventHandlers(e?.widget,e?.dragArea),this.regexMimeTypeList=this.options.accept.map((function(e,t){try{return"*/*"===e.trim()?/.*/:new RegExp(e.trim())}catch(e){window.console&&console.log(e)}}))}attachEventHandlers(e,t){e.addEventListener("change",(e=>{this.handleChange(e?.target?.files)}))}static isValid(e){return/^[^\\/:\*\;\$\%\?"<>\|]+$/.test(e)&&!/^\./.test(e)&&!/^(nul|prn|con|lpt[0-9]|com[0-9])(\.|$)/i.test(e)}getIndexOfText(e,t){let i=-1,n=this,s=!1;return this.values.find((function(r,a){let o=r,l="object"==typeof n.initialFileValueFileNameMap&&void 0!==typeof n.initialFileValueFileNameMap[r]?n._initialFileValueFileNameMap[r]:null;if(o.match(/\//g)&&o.match(/\//g).length>1&&(o=r.substring(r.lastIndexOf("/")+1)),o===e||l===e){if(i=a,s=-1!==n.values.indexOf(r,i+1),t&&s){let e=t.parentNode.parentNode;i=Array.prototype.indexOf.call(e.children,t.parentElement)}return r}})),i}static displaySVG(e){const t=e,i=document.createElement("img");i.src=t;const n=window.open("","_blank","scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no");n?.document?.body.appendChild(i)}static previewFileUsingObjectUrl(e){if(e){if(!window.navigator||!window.navigator.msSaveOrOpenBlob){let t=window.URL.createObjectURL(e);return"image/svg+xml"===e.type?this.displaySVG(t):window.open(t,"","scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no"),t}window.navigator.msSaveOrOpenBlob(e,e.name)}}static previewFile(e){let t=arguments[1].fileUrl,i=t.lastIndexOf("/");i>=0&&-1===t.indexOf("?")&&(t=t.substr(0,i)+"/"+encodeURIComponent(t.substr(i+1))),window.open(t,"","scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no")}handleFilePreview(e){let t=e.target,i=t.textContent,n=this.getIndexOfText(i,t),s=null;if(-1!==n)if(void 0!==t.dataset.key&&(s=t.dataset.key),s&&"[object Blob]"!==s)0!==s.lastIndexOf(this.options.contextPath,0)&&(s=this.options.contextPath+s),FileInputWidget.previewFile.apply(this,[null,{fileUrl:s}]);else{let e=this.fileArr[n]?.data,i=FileInputWidget.previewFileUsingObjectUrl(e);i&&(t.dataset.objectUrl=i)}}handleClick(e){let t=e.target,i=t.previousSibling.textContent,n=this.getIndexOfText(i,t),s=t.previousSibling.dataset.key,r=t.previousSibling.dataset.objectUrl;if(-1!==n){this.values.splice(n,1),this.fileArr.splice(n,1),this.model.value=this.fileArr;let e=Array.from(this.widget.files).findIndex((function(e){return e.name===i}));this.deleteFilesFromInputDom([e]),null!=s&&delete t.previousSibling.dataset.key,r&&window.URL.revokeObjectURL(r)}t.parentElement.remove(),this.widget.focus()}fileItem(e,t,i){let n=this,s=document.createElement("li");s.setAttribute("class","cmp-adaptiveform-fileinput__fileitem");let r=document.createElement("span");r.setAttribute("tabindex","0"),r.setAttribute("class","cmp-adaptiveform-fileinput__filename"),r.setAttribute("aria-label",e),r.textContent=e,r.addEventListener("keypress",(function(e){13!==e.keyCode&&32!==e.charCode||e.target.click()})),r.addEventListener("click",(function(e){n.handleFilePreview(e)})),s.appendChild(r),null!=i&&(r.dataset.key=i);let a=document.createElement("span");return a.setAttribute("tabindex","0"),a.setAttribute("class","cmp-adaptiveform-fileinput__filedelete"),a.setAttribute("aria-label",FormView.LanguageUtils.getTranslatedString(this.lang,"FileCloseAccessText")+e),a.setAttribute("role","button"),a.textContent="x",a.addEventListener("keypress",(function(e){13!==e.keyCode&&32!==e.charCode||e.target.click()})),a.addEventListener("click",(function(e){n.handleClick(e)})),s.appendChild(a),s}isMultiSelect(){return"file[]"===this.options.type||"string[]"===this.options.type}showFileList(e,t,i){if(!this.isMultiSelect()||null==e)for(;this.fileList.lastElementChild;)this.fileList.removeChild(this.fileList.lastElementChild);
1null!=e&&this.fileList.append(this.fileItem(e,t,i))}showInvalidMessage(e,t){let i=this,n=null!==navigator.userAgent.match(/iPad/i),s=null!==navigator.userAgent.match(/iPhone/i);n||s?setTimeout((function(){i.invalidMessage(i,e,t)}),0):this.invalidMessage(e,t)}invalidMessage(e,t){const i=this.options.constraintMessages||{},n={[this.invalidFeature.SIZE]:i.maxFileSize||FormView.LanguageUtils.getTranslatedString(this.lang,"FileSizeGreater",[e,this.options.maxFileSize]),[this.invalidFeature.NAME]:i.invalidFileName||FormView.LanguageUtils.getTranslatedString(this.lang,"FileNameInvalid",[e]),[this.invalidFeature.MIMETYPE]:i.accept||FormView.LanguageUtils.getTranslatedString(this.lang,"FileMimeTypeInvalid",[e])};alert(n[t])}getFileListItem(e){try{let t=new DataTransfer||new ClipboardEvent("").clipboardData;return e.forEach((function(e){t.items.add(e)})),t.files}catch(e){throw console.error(e),e}}updateFilesInDom(e){this.isFileUpdate=!0,this.widget.files=this.getFileListItem(e),this.isFileUpdate=!1}deleteFilesFromInputDom(e){let t=[];Array.from(this.widget.files).forEach((function(i,n){e.includes(n)||t.push(i)}));try{this.updateFilesInDom(t)}catch(e){console.error("Deleting files is not supported in your browser")}}setValue(e){let t=!1;if(null!=e&&(e=Array.isArray(e)?e:[e]),null!=this.fileArr&&null!=e&&(t=JSON.stringify(FormView.FileAttachmentUtils.extractFileInfo(this.fileArr))===JSON.stringify(e)),!t){let t={};for(this.fileList.querySelectorAll(".cmp-adaptiveform-fileinput__filename").forEach((function(e){let i=e.dataset.key;if(void 0!==i){let e=i.substring(i.lastIndexOf("/")+1);t[e]=i}}));this.fileList.lastElementChild;)this.fileList.removeChild(this.fileList.lastElementChild);if(null!=e){let i=this;this.values=e.map((function(e,n){let s=!!window.File&&e.data instanceof window.File,r="string"==typeof e?e:e.name,a="string"==typeof e?e:s?"":e.data;return t[r]&&(a=t[r]),i.showFileList(r,null,a),r})),this.fileArr=[...e]}}}handleChange(e){if(!this.isFileUpdate){let t="",i="",n="",s="",r=this,a=e,o=!1,l=!1,u=!1;if(void 0!==a){let e=[];Array.from(a).forEach((function(a,d){let c=!1,h=!1,p=!1;if(t=a.name.split("\\").pop(),a.size/1024/1024>parseFloat(this.options.maxFileSize))o=c=!0,i=t+","+i;else if(FileInputWidget.isValid(t)){let e=!1,i=t.split(".").pop().toLowerCase(),n=a.type||r.extensionToMimeTypeMap[i];e=!n&&this.options.acceptExtensions?this.options.acceptExtensions.some((function(e){return!!e&&e.replace(/^\./,"").toLowerCase()===i})):this.regexMimeTypeList.some((function(e){return e.test(n)})),e||(u=p=!0,s=t+","+s)}else l=h=!0,n=t+","+n;c||h||p?e.push(d):this.isMultiSelect()?(this.values.push(t),this.fileArr.push(a)):(this.values=[t],this.fileArr=[a])}),this),e.length>0&&null!==this.widget&&this.deleteFilesFromInputDom(e)}this.model.value=this.fileArr,o?this.showInvalidMessage(i.substring(0,i.lastIndexOf(",")),this.invalidFeature.SIZE):l?this.showInvalidMessage(n.substring(0,n.lastIndexOf(",")),this.invalidFeature.NAME):u&&this.showInvalidMessage(s.substring(0,s.lastIndexOf(",")),this.invalidFeature.MIMETYPE)}this.widget.value=null}},M=class extends m{constructor(e){super(e)}updateEnum(e){}updateEnumNames(e){}applyState(e){super.applyState(e),e?.enum&&this.updateEnum(e.enum),e?.enumNames&&this.updateEnumNames(e.enumNames)}updateEnumForRadioButtonAndCheckbox(e,t){let i=this.getWidget().length;0===i?e.forEach((e=>{this.getWidgets().appendChild(t.call(this,e,e))})):i===e.length?this.widget.forEach(((t,i)=>{t.value=e[i]})):i<e.length?(this.widget.forEach(((t,i)=>{t.value=e[i]})),e.forEach(((e,n)=>{n>i-1&&this.getWidgets().appendChild(t.call(this,e,e))}))):this.widget.forEach(((t,i)=>{if(i<e.length)t.value=e[i];else{let e=t.parentElement.parentElement;this.getWidgets().removeChild(e)}}))}updateEnumNamesForRadioButtonAndCheckbox(e,t){let i=this.getWidget().length;0===i?e.forEach((e=>{this.getWidgets().appendChild(t.call(this,e,e))})):i>
1e.length?[...this.getOptions()].forEach(((t,i)=>{let n=t.querySelector("span"),s=t.querySelector("input"),r=i<e.length?e[i]:s.value,a=window.DOMPurify?window.DOMPurify.sanitize(r):r;n.innerHTML=a;let o=`${this._model.label.value}:  ${a}`,l=window.DOMPurify?window.DOMPurify.sanitize(o,{ALLOWED_TAGS:[]}):o;s.hasAttribute("aria-label")&&s.setAttribute("aria-label",l)})):[...this.getOptions()].forEach(((t,i)=>{let n=t.querySelector("span"),s=t.querySelector("input"),r=window.DOMPurify?window.DOMPurify.sanitize(e[i]):e[i];if(n&&(n.innerHTML=r),s&&s.hasAttribute("aria-label")){let e=`${this._model.label.value}:  ${r}`,t=window.DOMPurify?window.DOMPurify.sanitize(e,{ALLOWED_TAGS:[]}):e;s.setAttribute("aria-label",t)}}))}},O=class extends T{attachEventHandlers(e,t,i){super.attachEventHandlers(e,i),t?.addEventListener("dragover",(e=>{e.preventDefault(),t.classList.add("cmp-adaptiveform-fileinput__dragarea--active")})),t?.addEventListener("dragleave",(e=>{t.classList.remove("cmp-adaptiveform-fileinput__dragarea--active")})),t?.addEventListener("drop",(e=>{e.preventDefault(),t.classList.remove("cmp-adaptiveform-fileinput__dragarea--active"),this.handleChange(e?.dataTransfer?.files)})),t?.addEventListener("paste",(e=>{e.preventDefault(),this.handleChange(e?.clipboardData?.files)}))}handleClick(e){let t=e.target,i=t.parentElement.previousSibling.textContent,n=this.getIndexOfText(i,t),s=t.parentElement.previousSibling.dataset.key,r=t.parentElement.previousSibling.dataset.objectUrl;if(-1!==n){this.values.splice(n,1),this.fileArr.splice(n,1),this.model.value=this.fileArr;let e=Array.from(this.widget.files).findIndex((function(e){return e.name===i}));this.deleteFilesFromInputDom([e]),null!=s&&delete t.parentElement.previousSibling.dataset.key,r&&window.URL.revokeObjectURL(r)}t.parentElement.parentElement.remove(),this.widget.focus()}formatBytes(e,t=0){if(!+e)return"0 Bytes";const i=t<0?0:t,n=Math.floor(Math.log(e)/Math.log(1024));return`${parseFloat((e/Math.pow(1024,n)).toFixed(i))} ${["bytes","kb","mb","gb","tb","pb"][n]}`}setValue(e){let t=!1;if(null!=e&&(e=Array.isArray(e)?e:[e]),null!=this.fileArr&&null!=e&&(t=JSON.stringify(FormView.FileAttachmentUtils.extractFileInfo(this.fileArr))===JSON.stringify(e)),!t){let t={};for(this.fileList.querySelectorAll(".cmp-adaptiveform-fileinput__filename").forEach((function(e){let i=e.dataset.key;if(void 0!==i){let e=i.substring(i.lastIndexOf("/")+1);t[e]=i}}));this.fileList.lastElementChild;)this.fileList.removeChild(this.fileList.lastElementChild);if(null!=e){let i=this;this.values=e.map((function(e,n){let s=!!window.File&&e.data instanceof window.File,r="string"==typeof e?e:e.name,a="string"==typeof e?e:s?"":e.data,o=e.size,l=a;return t[r]&&(l=t[r]),i.showFileList(r,o,null,l),r})),this.fileArr=[...e]}else this.values=[],this.fileArr=[],this.widget.value=""}}fileItem(e,t,i,n){let s=this,r=document.createElement("li");r.setAttribute("class","cmp-adaptiveform-fileinput__fileitem");let a=document.createElement("span"),o=document.createElement("span");o.setAttribute("class","cmp-adaptiveform-fileinput__filesize"),o.textContent=this.formatBytes(t),a.setAttribute("tabindex","0"),a.setAttribute("class","cmp-adaptiveform-fileinput__filename"),a.setAttribute("aria-label",e),a.textContent=e,a.addEventListener("keypress",(function(e){13!==e.keyCode&&32!==e.charCode||e.target.click()})),a.addEventListener("click",(function(e){s.handleFilePreview(e)})),r.appendChild(a),null!=n&&(a.dataset.key=n);let l=document.createElement("span"),u=document.createElement("span");return l.setAttribute("class","cmp-adaptiveform-fileinput__fileendcontainer"),u.setAttribute("tabindex","0"),u.setAttribute("class","cmp-adaptiveform-fileinput__filedelete"),u.setAttribute("aria-label",FormView.LanguageUtils.getTranslatedString(this.lang,"FileCloseAccessText")+e),u.setAttribute("role","button"),u.textContent="x",u.addEventListener("keypress",(function(e){13!==e.keyCode&&32!==e.charCode||e.target.click()})),u.addEventListener("click",(function(e){s.handleClick(e)})),l.appendChild(o),l.appendChild(u),r.appendChild(l),r}showFileList(e,t,i,n){if(!this.isMultiSelect()||null==e)for(;this.fileList.lastElementChild;)this.fileList.removeChild(this.fileList.lastElementChild);
1null!=e&&this.fileList.append(this.fileItem(e,t,i,n))}},w=class{#ae;#oe;#le;#ue;constructor(e){this.errors=!1,this.data=e.data,this.#ae=[],this.#oe=[],this.#le=[],this.#ue=this.#le}addMessage(e,t,i){this.errors=!0,this.#ae.push(t),this.#le.push(i),this.#oe.push(e)}getNextMessage(){if(0===this.#oe.length)return null;let e=this.#le.pop();return{code:this.#oe.pop(),somExpression:e,qualifiedName:e,message:this.#ae.pop()}}},I=class{data;contentType;attachments;constructor(e){this.data=e.data,this.contentType="application/json",this.attachments=e.attachments}getData(){return this.data}getContentType(){return this.contentType}getAttachments(){return this.attachments}toHTMLFormData(){let e=new FormData;this.contentType&&e.append("contentType",this.contentType),e.append("data",this.data);for(let t=0;t<this.attachments.length;t++){let i=this.attachments[t];if("undefined"!=typeof File&&i.data instanceof File)e.append("fileAttachments",i.data,i.name);else{let t=new Blob([JSON.stringify({data:i.data,name:i.name,contentType:i.contentType})],{type:"application/json"});e.append("fileAttachments",t)}e.append("fileAttachmentBindRefs",i.dataRef)}return e}toJsObject(){return{data:this.data,contentType:this.contentType,attachments:this.attachments}}};var A=i(6608);window.guideBridge=new class{#de={};#ce=[];#he="";#pe={};ConfigKeys={LOCALE_CONFIG:"localeConfig",RENDER_CONFIG:"renderConfig",SUBMIT_CONFIG:"submitConfig"};constructor(){let e=document.createEvent("CustomEvent");if(e.initCustomEvent(t.GUIDE_BRIDGE_INITIALIZE_START,!0,!0,{guideBridge:this}),window.dispatchEvent(e),window!==window.parent)try{window.parent.document.getElementById(window.name),window.parent.dispatchEvent(e)}catch(e){console.debug("Cross-origin access to parent window blocked")}let i=this;document.addEventListener(t.FORM_CONTAINER_INITIALISED,(function(e){let t=e.detail;i.#de[t.getPath()]=t,i.#fe(t.getPath())}))}#fe(e){this.#ce.forEach((function(t){t.formContainerPath===e&&t.handler.call(t.context),t.formContainerPath||t.handler.call(t.context)}))}getFormDataString(t){let i=this.getFormModel();if(!i)throw new Error("formModel is not defined");(0,e.readAttachments)(i).then((e=>{let n=Object.keys(e).flatMap((t=>e[t])),s=new I({data:JSON.stringify(i.exportData()),attachments:n}),r=new w({data:s});t&&"function"==typeof t.success&&t.success(r)}))}getFormDataObject(e){this.getFormDataString({success:function(t){e&&"function"==typeof e.success&&e.success(t)}})}getFormModel(){if(this.#he)return this.#de[this.#he]?this.#de[this.#he].getModel():null;{const e=this.#me();return this.#he=e,this.#de[e]?this.#de[e].getModel():null}}#me(){let e=this.#he;if(!e)for(let t in this.#de)this.#de.hasOwnProperty(t)&&(e=t);return e}validate(){let e=this.getFormModel();if(!e)throw new Error("formModel is not defined");let t=e.validate();return!(t&&t.length>0)}connect(e,t,i){if(t=t||this,i&&(this.#he=i),!e)throw new Error("handler arg is null");this.isConnected()?e.call(t):this.#ce.push({handler:e,context:t,formContainerPath:i})}isConnected(){return!!this.getFormModel()}disableForm(){let e=this.getFormModel();if(!e)throw new Error("formModel is not defined");e.enabled=!1}reset(){let e=this.getFormModel();if(!e)throw new Error("formModel is not defined");e.dispatch({type:"reset"})}hideSubmitButtons(){if(!this.isConnected())throw new Error("GuideBridge is not connected");this.#ge("submit")}hideResetButtons(){if(!this.isConnected())throw new Error("GuideBridge is not connected");this.#ge("reset")}#ge(e){this.getFormModel().visit((t=>{t.properties["fd:buttonType"]===e&&(t.visible=!1,t.subscribe((e=>
1{e.target.getState(),e.payload.changes.forEach((e=>{"visible"===e.propertyName&&e.currentValue&&(t.visible=!1)}))})))}))}hideSaveButtons(){}hideSummaryPanel(){}trigger(e,t,i){let n;n=i?this.#de[i]:this.#de[this.#me()],n&&n.getFormElement()&&n.getFormElement().dispatchEvent(new CustomEvent(e,{detail:t}))}on(e,t){if(!this.isConnected())throw new Error("GuideBridge is not connected");{const i=this.#de[this.#he];i&&i.getFormElement()&&i.getFormElement().addEventListener(e,t)}}registerConfig(e,t){this.#pe[e]||(this.#pe[e]=[]);const i="function"==typeof t?{fn:t,formContainerPath:this.#he}:{...t,formContainerPath:this.#he};return this.#pe[e].push(i),this.#pe[e]}resolveNode(e){return this.getFormModel().resolveQualifiedName(e)}getConfigsForKey(e){return this.#pe[e]||[]}unloadAdaptiveForm(e){const t=e||this.#he;if(!t)return void console.warn("No form container path specified or available to unload.");let i=null;if(this.#de[t]){const e=this.#de[t];i=e.getFormElement(),"function"==typeof e._disconnectMutationObservers&&e._disconnectMutationObservers()}window.formBridge&&"function"==typeof window.formBridge.destroyForm&&window.formBridge.destroyForm(),1===Object.keys(this.#de).length&&(window.afCache&&"object"==typeof window.afCache.store&&(window.afCache.store={}),[".cmp-adaptiveform-recaptcha__widget",".cmp-adaptiveform-turnstile__widget",".cmp-adaptiveform-hcaptcha__widget",".datetimepicker.datePickerTarget"].forEach((e=>{document.querySelectorAll(e).forEach((e=>e.remove()))})),c._clearState(),window.xfalib&&window.xfalib.ut&&(window.xfalib.ut=null)),i&&i.remove(),delete this.#de[t],this.#he===t&&(this.#he="")}};const C={Click:e.Click,Change:e.Change,Submit:e.Submit,Blur:e.Blur,AddItem:e.AddItem,RemoveItem:e.RemoveItem,UIChange:e.UIChange,Save:e.Save,CustomEvent:e.CustomEvent},N={formatDate:A.formatDate,parseDate:A.parseDate},S={FileObject:e.FileObject,extractFileInfo:e.extractFileInfo,readAttachments:e.readAttachments}})(),window.FormView=n})();
2/*******************************************************************************
3 * Copyright 2024 Adobe
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 ******************************************************************************/
17
18if (typeof window.HamburgerMenu === 'undefined') {
19    window.HamburgerMenu = class HamburgerMenu {
20        static activeItemId = '';
21
22        static bemBlock = 'cmp-adaptiveform-container__hamburger-menu';
23        static nestingSupport = 10;
24    
25        static selectors  = {
26            active: `.${HamburgerMenu.bemBlock}-item--active`,
27            hamburgerMenuMainContainer: `.${HamburgerMenu.bemBlock}-container`,
28            hamburgerMenuTopContainer: {
29                self: `.${HamburgerMenu.bemBlock}-top`,
30                hamburgerMenuIconContainer: `.${HamburgerMenu.bemBlock}-icon-container`,
31                hamburgerMenuIcon: `.${HamburgerMenu.bemBlock}-icon`,
32            },
33            hamburgerMenuWidget: {
34                hamburgerMenu: `.${HamburgerMenu.bemBlock}-dropdown`,
35                hamburgerSubMenu: `.${HamburgerMenu.bemBlock}-submenu`,
36                hamburgerMenuNavLink: `.${HamburgerMenu.bemBlock}-link`,
37                hamburgerMenuCloseNavButton: `.${HamburgerMenu.bemBlock}-button--close`,
38                hamburgerMenuOpenNavButton: `.${HamburgerMenu.bemBlock}-button--open`,
39            },
40            hamburgerMenuMiddleContainer: `.${HamburgerMenu.bemBlock}-middle`,
41            hamburgerMenuBottomContainer: {
42                self: `.${HamburgerMenu.bemBlock}-bottom`,
43                hamburgerMenuActiveItemTitle: `.${HamburgerMenu.bemBlock}-active-item-title`,
44                hamburgerMenuNextNavButton: `.${HamburgerMenu.bemBlock}-button--next`,
45                hamburgerMenuPreviousNavButton: `.${HamburgerMenu.bemBlock}-button--prev`,
46                hamburgerMenuNavButtonsContainer: `.${HamburgerMenu.bemBlock}-navigation-container`,
47            },
48        };
49    
50        static cssClasses = {
51            item: `${HamburgerMenu.bemBlock}-item`,
52            active: `${HamburgerMenu.bemBlock}-item--active`,
53            activeParent: `${HamburgerMenu.bemBlock}-item--activeparent`,
54            hamburgerMenuWidget: {
55                hamburgerMenu: `${HamburgerMenu.bemBlock}-dropdown`,
56                hamburgerSubMenu: `${HamburgerMenu.bemBlock}-submenu`,
57                hamburgerMenuNavLink: `${HamburgerMenu.bemBlock}-link`,
58                hamburgerMenuCloseNavButton: `${HamburgerMenu.bemBlock}-button--close`,
59                hamburgerMenuOpenNavButton: `${HamburgerMenu.bemBlock}-button--open`,
60            },
61        }
62
63        constructor(formContainer) {
64            this.formContainer = formContainer;
65            formContainer._model.subscribe((action) => {
66                const { payload } = action;
67                const { changes, field } = payload;
68                const { items } = field;
69                if (changes && changes.length > 0) {
70                    changes.forEach((change) => {
71                        switch (change.propertyName) {
72                            case "activeChild":
73                                this.#handleActiveItem(field);
74                                break;
75                            case "items":
76                                this.#handleItemsChange(change, items);
77                                break;
78                            case "visible":
79                                this.#updateAttribute(field.id, 'data-panel-visible', field.visible);
80                                break;
81                            case "enabled":
82                                this.#updateAttribute(field.id, 'data-panel-enabled', field.enabled);
83                                break;
84                        }
85                    });
86                }
87            }, "fieldChanged");
88        }
89
90        #updateAttribute(id, attributeName, value) {
91            const element = document.querySelector(`[data-panel-id='${id}']`);
92            if (attributeName === 'data-panel-enabled' && element) {
93                if (value === 'false') {
94                    element.setAttribute('disabled', 'true');
95                } else {
96                    element.removeAttribute('disabled');
97                }
98            }
99            if (element) {
100                element.setAttribute(attributeName, value);
101            }
102        }
103
104        #createListItem(item) {
105            const li = document.createElement('li');
106            const link = document.createElement('a');
107            const textSpan = document.createElement('span');
108            link.href = "#";
109            textSpan.textContent = item?.label?.value;
110            textSpan.setAttribute('tabindex', "0");
111            link.appendChild(textSpan);
112            li.appendChild(link);
113            li.classList.add(HamburgerMenu.cssClasses.item);
114            li.setAttribute('data-panel-id', item?.id);
115            li.setAttribute('data-panel-visible', item?.visible);
116            li.setAttribute('data-panel-enabled', item?.enabled);
117            return li;
118        }
119
120        #handleItemsChange(change, items) {
121            if (change?.prevValue !== null) {
122                document.querySelector(`[data-panel-id='${change?.prevValue?.id}']`)?.remove();
123            } else {
124                items.forEach((item) => {
125                    if (item.id === change.currentValue.id) {
126                        const prevListItem = document.querySelector(`[data-panel-id='${items[change.currentValue.index - 1]?.id}']`);
127                        const newListItem = this.#createListItem(change.currentValue);
128                        prevListItem?.parentNode?.insertBefore(newListItem, prevListItem?.nextSibling);
129                    }
130                });
131            }
132        }
133
134
135        #handleActiveItem(field) {
136            const menu = document.querySelector(HamburgerMenu.selectors.hamburgerMenuWidget.hamburgerMenu);
137            if (field !== null && field) {
138                const activeListItem = document.querySelector(`[data-panel-id='${field.id}']`);
139                if(activeListItem && activeListItem.tagName === 'LI') {
140                    const menuItems = document.querySelectorAll(HamburgerMenu.selectors.hamburgerMenuWidget.hamburgerMenu + ' li');
141                    const fieldModel = this.formContainer?.getField(activeListItem?.getAttribute('data-panel-id'))?.getModel();
142                    const elementID = this.#checkFirstNonPanel(fieldModel);
143                    const targetElement = menu.querySelector("[data-panel-id='"+ elementID + "']");
144                    this.#resetMenuItems(menuItems);
145                    this.#activateCurrentItem(targetElement);
146                    const anchorElement = targetElement?.querySelector('a');
147                    anchorElement?.classList.add(HamburgerMenu.cssClasses.active);
148                    anchorElement?.querySelector('button')?.classList?.toggle(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuCloseNavButton);
149                    this.#updateSelectedPanelTitle(anchorElement);
150                    this.#highlightMenuTree(anchorElement);
151                    this.#renderBreadCrumbs(menu);
152                }
153            }
154        }
155    
156         #updateSelectedPanelTitle(anchorElement, clickedAnchorElement) {
157            const activeItemTitleContent = anchorElement?.innerText;
158            const clickedAnchorElementText = clickedAnchorElement?.innerText;
159            const activeItemTitle = document.querySelector(HamburgerMenu.selectors.hamburgerMenuBottomContainer.hamburgerMenuActiveItemTitle);
160            activeItemTitle.innerText = activeItemTitleContent || clickedAnchorElementText || '';
161        }
162    
163         #checkFirstNonPanel(fieldModel) {
164            if(fieldModel && fieldModel._children && fieldModel._children[0]) {
165                if(fieldModel._children[0]?.fieldType !== 'panel') {
166                    return fieldModel._children[0].parent.id;
167                }
168                return this.#checkFirstNonPanel(fieldModel?._children[0])
169            }
170            return fieldModel?.id;
171        }
172    
173         #clickHandler(event) {
174            const menu = document.querySelector(HamburgerMenu.selectors.hamburgerMenuWidget.hamburgerMenu);
175            event.stopPropagation();
176            let targetElement = event.target.closest('li');    
177            if(targetElement?.getAttribute('data-panel-enabled') === 'false') {
178                return;
179            }
180            if(event.target.tagName === "BUTTON" && (event.target.classList.contains(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuCloseNavButton) || event.target.classList.contains(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuOpenNavButton)))  {
181                const isExpanded = event.target.getAttribute('aria-expanded') === 'true';
182                event.target.classList.toggle(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuCloseNavButton);
183                event.target.setAttribute('aria-expanded', !isExpanded);
184                return;
185            }
186            const menuItems = document.querySelectorAll(HamburgerMenu.selectors.hamburgerMenuWidget.hamburgerMenu + ' li');
187            const fieldModel = this.formContainer?.getModel().getElement(targetElement?.getAttribute('data-panel-id'));
188            const elementID = this.#checkFirstNonPanel(fieldModel) || targetElement?.getAttribute('data-panel-id');
189            
190            const parentAnchorElement = targetElement?.querySelector('a');
191            targetElement = menu.querySelector("[data-panel-id='"+ elementID + "']");
192            this.#resetMenuItems(menuItems);
193            this.#activateCurrentItem(targetElement);
194            const anchorElement = targetElement?.querySelector('a');
195            anchorElement?.classList.add(HamburgerMenu.cssClasse
195s.active);
196            anchorElement?.querySelector('button')?.classList?.toggle(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuCloseNavButton);
197            const isExpanded = anchorElement?.querySelector('button')?.getAttribute('aria-expanded') === 'true';
198            anchorElement?.querySelector('button')?.setAttribute('aria-expanded', !isExpanded);
199            this.#updateSelectedPanelTitle(anchorElement, parentAnchorElement);
200            this.#highlightMenuTree(anchorElement, parentAnchorElement);
201
202            this.formContainer.getModel().getElement('accordion-9fbafbc6e6');
203    
204            const itemId = targetElement?.getAttribute('data-panel-id') || HamburgerMenu.activeItemId;
205            const form = this.formContainer?.getModel();
206            const field = form?.getElement(itemId);
207            menu.style.display = menu.style.display === 'flex' ? 'none' : 'flex';
208            this.#renderBreadCrumbs(menu);
209            if (form && field) {
210              form.setFocus(field);
211            }
212        }
213    
214        #resetMenuItems(menuItems) {
215            menuItems.forEach(item => {
216                const subMenu = item.querySelector(HamburgerMenu.selectors.hamburgerMenuWidget.hamburgerSubMenu);
217                if (subMenu)  {
218                    subMenu.style.display = 'none';
219                    subMenu.setAttribute('aria-hidden', true);
220                }
221                const link = item.querySelector('a');
222                if(link) {
223                    link?.querySelector('button')?.classList.remove(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuCloseNavButton);
224                    link?.querySelector('button')?.classList.add(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuOpenNavButton);
225                    link?.classList.remove(HamburgerMenu.cssClasses.active, HamburgerMenu.cssClasses.activeParent);
226                    link.style.fontWeight = 'normal';
227                }
228            });
229        }
230        
231        #activateCurrentItem(currentItem) {
232            while (currentItem) {
233                const subMenu = currentItem.querySelector(HamburgerMenu.selectors.hamburgerMenuWidget.hamburgerSubMenu);
234                if (subMenu)  {
235                    subMenu.style.display = 'block';
236                    subMenu.setAttribute('aria-hidden', false);
237                }
238                currentItem = currentItem.parentElement.closest('li');
239            }
240        }
241    
242        #menuItemClickHandler(event, subMenu, li, link) {
243            event.preventDefault();
244            if (li.getAttribute('data-panel-enabled') === 'false') {
245                return;
246            }
247            const expanded = link.getAttribute('aria-expanded') === 'true';
248            link.setAttribute('aria-expanded', !expanded);
249            if (subMenu.style.display === 'flex' || subMenu.style.display === 'block') {
250                subMenu.style.display = 'none';
251                subMenu.setAttribute('aria-hidden', true);
252            } else {
253                subMenu.style.display = 'flex';
254                subMenu.setAttribute('aria-hidden', false);
255            }
256        }
257    
258        #createDownArrowButton() {
259            const downArrowButton = document.createElement('button');
260            downArrowButton.type='button';
261            downArrowButton.classList.add(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuOpenNavButton);
262            downArrowButton.setAttribute('aria-expanded', false);
263            return downArrowButton;
264        }
265    
266        #createHamburgerMenu(items, counter = 0) {
267            if (counter >= HamburgerMenu.nestingSupport) {
268                return;
269            }
270            if (!items?.length) return;
271            const ul = document.createElement('ul');
272            let activeItemTitleUpdated = false;
273            items.forEach((item) => {
274                if (item?.fieldType !== "panel") return;
275    
276                if (!activeItemTitleUpdated) {
277                    const activeItemTitle = document.querySelector(HamburgerMenu.selectors.hamburgerMenuBottomContainer.hamburgerMenuActiveItemTitle);
278                    if(activeItemTitle) {
279                        activeItemTitle.innerText = item?.label?.value;
280                        activeItemTitleUpdated = true;
281                    }
282                }
283    
284                const li = document.createElement('li');
285                const link = document.createElement('a');
286                link.setAttribute('role', 'menuitem');
287                link.setAttribute('aria-expanded', 'false');
288                const textSpan = document.createElement('span');
289                textSpan.setAttribute('tabindex', "0");
290                link.href = "#";
291                textSpan.textContent = item?.label?.value;
292                link.appendChild(textSpan);
293                link.style.visibility = item?.label?.visible ? 'visible' : 'hidden';
294                li.appendChild(link);
295
296                li.classList.add(HamburgerMenu.cssClasses.item);
297                li.setAttribute('data-panel-id', item?.id);
298                li.setAttribute('data-panel-visible', item?.visible);
299                li.setAttribute('data-panel-enabled', item?.enabled);
300                const children = this.formContainer?.getModel()?.getElement(item.id)?._children;
301                let flag = false;
302    
303                // setting an attibute(data-panel-has-input) if the item is having an input field
304                if(children) {
305                    for(let i = 0; i< children.length; i++) {
306                        if(children[i].fieldType !== 'panel') {
307                            flag = true;
308                        }
309                    }
310                }
311                if(flag) {
312                    li.setAttribute('data-panel-has-input', flag);
313                }
314    
315                link.classList.add(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuNavLink);
316                if (item?.repeatable) {
317                    const subMenu = this.#createHamburgerMenu(item.items, counter + 1);
318                    subMenu?.childNodes.forEach(child => ul.appendChild(child));
319                } else if (Array.isArray(item.items) && item.items.length > 0) {
320                    const subMenu = this.#createHamburgerMenu(item.items, counter + 1);
321                    if (subMenu?.childNodes?.length) {
322                        subMenu.classList.add(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerSubMenu);
323                        li.appendChild(subMenu);
324                        link.insertBefore(this.#createDownArrowButton(), link.firstChild);
325                        link.addEventListener('click', (event) => {
326                            this.#menuItemClickHandler(event, subMenu, li, link)
327                        });
328                        link.addEventListener('keydown', (event) => {
329                            if(event.key === 'Enter' || event.key === ' ') {
330                                this.#menuItemClickHandler(event, subMenu, li, link);
331                            }
332                        });
333                    }
334                }
335                ul.appendChild(li);
336            });
337        
338            return ul;
339        }
340    
341        // Function to find the currently active li
342        #findActiveLi() {
343            return document.querySelector(HamburgerMenu.selectors.active).parentElement;
344        }
345    
346        #highlightMenuTree(element, parentAnchorElement) {
347            const closestLI = element?.closest('li');
348            const clickedClosestLI = parentAnchorElement?.closest('li');
349    
350            const li = closestLI || clickedClosestLI;
351        
352            if (!li || li === document.body) {
353                return;
354            }
355            let anchorElement = li?.querySelector('a');
356    
357            if(anchorElement) {
358                anchorElement?.classList.add(HamburgerMenu.cssClasses.activeParent);
359                anchorElement?.querySelector('button')?.classList.add(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuCloseNavButton);
360                if(anchorElement?.querySelector('button')?.classList.contains(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuCloseNavButton)) {
361                    anchorElement?.querySelector('button')?.setAttribute('aria-expanded', true);
362                }
363                if(li.parentElement.classList.contains(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenu)) {
364                    anchorElement.style.fontWeight = 'bold'
365                }
366                this.#highlightMenuTree(li.parentElement);
367            }
368        }
369    
370        #isEligible(element, direction) {
371            if (element && element?.getAttribute('data-panel-visible') === 'false' || element?.getAttribute('data-panel-enabled') === 'false' || (direction === 'prev' && element?.getAttribute('data-panel-has-input') !== 'true')) {
372                return false;
373            } else if (element && element.parentNode && element.parentNode !== document) {
374                return this.#isEligible(element.parentNode);
375            } else {
376                return true;
377            }
378        }
379
380        #moveTo(menuListItems, direction) {
381            const currentActive = this.#findActiveLi();
382            if (!currentActive) return;
383        
384            let newActiveItemIndex = -1;
385            menuListItems.forEach((item, index) => {
386                if (item.getAttribute('data-panel-id') === currentActive.getAttribute('data-panel-id')) {
387                    newActiveItemIndex = direction === 'prev' ? index - 1 : index + 1;
388                }
389            });
390        
391            if (direction === 'prev' && newActiveItemIndex < 0) {
392                newActiveItemIndex = menuListItems.length - 1;
393            }
394            while (!this.#isEligible(menuListItems[newActiveItemIndex], direction)) {
395                if(direction === 'prev') {
396                    newActiveItemIndex = (newActiveItemIndex - 1) % menuListItems.length;
397                    if(newActiveItemIndex<=0) {
398                        newActiveItemIndex = 0;
399                        break;
400                    }
401                } else {
402                    newActiveItemIndex = (newActiveItemIndex + 1) % menuListItems.length;
403                }
404            }
405            const newActiveItem = menuListItems[newActiveItemIndex];
406            HamburgerMenu.activeItemId = newActiveItem?.getAttribute('data-panel-id');
407            newActiveItem?.click();
408        }
409    
410        #movePrev(menuListItems) {
411            this.#moveTo(menuListItems, 'prev');
412        }
413        
414        #moveNext(menuListItems) {
415            this.#moveTo(menuListItems, 'next');
416        }
417    
418        #addEventsToNavigationButtons() {
419            const previousNavButton = document.querySelector(HamburgerMenu.selectors.hamburgerMenuBottomContainer.hamburgerMenuPreviousNavButton);
420            const nextNavButton = document.querySelector(HamburgerMenu.selectors.hamburgerMenuBottomContainer.hamburgerMenuNextNavButton);
421            const menuListItems = document.querySelector(HamburgerMenu.selectors.hamburgerMenuWidget.hamburgerMenu).querySelectorAll('li');
422            previousNavButton.addEventListener('click', () => this.#movePrev(menuListItems));
423            nextNavButton.addEventListener('click', () => this.#moveNext(menuListItems));
424        }
425    
426        #generateBreadcrumbs(breadcrumbs) {
427            const container = document.createElement('nav');
428            container.setAttribute('aria-label', 'Breadcrumb');
429            const list = document.createElement('ul');
430            list.style.listStyleType = 'none';
431            list.style.padding = '0';
432            list.style.margin = '0';
433            if(breadcrumbs && breadcrumbs.length) {
434                [...breadcrumbs].forEach((breadcrumb, index) => {
435                    const listItem = document.createElement('li');
436                    listItem.style.display = 'inline';
437                    const span = document.createElement('span');
438                    span.textContent = breadcrumb.innerText;
439                    listItem.appendChild(span);
440                    if (index < breadcrumbs.length - 1) {
441                        const separator = document.createElement('span');
442                        separator.textContent = ' > ';
443                        separator.style.margin = '0 5px';
444                        listItem.appendChild(separator);
445                    }
446                    if(index  ===  breadcrumbs?.length-1) {
447                        listItem.style.fontWeight = 'bold';
448                    }
449                    list.appendChild(listItem);
450                });
451            }
452            container.appendChild(list);
453            return container;
454        }
455    
456        #renderBreadCrumbs(menu) {
457            const selectedPanels = menu.getElementsByClassName(HamburgerMenu.cssClasses.activeParent);
458            const breadCrumbsContainer = document.querySelector(HamburgerMenu.selectors.hamburgerMenuMiddleContainer);
459            breadCrumbsContainer.innerHTML = '';
460            const breadCrumbs = this.#generateBreadcrumbs(selectedPanels)
461            breadCrumbsContainer.appendChild(breadCrumbs);
462            breadCrumbsContainer.scrollLeft = breadCrumbs.scrollWidth;
463        }
464    
465        #renderHamburgerItems(panels) {
466            const parentContainer = document.querySelector(HamburgerMenu.selectors.hamburgerMenuTopContainer.self);
467            const hamburgerIcon = document.querySelector(HamburgerMenu.selectors.hamburgerMenuTopContainer.hamburgerMenuIcon);
468            const hamburgerMenuIconContainer = document.querySelector(HamburgerMenu.selectors.hamburgerMenuTopContainer.hamburgerMenuIconContainer);
469    
470            const menu = this.#createHamburgerMenu(panels);
471            if(menu) {
472                menu.classList.add(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenu);
473                menu.setAttribute('role', 'menu');
474                menu.setAttribute('id', 'hamburger-menu');
475    
476                this.#attachHamburgerEventListeners(hamburgerIcon, menu);
477                this.#attachOutsideClickHandler(hamburgerIcon, menu);
478                this.#attachMenuEventListeners(menu);
479                this.#styleSubmenuItems(menu);
480                parentContainer.innerHTML='';
481                parentContainer.appendChild(hamburgerMenuIconContainer);
482                parentContainer.appendChild(menu);
483    
484                // Add events to navigation buttons
485                this.#addEventsToNavigationButtons();
486    
487                 // Automatically click the first root list item if it exists
488                const rootListItems = menu.querySelectorAll(HamburgerMenu.selectors.hamburgerMenuWidget.hamburgerMenu + ' > li');
489                if (rootListItems[0] && rootListItems[0].tagName === 'LI') {
490                    rootListItems[0].click();
491                    menu.style.display = 'none';
492                }
493            }
494        }
495    
496        #attachMenuEventListeners(menu) {
497            menu.addEventListener('click', (event) => this.#clickHandler(event));
498            menu.addEventListener('keydown', (event) => {
499                if (event.key === 'Enter' || event.key === ' ') {
500                  event.preventDefault();
501                  this.#clickHandler(event);
502                }
503              });
504            menu.addEventListener('ontouchstart', (event) => this.#clickHandler(event));
505        }
506    
507        #attachHamburgerEventListeners(hamburgerIcon, menu) {
508            const toggleMenuVisibility = () => {
509                menu.style.display = menu.style.display === 'flex' ? 'none' : 'flex';
510            };
511            hamburgerIcon?.addEventListener('click', toggleMenuVisibility);
512            hamburgerIcon?.addEventListener('ontouchstart', toggleMenuVisibility);
513        }
514        
515        #styleSubmenuItems(menu) {
516            const rootListItems = menu.querySelectorAll(HamburgerMenu.selectors.hamburgerMenuWidget.hamburgerMenu + ' > li');
517            rootListItems.forEach((item) => {
518                let padding = 30;
519                const submenus = item.querySelectorAll(HamburgerMenu.selectors.hamburgerMenuWidget.hamburgerSubMenu);
520                submenus.forEach((submenu) => {
521                    const links = submenu.querySelectorAll('a');
522                    links.forEach((link) => {
523                        if(link.querySelector('button')) {
524                             link.style.paddingInlineStart = `${padding}px`;
525                        } else {
526                            link.style.paddingInlineStart = `${padding + 30}px`;
527                        }
528                    });
529                    padding += 15;
530                });
531            });
532        }
533    
534        #attachOutsideClickHandler(hamburger, menu) {
535            window.addEventListener('click', (e) => {
536                if (!hamburger.contains(e.target) && !menu.contains(e.target) && menu.style.display === 'flex') {
537                    menu.style.display = 'none';
538                }
539            });
540        }
541    
542        #getAllPanels() {
543            let items = this.formContainer?._model.getItemsState() || [];
544            const panels = items.filter(item => item?.fieldType ===  "panel");
545            return panels;
546        }
547    
548        init() {
549            if(this.formContainer?.getModel()?.properties?.['fd:isHamburgerMenuEnabled']) {
550                document.querySelector('.cmp-adaptiveform-container')?.setAttribute('data-cmp-hamburger-menu-enabled', 'true');
551                const panels = this.#getAllPanels();
552                this.#renderHamburgerItems(panels);
553            }
554        }
555    }
556}
557/*******************************************************************************
558 * Copyright 2024 Adobe
559 *
560 * Licensed under the Apache License, Version 2.0 (the "License");
561 * you may not use this file except in compliance with the License.
562 * You may obtain a copy of the License at
563 *
564 *     http://www.apache.org/licenses/LICENSE-2.0
565 *
566 * Unless required by applicable law or agreed to in writing, softw
566are
567 * distributed under the License is distributed on an "AS IS" BASIS,
568 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
569 * See the License for the specific language governing permissions and
570 * limitations under the License.
571 ******************************************************************************/
572
573(function() {
574
575    "use strict";
576    class FormContainerV2 extends FormView.FormContainer {
577        static NS = FormView.Constants.NS;
578        static IS = "adaptiveFormContainer";
579        static bemBlock = 'cmp-adaptiveform-container';
580        static selectors  = {
581            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
582        };
583        static loadingClass = `${FormContainerV2.bemBlock}--loading`;
584        #hamburgerMenuInstance = '';
585
586        constructor(params) {
587            super(params);
588            let self = this;
589            this.#hamburgerMenuInstance = new HamburgerMenu(this);
590            this._model.subscribe((action) => {
591                let state = action.target.getState();
592                // execute the handler only if there are no rules configured on submitSuccess event.
593                if (!state.events.submitSuccess || state.events.submitSuccess.length === 0) {
594                    const globals = {
595                        form: self.getModel().getRuleNode(),
596                        event: {
597                            type: action.type,
598                            payload: action.payload,
599                        }
600                    };
601                    FormView.customFunctions.defaultSubmitSuccessHandler(globals);
602                }
603            }, "submitSuccess");
604            this._model.subscribe((action) => {
605                let state = action.target.getState();
606                // execute the handler only if there are no rules configured on submitError event.
607                if (!state.events.submitError || state.events.submitError.length === 0) {
608                    let defaultSubmissionError = FormView.LanguageUtils.getTranslatedString(self.getLang(), "InternalFormSubmissionError");
609                    const globals = {
610                        form: self.getModel().getRuleNode(),
611                        formModel: self.getModel(),
612                        event: {
613                            type: action.type,
614                            payload: action.payload,
615                        }
616                    };
617                    FormView.customFunctions.defaultSubmitErrorHandler(defaultSubmissionError, globals);
618                }
619            }, "submitError");
620            this._model.subscribe((action) => {
621                let state = action.target.getState();
622                // execute the handler only if there are no rules configured on custom:saveSuccess event.
623                if (!state.events['custom:saveSuccess'] || state.events['custom:saveSuccess'].length === 0) {
624                    console.log("Draft id = " + action?.payload?.body?.draftId);
625                    window.alert(FormView.LanguageUtils.getTranslatedString(self.getLang(), "saveDraftSuccessMessage"));
626                }
627            }, "saveSuccess");
628            this._model.subscribe((action) => {
629                let state = action.target.getState();
630                // execute the handler only if there are no rules configured on custom:saveError event.
631                if (!state.events['custom:saveError'] || state.events['custom:saveError'].length === 0) {
632                    window.alert(FormView.LanguageUtils.getTranslatedString(self.getLang(), "saveDraftErrorMessage"));
633                }
634            }, "saveError");
635            this.#setupAutoSave(self.getModel());
636        }
637
638        initialiseHamburgerMenu() {
639            this.#hamburgerMenuInstance.init();
640        }
641
642        /**
643         * Register time based auto save
644         * @param formModel.
645         */
646         #setupAutoSave(formModel) {
647            const autoSaveProperties = formModel?.properties?.['fd:autoSave'];
648            const enableAutoSave = this.#getAutoSaveAttribute();
649            if (enableAutoSave) {
650                const autoSaveStrategyType = autoSaveProperties['fd:autoSaveStrategyType'];
651                const autoSaveInterval = autoSaveProperties['fd:autoSaveInterval'];
652                const saveEndPoint = FormView.Utils.getContextPath() + '/adobe/forms/af/save/' + formModel.id;
653                if (autoSaveStrategyType === 'time' && autoSaveInterval) {
654                    console.log("Registering time based auto save");
655                    setInterval(() => {
656                        formModel.dispatch(new FormView.Actions.Save({
657                            'action': saveEndPoint
658                        }));
659                    }, parseInt(autoSaveInterval) * 1000);
660                }
661            }
662        }
663
664        #getAutoSaveAttribute() {
665            return this.getFormElement()?.getAttribute('data-cmp-auto-save') === 'true';
666        }
667    }
668
669    async function onDocumentReady() {
670        const startTime = new Date().getTime();
671        let elements = document.querySelectorAll(FormContainerV2.selectors.self);
672
673        for (let i = 0; i < elements.length; i++) {
674            let loaderToAdd = document.querySelector("[data-cmp-adaptiveform-container-loader='"+ elements[i].id + "']");
675            if(loaderToAdd){
676                loaderToAdd.classList.add(FormContainerV2.loadingClass);
677            }
678            console.debug("Form loading started", elements[i].id);
679        }
680        function onInit(e) {
681            let formContainer =  e.detail;
682            let formEl = formContainer.getFormElement();
683            formContainer.initialiseHamburgerMenu();
684            setTimeout(() => {
685                let loaderToRemove = document.querySelector("[data-cmp-adaptiveform-container-loader='"+ formEl.id + "']");
686                if(loaderToRemove){
687                    loaderToRemove.classList.remove(FormContainerV2.loadingClass);
688                }
689                const timeTaken = new Date().getTime() - startTime;
690                console.debug("Form loading complete", formEl.id, timeTaken);
691                }, 10);
692        }
693        document.addEventListener(FormView.Constants.FORM_CONTAINER_INITIALISED, onInit);
694        await FormView.Utils.setupFormContainer(async ({
695            _formJson, _prefillData, _path, _element
696        }) => {
697            let formContainer = new FormContainerV2({_formJson, _prefillData, _path, _element});
698            // before initializing the form container load all the locale specific json resources
699            // for runtime
700            const formLanguage = formContainer.getLang();
701            const aemLangUrl = `/etc.clientlibs/core/fd/af-clientlibs/core-forms-components-runtime-all/resources/i18n/${formLanguage}.json`;
702            await FormView.LanguageUtils.loadLang(formLanguage, aemLangUrl, true);
703            formContainer.subscribe();
704            return formContainer;
705        }, FormContainerV2.selectors.self, FormContainerV2.IS);
706    }
707
708    // This is to ensure that the there is no WCM Mode cookie when Form Container is rendered.
709    // max-age=0 ensures that the cookie is deleted.
710    document.cookie="wcmmode=disabled; max-age=0; path=/";
711    
712    if (document.readyState !== "loading") {
713        onDocumentReady();
714    } else {
715        document.addEventListener("DOMContentLoaded", onDocumentReady);
716    }
717})();
718
719/*******************************************************************************
720 * Copyright 2023 Adobe
721 *
722 * Licensed under the Apache License, Version 2.0 (the "License");
723 * you may not use this file except in compliance with the License.
724 * You may obtain a copy of the License at
725 *
726 *     http://www.apache.org/licenses/LICENSE-2.0
727 *
728 * Unless required by applicable law or agreed to in writing, software
729 * distributed under the License is distributed on an "AS IS" BASIS,
730 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
731 * See the License for the specific language governing permissions and
732 * limitations under the License.
733 ******************************************************************************/
734(function() {
735
736    "use strict";
737    class Cache {
738
739        store = {};
740
741        put(el, key, value) {
742            this.store[el.id ] = {};
743            this.store[el.id][key] = value;
744        }
745
746        get(el, key) {
747            return this.store[el.id][key];
748        }
749    }
750    window.afCache = new Cache();
751})();
752
753/*******************************************************************************
754 * Copyright 2022 Adobe
755 *
756 * Licensed under the Apache License, Version 2.0 (the "License");
757 * you may not use this file except in compliance with the License.
758 * You may obtain a copy of the License at
759 *
760 *     http://www.apache.org/licenses/LICENSE-2.0
761 *
762 * Unless required by applicable law or agreed to in writing, software
763 * distributed under the License is distributed on an "AS IS" BASIS,
764 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
765 * See the License for the specific language governing permissions and
766 * limitations under the License.
767 ******************************************************************************/
768(function() {
769
770    "use strict";
771    class DatePicker extends FormView.FormFieldBase {
772
773        static NS = FormView.Constants.NS;
774        static IS = "adaptiveFormDatePicker";
775        static bemBlock = 'cmp-adaptiveform-datepicker';
776        static selectors  = {
777            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
778            widget: `.${DatePicker.bemBlock}__widget`,
779            label: `.${DatePicker.bemBlock}__label`,
780            description: `.${DatePicker.bemBlock}__longdescription`,
781            qm: `.${DatePicker.bemBlock}__questionmark`,
782            errorDiv: `.${DatePicker.bemBlock}__errormessage`,
783            tooltipDiv: `.${DatePicker.bemBlock}__shortdescription`
784        };
785
786        constructor(params) {
787            super(params);
788        }
789
790        getWidget() {
791            return this.element.querySelector(DatePicker.selectors.widget);
792        }
793
794        getDescription() {
795            return this.element.querySelector(DatePicker.selectors.description);
796        }
797
798        getLabel() {
799            return this.element.querySelector(DatePicker.selectors.label);
800        }
801
802        getErrorDiv() {
803            return this.element.querySelector(DatePicker.selectors.errorDiv);
804        }
805
806        getQuestionMarkDiv() {
807            return this.element.querySelector(DatePicker.selectors.qm);
808        }
809
810        getTooltipDiv() {
811            return this.element.querySelector(DatePicker.selectors.tooltipDiv);
812        }
813
814        updateValue(value) {
815            if (this.widgetObject) {
816                if (this.isActive()) {
817                    // Replacing undefined / null with empty string on reset
818                    this.widgetObject.setValue(value || '');
819                } else {
820                    // Replacing undefined / null with empty string on reset
821                    this.widgetObject.setDisplayValue(value || '');
822                }
823            } else {
824                // Replacing undefined / null with empty string on reset
825                super.updateValue(value || '');
826            }
827        }
828
829        updateReadOnly(readOnly, state) {
830            super.updateReadOnly(readOnly, state);
831            if (this.widgetObject != null) {
832                this.widgetObject.markAsReadOnly(readOnly);
833            }
834        }
835
836
837        setModel(model) {
838            super.setModel(model);
839            if (!this.#noFormats()) {
840                if (this.widgetObject == null) {
841                    this.widgetObject = new DatePickerWidget(this, this.getWidget(), model);
842                }
843                if (this.isActive()) {
844                    this.widgetObject.setValue(model.value);
845                } else {
846                    this.widgetObject.setDisplayValue(model.value);
847                }
848                this.widgetObject.addEventListener('blur', (e) => {
849                    this.setModelValue(this.widgetObject.getValue())
850                    //setDisplayValue is required for cases where value remains same while focussing in and out.
851                    this.widgetObject.setDisplayValue(this._model.value);
852                    this.widgetObject.setCalendarWidgetValue(this._model.value);
853                    this.setInactive();
854                    this.triggerExit();
855                }, this.getWidget());
856                this.widgetObject.addEventListener('focus', (e) => {
857                    this.widgetObject.setValue(e.target.value);
858                    this.setActive();
859                    this.triggerEnter();
860                }, this.getWidget());
861                this.widgetObject.addEventListener('input', (e) => {
862                    if( e.target.value === '') {
863                        // clear the value if user manually empties the value in date input box
864                        this.setModelValue("");
865                    }
866                }, this.getWidget());
867            } else {
868                if (this.widget.value !== '') {
869                    this.setModelValue(this.widget.value);
870                }
871                this.widget.addEventListener('blur', (e) => {
872                    this.setModelValue(e.target.value);
873                    this.setInactive();
874                    this.triggerExit();
875                });
876                this.widget.addEventListener('focus', (e) => {
877                    this.setActive();
878                    this.triggerEnter();
879                });
880            }
881        }
882
883        #noFormats() {
884            return (this._model.editFormat == null || this._model.editFormat === 'date|short') &&
885                (this._model.displayFormat == null || this._model.displayFormat === 'date|short') && (this._model.displayValueExpression == null)
886        }
887    }
888
889    FormView.Utils.setupField(({element, formContainer}) => {
890        return new DatePicker({element, formContainer})
891    }, DatePicker.selectors.self);
892})();
893
894/*******************************************************************************
895 * Copyright 2023 Adobe
896 *
897 * Licensed under the Apache License, Version 2.0 (the "License");
898 * you may not use this file except in compliance with the License.
899 * You may obtain a copy of the License at
900 *
901 *     http://www.apache.org/licenses/LICENSE-2.0
902 *
903 * Unless required by applicable law or agreed to in writing, software
904 * distributed under the License is distributed on an "AS IS" BASIS,
905 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
906 * See the License for the specific language governing permissions and
907 * limitations under the License.
908 ******************************************************************************/
909
910if (typeof window.DatePickerWidget === 'undefined') {
911
912  window.DatePickerWidget = class {
913
914    #widget = null;
915    #model = null // passed by reference
916    #options = null
917
918    #lang = "en";
919
920    #dp = null;
921    #curInstance = null;
922    #calendarIcon = null;
923    #documentTouchListener = null;
924    static #visible = false;
925    static #clickedWindow;
926
927    /** default configuration options
928     *
929     * yearsPerView: number of years to show in the yearset view
930     *
931     * width: with of the widget
932     *
933     * viewHeight: Height of the month,year and yearset view. This doesn't include
934     *             the height of the header
935     *
936     * locale: locale information for the locale in which to show the datepicker which comprises of
937     *        days: day names to display in the monthview
938     *        months: month names to display in the yearview
939     *        zero: string representation of zero in the locale. Numbers will be
940     *              displayed in that locale only
941     *        clearText: Text to display for the reset button
942     *        name: name of the locale
943     *
944     * format: input format for the datepicker (not implemented)
945     *
946     * pickerType: type of the datetimepicker (date, datetime and time)
947     *
948     * positioning: element around which datepicker will be displayed. if null then it
949     *              will be displayed around the input element
950     *
951     * showCalendarIcon: to show the Calendar on the right of the text field or not
952     */
953    #defaultOptions = {
954      yearsPerView: 16,
955      width: 340,
956      viewHeight: 248,
957      locale: {
958        days: ["S","M","T","W","T","F","S"],
959        months: ["January","February","March","April","May","June","July","August","September","October","November","December"],
960        zero: "0",
961        clearText: "Clear",
962        name: "en_US"
963      },
964      format: "YYYY-MM-DD",
965      pickerType: "date",
966      positioning: null,
967      showCalendarIcon: true
968    }
969
970    #dates = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
971    /*
972     *  Actions to perform when clicked on the datepicker buttons
973     *  for different views
974     *  caption: view to show when clicked on caption
975     *           (Year/YearSet/Month/null) null means don't change the view
976     *  li: view to show when clicked on date, month or year element
977     *  upDown: add(up key) or subtract(down key) current date (for monthview),
978     *          month(Year View) or year(YearSetView) with the number provided
979     *  key: identifies the key that needs to be changed for that view
980     */
981    #viewAction = {
982      Month: {
983        caption: 'Year',
984        li: null,
985        key: "day",
986        upDown: 7
987      },
988      Year: {
989        caption: "Yearset",
990        li: "Month",
991        key: "month",
992        upDown: 3
993      },
994      Yearset: {
995        caption: null,
996        li: "Year",
997        key: "year",
998        upDown: 4
999      }
1000    }
1001
1002    selectedDay = 0;
1003    selectedMonth = 0;
1004    selectedYear = 0;
1005    currentDay = 0;
1006    currentMonth = 0;
1007    currentYear = 0;
1008    //view="Month";
1009    #touchSupported = !!("ontouchstart" in window || window.DocumentTouch
1010        && document instanceof DocumentTouch);
1011    #defaultView = "Month";
1012    #keysEnabled = false;
1013    #focusedOnLi = false;
1014    #keyboardAccessibility = true;
1015    #scriptFocus;
1016
1017    /* template for the clear Button */
1018    #clearButtonTemplate = '<div class="dp-clear">' +
1019        '<a></a>' +
1020        '</div>';
1021
1022    /* template for the calendar
1023    * header contains the navigation icons (left and right arrows)
1024    * and the current caption (which can be date, year or month)
1025    *
1026    * monthview displays the grid for showing the dates for a particular
1027    * month
1028    *
1029    * yearview displays all the months of that year
1030    *
1031    * yearsetview displays a grid of 16 years. This can be configured
1032    * through the option: yearsPerView
1033    *
1034    */
1035    #calendarTemplate = '<div class="dp-header">' +
1036        '<div class="dp-leftnav"></div>' +
1037        '<div class="dp-caption"></div>' +
1038        '<div class="dp-rightnav"></div>' +
1039        '</div>' +
1040        '<div class="view dp-monthview" role="grid" aria-labelledby="dp-caption"></div>' +
1041        '<div class="view dp-yearview" role="grid" aria-labelledby="dp-caption"></div>' +
1042        '<div class="view dp-yearsetview" role="grid" aria-labelledby="dp-caption"></div>';
1043
1044    constructor(view, widget, model) {
1045      this.#model = model;
1046      this.#lang = view.getModel().lang;
1047      let editValFn = () => {
1048        return model.editValue;
1049      };
1050      let displayValueFn = () => {
1051        return model.displayValue;
1052      };
1053      this.#localizeDateElements(this.#defaultOptions, this.#lang);
1054      this.#options = Object.assign(
1055          {editValue: editValFn, displayValue: displayValueFn},
1056          this.#defaultOptions, this.#model._jsonModel);
1057
1058      this.#initialiseCalenderElement();
1059
1060      //update widget markup to have input type=text element.
1061      let newDatePickerElement = widget.cloneNode(true);
1062      newDatePickerElement.setAttribute("type", "text");
1063      newDatePickerElement.id = model.id + '-widget';
1064
1065      widget.parentNode.replaceChild(newDatePickerElement, widget);
1066      this.#widget = view.getWidget();
1067      this.#attachField(view.getWidget(), this.#options);
1068    }
1069
1070    #initialiseCalenderElement() {
1071      let self = this,
1072          html = "";
1073      if (this.#options.pickerType.match(/date/)) {
1074        html += this.#calendarTemplate;
1075      }
1076      html += this.#clearButtonTemplate;
1077
1078      if (!this.#dp) {
1079        this.#dp = document.createElement("div");
1080        this.#dp.classList.add("datetimepicker", "datePickerTarget");
1081        this.#dp.innerHTML = html;
1082        //Always inserting it in body
1083        document.body.appendChild(this.#dp);
1084      }
1085      // attach click event on entire datePicker popup
1086      this.#dp.addEventListener("click",
1087          function (evnt) {
1088            //focus only if the device doesn't support touch
1089            // input otherwise on screen keyboard will popup
1090            if (!self.#touchSupported) {
1091              if (self.#curInstance) {
1092                self.#curInstance.$field.focus();
1093              }
1094            }
1095          }, false);
1096      "touchstart mousedown".split(" ").forEach(function (e) {
1097        self.#dp.addEventListener(e, function (evt) {
1098          self.#checkWindowClicked(evt)
1099        }, false);
1100      });
1101
1102      this.$month = this.#dp.getElementsByClassName("dp-monthview")[0];
1103      this.$year = this.#dp.getElementsByClassName("dp-yearview")[0];
1104      this.$yearset = this.#dp.getElementsByClassName("dp-yearsetview")[0];
1105
1106      this.clear = this.#dp.getElementsByClassName(
1107          "dp-clear")[0].getElementsByTagName("a")[0];
1108      this.clear.addEventListener("click", function (evnt) {
1109        if (self.view && self.#curInstance) {
1110          self.#clearDate(self.view);
1111        }
1112      });
1113      this.prevNavWidthBtn = this.#dp.getElementsByClassName("dp-leftnav")[0];
1114      this.prevNavWidthBtn.addEventListener("click",
1115          function (evnt) {
1116            if (self.view && self.#curInstance) {
1117              self.#adjustDate(-1, self.view, false)
1118            }
1119          });
1120      this.nextNavWidthBtn = this.#dp.getElementsByClassName("dp-rightnav")[0];
1121      this.nextNavWidthBtn.addEventListener("click",
1122          function (evnt) {
1123            if (self.view && self.#curInstance) {
1124              self.#adjustDate(1, self.view, false)
1125            }
1126          });
1127      this.caption = this.#dp.getElementsByClassName("dp-caption")[0];
1128      this.caption.id = "dp-caption";
1129      this.caption.addEventListener("click",
1130          function (evnt) {
1131            if (self.view && self.#curInstance) {
1132              if (!self.caption.classList.contains("disabled")) {
1133                self.#layout(self.#viewAction[self.view].caption);
1134              }
1135            }
1136          });
1137      if (this.#keyboardAccessibility) {
1138        [this.prevNavWidthBtn, this.caption, this.nextNavWidthBtn,
1139          this.clear].forEach(function (elem, i) {
1140          elem.setAttribute("tabIndex", i + 1);
1141        });
1142      }
1143
1144    }
1145
1146    /*
1147     * attaches the date picker to the field. This is a one time operation
1148     * First creates a configuration object and stores it in the field data attributes
1149     * then attaches event handlers on click, focus (to show the picker) and blur 
1149(to hide) events
1150     */
1151    #attachField(widget, options) {
1152      let inst = this.#newInst(widget, options),
1153          self = this,
1154          activateField = function (evnt) {
1155            if (!self.#curInstance) {
1156              self.#activateField(evnt);
1157            }
1158
1159            if (self.#options.showCalendarIcon) {
1160              if (evnt.type === self.#getEvent()) {
1161                if (self._iconClicked) {
1162                  self._iconClicked = false;
1163                  if (DatePickerWidget.#visible) {
1164                    self.#hide(); // hide the calendar popup if visible when calendar icon is clicked
1165                    self.#curInstance.$field.focus(); // bring back focus in field
1166                  } else {
1167                    self.#show(); //// show the calendar popup if not visible when calendar icon is clicked
1168                  }
1169                }
1170              }
1171            } else {
1172              /*show the popup only if
1173               1. click/touch event
1174               2. focus event in case of non-touch devices and focus is not done using script
1175               */
1176              if (evnt.type === self.#getEvent() || (evnt.type === "focus"
1177                  && !self.#touchSupported && !self.#scriptFocus)) {
1178                self.#show(evnt);
1179              }
1180            }
1181
1182            DatePickerWidget.#clickedWindow = true;
1183            self.#scriptFocus = false;
1184          },
1185          deactivateField = function (evnt) {
1186            //deactivate only if clicked outside window
1187            // on touch devices only keyboard or calendar should be active at once, touching keyboard should deactivate calendar
1188            if ((DatePickerWidget.#clickedWindow && !self.#focusedOnLi)
1189                && (self.#options.showCalendarIcon || !self.#touchSupported)) {
1190              self.#hide();
1191              self.#deactivateField();
1192              DatePickerWidget.#clickedWindow = true;
1193            }
1194          };
1195
1196      window.afCache.put(widget, "datetimepicker", inst);
1197
1198      widget.addEventListener(this.#getEvent(), activateField);
1199      widget.onfocus = activateField;
1200      widget.onblur = deactivateField;
1201
1202      if (options.showCalendarIcon) {
1203        let existingCalendarIcons = widget.parentNode.querySelectorAll('.cmp-adaptiveform-datepicker__calendar-icon');
1204        existingCalendarIcons.forEach(icon => icon.remove());
1205
1206        let calendarIcon = document.createElement("div");
1207        calendarIcon.classList.add("cmp-adaptiveform-datepicker__calendar-icon");
1208
1209        widget.parentNode.insertBefore(calendarIcon, widget.nextSibling);
1210
1211        if (this.#keyboardAccessibility) {
1212          calendarIcon.setAttribute("tabindex", 0);
1213        }
1214        calendarIcon.addEventListener(this.#getEvent(), function (evnt) {
1215          self._iconClicked = true;
1216          widget.click();
1217        });
1218        calendarIcon.addEventListener("keydown", function (event) {
1219          if (event.keyCode === 32 || event.keyCode === 13) {
1220            event.preventDefault();
1221            event.stopPropagation();
1222            self._iconClicked = true;
1223            widget.click();
1224          }
1225        });
1226        this.#calendarIcon = calendarIcon;
1227        if (options.readOnly) {
1228          this.markAsReadOnly(true)
1229        }
1230      }
1231    }
1232
1233    markAsReadOnly(readonly) {
1234      if (readonly) {
1235        this.#calendarIcon.style.display = "none";
1236      } else {
1237        this.#calendarIcon.style.display = "";
1238      }
1239    }
1240
1241    #newInst(widget, options) {
1242      return {
1243        $field: widget,
1244        locale: options.locale,
1245        positioning: options.positioning || widget,
1246        access: options.access,
1247        selectedDate: options.value,
1248        editValue: options.editValue,
1249        displayValue: options.displayValue,
1250        minValidDate: options.minimum,
1251        maxValidDate: options.maximum,
1252        exclMinDate: options.exclusiveMinimum,
1253        exclMaxDate: options.exclusiveMaximum
1254      }
1255    }
1256
1257    /*
1258     * To check where the click happened, if happened outside the datepicker
1259     * then hide the picker. This is checked whether any ancestor of clicked target
1260     * has a class datePickerTarget. This class is added to the attached element as well
1261     */
1262    #checkWindowClicked(evnt) {
1263      let self = this;
1264      if (self.#curInstance) {
1265        // datepickerTarget class depicts that the component is a part of the Date Field
1266        // and on click of that class, we should not hide the datepicker or fire exit events.
1267        if (!evnt.target.closest(".datePickerTarget")) {
1268          //non-touch devices do not deactivate on blur. Hence needs to be done here
1269          if (self.#touchSupported) {
1270            self.#hide();
1271            //clicking outside a field doesn't blur the field in IPad. Doing it by script
1272            self.#curInstance.$field.blur();
1273            self.#deactivateField();
1274          } else {
1275            DatePickerWidget.#clickedWindow = true;
1276          }
1277        } else {
1278          DatePickerWidget.#clickedWindow = false;
1279        }
1280      }
1281    }
1282
1283    /*
1284     * handling of key strokes. All the key strokes prevent the default browser action
1285     * unless specified otherwise
1286     * tab: set focus on calendar icon when dateinput field is active, navigates through date picker buttons when datepicker is open,
1287     * otherwise perform default browser action
1288     * escape: hides the datepicker
1289     * down arrow key: navigate the picker downwards by the number specified in actionView.upDown of the current View
1290     * up arrow key: navigate the picker upwards by the number specified in actionView.upDown of the current View
1291     * left arrow key: navigate the picker one unit of that view backward
1292     * right arrow key: navigate the picker one unit of that view forward
1293     * shift + up: perform the action that happens on clicking the caption (as specified in actionView.caption)
1294     * shift + left: perform the action that happens on clicking the left navigation button
1295     * shift + right: perform the action that happens on clicking the right navigation button
1296     * space/enter: triggers the click event for the current focused element from datepicker/ opens datepicker when calendar icon is focused.
1297     */
1298    #hotKeys(evnt) {
1299      var handled = false, date;
1300      switch (evnt.keyCode) {
1301        case 9: //tab
1302          // CQ-4239352 : Setting clickedWindow property to true on tabbing so that deactivateField logic gets executed
1303          // When clicking on "x" on input field in in IE and when selecting the content and releasing the mouse select outside the field
1304          // the click event is not trigerred on the field and hence activateField is not executed, so clickedWindow remains as false
1305          DatePickerWidget.#clickedWindow = true;
1306          handled = false;
1307          break;
1308        case 27://escape
1309          if (DatePickerWidget.#visible) {
1310            this.#hide();
1311            this.#curInstance.$field.focus();
1312            this.#deactivateField();
1313            handled = true;
1314          }
1315          break;
1316        case 32: //space
1317        case 13: // enter
1318          if (evnt.target.classList.contains("cmp-adaptiveform-datepicker__calendar-icon")) {
1319            if (!DatePickerWidget.#visible) {
1320              this.#show();
1321              handled = true;
1322            } else {
1323              this.$focusedDate.classList.add("dp-focus");
1324              handled = true;
1325            }
1326          }
1327          break;
1328        case 40: //down arrow key
1329          if (!DatePickerWidget.#visible) {
1330            this.#show();
1331            return;
1332          }
1333          this.$focusedDate.classList.add("dp-focus");
1334          break;
1335      }
1336
1337      if (DatePickerWidget.#visible && this.#keysEnabled) {
1338        var v = this.#viewAction[this.view].key,
1339            updown = this.#viewAction[this.view].upDown;
1340        switch (evnt.keyCode) {
1341          case 9: // tab
1342            if (evnt.shiftKey) {
1343              if (evnt.target.classList.contains("dp-leftnav")
1344                  || evnt.target.classList.contains("dp-focus")) {
1345                this.#hide();
1346                this.#curInstance.$field.focus();
1347                handled = true;
1348              } else {
1349                handled = false;
1350              }
1351            } else {
1352              const buttonTabindex = evnt.target.getAttribute("tabindex");
1353              if (buttonTabindex === '0') {
1354                if (evnt.target.tagName.toLocaleLowerCase() === "input") {
1355                  this.#hide();
1356                  handled = false;
1357                } else {
1358                  this.prevNavWidthBtn.focus();
1359                  handled = true;
1360                }
1361              } else if (buttonTabindex === '4') {
1362                this.#hide();
1363                this.#curInstance.$field.focus();
1364                handled = true;
1365              } else {
1366                handled = false;
1367              }
1368            }
1369            break;
1370          case 32: //select on space
1371          case 13: // select on enter
1372            this.hotKeyPressed = true;
1373            this.#focusedOnLi = false;
1374            if (!this.#focusedOnLi) {
1375              evnt.target.click();
1376            } else {
1377              if (this.$focusedDate) {
1378                this.$focusedDate.click() //todo
1379              }
1380            }
1381            this.hotKeyPressed = false;
1382            handled = true;
1383            break;
1384          case 37: //left arrow key
1385            if (evnt.shiftKey) {
1386              this.prevNavWidthBtn.click();
1387            } else {
1388              this.#adjustDate(-1, v, true);
1389            }
1390            handled = true;
1391            break;
1392          case 38: //up arrow key
1393            if (evnt.shiftKey) {
1394              this.caption.click();
1395            } else {
1396              this.#adjustDate(-updown, v, true);
1397            }
1398            handled = true;
1399            break;
1400          case 39: //right arrow key
1401            if (evnt.shiftKey) {
1402              this.nextNavWidthBtn.click();
1403            } else {
1404              this.#adjustDate(+1, v, true);
1405            }
1406            handled = true;
1407            break;
1408          case 40: //down arrow key
1409            this.#adjustDate(updown, v, true);
1410            handled = true;
1411            break;
1412          default:
1413        }
1414      }
1415      if (handled) {
1416        evnt.preventDefault();
1417      }
1418    }
1419
1420    /*
1421     * show the datepicker. //TODO: migrate this to vanilla js
1422     */
1423    #show() {
1424      this.#options.locale = this.#curInstance.locale;
1425      if (!DatePickerWidget.#visible) {
1426        let date  = new Date(),
1427            validDate,
1428            parsedDate;
1429        if (this.#curInstance.selectedDate) {
1430          validDate = this.#curInstance.selectedDate;
1431        } else if (this.#model.valid) {
1432          validDate = this.#model.value;
1433        }
1434        if (validDate) {
1435          parsedDate = validDate ? new Date(validDate) : null;
1436          date = (parsedDate == null || parsedDate == 'Invalid Date') ? date : parsedDate;
1437        }
1438        const timezoneOffset = date.getTimezoneOffset();
1439        date.setMinutes(date.getMinutes() + timezoneOffset);
1440        this.selectedDay = this.currentDay = date.getDate();
1441        this.selectedMonth = this.currentMonth = date.getMonth();
1442        this.selectedYear = this.currentYear = date.getFullYear();
1443        this.maxValidDate = this.#options.maximum ? new Date(
1444            this.#curInstance.maxValidDate) : null;
1445        this.minValidDate = this.#options.minimum ? new Date(
1446            this.#curInstance.minValidDate) : null;
1447        this.exclMaxDate = this.#curInstance.exclMaxDate;
1448        this.exclMinDate = this.#curInstance.exclMinDate;
1449        this.#dp.getElementsByClassName("dp-clear")[0].getElementsByTagName(
1450            "a")[0].innerText = this.#options.locale.clearText;
1451        this.#layout(this.#defaultView);
1452        this.#dp.style.display = "flex";
1453        this.#focusedOnLi = false;
1454        DatePickerWidget.#visible = true;
1455        this.#position();
1456        
1457        // Add document touch listener for mobile to close datepicker when tapping outside
1458        if (this.#touchSupported && !this.#documentTouchListener) {
1459          this.#documentTouchListener = (evt) => {
1460            if (DatePickerWidget.#visible && this.#curInstance) {
1461              this.#checkWindowClicked(evt);
1462            }
1463          };
1464          document.addEventListener("touchstart", this.#documentTouchListener, false);
1465        }
1466        
1467        if (this.#options.showCalendarIcon) {
1468          this.#curInstance.$field.setAttribute('readonly', true);    // when the datepicker is active, deactivate the field
1469        }
1470      }
1471
1472      //   Disabling the focus on ipad  due to a bug where value of
1473      // date picker is not being set
1474      // Removing this code will only hamper one use case
1475      // where on ipad if you click on the calander then
1476      // the field becomes read only so
1477      // there is no indication where the current focus is
1478      // And  if you remove this foucs code all together
1479      // then what happens is that on desktop MF in iframe the exit event
1480      // is not getting called hence calander getting remained open even
1481      // when you click somewhere on window or focus into some other field
1482      if (this.#options.showCalendarIcon && !this.#touchSupported) {
1483        this.#curInstance.$field.focus(); // field loses focus after being marked readonly, causing blur event not to be fired later
1484      }
1485    }
1486
1487    /*
1488     * position the datepicker around the positioning element //TODO: migrate this to vanilla js
1489     * provided in the options
1490     */
1491    #position() {
1492      let $elem = this.#curInstance.positioning,
1493          windowScrollX = window.scrollX,
1494          windowScrollY = window.scrollY,
1495          windowInnerHeight = window.innerHeight,
1496          windowInnerWidth = window.innerWidth,
1497          inputRect = $elem.getBoundingClientRect(),
1498          height = $elem.offsetHeight,
1499          top = this.#getOffset($elem).top + height,
1500          left = this.#getOffset($elem).left,
1501          styles = {"top": (top + "px"), "left": (left + "px")},
1502          diffBottom = top + this.#dp.offsetHeight - windowInnerHeight - windowScrollY, //this.#dp.offsetHeight is the widget's height
1503          newLeft,
1504          newTop;
1505      if (diffBottom > 0) {
1506        //can't appear at the bottom
1507        //check top
1508        newTop = top - height - this.#dp.offsetHeight - 20;
1509        if (newTop < windowScrollY) {
1510          //can't appear at the top as well ... the datePicker pop up overlaps the date field
1511          newTop = top - diffBottom;
1512        }
1513        styles.top = newTop + "px";
1514      }
1515      if (left + this.#dp.offsetWidth > windowScrollX + windowInnerWidth) {
1516        //align with the right edge
1517        newLeft = windowScrollX + windowInnerWidth - this.#dp.offsetWidth - 20;
1518        styles.left = newLeft + "px";
1519      }
1520      this.#dp.style.top = styles.top;
1521      this.#dp.style.left = styles.left;
1522      const localeObj = new Intl.Locale(this.#lang);
1523      if(localeObj?.textInfo?.direction == "rtl") {
1524        let right = windowInnerWidth - (left + inputRect.width); // Calculate right offset
1525        if (right + this.#dp.offsetWidth > windowInnerWidth) { // this.#dp.offsetWidth is the widget's width
1526          // Align with the right edge of the viewport
1527          right = windowScrollX + windowInnerWidth - this.#dp.offsetWidth - 20;
1527 // Adjust with a 20px margin
1528      }
1529        this.#dp.style.right = right + "px";
1530        this.#dp.style.left = "unset"
1531      }
1532      return this;
1533    }
1534
1535    #getOffset(elem) {
1536      let box = elem.getBoundingClientRect();
1537      return {
1538        top: box.top + window.scrollY,
1539        left: box.left + window.scrollX
1540      };
1541    }
1542
1543    /*
1544     * layout the nextView. if nextView is null return
1545     *
1546     */
1547    #layout(nextView) {
1548      if (nextView == null) {
1549        this.#hide();
1550      } else {
1551        if (this.view) {
1552          this['$' + this.view.toLowerCase()].style.display = "none";
1553        }
1554        this.view = nextView;
1555        this.caption.classList.toggle("disabled",
1556            !this.#viewAction[this.view].caption);
1557        this['$' + this.view.toLowerCase()].style.display = "block";
1558        this["show" + this.view]();
1559      }
1560      return this;
1561    }
1562
1563    /*
1564     * show the month view
1565     */
1566    showMonth() {
1567      var self = this,
1568          curDate = new Date(this.currentYear, this.currentMonth),
1569          maxDay = this.#maxDate(this.currentMonth),
1570          prevMaxDay = this.#maxDate((this.currentMonth + 11) % 12),
1571          day1 = new Date(this.currentYear, this.currentMonth, 1).getDay(),
1572          data, display;
1573          var localizedYear = this.#getLocalizedYear(curDate);
1574
1575      this.#tabulateView(
1576          {
1577            caption: this.#options.locale.months[this.currentMonth] + ", "
1578                + this.#convertNumberToLocale(localizedYear),
1579            header: this.#options.locale.days,
1580            numRows: 7,
1581            numColumns: 7,
1582            elementAt: function (row, col) {
1583              var day = (row - 1) * 7 + col - day1 + 1;
1584              var monthVal = self.currentMonth + 1;
1585              let gridId = "day-" + day;
1586              display = self.#convertNumberToLocale(day);
1587              data = day;
1588              if (day < 1) {
1589                display = self.#convertNumberToLocale(prevMaxDay + day);
1590                data = -1;
1591                monthVal = self.currentMonth;
1592              } else if (day > maxDay) {
1593                display = self.#convertNumberToLocale(day - maxDay);
1594                data = -1;
1595                monthVal = self.currentMonth + 2;
1596              } else {
1597                curDate.setDate(day);
1598                // check if the currentdate is valid based on max and min valid date
1599                if (self.#compareVal(curDate, self.maxValidDate,
1600                    self.exclMaxDate) || self.#compareVal(self.minValidDate,
1601                    curDate, self.exclMinDate)) {
1602                  data = -1;
1603                }
1604              }
1605              return {
1606                data: data,
1607                gridId: gridId,
1608                display: display,
1609                ariaLabel: self.#options.editValue(
1610                    self.currentYear + "-" + self.#pad2(monthVal)
1611                    + "-" + self.#pad2(display))
1612              };
1613            }
1614          });
1615    }
1616
1617    /**
1618     * returns boolean based on val1, val2, checkEqual
1619     * For comparing date, use date object
1620     */
1621    #compareVal(val1, val2, checkEqual) {
1622      if (!val1 || !val2) {
1623        return false;
1624      }
1625
1626      if (checkEqual) {
1627        return val1 >= val2;
1628      } else {
1629        return val1 > val2;
1630      }
1631    }
1632
1633    /*
1634     * show the year view
1635     */
1636    showYear() {
1637      var self = this,
1638          minDate = this.minValidDate ? new Date(
1639                  this.minValidDate.getFullYear(), this.minValidDate.getMonth())
1640              : null,
1641          maxDate = this.maxValidDate ? new Date(
1642                  this.maxValidDate.getFullYear(), this.maxValidDate.getMonth())
1643              : null,
1644          curDate = new Date(this.currentYear, 0), //can't omit month, if only one param present it is treated as millisecond
1645          data,
1646          month;
1647          var localizedYear = this.#getLocalizedYear(curDate);
1648      this.#tabulateView(
1649          {
1650            caption: this.#convertNumberToLocale(localizedYear),
1651            numRows: 4,
1652            numColumns: 3,
1653            elementAt: function (row, col) {
1654              data = month = row * 3 + col;
1655              let gridId = "month-" + data;
1656              curDate.setMonth(month);
1657              if ((minDate && curDate < minDate) || (maxDate && curDate
1658                  > maxDate)) {
1659                data = -1;
1660              }
1661              return {
1662                data: data,
1663                gridId: gridId,
1664                display: self.#options.locale.months[month],
1665                ariaLabel: self.#options.locale.months[month] + " "
1666                    + self.currentYear
1667              };
1668            }
1669          });
1670    }
1671
1672    #getLocalizedYear(date) {
1673      /*
1674      // Only Thai language return year according to Buddhist calendar, rest all languages follows gregorian calendar in practice.
1675      // The Buddhist Year in 2024 = 543 + 2024  = B.E. 2567 (reference https://wesak.org.my/calculating-b-e/)
1676      // Intl.DateTimeFormat#formatToParts returns number (2024) for all languages except for Thai (2567) & for Persian ('Û±Û´Û°Û³')
1677      // For Persian ('Û±Û´Û°Û³'), returned year is not in numbers that is breaking next flow.
1678      */
1679      if(this.#lang === 'th') {
1680        const dateFormat = new Intl.DateTimeFormat(this.#lang, {
1681          year: 'numeric'
1682        });
1683        const dateParts = dateFormat.formatToParts(date);
1684        const yearObject = dateParts.find(yearObject => yearObject.type === "year");
1685        const localizedYear = yearObject.value;
1686        return Number(localizedYear);
1687      }
1688      else {
1689        return Number(date.getFullYear());
1690      }
1691    }
1692
1693    /*
1694     * show the year set view
1695     */
1696    showYearset() {
1697      var year,
1698          minDate = this.minValidDate ? new Date(
1699              this.minValidDate.getFullYear(), 0) : null,
1700          maxDate = this.maxValidDate ? new Date(
1701              this.maxValidDate.getFullYear() + 1, 0) : null,
1702          curDate = new Date(),
1703          data,
1704          self = this;
1705      var localizedYear = this.#getLocalizedYear(new Date(this.currentYear, 0)),
1706          localizedYearSet = this.#getLocalizedYear(new Date(self.currentYear, 0));
1707
1708      this.#tabulateView(
1709          {
1710            caption: this.#convertNumberToLocale(
1711                    localizedYear - this.#options.yearsPerView / 2) + "-"
1712                + this.#convertNumberToLocale(
1713                    localizedYear - this.#options.yearsPerView / 2
1714                    + this.#options.yearsPerView - 1),
1715            numRows: 4,
1716            numColumns: 4,
1717            elementAt: function (row, col) {
1718              data = year = localizedYearSet - 8 + (row * 4 + col);
1719              let gridId = "year-" + data;
1720              curDate.setFullYear(year);
1721              if ((minDate && curDate < minDate) || (maxDate && curDate
1722                  > maxDate)) {
1723                data = -1;
1724              }
1725              return {
1726                "data": data,
1727                "gridId": gridId,
1728                "display": self.#convertNumberToLocale(year),
1729                ariaLabel: year
1730              };
1731            }
1732          });
1733    }
1734
1735    insertRow(rowNum, rowArray, isHeader, elementAt) {
1736      let $view = this["$" + this.view.toLowerCase()],
1737          $row = $view.getElementsByTagName("ul")[rowNum],
1738          items, $li, element, $tmp,
1739          self = this;
1740      if (!$row) {
1741        let rowEl = document.createElement("ul");
1742        rowEl.removeAttribute("aria-label");
1743        rowEl.classList.toggle("header", isHeader);
1744        rowEl.setAttribute("role", "row");
1745        $row = $view.appendChild(rowEl);
1746      }
1747      items = $row.getElementsByTagName("li").length;
1748      while (items++ < rowArray.length) {
1749        let listItemEl = document.createElement("li");
1750        listItemEl.id = "li-" + elementAt(rowNum, items).gridId;
1751        listItemEl.setAttribute("role", isHeader ? "columnheader" : "gridcell");
1752        $tmp = $row.appendChild(listItemEl);
1753        if (!isHeader) {
1754          let cb = function (evnt) {
1755            self.#selectDate(evnt);
1756          };
1757          $tmp.addEventListener("click", cb);
1758        }
1759      }
1760
1761      rowArray.forEach(function (el, index) {
1762        $li = $row.getElementsByTagName("li")[index];
1763        if (isHeader) {
1764          $li.innerText = rowArray[index];
1765        } else {
1766          element = rowArray[index];
1767          window.afCache.put($li, "value", element.data);
1768          if (self.#checkDateIsFocussed(element.data)) {
1769            if (self.$focusedDate) {
1770              self.$focusedDate.classList.remove("dp-focus");
1771              self.$focusedDate.setAttribute("tabindex", "-1");
1772            }
1773            self.$focusedDate = $li;
1774            if (self.#keysEnabled) {
1775              self.$focusedDate.classList.add("dp-focus")
1776            }
1777          }
1778          $li.setAttribute("title", element.ariaLabel);
1779          $li.setAttribute("aria-label", element.ariaLabel);
1780          $li.setAttribute("tabindex", -1);
1781          $li.classList.toggle("dp-selected",
1782              self.#checkDateIsSelected(element.data));
1783          $li.classList.toggle("disabled", element.data === -1);
1784          $li.innerText = element.display;
1785        }
1786      });
1787      return $row;
1788    }
1789
1790    /*
1791     * creates a tabular view based on the options provided. The options that can be passed are
1792     * numRows: number of rows that needs rendering
1793     * numCols: number of columns that needs rendering
1794     * caption: text for the datepickers caption element
1795     * header: an array of elements that identifies the header row
1796     * elementAt: a function(row, column) that returns an object (data: <data>, display: <display>) where
1797     *            <data> is the value to set for that view when the element at (row,column) is clicked and
1798     *            <display> is the value that will be visible to the user
1799     */
1800    #tabulateView(options) {
1801      var r = 0, rows = 0,
1802          row = [],
1803          c;
1804      this.caption.innerHTML = options.caption;
1805      if (options.header) {
1806        this.insertRow(r++, options.header, true, options.elementAt);
1807      }
1808      while (r < options.numRows) {
1809        c = 0;
1810        while (c < options.numColumns) {
1811          row[c] = options.elementAt(r, c);
1812          c++;
1813        }
1814        this.insertRow(r++, row, false, options.elementAt);
1815      }
1816    }
1817
1818    #hotKeysCallBack = this.#hotKeys.bind(this);
1819
1820    #activateField(evnt) {
1821      let self = this;
1822      this.#curInstance = window.afCache.get(evnt.target, "datetimepicker");
1823      // Issue LC-7049:
1824      // datepickerTarget should be added when activate the field and should be removed
1825      // after the fields gets deactivated.
1826      if (this.#options.showCalendarIcon) {
1827        this.#curInstance.$field.parentNode.classList.add("datePickerTarget");
1828      }
1829      //enable hot keys only for non touch devices
1830      if (!this.#touchSupported && !this.#keysEnabled) {
1831        document.addEventListener("keydown", self.#hotKeysCallBack);
1832        this.#keysEnabled = true;
1833      }
1834    }
1835
1836    #deactivateField() {
1837      let self = this;
1838      if (self.#curInstance) {
1839        if (this.#keysEnabled) {
1840          document.removeEventListener("keydown", self.#hotKeysCallBack);
1841          this.#keysEnabled = false;
1842        }
1843        // Remove document touch listener if it exists
1844        if (this.#documentTouchListener) {
1845          document.removeEventListener("touchstart", this.#documentTouchListener);
1846          this.#documentTouchListener = null;
1847        }
1848        // Issue LC-7049:
1849        // datepickerTarget should be added when activate the field and should be removed
1850        // after the fields gets deactivated. Otherwise clicking on any other datefield
1851        // will not hide the existing datepicker
1852        if (this.#options.showCalendarIcon) {
1853          self.#curInstance.$field.parentNode.classList.remove(
1854              "datePickerTarget");
1855        }
1856        self.#curInstance = null;
1857        this.#hideAllViews();
1858      }
1859    }
1860
1861    #hide() {
1862      if (DatePickerWidget.#visible) {
1863        this.#dp.style.display = "none";
1864        this.#hideAllViews();
1865        DatePickerWidget.#visible = false;
1866        if (this.#options.showCalendarIcon) {
1867          this.#curInstance.$field.removeAttribute('readonly');    // when the datepicker is deactivated, activate the field
1868        }
1869      }
1870    }
1871
1872    #hideAllViews() {
1873      this['$month'].replaceChildren();
1874      this['$year'].replaceChildren();
1875      this['$yearset'].replaceChildren();
1876      this['$month'].style.display = "none";
1877      this['$year'].style.display = "none";
1878      this['$yearset'].style.display = "none";
1879    }
1880
1881    #adjustDate(step, view, focus) {
1882      let maxDate, prevMaxDate;
1883      let _focus = focus || false;
1884      switch (view.toLowerCase()) {
1885        case "day":
1886          this.currentDay += step;
1887          maxDate = this.#maxDate(this.currentMonth)
1888          if (this.currentDay < 1) {
1889            prevMaxDate = this.#maxDate((this.currentMonth - 1 + 12) % 12);
1890            this.currentDay = prevMaxDate + this.currentDay;
1891            return this.#adjustDate(-1, "month", _focus);
1892          }
1893          if (this.currentDay > maxDate) {
1894            this.currentDay -= maxDate;
1895            return this.#adjustDate(+1, "month", _focus);
1896          }
1897          break;
1898        case "month":
1899          this.currentMonth += step;
1900          if (this.currentMonth > 11) {
1901            this.currentYear++;
1902            this.currentMonth = 0;
1903          }
1904          if (this.currentMonth < 0) {
1905            this.currentYear--;
1906            this.currentMonth = 11;
1907          }
1908          break;
1909        case "year":
1910          this.currentYear += step;
1911          break;
1912        case "yearset":
1913          this.currentYear += step * this.#options.yearsPerView;
1914          break;
1915      }
1916      this.#layout(this.view);
1917      if (_focus) {
1918        this.#focusedOnLi = true;
1919        this.$focusedDate.setAttribute("tabindex", 0);
1920        this.$focusedDate.focus();
1921      }
1922    }
1923
1924    #checkDateIsSelected(data) {
1925      switch (this.view.toLowerCase()) {
1926        case "month":
1927          return this.currentYear === this.selectedYear && this.currentMonth
1928              === this.selectedMonth && data === this.selectedDay;
1929        case "year":
1930          return this.currentYear === this.selectedYear && this.selectedMonth
1931              === data;
1932        case "yearset":
1933          return this.selectedYear === data;
1934      }
1935    }
1936
1937    #checkDateIsFocussed(data) {
1938      switch (this.view.toLowerCase()) {
1939        case "month":
1940          return data === this.currentDay;
1941        case "year":
1942          return this.currentMonth === data;
1943        case "yearset":
1944          return this.currentYear === data;
1945      }
1946    }
1947
1948    #convertNumberToLocale(number) {
1949      const zeroCode = this.#options.locale.zero.charCodeAt(0);
1950      number += "";
1951      let newNumber = [];
1952      for (let i = 0; i < number.length; i++) {
1953        newNumber.push(
1954            String.fromCharCode(zeroCode + parseInt(number.charAt(i))));
1955      }
1956      return newNumber.join("");
1957    }
1958
1959    #clearDate(view) {
1960      this.#model.dispatch(new FormView.Actions.UIChange({'value': ''}));
1961      let existingSelectedItem = this['$' + view.toLowerCase()].getElementsByClassName("dp-selected")[0];
1962      if (existingSelectedItem) {
1963        existingSelectedItem.classList.remove("dp-selected");
1964      }
1965    }
1966
1967    #getEvent() {
1968      return "click";//this.#touchSupported ? "touchstart" : "click";
1969    }
1970
1971    #pad2(m) {
1972      return m = m < 10 ? "0" + m : m;
1973    }
1974
1975    toString() {
1976      if(this.selectedYear === -1 || this.selectedMonth === -1 || this.selectedDay === -1){
1977        return "";
1978      }
1979      const formattedDate = `${this.selectedYear}-${this.#pad2(this.selectedMonth + 1)}-${this.#pad2(this.selectedDay)}`;
1980      return formattedDate;
1981    }
1982
1983    #selectDate(evnt) {
1984      let val = window.afCache.get(evnt.target, "value"),
1985          nextView = this.#viewAction[this.view].li;
1986
1987      //disabled dates have a value of -1. Do nothing in that case
1988      if (val === -1) {
1989        return;
1990      }
1991      switch (this.view.toLowerCase()) {
1992        case "month":
1993          this.selectedMonth = this.currentMonth;
1994          this.selectedYear = this.currentYear;
1995          this.selectedDay = val;
1996          this.setValue(this.toString());
1997          this.#model.dispatch(new FormView.Actions.UIChange({'value': this.toString()})); // updating model value to the latest when calender is changed
1998          this.#curInstance.$field.focus();
1999          let existingSelectedElement = this['$'
2000          + this.view.toLowerCase()].getElementsByClassName("dp-selected")[0];
2001          if (existingSelectedElement) {
2002            existingSelectedElement.classList.remove("dp-selected");
2003          }
2004          evnt.target.classList.add("dp-selected");
2005          break;
2006        case "year":
2007          this.currentMonth = val;
2008          break;
2009        case "yearset":
2010          this.currentYear = val;
2011          break;
2012      }
2013      this.#layout(nextView);
2014      //manually focus on the field if clicked on the popup buttons for non-touch device
2015      if (!this.#touchSupported) {
2016        //No need to focus if selection is made by pressing space.
2017        if (!this.hotKeyPressed) {
2018          this.#scriptFocus = true;
2019        }
2020      } else if (nextView == null) {
2021        //For touch devices, deactivate the field if a selection is made
2022        this.#deactivateField()
2023      }
2024    }
2025
2026    #leapYear() {
2027      return this.currentYear % 400 === 0 || (this.currentYear % 100 !== 0
2028          && this.currentYear % 4 === 0);
2029    }
2030
2031    #maxDate(m) {
2032      if (this.#leapYear() && m === 1) {
2033        return 29;
2034      } else {
2035        return this.#dates[m];
2036      }
2037    }
2038
2039    #localizeDateElements(defaultOptions, locale) {
2040        var calendarSymbols = FormView.LanguageUtils.getTranslatedString(locale, "calendarSymbols");
2041        if (calendarSymbols && calendarSymbols.abbrdayNames) {
2042            defaultOptions.locale.days = calendarSymbols.abbrdayNames;
2043        }
2044        if (calendarSymbols && calendarSymbols.abbrdayNames) {
2045            defaultOptions.locale.months = calendarSymbols.monthNames;
2046        }
2047        var clearText = FormView.LanguageUtils.getTranslatedString(locale, "clearText");
2048        if (clearText) {
2049            defaultOptions.locale.clearText = clearText;
2050        }
2051        var zero = FormView.LanguageUtils.getTranslatedString(locale, "0");
2052        if (zero) {
2053            defaultOptions.locale.zero = zero;
2054        }
2055    }
2056
2057    #isEditValueOrDisplayValue(value) {
2058      return (this.#model.editValue === value || this.#model.displayValue
2059          === value);
2060    }
2061
2062    /**
2063     * returns the original value of format YYYY-MM-DD
2064     * @returns {*|string}
2065     */
2066    getValue() {
2067      if (this.#isEditValueOrDisplayValue(this.#widget.value)) {
2068        return this.#model.value; // if the widget has edit/display value thiss method should return model value
2069      }
2070      return this.#widget.value;
2071    }
2072
2073    /**
2074     * Sets the formatted display value on the widget.
2075     * value should be in YYYY-MM-DD format
2076     * @param value
2077     */
2078    setDisplayValue(value) {
2079      if (this.#curInstance != null) {
2080        this.#curInstance.$field.value = this.#curInstance.displayValue(
2081            this.toString()) || value;
2082      } else {
2083        this.#widget.value = this.#model.displayValue || value;
2084      }
2085    }
2086
2087    setCalendarWidgetValue(value) {
2088      if (this.#curInstance === null && this.#widget != null) {
2089        this.#curInstance = window.afCache.get(this.#widget, "datetimepicker");
2090      }
2091      if (this.#curInstance != null) {
2092        // also change the date of the calendar widget
2093        this.#curInstance.selectedDate = value;
2094      }
2095    }
2096
2097    /**
2098     * Sets the formatted edit value on the widget
2099     * @param value
2100     */
2101
2102    setValue(value) {
2103      let currDate;
2104      if (value instanceof Date && !isNaN(value)) {
2105        // If value is already a Date object and it's valid, use it as is
2106        currDate = value;
2107      } else {
2108        // Check if value is empty
2109        if (!value || value.trim() === '') {
2110          currDate = new Date();
2111        } else {
2112          let displayFormat = this.#model._jsonModel?.displayFormat;
2113          // If displayFormat is null/undefined, use default parsing
2114          if (!displayFormat) {
2115            currDate = new Date(value);
2116          } else {
2117            // Use FormView.Formatters.parseDate for custom formats
2118            currDate = FormView.Formatters.parseDate(value, this.#lang || 'en', displayFormat);
2119            // If parseDate failed (returned null), fallback to default parsing
2120            if (currDate === null) {
2121              currDate = new Date(value);
2122            }
2123            const timezoneOffset = currDate.getTimezoneOffset();
2124            currDate.setMinutes(currDate.getMinutes() + timezoneOffset);
2125          }
2126        }
2127      }
2128
2129      if (!isNaN(currDate) && value != null) {
2130        //in case the value is directly updated from the field without using calendar widget
2131        this.selectedMonth = currDate.getMonth();
2132        this.selectedYear = currDate.getFullYear();
2133        this.selectedDay = currDate.getDate();
2134      } else {
2135        this.selectedYear
2136            = this.selectedMonth
2137            = this.selectedDay
2138            = -1;
2139      }
2140      if (this.#curInstance != null) {
2141        if (!this.#isEditValueOrDisplayValue(value)) {
2142          this.#curInstance.selectedDate = value;  // prevent edit/display value from getting set in calender
2143        }
2144        this.#curInstance.$field.value = this.#curInstance.editValue() || value;
2145      } else {
2146        this.#widget.value = value;
2147      }
2148    }
2149
2150    addEventListener(event, handler, widget) {
2151      let inst = window.afCache.get(widget, "datetimepicker");
2152      inst.$field.addEventListener(event, function (e) {
2153        switch (e.type) {
2154          case 'blur':
2155            if (!DatePickerWidget.#visible) {
2156              handler(e);
2157            }
2158            break;
2159          case 'focus':
2160            handler(e);
2161            break;
2162          case 'input':
2163            handler(e);
2164            break;
2165
2166        }
2167      });
2168    }
2169
2170  }
2171}
2172/*******************************************************************************
2173 * Copyright 2022 Adobe
2174 *
2175 * Licensed under the Apache License, Version 2.0 (the "License");
2176 * you may not use this file except in compliance with the License.
2177 * You may obtain a copy of the License at
2178 *
2179 *     http://www.apache.org/licenses/LICENSE-2.0
2180 *
2181 * Unless required by applicable law or agreed to in writing, software
2182 * distributed under the License is distributed on an "AS IS" BASIS,
2183 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2184 * See the License for the specific language governing permissions and
2185 * limitations under the License.
2186 ******************************************************************************/
2187(function() {
2188
2189    "use strict";
2190    class TextInput extends FormView.FormFieldBase {
2191
2192        static NS = FormView.Constants.NS;
2193        /**
2194         * Each FormField has a data attribute class that is prefixed along with the global namespace to
2195         * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be
2196         * data-{NS}-{IS}-x=""
2197         * @type {string}
2198         */
2199        static IS = "adaptiveFormTextInput";
2200        static bemBlock = 'cmp-adaptiveform-textinput'
2201        static selectors  = {
2202            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
2203            widget: `.${TextInput.bemBlock}__widget`,
2204            label: `.${TextInput.bemBlock}__label`,
2205            description: `.${TextInput.bemBlock}__longdescription`,
2206            qm: `.${TextInput.bemBlock}__questionmark`,
2207            errorDiv: `.${TextInput.bemBlock}__errormessage`,
2208            tooltipDiv: `.${TextInput.bemBlock}__shortdescription`
2209        };
2210
2211        constructor(params) {
2212            super(params);
2213        }
2214
2215        getWidget() {
2216            return this.element.querySelector(TextInput.selectors.widget);
2217        }
2218
2219        getDescription() {
2220            return this.element.querySelector(TextInput.selectors.description);
2221        }
2222
2223        getLabel() {
2224            return this.element.querySelector(TextInput.selectors.label);
2225        }
2226
2227        getErrorDiv() {
2228            return this.element.querySelector(TextInput.selectors.errorDiv);
2229        }
2230
2231        getTooltipDiv() {
2232            return this.element.querySelector(TextInput.selectors.tooltipDiv);
2233        }
2234
2235        getQuestionMarkDiv() {
2236            return this.element.querySelector(TextInput.selectors.qm);
2237        }
2238
2239        setModel(model) {
2240            super.setModel(model);
2241            if (this.widget.value !== '') {
2242                this.setModelValue(this.widget.value);
2243            }
2244            this.widget.addEventListener('blur', (e) => {
2245                this.setModelValue(e.target.value);
2246                this.setWidgetValueToDisplayValue();
2247                this.setInactive();
2248                this.triggerExit();
2249            });
2250            this.widget.addEventListener('focus', (e) => {
2251                this.setActive();
2252                this.setWidgetValueToModelValue();
2253                this.triggerEnter();
2254            });
2255            if (model.fieldType === "multiline-input") {
2256                this.widget.addEventListener('keydown', (event) => {
2257                    if (event.key === 'Enter') {
2258                        // Prevent default action of Enter key to avoid form submission
2259                        event.preventDefault();
2260                        // Add a newline character to the widget value
2261                        let cursorPosition = this.widget.selectionStart;
2262                        let textBefore = this.widget.value.substring(0, cursorPosition);
2263                        let textAfter = this.widget.value.substring(this.widget.selectionEnd);
2264                        this.widget.value = textBefore + '\n' + textAfter;
2265                        this.widget.selectionStart = this.widget.selectionEnd = cursorPosition + 1;
2266                    }
2267                });
2268            }
2269        }
2270    }
2271
2272    FormView.Utils.setupField(({element, formContainer}) => {
2273        return new TextInput({element, formContainer})
2274    }, TextInput.selectors.self);
2275
2276})();
2277
2278/*******************************************************************************
2279 * Copyright 2022 Adobe
2280 *
2281 * Licensed under the Apache License, Version 2.0 (the "License");
2282 * you may not use this file except in compliance with the License.
2283 * You may obtain a copy of the License at
2284 *
2285 *     http://www.apache.org/licenses/LICENSE-2.0
2286 *
2287 * Unless required by applicable law or agreed to in writing, software
2288 * distributed under the License is distributed on an "AS IS" BASIS,
2289 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2290 * See the License for the specific language governing permissions and
2291 * limitations under the License.
2292 ******************************************************************************/
2293(function() {
2294
2295    "use strict";
2296    class TelephoneInput extends FormView.FormFieldBase {
2297
2298        static NS = FormView.Constants.NS;
2299        /**
2300         * Each FormField has a data attribute class that is prefixed along with the global namespace to
2301         * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be
2302         * data-{NS}-{IS}-x=""
2303         * @type {string}
2304         */
2305        static IS = "adaptiveFormTelephoneInput";
2306        static bemBlock = 'cmp-adaptiveform-telephoneinput'
2307        static selectors  = {
2308            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
2309            widget: `.${TelephoneInput.bemBlock}__widget`,
2310            label: `.${TelephoneInput.bemBlock}__label`,
2311            description: `.${TelephoneInput.bemBlock}__longdescription`,
2312            qm: `.${TelephoneInput.bemBlock}__questionmark`,
2313            errorDiv: `.${TelephoneInput.bemBlock}__errormessage`,
2314            tooltipDiv: `.${TelephoneInput.bemBlock}__shortdescription`
2315        };
2316
2317        constructor(params) {
2318            super(params);
2319        }
2320
2321        getWidget() {
2322            return this.element.querySelector(TelephoneInput.selectors.widget);
2323        }
2324
2325        getDescription() {
2326            return this.element.querySelector(TelephoneInput.selectors.description);
2327        }
2328
2329        getLabel() {
2330            return this.element.querySelector(TelephoneInput.selectors.label);
2331        }
2332
2333        getErrorDiv() {
2334            return this.element.querySelector(TelephoneInput.selectors.errorDiv);
2335        }
2336
2337        getTooltipDiv() {
2338            return this.element.querySelector(TelephoneInput.selectors.tooltipDiv);
2339        }
2340
2341        getQuestionMarkDiv() {
2342            return this.element.querySelector(TelephoneInput.selectors.qm);
2343        }
2344
2345        setModel(model) {
2346            super.setModel(model);
2347            if (this.widget.value !== '') {
2348                this.setModelValue(this.widget.value);
2349            }
2350            this.widget.addEventListener('blur', (e) => {
2351                this.setModelValue(e.target.value);
2352                this.setWidgetValueToDisplayValue();
2353                this.setInactive();
2354                this.triggerExit();
2355            });
2356            this.widget.addEventListener('focus', (e) => {
2357                this.setActive();
2358                this.setWidgetValueToModelValue();
2359                this.triggerEnter();
2360            });
2361        }
2362    }
2363
2364    FormView.Utils.setupField(({element, formContainer}) => {
2365        return new TelephoneInput({element, formContainer})
2366    }, TelephoneInput.selectors.self);
2367
2368})();
2369
2370/*******************************************************************************
2371 * Copyright 2022 Adobe
2372 *
2373 * Licensed under the Apache License, Version 2.0 (the "License");
2374 * you may not use this file except in compliance with the License.
2375 * You may obtain a copy of the License at
2376 *
2377 *     http://www.apache.org/licenses/LICENSE-2.0
2378 *
2379 * Unless required by applicable law or agreed to in writing, software
2380 * distributed under the License is distributed on an "AS IS" BASIS,
2381 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2382 * See the License for the specific language governing permissions and
2383 * limitations under the License.
2384 ******************************************************************************/
2385(function() {
2386
2387    "use strict";
2388    class EmailInput extends FormView.FormFieldBase {
2389
2390        static NS = FormView.Constants.NS;
2391        /**
2392         * Each FormField has a data attribute class that is prefixed along with the global namespace to
2393         * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be
2394         * data-{NS}-{IS}-x=""
2395         * @type {string}
2396         */
2397        static IS = "adaptiveFormEmailInput";
2398        static bemBlock = 'cmp-adaptiveform-emailinput'
2399        static selectors  = {
2400            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
2401            widget: `.${EmailInput.bemBlock}__widget`,
2402            label: `.${EmailInput.bemBlock}__label`,
2403            description: `.${EmailInput.bemBlock}__longdescription`,
2404            qm: `.${EmailInput.bemBlock}__questionmark`,
2405            errorDiv: `.${EmailInput.bemBlock}__errormessage`,
2406            tooltipDiv: `.${EmailInput.bemBlock}__shortdescription`
2407        };
2408
2409        constructor(params) {
2410            super(params);
2411        }
2412
2413        getWidget() {
2414            return this.element.querySelector(EmailInput.selectors.widget);
2415        }
2416
2417        getDescription() {
2418            return this.element.querySelector(EmailInput.selectors.description);
2419        }
2420
2421        getLabel() {
2422            return this.element.querySelector(EmailInput.selectors.label);
2423        }
2424
2425        getErrorDiv() {
2426            return this.element.querySelector(EmailInput.selectors.errorDiv);
2427        }
2428
2429        getTooltipDiv() {
2430            return this.element.querySelector(EmailInput.selectors.tooltipDiv);
2431        }
2432
2433        getQuestionMarkDiv() {
2434            return this.element.querySelector(EmailInput.selectors.qm);
2435        }
2436
2437        setModel(model) {
2438            super.setModel(model);
2439            if (this.widget.value !== '') {
2440                this.setModelValue(this.widget.value);
2441            }
2442            this.widget.addEventListener('blur', (e) => {
2443                this.setModelValue(e.target.value);
2444                this.setWidgetValueToDisplayValue();
2445                this.setInactive();
2446                this.triggerExit();
2447            });
2448            this.widget.addEventListener('focus', (e) => {
2449                this.setActive();
2450                this.setWidgetValueToModelValue();
2451                this.triggerEnter();
2452            });
2453        }
2454    }
2455
2456    FormView.Utils.setupField(({element, formContainer}) => {
2457        return new EmailInput({element, formContainer})
2458    }, EmailInput.selectors.self);
2459
2460})();
2461
2462/*******************************************************************************
2463 * Copyright 2022 Adobe
2464 *
2465 * Licensed under the Apache License, Version 2.0 (the "License");
2466 * you may not use this file except in compliance with the License.
2467 * You may obtain a copy of the License at
2468 *
2469 *     http://www.apache.org/licenses/LICENSE-2.0
2470 *
2471 * Unless required by applicable law or agreed to in writing, software
2472 * distributed under the License is distributed on an "AS IS" BASIS,
2473 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2474 * See the License for the specific language governing permissions and
2475 * limitations under the License.
2476 ******************************************************************************/
2477
2478/**
2479 * This class is responsible for interacting with the numeric input widget. It implements edit/display format
2480 * for numeric input, along with the following features
2481 * - Convert's input type number to text to support display/edit format (for example `$` symbol)
2482 * - One cannot type or paste alphabets in the html input element
2483 */
2484
2485 if (typeof window.NumericInputWidget === 'undefined') {
2486
2487     window.NumericInputWidget =  class {
2488         #widget=null
2489         #model=null // passed by reference
2490         #options=null
2491         #defaultOptions={
2492             value : null,
2493             curValue: null,
2494             pos: 0,
2495             lengthLimitVisible: true,
2496             zero:"0",
2497             decimal:".",
2498             minus:"-"
2499         }
2500         //TODO: to support writing in different locales \d should be replaced by [0-9] for different locales
2501         #matchArray ={
2502             "integer":"^[+-]?{digits}*$"
2503         }
2504         #regex=null
2505         #processedValue=null
2506         #engRegex=null
2507         #writtenInLocale=false
2508         #previousCompositionVal=""
2509
2510         #toLatinForm    (halfOrFullWidthStr) {
2511             // refer http://www.fileformat.info/info/unicode/block/halfwidth_and_fullwidth_forms/utf8test.htm
2512             return halfOrFullWidthStr.replace(
2513                 /[\uff00-\uffef]/g,
2514                 function(ch) { return String.fromCharCode(ch.charCodeAt(0) - 0xfee0); }
2515             );
2516         }
2517
2518         constructor(widget, model) {
2519             // initialize the widget and model
2520             this.#widget = widget;
2521             this.#model = model;
2522             // initialize options for backward compatibility
2523             this.#options = Object.assign({}, this.#defaultOptions, this.#model._jsonModel);
2524             let matchStr =  this.#matchArray[this.#options.type];
2525             if(matchStr) {
2526                 let ld = this.#options.leadDigits,
2527                     fd = this.#options.fracDigits,
2528                     ldstr = ld && ld !== -1 ? "{0,"+ld+"}"
2529                         : "*",
2530                     fdstr = fd && fd !== -1 ? "{0,"+fd+"}"
2531                         : "*";
2532                 matchStr =  matchStr.replace("{leading}",ldstr)
2533                     .replace("{fraction}",fdstr);
2534                 let localeStr = matchStr.replace(/{digits}/g,this.#getDigits())
2535                         .replace("{decimal}",this.#escape(this.#options.decimal)),
2536                     engStr = matchStr.replace(/{digits}/g,"[0-9]")
2537                         .replace("{decimal}","\\.")
2538                 this.#processedValue = !(this.#getDigits() === "[0123456789]" && this.#options.decimal === ".")
2539                 this.#regex = new RegExp(localeStr, "g");
2540                 this.#engRegex = new RegExp(engStr, "g");
2541             }
2542
2543             // change the input type to text for patterns
2544             this.#widget.setAttribute("type", "text");
2545             this.#attachEventHandlers(widget);
2546         }
2547
2548         #attachEventHandlers(widget, model) {
2549             widget.addEventListener('keydown', (e)=> {
2550                 this.#handleKeyDown(e);
2551             });
2552             widget.addEventListener('keypress', (e)=> {
2553                 this.#handleKeyPress(e);
2554             });
2555             widget.addEventListener('focus', (e)=> {
2556                 this.#widget.value = this.#model.value;
2557             });
2558             widget.addEventListener('paste', (e)=> {
2559                 this.#handlePaste(e);
2560             });
2561             widget.addEventListener('cut', (e)=> {
2562                 this.#handleCut(e);
2563             });
2564             widget.addEventListener('blur', (e) => {
2565                 this.#model.dispatch(new FormView.Actions.UIChange({'value': this.getValue(e.target.value)}));
2566                 this.#widget.value = this.#model.displayValue;
2567             });
2568             // IME specific handling, to handle japanese languages max limit
2569             this.#attachCompositionEventHandlers(widget);
2570         }
2571
2572         #attachCompositionEventHandlers(widget) {
2573             let isComposing = false; // IME Composing going on
2574             let hasCompositionJustEnded = false; // Used to swallow keyup event related to compositionend
2575             // IME specific handling, to handle japanese languages max limit
2576             // since enter can also be invoked during composing, a special handling is done here
2577             let that = this,
2578                 changeCaratPosition = function() {
2579                     // change the carat selection position to further limit input of characters
2580                     let range = window.getSelection();
2581                     range.selectAllChildren(widget);
2582                     range.collapseToEnd();
2583                 };
2584             widget.addEventListener('keyup', function(event) {
2585                 if (/*isComposing || */hasCompositionJustEnded) {
2586                     if (that.#compositionUpdateCallback(event)) {
2587                         changeCaratPosition();
2588                     }
2589                     // IME composing fires keydown/keyup events
2590                     hasCompositionJustEnded = false;
2591                 }
2592             });
2593             widget.addEventListener('compositionstart',
2594                 function(event) {
2595                     isComposing = true;
2596                 });
2597             widget.addEventListener("compositionupdate",
2598                 function(event) {
2599                     // event.originalEvent.data refers to the actual content
2600                     if (that.#compositionUpdateCallback(event)) {
2601                         changeCaratPosition();
2602                     }
2603                 });
2604             widget.addEventListener("compositionend",
2605                 function(event) {
2606                     isComposing = false;
2607                     // some browsers (IE, Firefox, Safari) send a keyup event after
2608                     //  compositionend, some (Chrome, Edge) don't. This is to swallow
2609                     // the next keyup event, unless a keydown event happens first
2610                     hasCompositionJustEnded = true;
2611                 });
2612             widget.addEventListener("keydown",
2613                 function(event) {
2614                     // Safari on OS X may send a keydown of 229 after compositionend
2615                     if (event.which !== 229) {
2616                         hasCompositionJustEnded = false;
2617                     }
2618                 });
2619         }
2620
2621         #getDigits() {
2622             let zeroCode = this.#options.zero.charCodeAt(0),
2623                 digits = "";
2624             for(let i = 0;i < 10;i++) {
2625                 digits += String.fromCharCode(zeroCode + i);
2626             }
2627             return "["+digits+"]"
2628         }
2629
2630         #escape(str) {
2631             return str.replace(".", "\\.")
2632         }
2633
2634
2635         getValue(value) {
2636             // we support full width, half width and locale specific numbers
2637             value = this.#toLatinForm(value);
2638             if(value.length > 0 && this.#processedValue && !value.match(this.#engRegex)) {
2639                 this.#writtenInLocale = true;
2640                 value = this.#convertValueFromLocale(value);
2641             } else {
2642                 this.#writtenInLocale = false
2643             }
2644             if(value && value.length >= this.#options.combCells )
2645                 value = value.slice(0,this.#options.combCells);
2646             this.#previousCompositionVal = value;
2647             return value;
2648         }
2649
2650         #compositionUpdateCallback(event) {
2651             let that = this;
2652             let flag = false;
2653             let leadDigits = that.#options.leadDigits;
2654             let fracDigits = that.#options.fracDigits;
2655             // we don't check use-case where just fracDigits is set since in case of composition update, the value to update is not known
2656             if (leadDigits !== -1) {
2657                 let val = this.#widget.value;
2658                 if (event.type === "compositionupdate" && event.originalEvent.data) {
2659                     val = val + event.originalEvent.data.substr(event.originalEvent.data.length - 1);
2660                 }
2661                 // can't use the existing regex (since current regex checks for english digits), rather doing leadDigit compare
2662                 let totalLength = leadDigits + (fracDigits !== -1 ? (fracDigits + that.#options.decimal.length) : 0);
2663                 if (val.indexOf(that.#options.decimal) === -1) {
2664                     totalLength = leadDigits;
2665                 }
2666                 let latinVal = this.#toLatinForm(val);
2667                 // match both since we support full width, half width and locale specific input
2668                 let match = latinVal.match(that.#regex)|| latinVal.match(this.#engRegex);
2669                 flag  = !match;
2670                 if (match === null) {
2671                     // entered invalid character, revert to previous value
2672                     that.#widget.value = that.#previousCompositionVal;
2673                     flag = true;
2674                 } else if (flag) {
2675                     // if max reached
2676                     let newVal = val.substr(0, totalLength);
2677                     that.#widget.value = newVal;
2678                     that.#previousCompositionVal = newVal;
2679                     flag = true;
2680                 } else {
2681                     that.#previousCompositionVal = val;
2682                 }
2683             }
2684             return flag;
2685         }
2686
2687         trigger(event, detail) {
2688             if (!this.#widget) {
2689                 return this;
2690             }
2691             const eventName = event.split('.')[0];
2692             const isNativeEvent =
2693                 typeof document.body[`on${eventName}`] !== 'undefined';
2694             if (isNativeEvent) {
2695                 this.#widget.dispatchEvent(new Event(eventName));
2696                 return this;
2697             }
2698             const customEvent = new CustomEvent(eventName, {
2699                 detail: detail || null,
2700             });
2701             this.#widget.dispatchEvent(customEvent);
2702             return this;
2703         }
2704
2705         getHTMLSupportedAttr(domElement, attr){
2706             try{
2707                 return domElement[attr];
2708             }
2709             catch (err){
2710                 return undefined;
2711             }
2712         }
2713
2714         #handleKeyInput(event, character, code){
2715             if(event.ctrlKey && !(['paste', 'cut'].includes(event.type))) {
2716                 return true;
2717             }
2718
2719             this.#handleKeyDown(arguments);
2720             this.#options.lengthLimitVisible = true;
2721             let val = this.#widget.value,
2722                 // if selectionStart attribute isn't supported then its value will be undefined
2723                 selectionStart = this.getHTMLSupportedAttr(this.#widget, "selectionStart") || 0,
2724                 isSelectionAttrSupported = !(selectionStart === undefined || selectionStart === null),
2725                 selectionEnd = this.getHTMLSupportedAttr(this.#widget, "selectionEnd") || 0,
2726                 combCells = parseInt(this.#options.combCells) || 0,
2727                 current,
2728                 change = character;
2729
2730             if (combCells > 0 ) {
2731                 change = character.substr(0, combCells - val.length + selectionEnd - selectionStart);
2732             }
2733
2734             // CQ-4245407 : selectionStart and selectionEnd attributes aren't supported in case of input type = number
2735             // it is used for providing native HTML5 implementation for numeric field, so no further processing is required
2736             // As it is specific to AF and AF doesn't support change event on each keypress, so this change should be fine
2737             if (!isSelectionAttrSupported) {
2738                 return true;
2739             }
2740
2741             current = val.substr(0, selectionStart) + change + val.substr(selectionEnd);
2742             // done to handle support for both full width, half width or mixed input in number field
2743             let latinCurrentValue = this.#toLatinForm(current);
2744
2745             if (!(this.#regex == null || latinCurrentValue.match(this.#regex) || latinCurrentValue.match(this.#engRegex))) {
2746                 event.preventDefault();
2747                 return false;
2748             }
2749             if (!(['keydown', 'cut'].includes(event.type)) && combCells && (val.length >= combCells || current.length > combCells) && selectionStart === selectionEnd) {
2750                 event.preventDefault();
2751                 return false;
2752             }
2753
2754             this.#options.curValue = val;
2755             this.#previousCompositionVal = val;
2756             this.#options.pos = selectionStart;
2757         }
2758
2759         #handleKeyDown(event){
2760             if (event) {
2761                 let code = event.charCode || event.which || event.keyCode || 0;
2762                 if(code === 8 || code === 46) // backspace and del
2763                     this.#handleKeyInput(event, "", code);
2764                 else if(code === 32) { // suppress space
2765                     event.preventDefault();
2766                     return false;
2767                 }
2768             }
2769         }
2770
2771         #isValidChar(character) {
2772             character = this.#toLatinForm(character);
2773             let lastSingleDigitChar = String.fromCharCode(this.#options.zero.charCodeAt(0) + 9);
2774             // we only full width, half width and also locale specific if customer has overlayed the i18n file
2775             return (character >= "0" && character <= "9") || (character>=this.#options.zero && character<=lastSingleDigitChar) || character===this.#options.decimal || character===this.#options.minus;
2776         }
2777
2778         isNonPrintableKey(key) {
2779             return (key   // In IE, event.key returns words instead of actual characters for some keys.
2780                 && !['MozPrintableKey','Divide','Multiply','Subtract','Add','Enter','Decimal','Spacebar','Del'].includes(key)
2781                 && key.length !== 1 )
2782         }
2783
2784         #handleKeyPress(event){
2785             if (event) {
2786                 let code = event.charCode || event.which || event.keyCode || 0,
2787                     character = String.fromCharCode(code);
2788
2789                 if(this.isNonPrintableKey(event.key)) { // mozilla also generates a keypress, along with keydown
2790                     return true;                                               // for all keys, so only handling printable keys in keypress
2791                 }
2792
2793                 if (this.#isValidChar(character))
2794                     this.#handleKeyInput(event, character, code);
2795                 else if (!event.ctrlKey){
2796                     event.preventDefault();
2797                     return false;
2798                 }
2799             }
2800         }
2801
2802         #handlePaste(event){
2803             if (event) {
2804                 // get the contents
2805                 let pastedChar = undefined;
2806                 if (window.clipboardData && window.clipboardData.getData) { // IE
2807                     pastedChar = window.clipboardData.getData('Text');
2808                 } else if ((event.originalEvent || event).clipboardData && (event.originalEvent || event).clipboardData.getData) {
2809                     pastedChar = (event.originalEvent || event).clipboardData.getData('text/plain');
2810                 }
2811
2812                 if(pastedChar) {
2813                     let allPastedCharsValid = pastedChar.split('').every(function (character) {
2814                         return this.#isValidChar(character);
2815                     }, this);
2816                     if (allPastedCharsValid) {
2817                         // during paste we support both half width, full width and locale specific numbers
2818                         pastedChar = this.#toLatinForm(pastedChar);
2819                         this.#handleKeyInput(event, pastedChar, 0);
2820                     }
2821                     else if (!event.ctrlKey) {
2822                         event.preventDefault();
2823                         return false;
2824                     }
2825                 }
2826             }
2827         }
2828
2829         #handleCut(event) {
2830             if (event) {
2831                 this.#handleKeyInput(event, "", 0);
2832             }
2833         }
2834
2835         #convertValueToLocale(val) {
2836             let zeroCode = this.#options.zero.charCodeAt(0);
2837             return  val.map(function(c) {
2838                 if(c === ".") {
2839                     return this.#options.decimal;
2840                 } else if(c === "-") {
2841                     return this.#options.minus;
2842                 } else {
2843                     return String.fromCharCode(parseInt(c) + zeroCode);
2844                 }
2845             },this).join("");
2846         }
2847
2848         #convertValueFromLocale(val) {
2849             val = this.#toLatinForm(val);
2850             let zeroCode = this.#options.zero.charCodeAt(0);
2851             return  val.map(function(c) {
2852                 if(c === this.#options.decimal) {
2853                     return ".";
2854                 } else if(c === this.#options.minus) {
2855                     return "-";
2856                 } else {
2857                     return (c.charCodeAt(0) - zeroCode).toString();
2858                 }
2859             },this).join("");
2860         }
2861
2862         /**
2863          * Checks if the edit value is same as value present in the user control(html form element)
2864          * @returns {boolean}
2865          */
2866         #isValueSame() {
2867             return (((this.#model.value === null) && (this.#widget.value === "")) || (this.#model.value === this.#widget.value));
2868         }
2869
2870         setValue(value) {
2871             // if the value is same, don't do anything
2872             if(!this.#isValueSame()){
2873                 if(value && this.#writtenInLocale) {
2874                     this.#widget.value = this.#convertValueToLocale(value);
2875                 } else {
2876                     this.#widget.value=  this.#model.displayValue;
2877                 }
2878             }
2879         }
2880     }
2881 }
2882
2883
2884/*******************************************************************************
2885 * Copyright 2022 Adobe
2886 *
2887 * Licensed under the Apache License, Version 2.0 (the "License");
2888 * you may not use this file except in compliance with the License.
2889 * You may obtain a copy of the License at
2890 *
2891 *     http://www.apache.org/licenses/LICENSE-2.0
2892 *
2893 * Unless required by applicable law or agreed to in writing, software
2894 * distributed under the License is distributed on an "AS IS" BASIS,
2895 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2896 * See the License for the specific language governing permissions and
2897 * limitations under the License.
2898 ******************************************************************************/
2899(function() {
2900
2901    "use strict";
2902    class NumberInput extends FormView.FormFieldBase {
2903
2904        static NS = FormView.Constants.NS;
2905        static IS = "adaptiveFormNumberInput";
2906        static bemBlock = 'cmp-adaptiveform-numberinput';
2907        static selectors  = {
2908            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
2909            widget: `.${NumberInput.bemBlock}__widget`,
2910            label: `.${NumberInput.bemBlock}__label`,
2911            description: `.${NumberInput.bemBlock}__longdescription`,
2912            errorDiv: `.${NumberInput.bemBlock}__errormessage`,
2913            qm: `.${NumberInput.bemBlock}__questionmark`,
2914            tooltipDiv: `.${NumberInput.bemBlock}__shortdescription`
2915        };
2916
2917        constructor(params) {
2918            super(params);
2919        }
2920
2921        getClass() {
2922            return NumberInput.IS;
2923        }
2924
2925        getWidget() {
2926            return this.element.querySelector(NumberInput.selectors.widget);
2927        }
2928
2929        getDescription() {
2930            return this.element.querySelector(NumberInput.selectors.description);
2931        }
2932
2933        getLabel() {
2934            return this.element.querySelector(NumberInput.selectors.label);
2935        }
2936
2937        getErrorDiv() {
2938            return this.element.querySelector(NumberInput.selectors.errorDiv);
2939        }
2940
2941        getTooltipDiv() {
2942            return this.element.querySelector(NumberInput.selectors.tooltipDiv);
2943        }
2944
2945        getQuestionMarkDiv() {
2946            return this.element.querySelector(NumberInput.selectors.qm);
2947        }
2948
2949        initializeWidget() {
2950            this.widgetObject = new NumericInputWidget(this.getWidget(), this._model);
2951            this.getWidget().addEventListener('blur', (e) => {
2952                if(this.element) {
2953                    this.setInactive();
2954                }
2955            });
2956        }
2957
2958        updateValue(value) {
2959            if (this.widgetObject == null && (this._model._jsonModel.editFormat || this._model._jsonModel.displayFormat || FormView.Utils.isUserAgent('safari'))) {
2960                this.initializeWidget();
2961            }
2962            if (this.widgetObject) {
2963                this.widgetObject.setValue(value);
2964                super.updateEmptyStatus();
2965            } else {
2966                super.updateValue(value);
2967            }
2968        }
2969
2970        setModel(model) {
2971            super.setModel(model);
2972            // only initialize if patterns are set
2973            if (this._model._jsonModel.editFormat || this._model._jsonModel.displayFormat || this._model._jsonModel.displayValueExpression
2974                || this._model._jsonModel.type === 'integer' || FormView.Utils.isUserAgent('safari')) {
2975                if (this.widgetObject == null) {
2976                    this.initializeWidget();
2977                }
2978            } else {
2979                if (this.widget.value !== '') {
2980                    this.setModelValue(this.widget.value);
2981                }
2982                this.getWidget().addEventListener('blur', (e) => {
2983                    this.setModelValue(e.target.value);
2984                    if(this.element) {
2985                        this.setInactive();
2986                        this.triggerExit();
2987                    }
2988                });
2989            }
2990            this.getWidget().addEventListener('focus', (e) => {
2991                if (this.element) {
2992                    this.setActive();
2993                    this.triggerEnter();
2994                }
2995            });
2996        }
2997    }
2998
2999    FormView.Utils.setupField(({element, formContainer}) => {
3000        return new NumberInput({element,formContainer})
3001    }, NumberInput.selectors.self);
3002})();
3003
3004/*******************************************************************************
3005 * Copyright 2022 Adobe
3006 *
3007 * Licensed under the Apache License, Version 2.0 (the "License");
3008 * you may not use this file except in compliance with the License.
3009 * You may obtain a copy of the License at
3010 *
3011 *     http://www.apache.org/licenses/LICENSE-2.0
3012 *
3013 * Unless required by applicable law or agreed to in writing, software
3014 * distributed under the License is distributed on an "AS IS" BASIS,
3015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3016 * See the License for the specific language governing permissions and
3017 * limitations under the License.
3018 ******************************************************************************/
3019(function () {
3020
3021    class Panel extends FormView.FormPanel {
3022
3023        _templateHTML = {};
3024        #childIdMap = {}
3025
3026        static NS = FormView.Constants.NS;
3027        static IS = "adaptiveFormPanel";
3028        static bemBlock = 'cmp-container';
3029        static selectors = {
3030            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
3031            label: `.${Panel.bemBlock}__label`,
3032            description: `.${Panel.bemBlock}__longdescription`,
3033            qm: `.${Panel.bemBlock}__questionmark`,
3034            tooltipDiv: `.${Panel.bemBlock}__shortdescription`
3035        };
3036
3037        constructor(params) {
3038            super(params);
3039        }
3040
3041        getClass() {
3042            return Panel.IS;
3043        }
3044
3045        setFocus(id) {
3046            super.setFocus(id);
3047            this.setActive();
3048        }
3049
3050        getWidgetId(){
3051          return this.getId();
3052        }
3053
3054        getWidget() {
3055            return null;
3056        }
3057
3058        getDescription() {
3059            return this.element.querySelector(Panel.selectors.description);
3060        }
3061
3062        getLabel() {
3063            return this.element.querySelector(Panel.selectors.label);
3064        }
3065
3066        getErrorDiv() {
3067            //error div is not defined
3068            //return this.element.querySelector(Panel.selectors.errorDiv);
3069            return null;
3070        }
3071
3072        getTooltipDiv() {
3073            return this.element.querySelector(Panel.selectors.tooltipDiv);
3074        }
3075
3076        getQuestionMarkDiv() {
3077            return this.element.querySelector(Panel.selectors.qm);
3078        }
3079
3080        addChild(childView) {
3081            super.addChild(childView);
3082            if (this.getCountOfAllChildrenInModel() === this.children.length) {
3083                this.#cacheElements(this.element);
3084                this.#cacheDivToAppendChildMarkup();
3085                this.cacheClosestFieldsInView();
3086            } else if (childView.getInstanceManager() != null) {
3087                // this is for cases when repeatable instances are added after first initialisation
3088                this.#cacheElements(this.element);
3089            }
3090        }
3091
3092        getChildViewByIndex(index) {
3093            if (this.#getCachedElements()[index] != null) {
3094                return this.getChild(this.#getCachedElements()[index].id)
3095            }
3096        }
3097
3098        /**
3099         * Adds unique HTML for added instance corresponding to requirements of different types of repeatableParent
3100         * @param instanceManager of the repeated component
3101         * @param addedModel of the repeated component
3102         * @param htmlElement of the repeated component
3103         */
3104        addRepeatableMarkup(instanceManager, addedModel, htmlElement) {
3105            let result = this.#getBeforeViewElement(instanceManager, addedModel.index);
3106            if (result.beforeViewElement != null) {
3107                result.beforeViewElement.after(htmlElement);
3108            } else if (result.parentElement != null) {
3109                if (result.parentElement.children.length == 0) {
3110                    result.parentElement.append(htmlElement);
3111                } else {
3112                    result.parentElement.insertBefore(htmlElement, result.parentElement.firstElementChild);
3113                }
3114            }
3115            return htmlElement;
3116        }
3117
3118        handleChildRemoval(removedInstanceView) {
3119            this.children.splice(this.children.indexOf(removedInstanceView), 1);
3120            this.#cacheElements(this._elements.self);
3121        }
3122
3123        handleChildAddition(childView) {
3124            //can't initiate cacheElement From here as children property of the panel is not updated at this point,
3125            // hence cacheElement is called from addChild method which ensures panel's addChild is called first and children
3126            // property is updated
3127        }
3128
3129        #cacheElements(wrapper) {
3130            this._elements = {};
3131            this._elements.self = wrapper;
3132            this._elements.items = [];
3133            this.#childIdMap = {};
3134            for (let i = 0; i < this.children.length; i++) {
3135                this.#childIdMap[this.children[i].id] = this.children[i];
3136            }
3137            let components = this._elements.self.querySelectorAll("[data-cmp-is]");
3138            for (let i = 0; i < components.length; i++) {
3139                //only consider this panel's child and not children of some  child panel.
3140                if (this.#childIdMap.hasOwnProperty(components[i].id)) {
3141                    this._elements.items.push(components[i]);
3142                }
3143            }
3144        }
3145
3146        #getCachedElements() {
3147            return this._elements.items;
3148        }
3149
3150        #getCachedElementById(id) {
3151            for (let i = 0; i < this.#getCachedElements().length; i++) {
3152                if (this.#getCachedElements()[i].id == id) {
3153                    return this.#getCachedElements()[i];
3154                }
3155            }
3156        }
3157
3158        #cacheDivToAppendChildMarkup() {
3159            if (this.children.length > 0 && this._templateHTML['divToAppendChild'] === undefined) {
3160                var fieldView = this.children[0];
3161                //because htmlElement cached for repeating is element.parentElement in instanceManager
3162                this._templateHTML['divToAppendChild'] = fieldView.element.parentElement.parentElement;
3163            }
3164        }
3165
3166        #getBeforeViewElement(instanceManager, instanceIndex) {
3167            var result = {};
3168            var instanceManagerId = instanceManager.getId();
3169            if (instanceIndex == 0) {
3170                var closestNonRepeatableFieldId = this._templateHTML[instanceManagerId]['closestNonRepeatableFieldId'];
3171                var closestRepeatableFieldInstanceManagerIds = this._templateHTML[instanceManagerId]['closestRepeatableFieldInstanceManagerIds'];
3172                var indexToInsert = this.getIndexToInsert(closestNonRepeatableFieldId, closestRepeatableFieldInstanceManagerIds);
3173                if (indexToInsert > 0) {
3174                    result.beforeViewElement = this.#getCachedElements()[indexToInsert - 1].parentElement;
3175                } else {
3176                    result.parentElement = this._templateHTML['divToAppendChild'];
3177                }
3178            } else {
3179                let previousInstanceItemDiv = instanceManager.getElementAt(instanceIndex - 1);
3180                result.beforeViewElement = previousInstanceItemDiv;
3181            }
3182            return result;
3183        }
3184    }
3185
3186    FormView.Utils.setupField(({element, formContainer}) => {
3187        return new Panel({element, formContainer})
3188    }, Panel.selectors.self);
3189})();
3190
3191/*******************************************************************************
3192 * Copyright 2022 Adobe
3193 *
3194 * Licensed under the Apache License, Version 2.0 (the "License");
3195 * you may not use this file except in compliance with the License.
3196 * You may obtain a copy of the License at
3197 *
3198 *     http://www.apache.org/licenses/LICENSE-2.0
3199 *
3200 * Unless required by applicable law or agreed to in writing, software
3201 * distributed under the License is distributed on an "AS IS" BASIS,
3202 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3203 * See the License for the specific language governing permissions and
3204 * limitations under the License.
3205 ******************************************************************************/
3206(function() {
3207
3208    "use strict";
3209    class RadioButton extends FormView.FormOptionFieldBase {
3210
3211        static NS = FormView.Constants.NS;
3212        /**
3213         * Each FormField has a data attribute class that is prefixed along with the global namespace to
3214         * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be
3215         * data-{NS}-{IS}-x=""
3216         * @type {string}
3217         */
3218        static IS = "adaptiveFormRadioButton";
3219        static bemBlock = 'cmp-adaptiveform-radiobutton';
3220        static selectors  = {
3221            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
3222            widgets: `.${RadioButton.bemBlock}__widget`,
3223            widget: `.${RadioButton.bemBlock}__option__widget`,
3224            label: `.${RadioButton.bemBlock}__label`,
3225            description: `.${RadioButton.bemBlock}__longdescription`,
3226            qm: `.${RadioButton.bemBlock}__questionmark`,
3227            errorDiv: `.${RadioButton.bemBlock}__errormessage`,
3228            tooltipDiv: `.${RadioButton.bemBlock}__shortdescription`,
3229            option: `.${RadioButton.bemBlock}__option`,
3230            optionLabel: `.${RadioButton.bemBlock}__option-label`
3231        };
3232
3233        constructor(params) {
3234            super(params);
3235            this.qm = this.element.querySelector(RadioButton.selectors.qm);
3236        }
3237
3238        getWidgets() {
3239            return this.element.querySelector(RadioButton.selectors.widgets);
3240        }
3241
3242        getWidget() {
3243          return this.element.querySelectorAll(RadioButton.selectors.widget);
3244        }
3245
3246        getDescription() {
3247            return this.element.querySelector(RadioButton.selectors.description);
3248        }
3249
3250        getLabel() {
3251            return this.element.querySelector(RadioButton.selectors.label);
3252        }
3253
3254        getQuestionMarkDiv() {
3255            return this.element.querySelector(RadioButton.selectors.qm);
3256        }
3257
3258        getTooltipDiv() {
3259            return this.element.querySelector(RadioButton.selectors.tooltipDiv);
3260        }
3261
3262        getErrorDiv() {
3263            return this.element.querySelector(RadioButton.selectors.errorDiv);
3264        }
3265
3266        getOptions() {
3267            return this.element.querySelectorAll(RadioButton.selectors.option);
3268        }
3269
3270        #addWidgetListeners(optionWidget) {
3271            optionWidget.addEventListener('change', (e) => {
3272                this.setModelValue(e.target.value);
3273            });
3274            optionWidget.addEventListener('focus', (e) => {
3275                this.setActive();
3276            });
3277            optionWidget.addEventListener('blur', (e) => {
3278                this.setInactive();
3279            });
3280        }
3281
3282        setModel(model) {
3283            super.setModel(model);
3284            this.widget.forEach(optionWidget => {
3285                this.#addWidgetListeners(optionWidget);
3286            });
3287        }
3288
3289        updateEnabled(enabled, state) {
3290            this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_ENABLED, enabled);
3291            let widgets = this.widget;
3292            widgets.forEach(widget => {
3293                if (enabled === false) {
3294                    if(state.readOnly === false){
3295                        widget.setAttribute(FormView.Constants.HTML_ATTRS.DISABLED, "disabled");
3296                    }
3297                } else if (state.readOnly === false) {
3298                    widget.removeAttribute(FormView.Constants.HTML_ATTRS.DISABLED);
3299                }
3300            });
3301        }
3302
3303        updateReadOnly(readonly) {
3304            let widgets = this.widget;
3305            this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_READONLY, readonly);
3306            widgets.forEach(widget => {
3307                if (readonly === true) {
3308                    widget.setAttribute(FormView.Constants.HTML_ATTRS.DISABLED, "disabled");
3309                } else {
3310                    widget.removeAttribute(FormView.Constants.HTML_ATTRS.DISABLED);
3311                }
3312            });
3313        }
3314
3315        updateValidity(validity) {
3316            if(validity.valid === undefined) {
3317                this.element.removeAttribute(FormView.Constants.DATA_ATTRIBUTE_VALID);
3318                this.widget.forEach(widget => widget.removeAttribute(FormView.Constants.ARIA_INVALID));
3319            } else {
3320                this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_VALID, validity.valid);
3321                this.widget.forEach(widget => widget.setAttribute(FormView.Constants.ARIA_INVALID, !validity.valid));
3322            }
3323        }
3324
3325        updateValue(modelValue) {
3326            this.widget.forEach(widget => {
3327                if (modelValue != null && widget.value != null && (modelValue.toString() == widget.value.toString())) {
3328                    widget.checked = true;
3329                    widget.setAttribute(FormView.Constants.HTML_ATTRS.CHECKED, FormView.Constants.HTML_ATTRS.CHECKED);
3330                } else {
3331                    widget.checked = false;
3332                    widget.removeAttribute(FormView.Constants.HTML_ATTRS.CHECKED);
3333                }
3334            }, this)
3335            super.updateEmptyStatus();
3336        }
3337
3338        #createRadioOption(value, itemLabel) {
3339            const optionTemplate = `
3340            <div class="${RadioButton.selectors.option.slice(1)}">
3341                <label class="${RadioButton.selectors.optionLabel.slice(1)}">
3342                    <input type="radio" name="${this._model.name}" class="${RadioButton.selectors.widget.slice(1)}" value="${value}" tabindex="0">
3343                    <span>${itemLabel}</span>
3344                </label>
3345            </div>`;
3346
3347            const container = document.createElement('div'); // Create a container element to hold the template
3348            container.innerHTML = optionTemplate;
3349            let addedOptionWidget = container.querySelector(RadioButton.selectors.widget);
3350            if(this._model.readOnly === true || this._model.enabled === false) {
3351                addedOptionWidget.setAttribute("disabled", true);
3352                if(this._model.readOnly === true) {
3353                    addedOptionWidget.setAttribute("aria-readonly", true);
3354                }
3355            }
3356            this.#addWidgetListeners(addedOptionWidget);
3357            return container.firstElementChild; // Return the first child, which is the created option
3358        }
3359
3360        updateEnum(newEnums) {
3361            super.updateEnumForRadioButtonAndCheckbox(newEnums, this.#createRadioOption);
3362            // refresh the widget references, to dynamically added options
3363            this.widget = this.getWidget();
3364        }
3365
3366        updateEnumNames(newEnumNames) {
3367            super.updateEnumNamesForRadioButtonAndCheckbox(newEnumNames, this.#createRadioOption);
3368            // refresh the widget references, to dynamically added options
3369            this.widget = this.getWidget();
3370        }
3371
3372        updateRequired(required, state) {
3373            if (this.widget) {
3374                this.element.toggleAttribute("required", required);
3375                this.element.setAttribute("data-cmp-required", required);
3376            }
3377        }
3378
3379        syncMarkupWithModel() {
3380            super.syncMarkupWithModel();
3381            this.#syncWidgetName();
3382        }
3383
3384        #syncWidgetName() {
3385            const name = this.getModel()?.name;
3386            this.widget.forEach(widget => {
3387                widget.setAttribute("name", `${this.id}_${name}`);
3388            });
3389        }
3390    }
3391
3392    FormView.Utils.setupField(({element, formContainer}) => {
3393        return new RadioButton({element, formContainer});
3394    }, RadioButton.selectors.self);
3395
3396})();
3397
3398/*******************************************************************************
3399 * Copyright 2022 Adobe
3400 *
3401 * Licensed under the Apache License, Version 2.0 (the "License");
3402 * you may not use this file except in compliance with the License.
3403 * You may obtain a copy of the License at
3404 *
3405 *     http://www.apache.org/licenses/LICENSE-2.0
3406 *
3407 * Unless required by applicable law or agreed to in writing, software
3408 * distributed under the License is distributed on an "AS IS" BASIS,
3409 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3410 * See the License for the specific language governing permissions and
3411 * limitations under the License.
3412 ******************************************************************************/
3413(function() {
3414    "use strict";
3415
3416    class Text extends FormView.FormFieldBase {
3417
3418            static NS = FormView.Constants.NS;
3419            static IS = "adaptiveFormText";
3420            static bemBlock = 'cmp-adaptiveform-text';
3421
3422            static selectors  = {
3423                self: "[data-" + this.NS + '-is="' + this.IS + '"]'
3424            };
3425
3426            constructor(params) {
3427                super(params);
3428            }
3429
3430            getWidget() {
3431                return null;
3432            }
3433
3434            getDescription() {
3435                return null;
3436            }
3437
3438            getLabel() {
3439                return null;
3440            }
3441
3442            getErrorDiv() {
3443                return null;
3444            }
3445
3446            getTooltipDiv() {
3447                return null;
3448            }
3449
3450            getQuestionMarkDiv() {
3451                return null;
3452            }
3453
3454            getClass() {
3455                return Text.IS;
3456            }
3457
3458            setFocus() {
3459                const fieldType = this.parentView?.getModel()?.fieldType;
3460                if (fieldType !== 'form' && this.parentView.setFocus) {
3461                    this.parentView.setFocus(this.getId());
3462                }
3463                this.setActive();
3464                this.element.scrollIntoView({ behavior: 'smooth', block: 'start' });
3465            }
3466
3467            updateValue(value) {
3468                // html sets undefined value as undefined string in input value, hence this check is added
3469                let actualValue = typeof value === "undefined" ? "" :  value;
3470
3471                // Custom configuration for DOMPurify for RTE content
3472                const cleanHTML = (dirtyHTML) => {
3473                    // Specify the allowed tags and attributes
3474                    const allowedTags = [
3475                        'b', 'strong', 'caption', 'i', 'em', 'u',
3476                        'sub', 'sup', 'small', 'blockquote',
3477                        'ul', 'ol', 'li', 'a', 'img',
3478                        'table', 'tbody', 'tr', 'td', 'th',
3479                        'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
3480                        'br', 'p', 'span'
3481                    ];
3482                    const allowedAttributes = [
3483                        'href', 'target', 'rel', '_rte_href',
3484                        'src', 'alt' , 'style', '_rte_a_id_repl',
3485                        'class', 'id', 'title', 'colspan', 'rowspan',
3486                        'cellPadding', 'cellSpacing', 'border', 'width', 'height', 'scope'
3487                    ];
3488
3489                    // Sanitize the HTML
3490                    const sanitizedHTML = window.DOMPurify ? window.DOMPurify.sanitize(dirtyHTML, {
3491                        ALLOWED_TAGS: allowedTags,
3492                        ALLOWED_ATTR: allowedAttributes,
3493                    }) : dirtyHTML;
3494
3495                    return sanitizedHTML;
3496                };
3497
3498                const sanitizedValue = cleanHTML(actualValue);
3499
3500                // since there is no widget for textview, the innerHTML is being changed
3501                if (this.element.children[0]) {
3502                    this.element.children[0].innerHTML = sanitizedValue;
3503                } else {
3504                    this.element.innerHTML = sanitizedValue;
3505                }
3506            }
3507    }
3508
3509    FormView.Utils.setupField(({element, formContainer}) => {
3510        return new Text({element, formContainer})
3511    }, Text.selectors.self);
3512})();
3513
3514/*******************************************************************************
3515 * Copyright 2026 Adobe
3516 *
3517 * Licensed under the Apache License, Version 2.0 (the "License");
3518 * you may not use this file except in compliance with the License.
3519 * You may obtain a copy of the License at
3520 *
3521 *     http://www.apache.org/licenses/LICENSE-2.0
3522 *
3523 * Unless required by applicable law or agreed to in writing, software
3524 * distributed under the License is distributed on an "AS IS" BASIS,
3525 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3526 * See the License for the specific language governing permissions and
3527 * limitations under the License.
3528 ******************************************************************************/
3529(function() {
3530
3531
3532    "use strict";
3533    class CheckBoxGroup extends FormView.FormOptionFieldBase {
3534
3535        static NS = FormView.Constants.NS;
3536        /**
3537         * Each FormField has a data attribute class that is prefixed along with the global namespace to
3538         * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be
3539         * data-{NS}-{IS}-x=""
3540         * @type {string}
3541         */
3542        static IS = "adaptiveFormCheckBoxGroup";
3543        static bemBlock = 'cmp-adaptiveform-checkboxgroup'
3544        static checkboxBemBlock = 'cmp-adaptiveform-checkbox'
3545        static selectors  = {
3546            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
3547            widgets: `.${CheckBoxGroup.bemBlock}__widget`,
3548            widget: `.${CheckBoxGroup.bemBlock}__option__widget`,
3549            widgetLabel: `.${CheckBoxGroup.bemBlock}__label`,
3550            label: `.${CheckBoxGroup.bemBlock}__label`,
3551            description: `.${CheckBoxGroup.bemBlock}__longdescription`,
3552            qm: `.${CheckBoxGroup.bemBlock}__questionmark`,
3553            errorDiv: `.${CheckBoxGroup.bemBlock}__errormessage`,
3554            tooltipDiv: `.${CheckBoxGroup.bemBlock}__shortdescription`,
3555            item:  `.${CheckBoxGroup.bemBlock}-item`,
3556            optionLabel: `${CheckBoxGroup.bemBlock}__option-label`,
3557            optionLink: `${CheckBoxGroup.bemBlock}__links`
3558        };
3559
3560        constructor(params) {
3561            super(params);
3562            this.qm = this.element.querySelector(CheckBoxGroup.selectors.qm)
3563            this.widgetLabel = this.element.querySelector(CheckBoxGroup.selectors.widgetLabel)
3564        }
3565
3566        getWidgets() {
3567            return this.element.querySelector(CheckBoxGroup.selectors.widgets);
3568        }
3569
3570        getWidget() {
3571          return this.element.querySelectorAll(CheckBoxGroup.selectors.widget);
3572        }
3573
3574        getDescription() {
3575            return this.element.querySelector(CheckBoxGroup.selectors.description);
3576        }
3577
3578        getLabel() {
3579            return this.element.querySelector(CheckBoxGroup.selectors.label);
3580        }
3581
3582        getErrorDiv() {
3583            return this.element.querySelector(CheckBoxGroup.selectors.errorDiv);
3584        }
3585
3586        getQuestionMarkDiv() {
3587            return this.element.querySelector(CheckBoxGroup.selectors.qm);
3588        }
3589
3590        getTooltipDiv() {
3591            return this.element.querySelector(CheckBoxGroup.selectors.tooltipDiv);
3592        }
3593
3594        getOptions() {
3595            return this.element.querySelectorAll(CheckBoxGroup.selectors.item);
3596        }
3597
3598        #addWidgetListeners(optionWidget) {
3599            optionWidget.addEventListener('change', (e) => {
3600                this.#updateModelValue(optionWidget);
3601            });
3602            optionWidget.addEventListener('focus', (e) => {
3603                this.setActive();
3604            });
3605            optionWidget.addEventListener('blur', (e) => {
3606                this.setInactive();
3607            });
3608        }
3609
3610        setModel(model) {
3611            super.setModel(model);
3612            this.widget.forEach(optionWidget => {
3613                this.#addWidgetListeners(optionWidget);
3614            });
3615            let optionLinks = this.element.querySelectorAll(`.${CheckBoxGroup.selectors.optionLink}`);
3616            const actionKeys = ['Enter', ' ', 'Spacebar', 'Space'];
3617            optionLinks.forEach(optionLink => {
3618                optionLink.addEventListener('keydown', (e)=>{
3619                    if(actionKeys.includes(e.key)) {
3620                        optionLink.click();
3621                    }
3622                });
3623            });
3624            this.#updateModelValue();
3625        }
3626
3627        #updateModelValue() {
3628            let value = [];
3629            this.widget.forEach(widget => {
3630                if (widget.checked) {
3631                    value.push(widget.value)
3632                }
3633            }, this);
3634            if (value.length !== 0 || this._model.value != null) {
3635                this.setModelValue(value)
3636            }
3637        }
3638
3639        updateValidity(validity) {
3640            if(validity.valid === undefined) {
3641                this.element.removeAttribute(FormView.Constants.DATA_ATTRIBUTE_VALID);
3642                this.widget.forEach(widget => widget.removeAttribute(FormView.Constants.ARIA_INVALID));
3643            } else {
3644                this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_VALID, validity.valid);
3645                this.widget.forEach(widget => widget.setAttribute(FormView.Constants.ARIA_INVALID, !validity.valid));
3646            }
3647        }
3648
3649        updateValue(modelValue) {
3650            modelValue = [].concat(modelValue);
3651            let selectedWidgetValues = modelValue.map(String);
3652            this.widget.forEach(widget => {
3653                if (selectedWidgetValues.includes((widget.value))) {
3654                    widget.checked = true
3655                    widget.setAttribute(FormView.Constants.HTML_ATTRS.CHECKED, FormView.Constants.HTML_ATTRS.CHECKED);
3656                } else {
3657                    widget.checked = false
3658                    widget.removeAttribute(FormView.Constants.HTML_ATTRS.CHECKED);
3659                }
3660            }, this)
3661            super.updateEmptyStatus();
3662        }
3663
3664        #createCheckBoxItem(value, itemLabel) {
3665            // This doesn't cater for optionLink __links as toggelablelink component is hidden
3666            let richScreenReaderText = `${this._model.label.value}:  ${itemLabel}`;
3667            let plainScreenReaderText = window.DOMPurify ? window.DOMPurify.sanitize(richScreenReaderText, { ALLOWED_TAGS: [] }) : richScreenReaderText;
3668            const optionTemplate = `
3669            <div class="${CheckBoxGroup.selectors.item.slice(1)}">
3670                <label class="${CheckBoxGroup.selectors.optionLabel}">
3671                    <input type="checkbox" class="${CheckBoxGroup.selectors.widget.slice(1)}" name="${this._model.name}" value="${value}" tabindex="0">
3672                    <span>${itemLabel}</span>
3673                </label>
3674            </div>`;
3675
3676            const container = document.createElement('div'); // Create a container element to hold the template
3677            container.innerHTML = optionTemplate;
3678            let addedOptionWidget = container.querySelector(CheckBoxGroup.selectors.widget);
3679            if(this._model.readOnly === true || this._model.enabled === false) {
3680                addedOptionWidget.setAttribute("disabled", true);
3681                if(this._model.readOnly === true) {
3682                    addedOptionWidget.setAttribute("aria-readonly", true);
3683                }
3684            }
3685            this.#addWidgetListeners(addedOptionWidget);
3686            return container.firstElementChild; // Return the first child, which is the created option
3687        }
3688        updateEnum(newEnums) {
3689            super.updateEnumForRadioButtonAndCheckbox(newEnums, this.#createCheckBoxItem);
3690            // refresh the widget references, to dynamically added options
3691            this.widget = this.getWidget();
3692        }
3693
3694        updateEnumNames(newEnumNames) {
3695            super.updateEnumNamesForRadioButtonAndCheckbox(newEnumNames, this.#createCheckBoxItem);
3696            // refresh the widget references, to dynamically added options
3697            this.widget = this.getWidget();
3698        }
3699
3700        updateEnabled(enabled, state) {
3701            this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_ENABLED, enabled);
3702            let widgets = this.widget;
3703            widgets.forEach(widget => {
3704                if (enabled === false) {
3705                    if(state.readOnly === false){
3706                        widget.setAttribute(FormView.Constants.HTML_ATTRS.DISABLED, "disabled");
3707                    }
3708                } else if (state.readOnly === false) {
3709                    widget.removeAttribute(FormView.Constants.HTML_ATTRS.DISABLED);
3710                }
3711            });
3712        }
3713
3714        updateReadOnly(readonly) {
3715            let widgets = this.widget;
3716            this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_READONLY, readonly);
3717            widgets.forEach(widget => {
3718                if (readonly === true) {
3719                    widget.setAttribute(FormView.Constants.HTML_ATTRS.DISABLED, "disabled");
3720                    widget.setAttribute("aria-readonly", true);
3721                } else {
3722                    widget.removeAttribute(FormView.Constants.HTML_ATTRS.DISABLED);
3723                    widget.removeAttribute("aria-readonly");
3724                }
3725            });
3726        }
3727        updateRequired(required, state) {
3728            if (this.widget) {
3729                this.element.toggleAttribute("required", required);
3730                this.element.setAttribute("data-cmp-required", required);
3731            }
3732        }
3733
3734        syncMarkupWithModel() {
3735            super.syncMarkupWithModel();
3736            this.updateEnum(this._model.enum);
3737            this.updateEnumNames(this._model.enumNames);
3738        }
3739    }
3740
3741    FormView.Utils.setupField(({element, formContainer}) => {
3742        return new CheckBoxGroup({element, formContainer})
3743    }, CheckBoxGroup.selectors.self);
3744
3745})();
3746
3747/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3748  ~ Copyright 2024 Adobe
3749  ~
3750  ~ Licensed under the Apache License, Version 2.0 (the "License");
3751  ~ you may not use this file except in compliance with the License.
3752  ~ You may obtain a copy of the License at
3753  ~
3754  ~     http://www.apache.org/licenses/LICENSE-2.0
3755  ~
3756  ~ Unless required by applicable law or agreed to in writing, software
3757  ~ distributed under the License is distributed on an "AS IS" BASIS,
3758  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3759  ~ See the License for the specific language governing permissions and
3760  ~ limitations under the License.
3761  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
3762(function() {
3763
3764    "use strict";
3765    class Button extends FormView.FormFieldBase {
3766
3767        static NS = FormView.Constants.NS;
3768        /**
3769         * Each FormField has a data attribute class that is prefixed along with the global namespace to
3770         * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be
3771         * data-{NS}-{IS}-x=""
3772         * @type {string}
3773         */
3774        static IS = "adaptiveFormButton";
3775        static bemBlock = 'cmp-adaptiveform-button';
3776        static selectors  = {
3777            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
3778            widget: `.${Button.bemBlock}__widget`,
3779            label: `.${Button.bemBlock}__text`,
3780            description: `.${Button.bemBlock}__longdescription`,
3781            qm: `.${Button.bemBlock}__questionmark`,
3782            tooltipDiv: `.${Button.bemBlock}__shortdescription`
3783        };
3784
3785        constructor(params) {
3786            super(params);
3787            const formModel = this.formContainer?.getModel?.();
3788            if (!formModel) { return; }
3789            
3790            formModel.subscribe((action) => { // hide loader if validation fails (no submit performed)
3791                const errors = action?.payload;
3792                if (Array.isArray(errors) && errors.length > 0) {
3793                    this._hideLoader();
3794                }
3795            }, 'validationComplete');
3796
3797            formModel.subscribe(() => { // hide loader on submit success
3798                this._hideLoader();
3799            }, 'submitSuccess');
3800            
3801            formModel.subscribe(() => { // hide loader on submit error
3802                this._hideLoader();
3803            }, 'submitError');
3804        }
3805
3806        _container = null;
3807
3808        _getContainer() {
3809            if (this._container) return this._container;
3810            const container = this.formContainer?.getFormElement?.();
3811            if (container) this._container = container;
3812            return this._container;
3813        }
3814
3815        _showLoader() {
3816            const container = this._getContainer();
3817            if (container) {
3818                container.classList.add('cmp-adaptiveform-container--submitting');
3819            }
3820        }
3821
3822        _hideLoader() {
3823            const container = this._getContainer();
3824            if (container) {
3825                container.classList.remove('cmp-adaptiveform-container--submitting');
3826            }
3827        }
3828
3829        getQuestionMarkDiv() {
3830            return this.element.querySelector(Button.selectors.qm);
3831        }
3832
3833        getLabel() {
3834            return this.element.querySelector(Button.selectors.label);
3835        }
3836
3837        getWidget() {
3838            return this.element.querySelector(Button.selectors.widget);
3839        }
3840
3841        /**
3842         * Return the description element.
3843         * @returns {HTMLElement}
3844         */
3845        getDescription() {
3846            return this.element.querySelector(Button.selectors.description);
3847        }
3848
3849        getErrorDiv() {
3850            return null;
3851        }
3852
3853        getTooltipDiv() {
3854            return this.element.querySelector(Button.selectors.tooltipDiv);
3855        }
3856
3857        setModel(model) {
3858            super.setModel(model);
3859            this.getWidget().addEventListener("click", (event) => {
3860                if (this.widget.type === 'submit' || this.widget.type === 'reset') {
3861                    event.preventDefault();
3862                }
3863                if (this.widget.type === 'submit') {
3864                    this._showLoader();
3865                }
3866                this._model.dispatch(new FormView.Actions.Click());
3867            });
3868        }
3869    }
3870
3871    FormView.Utils.setupField(({element, formContainer}) => {
3872        return new Button({element, formContainer})
3873    }, Button.selectors.self);
3874
3875})();
3876/*******************************************************************************
3877 * Copyright 2022 Adobe
3878 *
3879 * Licensed under the Apache License, Version 2.0 (the "License");
3880 * you may not use this file except in compliance with the License.
3881 * You may obtain a copy of the License at
3882 *
3883 *     http://www.apache.org/licenses/LICENSE-2.0
3884 *
3885 * Unless required by applicable law or agreed to in writing, software
3886 * distributed under the License is distributed on an "AS IS" BASIS,
3887 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3888 * See the License for the specific language governing permissions and
3889 * limitations under the License.
3890 ******************************************************************************/
3891(function(document) {
3892
3893    "use strict";
3894     class Image extends FormView.FormFieldBase {
3895
3896            static NS = FormView.Constants.NS;
3897            static IS = "adaptiveFormImage";
3898            static bemBlock = 'cmp-image';
3899
3900            static selectors  = {
3901                self: "[data-" + this.NS + '-is="' + this.IS + '"]'
3902            };
3903
3904            constructor(params) {
3905                super(params);
3906            }
3907
3908            getClass() {
3909                return Image.IS;
3910            }
3911
3912             getWidget() {
3913                 return null;
3914             }
3915
3916             getDescription() {
3917                 return null;
3918             }
3919
3920             getLabel() {
3921                 return null;
3922             }
3923
3924             getErrorDiv() {
3925                 return null;
3926             }
3927
3928             getTooltipDiv() {
3929                 return null;
3930             }
3931
3932             getQuestionMarkDiv() {
3933                 return null;
3934             }
3935
3936            setFocus() {
3937                this.setActive();
3938            }
3939
3940            updateValue(value) {
3941                if (this.element) {
3942                    this.element.setAttribute('data-cmp-src', value);
3943                    const imgElement = this.element.querySelector('img');
3944                    if (imgElement) {
3945                        imgElement.setAttribute('src', value);
3946                    }
3947                }
3948            }
3949    }
3950
3951    FormView.Utils.setupField(({element, formContainer}) => {
3952        return new Image({element, formContainer})
3953    }, Image.selectors.self);
3954})();
3955
3956/*******************************************************************************
3957 * Copyright 2022 Adobe
3958 *
3959 * Licensed under the Apache License, Version 2.0 (the "License");
3960 * you may not use this file except in compliance with the License.
3961 * You may obtain a copy of the License at
3962 *
3963 *     http://www.apache.org/licenses/LICENSE-2.0
3964 *
3965 * Unless required by applicable law or agreed to in writing, software
3966 * distributed under the License is distributed on an "AS IS" BASIS,
3967 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3968 * See the License for the specific language governing permissions and
3969 * limitations under the License.
3970 ******************************************************************************/
3971(function() {
3972
3973    "use strict";
3974    class DropDown extends FormView.FormOptionFieldBase {
3975
3976        static NS = FormView.Constants.NS;
3977        /**
3978         * Each FormField has a data attribute class that is prefixed along with the global namespace to
3979         * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be
3980         * data-{NS}-{IS}-x=""
3981         * @type {string}
3982         */
3983        static IS = "adaptiveFormDropDown";
3984        static bemBlock = 'cmp-adaptiveform-dropdown';
3985        static selectors  = {
3986            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
3987            widget: `.${DropDown.bemBlock}__widget`,
3988            options: `.${DropDown.bemBlock}__option`,
3989            label: `.${DropDown.bemBlock}__label`,
3990            description: `.${DropDown.bemBlock}__longdescription`,
3991            qm: `.${DropDown.bemBlock}__questionmark`,
3992            errorDiv: `.${DropDown.bemBlock}__errormessage`,
3993            tooltipDiv: `.${DropDown.bemBlock}__shortdescription`
3994        };
3995
3996        constructor(params) {
3997            super(params);
3998            this.qm = this.element.querySelector(DropDown.selectors.qm);
3999        }
4000
4001        getWidget() {
4002            return this.element.querySelector(DropDown.selectors.widget);
4003        }
4004
4005        getDescription() {
4006            return this.element.querySelector(DropDown.selectors.description);
4007        }
4008
4009        getLabel() {
4010            return this.element.querySelector(DropDown.selectors.label);
4011        }
4012
4013        getErrorDiv() {
4014            return this.element.querySelector(DropDown.selectors.errorDiv);
4015        }
4016
4017        getQuestionMarkDiv() {
4018            return this.element.querySelector(DropDown.selectors.qm);
4019        }
4020
4021        getTooltipDiv() {
4022            return this.element.querySelector(DropDown.selectors.tooltipDiv);
4023        }
4024
4025        getOptions() {
4026            return this.element.querySelectorAll(DropDown.selectors.options);
4027        }
4028
4029         #checkIfEqual = function(value, optionValue, multiSelect) {
4030            if(multiSelect) {
4031                let isPresent = false;
4032                value.forEach((saveValue) => {
4033                    if(String(saveValue) === optionValue)  // save value can be number and boolean also.
4034                        isPresent = true;
4035                })
4036                return isPresent;
4037            }
4038            return String(value) === optionValue;
4039        }
4040
4041        updateEnabled(enabled, state) {
4042            this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_ENABLED, enabled);
4043            let widget = this.widget;
4044            if (enabled === false) {
4045                if(state.readOnly === false){
4046                    widget.setAttribute(FormView.Constants.HTML_ATTRS.DISABLED, "disabled");
4047                }
4048            } else if (state.readOnly === false) {
4049                widget.removeAttribute(FormView.Constants.HTML_ATTRS.DISABLED);
4050            }
4051        }
4052
4053        updateReadOnly(readonly) {
4054            let widget = this.widget;
4055            this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_READONLY, readonly);
4056            if (readonly === true) {
4057                widget.setAttribute(FormView.Constants.HTML_ATTRS.DISABLED, "disabled");
4058                widget.setAttribute("aria-readonly", true);
4059            } else {
4060                widget.removeAttribute(FormView.Constants.HTML_ATTRS.DISABLED);
4061                widget.removeAttribute("aria-readonly");
4062            }
4063        }
4064
4065        updateValue(value) {
4066            // Clear selection from all options first to avoid stale selected state
4067            [...this.widget].forEach((option) => {
4068                option.removeAttribute('selected');
4069            });
4070            if(value == null) { // if undefined or null, reset to placeholder (first option)
4071                const placeholderOption = this.widget.options[0];
4072                if(placeholderOption && placeholderOption.value === '') {
4073                    placeholderOption.setAttribute('selected', 'selected');
4074                    this.widget.selectedIndex = 0;
4075                } else {
4076                    this.widget.selectedIndex = -1; 
4077                }
4078                super.updateEmptyStatus();
4079                return;
4080            }
4081            let isMultiSelect = this._model.isArrayType();
4082            [...this.widget].forEach((option) => {
4083                if(this.#checkIfEqual(value, option.value, isMultiSelect)) {
4084                    option.setAttribute('selected', 'selected');
4085                }
4086            });
4087            super.updateEmptyStatus();
4088        }
4089
4090        #createDropDownOptions(value, label) {
4091            const optionTemplate = `<option value="${value}" class="${DropDown.selectors.options.slice(1)}">${label}</option>`;
4092            const container = document.createElement('div'); // Create a container element to hold the template
4093            container.innerHTML = optionTemplate;
4094            return container.firstElementChild; // Return the first child, which is the created option
4095        }
4096
4097        #removeAllOptions() {
4098            while(this.getOptions().length !== 0) {
4099                this.getWidget().remove(this.getOptions().length) // not removing the blank option
4100            }
4101        }
4102
4103        /**
4104         * @override
4105         * Method for updating the saved value in the option field.
4106         * It contains the logic for updating the 'enum' value.
4107         *
4108         * @param {Array} newEnums - An array of primitive values to be saved in the option field.
4109         */
4110        updateEnum(newEnums) {
4111            let options = this.getOptions();
4112            let currentEnumSize = options.length;
4113            let startIndex = options[0] && options[0].value === '' ? 1 : 0; // Check if the first option is a blank option
4114
4115            // Update existing options and add new options in the same loop
4116            newEnums.forEach((value, index) => {
4117                if (index + startIndex < currentEnumSize) {
4118                    // Update existing option
4119                    options[index + startIndex].value = value;
4120                } else {
4121                    // Add new option
4122                    this.getWidget().add(this.#createDropDownOptions(value, value));
4123                }
4124            });
4125
4126            // Remove extra options, but never remove the first option
4127            while (currentEnumSize > newEnums.length + startIndex) {
4128                this.getWidget().remove(currentEnumSize--);
4129            }
4130        }
4131
4132        /**
4133         * @override
4134         * Method for updating the display value in the option field.
4135         * It contains the logic for updating the 'enumNames' value.
4136         *
4137         * @param {Array} newEnumNames - An array of primitive values to be displayed in the option field.
4138         */
4139        updateEnumNames(newEnumNames) {
4140            let options = this.getOptions();
4141            let currentEnumNameSize = options.length;
4142            if(currentEnumNameSize === 0) {  // case 1: Create all dropdown new options
4143                newEnumNames.forEach((value) => {
4144                    this.getWidget().add(this.#createDropDownOptions(value, value));
4145                })
4146            } else if(currentEnumNameSize > newEnumNames.length) {  // case 2: Replace existing enumNames, remaining enumNames = enums
4147                newEnumNames.forEach((value, index) => {
4148                    options[index].text = value;
4149                });
4150
4151                options.forEach((option, index) => {
4152                    if(index >= newEnumNames.length) {
4153                        option.text = option.value;
4154                    }
4155                })
4156            } else {    // case 3: Replace all existing enumNames
4157                options.forEach((option, index) => {
4158                    option.text = newEnumNames[index];
4159                });
4160            }
4161        }
4162
4163        setModel(model) {
4164            super.setModel(model);
4165            if (this.widget.value !== '') {
4166                this.#updateModelValue(this.widget);
4167            }
4168            this.widget.addEventListener('change', (e) => {
4169                this.#updateModelValue(e.target);
4170            });
4171            this.widget.addEventListener('focus', (e) => {
4172                this.setActive();
4173                this.triggerEnter();
4174            });
4175            this.widget.addEventListener('blur', (e) => {
4176                this.setInactive();
4177                this.triggerExit();
4178            });
4179        }
4180
4181        #updateModelValue(widget) {
4182            if(this._model.isArrayType()) {
4183                let valueArray = [];
4184                [...this.widget].forEach((option) => {
4185                    if(option.selected) {
4186                        valueArray.push(option.value);
4187                    }
4188                });
4189                if (valueArray.length !== 0 || this._model.value != null) {
4190                    this.setModelValue(valueArray);
4191                }
4192            } else {
4193                this.setModelValue(widget.value);
4194            }
4195        }
4196    }
4197
4198    FormView.Utils.setupField(({element, formContainer}) => {
4199        return new DropDown({element, formContainer})
4200    }, DropDown.selectors.self);
4201
4202})();
4203
4204/*******************************************************************************
4205 * Copyright 2025 Adobe
4206 *
4207 * Licensed under the Apache License, Version 2.0 (the "License");
4208 * you may not use this file except in compliance with the License.
4209 * You may obtain a copy of the License at
4210 *
4211 *     http://www.apache.org/licenses/LICENSE-2.0
4212 *
4213 * Unless required by applicable law or agreed to in writing, software
4214 * distributed under the License is distributed on an "AS IS" BASIS,
4215 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4216 * See the License for the specific language governing permissions and
4217 * limitations under the License.
4218 ******************************************************************************/
4219
4220/**
4221 * This class is responsible for interacting with the file input widget. It implements the file preview,
4222 * file list, handling invalid file size, file name, file mime type functionality
4223 */
4224
4225if (typeof window.FileInputWidget === 'undefined') {
4226    window.FileInputWidget = class extends FormView.FormFileInputWidget {
4227
4228        constructor(params) {
4229            super(params);
4230            this.invalidFeature = {
4231                ...this.invalidFeature,
4232                "SIZE_ZERO": 4
4233            }
4234        }
4235
4236        attachEventHandlers(widget, dragArea, model) {
4237            super.attachEventHandlers(widget, dragArea, model)
4238            const customBtn = dragArea?.querySelector(".cmp-adaptiveform-fileinput__widgetlabel")
4239            customBtn?.addEventListener("click", () => {
4240                widget.click();
4241            });
4242            customBtn?.addEventListener('keydown', function(event) {
4243                // Check if the Enter key is pressed
4244                if (event.key === 'Enter' || event.keyCode === 13) {
4245                    // Trigger the click event of the file input
4246                    widget.click();
4247                }
4248            });
4249        }
4250        
4251        fileItem(fileName, fileSize, comment, fileUrl) {
4252            let self = this;
4253            let id = `${Date.now() + '_' + Math.floor(Math.random() * 10000)}_file_size`
4254            let fileItem = document.createElement('li');
4255            fileItem.setAttribute("class", "cmp-adaptiveform-fileinput__fileitem");
4256            let fileNameDom = document.createElement('a');
4257            let fileSizeDom = document.createElement('span');
4258
4259            fileSizeDom.setAttribute('class', "cmp-adaptiveform-fileinput__filesize");
4260            fileSizeDom.setAttribute('id', id);
4261            fileSizeDom.textContent = this.formatBytes(fileSize);
4262
4263            fileNameDom.setAttribute('tabindex', '0');
4264            fileNameDom.setAttribute('class', "cmp-adaptiveform-fileinput__filename");
4265            fileNameDom.setAttribute('aria-describedby', id);
4266            fileNameDom.textContent = fileName;
4267            fileNameDom.addEventListener('keypress', function(e) {
4268                if (e.keyCode === 13 || e.charCode === 32) {
4269                    e.target.click();
4270                }
4271            });
4272            fileNameDom.addEventListener('click', function(e) {
4273                self.handleFilePreview(e);
4274            });
4275            fileItem.appendChild(fileNameDom);
4276            if(fileUrl != null){
4277                fileNameDom.dataset.key = fileUrl;
4278            }
4279            let fileEndContainer = document.createElement('span');
4280            let fileClose = document.createElement('button');
4281            fileEndContainer.setAttribute('class', "cmp-adaptiveform-fileinput__fileendcontainer");
4282            fileClose.setAttribute('tabindex', '0');
4283            fileClose.setAttribute('class', "cmp-adaptiveform-fileinput__filedelete");
4284            fileClose.setAttribute('aria-label', FormView.LanguageUtils.getTranslatedString(this.lang, "FileCloseAccessText") + f
4284ileName);
4285            fileClose.textContent = "x";
4286            fileClose.addEventListener('keypress', function(e) {
4287                if (e.keyCode === 13 || e.charCode === 32) {
4288                    e.target.click();
4289                }
4290            });
4291            fileClose.addEventListener('click', function(e) {
4292                self.handleClick(e);
4293            });
4294            fileEndContainer.appendChild(fileSizeDom);
4295            fileEndContainer.appendChild(fileClose);
4296            fileItem.appendChild(fileEndContainer);
4297            return fileItem;
4298        }
4299        handleChange(filesUploaded) {
4300            if (!this.isFileUpdate) {
4301                let self = this,
4302                    files = filesUploaded;
4303                // Object of arrays to collect invalid file names by type
4304                let invalidFilesByType = { SIZE: [], SIZE_ZERO: [], NAME: [], MIMETYPE: [] };
4305                if (typeof files !== "undefined") {
4306                    let invalidFilesIndexes = [];
4307                    Array.from(files).forEach(function (file, fileIndex) {
4308                        let currFileName = file.name.split("\\").pop();
4309                        let size = file.size / 1024 / 1024;
4310                        let isCurrentInvalid = false;
4311                        if (file.size === 0) {
4312                            invalidFilesByType.SIZE_ZERO.push(currFileName);
4313                            isCurrentInvalid = true;
4314                        } else if (size > parseFloat(this.options.maxFileSize)) {
4315                            invalidFilesByType.SIZE.push(currFileName);
4316                            isCurrentInvalid = true;
4317                        } else if (!FileInputWidget.isValid(currFileName)) {
4318                            invalidFilesByType.NAME.push(currFileName);
4319                            isCurrentInvalid = true;
4320                        } else {
4321                            let isMatch = false;
4322                            let extension = currFileName.split('.').pop().toLowerCase();
4323                            let mimeType = file.type || this.extensionToMimeTypeMap[extension];
4324                            // If no MIME type is detected, check if the file extension is in the accept list
4325                            if (!mimeType && this.options.acceptExtensions) {
4326                                isMatch = this.options.acceptExtensions.some(function(acceptPattern) {
4327                                    if (!acceptPattern) {
4328                                        return false;
4329                                    }
4330                                    // Remove leading dot if present and convert to lowercase
4331                                    let cleanPattern = acceptPattern.replace(/^\./, '').toLowerCase();
4332                                    return cleanPattern === extension;
4333                                });
4334                            } else {
4335                                isMatch = this.regexMimeTypeList.some(rx => rx.test(mimeType));
4336                            }
4337                            if (!isMatch) {
4338                                invalidFilesByType.MIMETYPE.push(currFileName);
4339                                isCurrentInvalid = true;
4340                            }
4341                        }
4342                        if (!isCurrentInvalid) {
4343                            if (self.isMultiSelect()) {
4344                                self.values.push(currFileName);
4345                                self.fileArr.push(file);
4346                            } else {
4347                                self.values = [currFileName];
4348                                self.fileArr = [file];
4349                            }
4350                        } else {
4351                            invalidFilesIndexes.push(fileIndex);
4352                        }
4353                    }, this);
4354                    if (invalidFilesIndexes.length > 0 && this.widget !== null) {
4355                        this.deleteFilesFromInputDom(invalidFilesIndexes);
4356                    }
4357                }
4358                // set the new model value.
4359                this.model.value = this.fileArr;
4360                // Collate all error messages
4361                let errorMessages = [];
4362                if (invalidFilesByType.SIZE_ZERO.length > 0) {
4363                    errorMessages.push(this.showInvalidMessage(invalidFilesByType.SIZE_ZERO.join(', '), this.invalidFeature.SIZE_ZERO));
4364                }
4365                if (invalidFilesByType.SIZE.length > 0) {
4366                    errorMessages.push(this.showInvalidMessage(invalidFilesByType.SIZE.join(', '), this.invalidFeature.SIZE));
4367                }
4368                if (invalidFilesByType.NAME.length > 0) {
4369                    errorMessages.push(this.showInvalidMessage(invalidFilesByType.NAME.join(', '), this.invalidFeature.NAME));
4370                }
4371                if (invalidFilesByType.MIMETYPE.length > 0) {
4372                    errorMessages.push(this.showInvalidMessage(invalidFilesByType.MIMETYPE.join(', '), this.invalidFeature.MIMETYPE));
4373                }
4374                if (errorMessages.length > 0) {
4375                    alert(errorMessages.join('\n'));
4376                }
4377            }
4378            this.widget.value = null;
4379        }
4380        showInvalidMessage(fileNames, invalidFeature) {
4381            let that = this;
4382            let IS_IPAD = navigator.userAgent.match(/iPad/i) !== null,
4383                IS_IPHONE = (navigator.userAgent.match(/iPhone/i) !== null);
4384            if (IS_IPAD || IS_IPHONE) {
4385                setTimeout(function () {
4386                    return that.invalidMessage(fileNames, invalidFeature);
4387                }, 0);
4388            } else {
4389                return this.invalidMessage(fileNames, invalidFeature);
4390            }
4391        }
4392        invalidMessage(fileNames, invalidFeature) {
4393            const customMessages = this.options.constraintMessages || {};
4394            const messages = {
4395                [this.invalidFeature.SIZE]: customMessages.maxFileSize || FormView.LanguageUtils.getTranslatedString(this.lang, "FileSizeGreater", [fileNames, this.options.maxFileSize]),
4396                [this.invalidFeature.NAME]: customMessages.invalidFileName || FormView.LanguageUtils.getTranslatedString(this.lang, "FileNameInvalid", [fileNames]),
4397                [this.invalidFeature.MIMETYPE]: customMessages.accept || FormView.LanguageUtils.getTranslatedString(this.lang, "FileMimeTypeInvalid", [fileNames]),
4398                [this.invalidFeature.SIZE_ZERO]: customMessages.zeroFileSize || FormView.LanguageUtils.getTranslatedString(this.lang, "FileSizeZero", [fileNames])
4399            };
4400            return messages[invalidFeature];
4401        }
4402
4403        handleClick (event){
4404            let elem = event.target,
4405                text = elem.parentElement.previousSibling.textContent,
4406                index = this.getIndexOfText(text, elem.parentElement),
4407                url = elem.parentElement.previousSibling.dataset.key,
4408                objectUrl = elem.parentElement.previousSibling.dataset.objectUrl;   
4409            if (index !== -1) {
4410                this.values.splice(index, 1);
4411                this.fileArr.splice(index, 1);
4412                // set the model with the new value
4413                this.model.value = this.fileArr;
4414                // value and fileArr contains items of both URL and file types, hence while removing from DOM
4415                // get the correct index as per this.#widget.files
4416                let domIndex = Array.from(this.widget.files).findIndex(function(file) {
4417                return file.name === text;
4418                });
4419                this.deleteFilesFromInputDom([domIndex]);
4420                if (url != null) {
4421                    // remove the data so that others don't use this url
4422                    delete elem.parentElement.previousSibling.dataset.key;
4423                }
4424                if(objectUrl) {
4425                    // revoke the object URL to avoid memory leaks in browser
4426                    // since file is anyways getting deleted, remove the object URL's too
4427                    window.URL.revokeObjectURL(objectUrl);
4428                }
4429            }
4430            // Remove the dom from view
4431            //All bound events and jQuery data associated with the element are also removed
4432            elem.parentElement.parentElement.remove();
4433            // Set the focus on file upload button after click of close
4434            this.widget.focus();
4435
4436        }
4437    }
4438}
4439/*******************************************************************************
4440 * Copyright 2025 Adobe
4441 *
4442 * Licensed under the Apache License, Version 2.0 (the "License");
4443 * you may not use this file except in compliance with the License.
4444 * You may obtain a copy of the License at
4445 *
4446 *     http://www.apache.org/licenses/LICENSE-2.0
4447 *
4448 * Unless required by applicable law or agreed to in writing, software
4449 * distributed under the License is distributed on an "AS IS" BASIS,
4450 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4451 * See the License for the specific language governing permissions and
4452 * limitations under the License.
4453 ******************************************************************************/
4454(function() {
4455
4456    "use strict";
4457    class FileInputV4 extends FormView.FormFileInput {
4458
4459        static NS = FormView.Constants.NS;
4460        /**
4461         * Each FormField has a data attribute class that is prefixed along with the global namespace to
4462         * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be
4463         * data-{NS}-{IS}-x=""
4464         * @type {string}
4465         */
4466        static IS = "adaptiveFormFileInput";
4467        static bemBlock = 'cmp-adaptiveform-fileinput'
4468        static selectors  = {
4469            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
4470            widget: `.${FileInputV4.bemBlock}__widget`,
4471            label: `.${FileInputV4.bemBlock}__label`,
4472            description: `.${FileInputV4.bemBlock}__longdescription`,
4473            qm: `.${FileInputV4.bemBlock}__questionmark`,
4474            errorDiv: `.${FileInputV4.bemBlock}__errormessage`,
4475            tooltipDiv: `.${FileInputV4.bemBlock}__shortdescription`,
4476            fileListDiv : `.${FileInputV4.bemBlock}__filelist`,
4477            attachButtonLabel : `.${FileInputV4.bemBlock}__widgetlabel`,
4478            dragArea: `.${FileInputV4.bemBlock}__dragarea`
4479        };
4480
4481        constructor(params) {
4482            super(params);
4483        }
4484        widgetFields = {
4485            widget: this.getWidget(),
4486            fileListDiv: this.getFileListDiv(),
4487            model: () => this._model,
4488            dragArea: this.getDragArea()
4489        };
4490        
4491        getWidget() {
4492            return this.element.querySelector(FileInputV4.selectors.widget);
4493        }
4494
4495        getDragArea() {
4496            return this.element.querySelector(FileInputV4.selectors.dragArea);
4497        }
4498
4499        getDescription() {
4500            return this.element.querySelector(FileInputV4.selectors.description);
4501        }
4502
4503        getLabel() {
4504            return this.element.querySelector(FileInputV4.selectors.label);
4505        }
4506
4507        getErrorDiv() {
4508            return this.element.querySelector(FileInputV4.selectors.errorDiv);
4509        }
4510
4511        getTooltipDiv() {
4512            return this.element.querySelector(FileInputV4.selectors.tooltipDiv);
4513        }
4514
4515        getQuestionMarkDiv() {
4516            return this.element.querySelector(FileInputV4.selectors.qm);
4517        }
4518
4519        getFileListDiv() {
4520            return this.element.querySelector(FileInputV4.selectors.fileListDiv);
4521        }
4522
4523        getAttachButtonLabel() {
4524            return this.element.querySelector(FileInputV4.selectors.attachButtonLabel);
4525        }
4526
4527        updateEnabled(enabled, state) {
4528            if (this.widget) {
4529                this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_ENABLED, enabled);
4530                const isDisabled = !enabled || state.readOnly;
4531                if (isDisabled) {
4532                    this.widget.setAttribute("disabled", "disabled");
4533                } else {
4534                    this.widget.removeAttribute("disabled");
4535                }
4536            }
4537        }
4538
4539        updateValue(value) {
4540            if (this.widgetObject == null) {
4541                this.widgetObject = new FileInputWidget(this.widgetFields);
4542            }
4543            this.widgetObject.setValue(value);
4544            super.updateEmptyStatus();
4545        }
4546
4547        setModel(model) {
4548            super.setModel(model);
4549            if (this.widgetObject == null) {
4550                this.widgetObject = new FileInputWidget(this.widgetFields);
4551            }
4552            this.getAttachButtonLabel().addEventListener('focus', () => {
4553                this.setActive();
4554            })
4555            this.getAttachButtonLabel().addEventListener('blur', () => {
4556                this.setInactive();
4557            })
4558        }
4559
4560        syncWidget() {
4561            let widgetElement = this.getWidget ? this.getWidget() : null;
4562            if (widgetElement) {
4563                widgetElement.id = this.getId() + "__widget";
4564                const closestElement = widgetElement?.previousElementSibling;
4565                if (closestElement && closestElement.tagName.toLowerCase() === 'label') {
4566                    closestElement.setAttribute('for', this.getId() + "__widget");
4567                } else {
4568                    this.getAttachButtonLabel().removeAttribute('for');
4569                }
4570            }
4571        }
4572    }
4573
4574    FormView.Utils.setupField(({element, formContainer}) => {
4575        return new FileInputV4({element, formContainer})
4576    }, FileInputV4.selectors.self);
4577
4578})();
4579
4580/*******************************************************************************
4581 * Copyright 2022 Adobe
4582 *
4583 * Licensed under the Apache License, Version 2.0 (the "License");
4584 * you may not use this file except in compliance with the License.
4585 * You may obtain a copy of the License at
4586 *
4587 *     http://www.apache.org/licenses/LICENSE-2.0
4588 *
4589 * Unless required by applicable law or agreed to in writing, software
4590 * distributed under the License is distributed on an "AS IS" BASIS,
4591 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4592 * See the License for the specific language governing permissions and
4593 * limitations under the License.
4594 ******************************************************************************/
4595(function () {
4596
4597    function onAccordionMixinLoaded(event) {
4598        const AccordionMixin = event.detail.AccordionMixin;
4599
4600        class Accordion extends AccordionMixin(FormView.FormPanel) {
4601
4602            static NS = FormView.Constants.NS;
4603            static DATA_ATTRIBUTE_VISIBLE = 'data-cmp-visible';
4604            _templateHTML = {};
4605            static selectors = {
4606                self: "[data-" + this.NS + '-is="' + this.IS + '"]',
4607                widget: `.${Accordion.bemBlock}__widget`,
4608                description: `.${Accordion.bemBlock}__longdescription`,
4609                qm: `.${Accordion.bemBlock}__questionmark`,
4610                tooltipDiv: `.${Accordion.bemBlock}__shortdescription`,
4611                label: `.${Accordion.bemBlock}__label`,
4612                item: `.${Accordion.bemBlock}__item`
4613            };
4614
4615            static keyCodes = {
4616                ENTER: 13,
4617                SPACE: 32,
4618                END: 35,
4619                HOME: 36,
4620                ARROW_LEFT: 37,
4621                ARROW_UP: 38,
4622                ARROW_RIGHT: 39,
4623                ARROW_DOWN: 40
4624            };
4625
4626            constructor(params) {
4627                super(params);
4628                const {element} = params;
4629                this.cacheElements(element);
4630                if (this.getCachedItems()) {
4631                    var expandedItems = this.getExpandedItems();
4632                    // multiple expanded items annotated, display the last item open.
4633                    if (expandedItems.length > 1) {
4634                        var lastExpandedItem = expandedItems[expandedItems.length - 1]
4635                        this.expandItem(lastExpandedItem);
4636                        this.collapseAllOtherItems(lastExpandedItem.id);
4637                    }
4638                    this.refreshItems();
4639                    this.#bindEvents();
4640                }
4641            }
4642
4643            getClass() {
4644                return Accordion.IS;
4645            }
4646
4647            getWidget() {
4648                return null;
4649            }
4650
4651            getDescription() {
4652                return this.element.querySelector(Accordion.selectors.description);
4653            }
4654
4655            getLabel() {
4656                return this.element.querySelector(Accordion.selectors.label);
4657            }
4658
4659            getErrorDiv() {
4660                return null;
4661            }
4662
4663            getTooltipDiv() {
4664                return this.element.querySelector(Accordion.selectors.tooltipDiv);
4665            }
4666
4667            getQuestionMarkDiv() {
4668                return this.element.querySelector(Accordion.selectors.qm);
4669            }
4670
4671            setFocus(id) {
4672                super.setFocus(id);
4673                this.setActive();
4674                this.#collapseAllItems();
4675                const item = this.getItemById(id + '-item');
4676                this.expandItem(item)
4677            }
4678
4679            #collapseAllItems() {
4680                var items = this.getCachedItems();
4681                if (items) {
4682                    for (var i = 0; i < items.length; i++) {
4683                        if (this.isItemExpanded(items[i])) {
4684                            this.collapseItem(items[i])
4685                        }
4686                    }
4687                }
4688            }
4689
4690            /**
4691             * Binds Accordion event handling.
4692             *
4693             * @private
4694             */
4695            #bindEvents() {
4696                var buttons = this.getCachedButtons();
4697                if (buttons) {
4698                    var _self = this;
4699                    for (var i = 0; i < buttons.length; i++) {
4700                        (function (index) {
4701                            buttons[index].addEventListener("click", function (event) {
4702                                var itemDivId = _self.#convertToItemDivId(buttons[index].id);
4703                                _self.toggle(itemDivId);
4704                                _self.collapseAllOtherItems(itemDivId);
4705                                _self.#focusButton(buttons[index].id);
4706                            });
4707                            buttons[index].addEventListener("keydown", function (event) {
4708                                _self.#onButtonKeyDown(event, buttons[index].id);
4709                            });
4710                        })(i);
4711                    }
4712                }
4713            }
4714
4715            /**
4716             * Binds Accordion event handling.
4717             *
4718             * @private
4719             */
4720            #bindEventsToAddedChild(addedChildId) {
4721                var _self = this;
4722                var buttonId = addedChildId + Accordion.idSuffixes.button;
4723                var button = this.#getButtonById(buttonId);
4724                button.addEventListener("click", function (event) {
4725                    var itemDivId = _self.#convertToItemDivId(buttonId);
4726                    _self.toggle(itemDivId);
4727                    _self.collapseAllOtherItems(itemDivId);
4728                    _self.#focusButton(buttonId);
4729                });
4730                button.addEventListener("keydown", function (event) {
4731                    _self.#onButtonKeyDown(event, buttonId);
4732                });
4733            }
4734
4735            /**
4736             * Handles button keydown events.
4737             *
4738             * @private
4739             * @param {Object} event The keydown event
4740             * @param {Number} id The id of the button triggering the event
4741             */
4742            #onButtonKeyDown(event, id) {
4743                var buttons = this.getCachedButtons();
4744                var lastIndex = buttons.length - 1;
4745                var index = this.#getButtonIndexById(id);
4746
4747                switch (event.keyCode) {
4748                    case Accordion.keyCodes.ARROW_LEFT:
4749                    case Accordion.keyCodes.ARROW_UP:
4750                        event.preventDefault();
4751                        if (index > 0) {
4752                            this.#focusButton(buttons[index - 1].id);
4753                        }
4754                        break;
4755                    case Accordion.keyCodes.ARROW_RIGHT:
4756                    case Accordion.keyCodes.ARROW_DOWN:
4757                        event.preventDefault();
4758                        if (index < lastIndex) {
4759                            this.#focusButton(buttons[index + 1].id);
4760                        }
4761                        break;
4762                    case Accordion.keyCodes.HOME:
4763                        event.preventDefault();
4764                        this.#focusButton(buttons[0].id);
4765                        break;
4766                    case Accordion.keyCodes.END:
4767                        event.preventDefault();
4768                        this.#focusButton(buttons[lastIndex].id);
4769                        break;
4770                    case Accordion.keyCodes.ENTER:
4771                    case Accordion.keyCodes.SPACE:
4772                        event.preventDefault();
4773                        var itemDivId = this.#convertToItemDivId(buttons[index].id);
4774                        this.toggle(itemDivId);
4775                        this.collapseAllOtherItems(itemDivId);
4776                        this.#focusButton(buttons[index].id);
4777                        break;
4778                    default:
4779                        return;
4780                }
4781            }
4782
4783            /**
4784             * Focuses the button at the provided index.
4785             *
4786             * @private
4787             * @param {Number} id The id of the button to focus
4788             */
4789            #focusButton(id) {
4790                var button = this.#getButtonById(id);
4791                button.focus();
4792            }
4793
4794            addChild(childView) {
4795                super.addChild(childView);
4796                this.#cacheTemplateHTML(childView);
4797                if (this.getCountOfAllChildrenInModel() === this.children.length) {
4798                    this.cacheClosestFieldsInView();
4799                    this.handleHiddenChildrenVisibility();
4800                }
4801            }
4802
4803            /**
4804             * Adds unique HTML for added instance corresponding to requirements of different types of repeatableParent
4805             * @param instanceManager of the repeated component
4806             * @param addedModel of the repeated component
4807             * @param htmlElement of the repeated component
4808             */
4809            addRepeatableMarkup(instanceManager, addedModel, htmlElement) {
4810                var accordionItemDivToBeRepeated = this.#prepareAccordionMarkupToBeAdded(instanceManager, addedModel, htmlElement);
4811                let result = this.#getBeforeViewElement(instanceManager, addedModel.index);
4812                if (result.beforeViewElement != null) {
4813                    result.beforeViewElement.after(accordionItemDivToBeRepeated);
4814                } else if (result.parentElement != null) {
4815                    var firstChildAccordionItem = result.parentElement.querySelector(Accordion.selectors.item);
4816                    if (firstChildAccordionItem != null) {
4817                        result.parentElement.insertBefore(accordionItemDivToBeRepeated, firstChildAccordionItem);
4818                    } else {
4819                        result.parentElement.append(accordionItemDivToBeRepeated);
4820                    }
4821                }
4822                this.#showHideRepeatableButtons(instanceManager);
4823                return accordionItemDivToBeRepeated;
4824            }
4825
4826            focusOnRepeatableInstances(id) {
4827                const panelId = id.replace(Accordion.idSuffixes.item, "");
4828                const form = this.formContainer.getModel();
4829                const tab = this.getModel().getState().items.find(item => item.type === 'array')?.items?.find(subItem => subItem.id === panelId)
4830                const field = form.getElement(tab?.id);
4831                if (field) {
4832                    setTimeout(() => {form.setFocus(field)}, 0);
4833                }
4834            }
4835
4836            handleChildAddition(childView) {
4837                var itemDivToExpand;
4838                this.cacheElements(this._elements.self);
4839                this.#bindEventsToAddedChild(childView.id);
4840                if (childView.getInstanceManager().getModel().minOccur != undefined && childView.getInstanceManager().children.length > childView.getInstanceManager().getModel().minOccur) {
4841                    itemDivToExpand = this.getItemById(childView.id + Accordion.idSuffixes.item);
4842                } else {
4843                    //this will run at initial runtime loading when the repeatable panel is being added minOccur no of times.
4844                    // in this case we want the focus to stay at first tab
4845                    itemDivToExpand = this.findFirstVisibleChild(this.getCachedItems());
4846                }
4847                this.expandItem(itemDivToExpand);
4848                this.collapseAllOtherItems(itemDivToExpand.id);
4849
4850                const cachedItems = this.getCachedItems();
4851                const newIndex = cachedItems.indexOf(itemDivToExpand);
4852                this.getCachedButtons()[newIndex].classList.remove(this.constructor.cssClasses.button.stepped);
4853                this.getCachedPanels()[newIndex].classList.remove(this.constructor.cssClasses.panel.stepped);
4854
4855                this.focusOnRepeatableInstances(itemDivToExpand.id);
4856
4857                this.#showHideRepeatableButtons(childView.getInstanceManager());
4858            }
4859
4860            handleChildRemoval(removedInstanceView) {
4861                var removedAccordionItemDivId = removedInstanceView.element.id + Accordion.idSuffixes.item;
4862                var removedAccordionItemDiv = this.getItemById(removedAccordionItemDivId);
4863                
4864                // Find the previous item before removing the current one
4865                var cachedItems = this.getCachedItems();
4866                var currentIndex = cachedItems.indexOf(removedAccordionItemDiv);
4867                var itemDivToExpand = null;
4868                
4869                // If there are items and current item is found
4870                if (cachedItems && cachedItems.length > 0 && currentIndex > -1) {
4871                    // If there's a previous item, use it
4872                    if (currentIndex > 0) {
4873                        itemDivToExpand = cachedItems[currentIndex - 1];
4874                    } else {
4875                        // If we're removing the first item, use the next one if available
4876                        itemDivToExpand = cachedItems[1] || null;
4877                    }
4878                }
4879                
4880                // Now remove the item
4881                removedAccordionItemDiv.remove();
4882                this.children.splice(this.children.indexOf(removedInstanceView), 1);
4883                this.cacheElements(this._elements.self);
4884                
4885                // Expand the target item if found
4886                if (itemDivToExpand) {
4887                    this.expandItem(itemDivToExpand);
4888                    this.collapseAllOtherItems(itemDivToExpand.id);
4889                    this.focusOnRepeatableInstances(itemDivToExpand.id)
4890                }
4891
4892                this.#showHideRepeatableButtons(removedInstanceView.getInstanceManager());
4893            }
4894
4895            #syncLabel() {
4896                let labelElement = typeof this.getLabel === 'function' ? this.getLabel() : null;
4897                if (labelElement) {
4898                    labelElement.setAttribute('for', this.getId());
4899                }
4900            }
4901
4902            syncMarkupWithModel() {
4903                super.syncMarkupWithModel();
4904                this.#syncLabel();
4905                for (var itemDiv of this.getCachedItems()) {
4906                    this.#syncAccordionMarkup(itemDiv);
4907                }
4908            }
4909
4910            getChildViewByIndex(index) {
4911                var accordionPanels = this.getCachedPanels();
4912                var fieldId = accordionPanels[index].id.substring(0, accordionPanels[index].id.lastIndexOf("-"));
4913                return this.getChild(fieldId);
4914            }
4915
4916            #getBeforeViewElement(instanceManager, instanceIndex) {
4917                var result = {};
4918                var instanceManagerId = instanceManager.getId();
4919                if (instanceIndex == 0) {
4920                    var closestNonRepeatableFieldId = this._templateHTML[instanceManagerId]['closestNonRepeatableFieldId'];
4921                    var closestRepeatableFieldInstanceManagerIds = this._templateHTML[instanceManagerId]['closestRepeatableFieldInstanceManagerIds'];
4922                    var indexToInsert = this.getIndexToInsert(closestNonRepeatableFieldId, closestRepeatableFieldInstanceManagerIds);
4923                    if (indexToInsert > 0) {
4924                        result.beforeViewElement = this.getCachedItems()[indexToInsert - 1];
4925                    } else {
4926                        result.parentElement = this.element;
4927                    }
4928                } else {
4929                    let previousInstanceElement = this.#getRepeatableElementAt(instanceManager, instanceIndex - 1);
4930                    result.beforeViewElement = previousInstanceElement;
4931                }
4932                return result;
4933            }
4934
4935            #getRepeatableElementAt(instanceManager, index) {
4936                let childId = instanceManager._model.items.find((model) => model.index === index)?.id;
4937                return this.element.querySelector(`#${childId}${Accordion.idSuffixes.item}`);
4938            }
4939
4940            #prepareAccordionMarkupToBeAdded(instanceManager, addedModel, htmlElement) {
4941                var accordionItemDivToBeRepeated = this._templateHTML[instanceManager.getId()]['accordionItemDiv'].cloneNode(true);
4942                var itemDivId = accordionItemDivToBeRepeated.id;
4943                var accordionPanelId = this.#convertToPanelId(itemDivId);
4944                var accordionPanelToBeRepeated = accordionItemDivToBeRepeated.querySelector('#' + accordionPanelId);
4945                while (accordionPanelToBeRepeated.hasChildNodes()) {
4946                    accordionPanelToBeRepeated.removeChild(accordionPanelToBeRepeated.firstChild);
4947                }
4948                accordionPanelToBeRepeated.append(htmlElement);
4949                this.#syncAccordionMarkup(accordionItemDivToBeRepeated);
4950                return accordionItemDivToBeRepeated;
4951            }
4952
4953            #syncAccordionMarkup(accordionItemDiv) {
4954                var accordionItemDivId = accordionItemDiv.id;
4955                var accordionPanelId = this.#convertToPanelId(accordionItemDivId);
4956                var accordionButtonId = this.#convertToButtonId(accordionItemDivId);
4957                var accordionButton = accordionItemDiv.querySelector('#' + accordionButtonId);
4958                var accordionPanelDiv = accordionItemDiv.querySelector('#' + accordionPanelId);
4959                var childViewId = accordionItemDiv.querySelector("[data-cmp-is]").id;
4960                accordionItemDiv.id = childViewId + Accordion.idSuffixes.item;
4961                accordionButton.id = childViewId + Accordion.idSuffixes.button;
4962                accordionPanelDiv.id = childViewId + Accordion.idSuffixes.panel;
4963                accordionButton.setAttribute("aria-controls", childViewId + Accordion.idSuffixes.panel);
4964                accordionPanelDiv.setAttribute("aria-labelledby", childViewId + Accordion.idSuffixes.button);
4965                var accordionAdd = accordionItemDiv.querySelector(".cmp-accordion__add-button");
4966                if (accordionAdd) {
4967                    accordionAdd.setAttribute('data-cmp-hook-add-instance', 
4967childViewId);
4968                }
4969                var accordionRemove = accordionItemDiv.querySelector(".cmp-accordion__remove-button");
4970                if (accordionRemove) {
4971                    accordionRemove.setAttribute('data-cmp-hook-remove-instance', childViewId);
4972                }
4973            }
4974
4975            #cacheTemplateHTML(childView) {
4976                if (childView.getInstanceManager() != null && (this._templateHTML == null || this._templateHTML[childView.getInstanceManager().getId()] == null)) {
4977                    var accordionItemDivId = childView.element.id + Accordion.idSuffixes.item;
4978                    var instanceManagerId = childView.getInstanceManager().getId();
4979                    var accordionItemDiv = this.getItemById(accordionItemDivId);
4980                    this._templateHTML[instanceManagerId] = {};
4981                    this._templateHTML[instanceManagerId]['accordionItemDiv'] = accordionItemDiv;
4982                }
4983            }
4984
4985            #getButtonById(buttonId) {
4986                var buttons = this.getCachedButtons();
4987                if (buttons) {
4988                    for (var i = 0; i < buttons.length; i++) {
4989                        if (buttons[i].id === buttonId) {
4990                            return buttons[i];
4991                        }
4992                    }
4993                }
4994            }
4995
4996            #getButtonIndexById(buttonId) {
4997                var buttons = this.getCachedButtons();
4998                if (buttons) {
4999                    for (var i = 0; i < buttons.length; i++) {
5000                        if (buttons[i].id === buttonId) {
5001                            return i;
5002                        }
5003                    }
5004                }
5005                return -1;
5006            }
5007
5008            /**
5009             * Changes provided panel or buttonId to ItemId
5010             *
5011             * @private
5012             * @param {Number} id The id of the panel/button to convert to corresponding item div
5013             */
5014            #convertToItemDivId(idToConvert) {
5015                return idToConvert.substring(0, idToConvert.lastIndexOf("-")) + Accordion.idSuffixes.item;
5016            }
5017
5018            /**
5019             * Changes provided panel or item id to Button Id
5020             *
5021             * @private
5022             * @param {Number} id The id of the panel/item to convert to corresponding button id
5023             */
5024            #convertToButtonId(idToConvert) {
5025                return idToConvert.substring(0, idToConvert.lastIndexOf("-")) + Accordion.idSuffixes.button;
5026            }
5027
5028            /**
5029             * Changes provided button or item id to Panel Id
5030             *
5031             * @private
5032             * @param {Number} id The id of the button/item to convert to corresponding button id
5033             */
5034            #convertToPanelId(idToConvert) {
5035                return idToConvert.substring(0, idToConvert.lastIndexOf("-")) + Accordion.idSuffixes.panel;
5036            }
5037
5038            updateChildVisibility(visible, state) {
5039                this.updateVisibilityOfNavigationElement(this.getItemById(state.id + Accordion.idSuffixes.item), visible);
5040                if (!visible) {
5041                    var expandedItems = this.getExpandedItems();
5042                    for (let i = 0; i < expandedItems.length; i++) {
5043                        if (expandedItems[i].getAttribute(Accordion.DATA_ATTRIBUTE_VISIBLE) === 'false') {
5044                            this.collapseItem(expandedItems[i]);
5045                        }
5046                    }
5047                    let child = this.findFirstVisibleChild(this.getCachedItems());
5048                    if (child) {
5049                        this.expandItem(child);
5050                    }
5051                }
5052            }
5053
5054            getRepeatableRootElement(childView) {
5055                return this.element.querySelector('#' + childView.id + '-item div[data-cmp-hook-adaptiveFormAccordion="repeatableButton"]')
5056            }
5057
5058            #showHideRepeatableButtons(instanceManager) {
5059                const {_model: {minOccur, maxOccur, items = []} = {}, children} = instanceManager;
5060                children.forEach(child => {
5061                    const addButtonElement = this.element.querySelector('#' + child.id + '-item')?.querySelector('[data-cmp-hook-add-instance]');
5062                    const removeButtonElement = this.element.querySelector('#' + child.id + '-item')?.querySelector('[data-cmp-hook-remove-instance]');
5063                    if (addButtonElement) {
5064                        addButtonElement.setAttribute(Accordion.DATA_ATTRIBUTE_VISIBLE, !(items.length === maxOccur && maxOccur != -1))
5065                    }
5066                    if (removeButtonElement) {
5067                        removeButtonElement.setAttribute(Accordion.DATA_ATTRIBUTE_VISIBLE, items.length > minOccur && minOccur != -1)
5068                    }
5069                });
5070            }
5071        }
5072
5073        FormView.Utils.setupField(({element, formContainer}) => {
5074            return new Accordion({element, formContainer})
5075        }, Accordion.selectors.self);
5076    }
5077
5078    if (window.Forms && window.Forms.CoreComponentsCommons && window.Forms.CoreComponentsCommons.AccordionMixin) {
5079        onAccordionMixinLoaded({ detail: { AccordionMixin: window.Forms.CoreComponentsCommons.AccordionMixin } });
5080    } else {
5081        window.addEventListener('AccordionMixinLoaded', onAccordionMixinLoaded);
5082    }
5083})();
5084
5085/*******************************************************************************
5086 * Copyright 2022 Adobe
5087 *
5088 * Licensed under the Apache License, Version 2.0 (the "License");
5089 * you may not use this file except in compliance with the License.
5090 * You may obtain a copy of the License at
5091 *
5092 *     http://www.apache.org/licenses/LICENSE-2.0
5093 *
5094 * Unless required by applicable law or agreed to in writing, software
5095 * distributed under the License is distributed on an "AS IS" BASIS,
5096 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5097 * See the License for the specific language governing permissions and
5098 * limitations under the License.
5099 ******************************************************************************/
5100
5101(function () {
5102
5103    class Tabs extends FormView.FormTabs {
5104        _templateHTML = {};
5105        static NS = FormView.Constants.NS;
5106        static IS = "adaptiveFormTabs";
5107        static bemBlock = "cmp-tabs";
5108        static selectors = {
5109            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
5110            active: {
5111                tab: "cmp-tabs__tab--active",
5112                tabpanel: "cmp-tabs__tabpanel--active"
5113            },
5114            stepped: {
5115                tab: "cmp-tabs__tab--stepped",
5116                tabpanel: "cmp-tabs__tabpanel--stepped"
5117            },
5118            label: `.${Tabs.bemBlock}__label`,
5119            description: `.${Tabs.bemBlock}__longdescription`,
5120            qm: `.${Tabs.bemBlock}__questionmark`,
5121            tooltipDiv: `.${Tabs.bemBlock}__shortdescription`,
5122            olTabList: `.${Tabs.bemBlock}__tablist`,
5123            widget: `.${Tabs.bemBlock}__tablist`
5124        };
5125
5126        constructor(params) {
5127            super(params, Tabs.NS, Tabs.IS, Tabs.selectors);
5128        }
5129
5130
5131        getClass() {
5132            return Tabs.IS;
5133        }
5134
5135        setFocus(id) {
5136            super.setFocus(id);
5137            this.setActive();
5138            if (id) {
5139                this.navigateAndFocusTab(id + '__tab');
5140            }
5141        }
5142
5143        getWidget() {
5144            return this.element.querySelector(Tabs.selectors.widget);
5145        }
5146
5147        getDescription() {
5148            return this.element.querySelector(Tabs.selectors.description);
5149        }
5150
5151        getLabel() {
5152            return this.element.querySelector(Tabs.selectors.label);
5153        }
5154
5155        getErrorDiv() {
5156            return this.element.querySelector(Tabs.selectors.errorDiv);
5157        }
5158
5159        getTooltipDiv() {
5160            return this.element.querySelector(Tabs.selectors.tooltipDiv);
5161        }
5162
5163        getQuestionMarkDiv() {
5164            return this.element.querySelector(Tabs.selectors.qm);
5165        }
5166    }
5167
5168    FormView.Utils.setupField(({element, formContainer}) => {
5169        return new Tabs({element, formContainer})
5170    }, Tabs.selectors.self);
5171
5172}());
5173
5174/*******************************************************************************
5175 * Copyright 2022 Adobe
5176 *
5177 * Licensed under the Apache License, Version 2.0 (the "License");
5178 * you may not use this file except in compliance with the License.
5179 * You may obtain a copy of the License at
5180 *
5181 *     http://www.apache.org/licenses/LICENSE-2.0
5182 *
5183 * Unless required by applicable law or agreed to in writing, software
5184 * distributed under the License is distributed on an "AS IS" BASIS,
5185 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5186 * See the License for the specific language governing permissions and
5187 * limitations under the License.
5188 ******************************************************************************/
5189
5190(function () {
5191
5192    function onWizardMixinLoaded(event) {
5193        const WizardMixin = event.detail.WizardMixin;
5194        const keyCodes = {
5195            END: 35,
5196            HOME: 36,
5197            ARROW_LEFT: 37,
5198            ARROW_UP: 38,
5199            ARROW_RIGHT: 39,
5200            ARROW_DOWN: 40
5201        };
5202
5203        class Wizard extends WizardMixin(FormView.FormPanel) {
5204
5205            _templateHTML = {};
5206
5207            static NS = FormView.Constants.NS;
5208            static #tabIdSuffix = "_wizard-item-nav";
5209            static #wizardPanelIdSuffix = "__wizardpanel";
5210
5211            static selectors = {
5212                self: "[data-" + Wizard.NS + '-is="' + Wizard.IS + '"]',
5213                active: {
5214                    tab: "cmp-adaptiveform-wizard__tab--active",
5215                    wizardpanel: "cmp-adaptiveform-wizard__wizardpanel--active"
5216                },
5217                stepped: {
5218                    tab: "cmp-adaptiveform-wizard__tab--stepped",
5219                    wizardpanel: "cmp-adaptiveform-wizard__wizardpanel--stepped",
5220                },
5221                label: `.${Wizard.bemBlock}__label`,
5222                description: `.${Wizard.bemBlock}__longdescription`,
5223                qm: `.${Wizard.bemBlock}__questionmark`,
5224                widget: `.${Wizard.bemBlock}__widget`,
5225                tooltipDiv: `.${Wizard.bemBlock}__shortdescription`,
5226                previousButton: `.${Wizard.bemBlock}__previousNav`,
5227                previousButtonHidden: "cmp-adaptiveform-wizard__previousNav--hidden",
5228                nextButton: `.${Wizard.bemBlock}__nextNav`,
5229                previousButtonV2: `.${Wizard.bemBlock}__nav--previous`,
5230                nextButtonV2: `.${Wizard.bemBlock}__nav--next`,
5231                nextButtonHidden: "cmp-adaptiveform-wizard__nextNav--hidden",
5232                olTabList: `.${Wizard.bemBlock}__tabList`
5233            };
5234
5235            constructor(params) {
5236                super(params);
5237                const {element, formContainer} = params;
5238                this.formContainer = formContainer;
5239                this.cacheElements(element);
5240                this.setActive(this.getCachedTabs())
5241                this._active = this.getActiveIndex(this.getCachedTabs());
5242                this.#setNavigationRange();
5243                this.#hideUnhideNavButtons(this._active);
5244                this.refreshActive();
5245
5246                this.#bindEvents();
5247            }
5248
5249            getClass() {
5250                return Wizard.IS;
5251            }
5252
5253            setFocus(id) {
5254                super.setFocus(id);
5255                this.setActive();
5256                const index = this.#getTabIndexById(id + '_wizard-item-nav');
5257                this.navigate(index);
5258            }
5259
5260            getWidget() {
5261                return this.element.querySelector(Wizard.selectors.widget);
5262            }
5263
5264            getDescription() {
5265                return this.element.querySelector(Wizard.selectors.description);
5266            }
5267
5268            getLabel() {
5269                return this.element.querySelector(Wizard.selectors.label);
5270            }
5271
5272            getErrorDiv() {
5273                return this.element.querySelector(Wizard.selectors.errorDiv);
5274            }
5275
5276            getTooltipDiv() {
5277                return this.element.querySelector(Wizard.selectors.tooltipDiv);
5278            }
5279
5280            getQuestionMarkDiv() {
5281                return this.element.querySelector(Wizard.selectors.qm);
5282            }
5283
5284            getPreviousButtonDiv() {
5285                return (this.element.querySelector(Wizard.selectors.previousButton) || this.element.querySelector(Wizard.selectors.previousButtonV2));
5286            }
5287
5288            getNextButtonDiv() {
5289                return (this.element.querySelector(Wizard.selectors.nextButton) || this.element.querySelector(Wizard.selectors.nextButtonV2));
5290            }
5291
5292            #getTabListElement() {
5293                return this.element.querySelector(Wizard.selectors.olTabList)
5294            }
5295
5296
5297            /**
5298             * Binds navigation buttons event handling
5299             *
5300             * @private
5301             */
5302            #bindEvents() {
5303                const _self = this;
5304                const actionKeys = ['Enter', ' ', 'Spacebar', 'Space'];
5305
5306                ["click", "keydown"].forEach(function(event){
5307                    _self.getNextButtonDiv().addEventListener(event, function(event){
5308                        if (event.type ==='click' || (event.type === 'keydown' && actionKeys.includes(event.key))) {
5309                            _self.#navigateToNextTab();
5310                        }
5311                    });
5312                    _self.getPreviousButtonDiv().addEventListener(event, function(event){
5313                        if (event.type ==='click' || (event.type === 'keydown' && actionKeys.includes(event.key))) {
5314                            _self.#navigateToPreviousTab();
5315                        }
5316                    });
5317                })
5318            }
5319
5320            /**
5321             * Handles tab keydown events
5322             *
5323             * @private
5324             * @param {Object} event The keydown event
5325             */
5326            #onKeyDown(event) {
5327                const index = this._active;
5328
5329                const lastIndex = this.getCachedTabs().length - 1;
5330
5331                switch (event.keyCode) {
5332                    case keyCodes.ARROW_LEFT:
5333                    case keyCodes.ARROW_UP:
5334                        event.preventDefault();
5335                        if (index > 0) {
5336                            this.#navigateAndFocusTab(index - 1);
5337                        }
5338                        break;
5339                    case keyCodes.ARROW_RIGHT:
5340                    case keyCodes.ARROW_DOWN:
5341                        event.preventDefault();
5342                        if (index < lastIndex) {
5343                            this.#navigateAndFocusTab(index + 1);
5344                        }
5345                        break;
5346                    case keyCodes.HOME:
5347                        event.preventDefault();
5348                        this.#navigateAndFocusTab(0);
5349                        break;
5350                    case keyCodes.END:
5351                        event.preventDefault();
5352                        this.#navigateAndFocusTab(lastIndex);
5353                        break;
5354                    default:
5355                        return;
5356                }
5357            }
5358
5359            /**
5360             * Refreshes the tab markup based on the current {@code Tabs_active} index
5361             *
5362             * @private
5363             */
5364            refreshActive() {
5365                super.refreshActive();
5366                this.#hideUnhideNavButtons(this._active);
5367            }
5368
5369            /**
5370             * Focuses the element and prevents scrolling the element into view
5371             *
5372             * @param {HTMLElement} element Element to focus
5373             */
5374            focusWithoutScroll(element) {
5375                const x = window.scrollX || window.pageXOffset;
5376                const y = window.scrollY || window.pageYOffset;
5377                element.focus();
5378                window.scrollTo(x, y);
5379            }
5380
5381
5382            getFocusElementId() {
5383                const activeIndex = this._active;
5384                const activeTabElement = this.getCachedTabs()[activeIndex];
5385                return activeTabElement.id.substring(0, activeTabElement.id.lastIndexOf(Wizard.#tabIdSuffix));
5386            }
5387
5388            #navigateToNextTab() {
5389                const activeIndex = this._active;
5390                const activeTabElement = this.getCachedTabs()[activeIndex];
5391                const activeChildId = activeTabElement.id.substring(0, activeTabElement.id.lastIndexOf(Wizard.#tabIdSuffix));
5392                const activeChildView = this.getChild(activeChildId);
5393                let activeChildModel;
5394                if (activeChildView) {
5395                    activeChildModel = activeChildView.getModel();
5396                } else {
5397                    activeChildModel = this.getModel().items.find(child => child.id === activeChildId);
5398                }
5399                let validationErrorList;
5400                if (!this.#isAuthoring()) {
5401                    validationErrorList = activeChildModel.validate();
5402                }
5403                if (validationErrorList === undefined || validationErrorList.length == 0) {
5404                    let tabs = this.getCachedTabs();
5405                    let nextVisibleIndex = this.#findNextVisibleChildIndex(activeIndex);
5406                    if (tabs && nextVisibleIndex >= 0) {
5407                        this.#navigateAndFocusTab(nextVisibleIndex);
5408                    }
5409                } else {
5410                    this.formContainer?.setFocus(validationErrorList[0].fieldName);
5411                }
5412                this.#hideUnhideNavButtons(this._active);
5413            }
5414
5415            #isAuthoring() {
5416                return window.Granite && window.Granite.author;
5417            }
5418
5419            #navigateToPreviousTab() {
5420                const activeIndex = this._active;
5421                const tabs = this.getCachedTabs();
5422                const lastVisibleIndex = this.#findLastVisibleChildIndex(activeIndex);
5423                if (tabs && lastVisibleIndex >= 0) {
5424                    this.#navigateAndFocusTab(lastVisibleIndex);
5425                }
5426                this.#hideUnhideNavButtons(this._active);
5427            }
5428
5429            /**
5430             * Hides or shows, next and previous navigation buttons
5431             *
5432             * @private
5433             * @param {Number} index The index of the tab to navigate to
5434             * @param {Number} total number of tabs
5435             */
5436            #hideUnhideNavButtons(activeTabIndex) {
5437                const tabsLength = this.getCachedTabs() ? this.getCachedTabs().length : 0;
5438
5439                const nextVisible = this.#findNextVisibleChildIndex(activeTabIndex);
5440                const previousVisible = this.#findLastVisibleChildIndex(activeTabIndex);
5441
5442                if (tabsLength === 0 || this.maxEnabledTab <= this.minEnabledTab) {
5443                    this.getPreviousButtonDiv().setAttribute(Wizard.DATA_ATTRIBUTE_VISIBLE, "false");
5444                    this.getNextButtonDiv().setAttribute(Wizard.DATA_ATTRIBUTE_VISIBLE, "false");
5445                }
5446
5447                if (activeTabIndex <= this.minEnabledTab || previousVisible === -1) {
5448                    this.getPreviousButtonDiv().setAttribute(Wizard.DATA_ATTRIBUTE_VISIBLE, "false");
5449                }
5450                if (activeTabIndex === this.maxEnabledTab || nextVisible === -1) {
5451                    this.getNextButtonDiv().setAttribute(Wizard.DATA_ATTRIBUTE_VISIBLE, "false");
5452                }
5453
5454                if (tabsLength > 1 && activeTabIndex > this.minEnabledTab && previousVisible > -1) {
5455                    this.getPreviousButtonDiv().setAttribute(Wizard.DATA_ATTRIBUTE_VISIBLE, "true");
5456                }
5457
5458                if (activeTabIndex < this.maxEnabledTab && nextVisible > -1) {
5459                    this.getNextButtonDiv().setAttribute(Wizard.DATA_ATTRIBUTE_VISIBLE, "true");
5460                }
5461            }
5462
5463            #setNavigationRange() {
5464                const wizardPanels = this.getCachedWizardPanels();
5465                if (wizardPanels) {
5466                    this.maxEnabledTab = wizardPanels.length - 1;
5467                    this.minEnabledTab = 0;
5468                    for (let i = 0; i < wizardPanels.length; i++) {
5469                        if (!this.#childComponentVisible(this.getCachedWizardPanels()[i])) {
5470                            this.minEnabledTab = i + 1;
5471                        } else {
5472                            break;
5473                        }
5474                    }
5475                    for (let i = wizardPanels.length - 1; i >= 0; i--) {
5476                        if (!this.#childComponentVisible(this.getCachedWizardPanels()[i])) {
5477                            this.maxEnabledTab = i;
5478                        } else {
5479                            break;
5480                        }
5481                    }
5482                    this.minEnabledTab = Math.max(0, this.minEnabledTab);
5483                    this.maxEnabledTab = Math.min(this.getCachedTabs().length - 1, this.maxEnabledTab);
5484                }
5485            }
5486
5487            #childComponentVisible(wizardTab) {
5488                return wizardTab.children[0].getAttribute('data-cmp-visible') === 'true';
5489            }
5490
5491            #findNextVisibleChildIndex(currentIndex) {
5492                const tabs = this.getCachedTabs();
5493                const tabsLength = tabs ? tabs.length : 0;
5494                for (let i = currentIndex + 1; i < tabsLength; i++) {
5495                    let isVisible = tabs[i].getAttribute(Wizard.DATA_ATTRIBUTE_VISIBLE);
5496                    if (isVisible === null || isVisible === 'true') {
5497                        return i;
5498                    }
5499                }
5500                return -1;
5501            }
5502
5503            #findLastVisibleChildIndex(currentIndex) {
5504                const tabs = this.getCachedTabs();
5505                if (tabs) {
5506                    for (let i = currentIndex - 1; i >= 0; i--) {
5507                        let isVisible = tabs[i].getAttribute(Wizard.DATA_ATTRIBUTE_VISIBLE);
5508                        if (isVisible === null || isVisible === 'true') {
5509                            return i;
5510                        }
5511                    }
5512                }
5513                return -1;
5514            }
5515
5516            /**
5517             * Navigates to the item at the provided index and ensures the active tab gains focus
5518             *
5519             * @private
5520             * @param {Number} index The index of the item to navigate to
5521             */
5522            #navigateAndFocusTab(index) {
5523                this.navigate(index);
5524                this.focusWithoutScroll(this.getCachedTabs()[index]);
5525                const id = this.getFocusElementId();
5526                this.focusToFirstVisibleField(id);
5527            }
5528   
5529            #syncWizardNavLabels() {
5530                const tabs = this.getCachedTabs();
5531                const wizardPanels = this.getCachedWizardPanels();
5532                if (tabs) {
5533                    for (let i = 0; i < tabs.length; i++) {
5534                        let id = wizardPanels[i].querySelectorAll("[data-cmp-is]")[0].id;
5535                        tabs[i].id = id + Wizard.#tabIdSuffix;
5536                        tabs[i].setAttribute("aria-controls", id + Wizard.#wizardPanelIdSuffix);
5537                    }
5538                }
5539            }
5540
5541            #syncWizardPanels() {
5542                const wizardPanels = this.getCachedWizardPanels();
5543                if (wizardPanels) {
5544                    for (let i = 0; i < wizardPanels.length; i++) {
5545                        let id = wizardPanels[i].querySelectorAll("[data-cmp-is]")[0].id;
5546                        wizardPanels[i].id = id + Wizard.#wizardPanelIdSuffix;
5547                        wizardPanels[i].setAttribute("aria-labelledby", id + Wizard.#tabIdSuffix);
5548                    }
5549                }
5550            }
5551
5552            syncMarkupWithModel() {
5553                super.syncMarkupWithModel();
5554                this.#syncWizardNavLabels();
5555                this.#syncWizardPanels();
5556            }
5557
5558            handleChildAddition(childView) {
5559                if (childView.getInstanceManager() != null && this._templateHTML[childView.getInstanceManager().getId()] != null) {
5560                    let navigationTabToBeRepeated = this._templateHTML[childView.getInstanceManager().getId()]['navigationTab']
5561                        .cloneNode(true);
5562                    navigationTabToBeRepeated.id = childView.id + Wizard.#tabIdSuffix;
5563                    navigationTabToBeRepeated.setAttribute("aria-controls", childView.id + Wizard.#wizardPanelIdSuffix);
5564                    let instanceIndex = childView.getModel().index;
5565                    let instanceManagerId = childView.getInstanc
5565eManager().getId()
5566                    if (instanceIndex == 0) {
5567                        let closestNonRepeatableFieldId = this._templateHTML[instanceManagerId]['closestNonRepeatableFieldId'];
5568                        let closestRepeatableFieldInstanceManagerIds = this._templateHTML[instanceManagerId]['closestRepeatableFieldInstanceManagerIds'];
5569                        let indexToInsert = this.getIndexToInsert(closestNonRepeatableFieldId, closestRepeatableFieldInstanceManagerIds);
5570                        if (indexToInsert == 0) {
5571                            let tabListParentElement = this.#getTabListElement();
5572                            tabListParentElement.insertBefore(navigationTabToBeRepeated, tabListParentElement.firstChild);
5573                        } else {
5574                            let beforeElement = this.getCachedTabs()[indexToInsert - 1];
5575                            beforeElement.after(navigationTabToBeRepeated);
5576                        }
5577                    } else {
5578                        let beforeTabNavElementId = childView.getInstanceManager().children[instanceIndex - 1].element.id + Wizard.#tabIdSuffix
5579                        let beforeElement = this.getTabNavElementById(beforeTabNavElementId);
5580                        beforeElement.after(navigationTabToBeRepeated);
5581                    }
5582                    this.cacheElements(this._elements.self);
5583                    let repeatedWizardPanel = this.#getWizardPanelElementById(childView.id + Wizard.#wizardPanelIdSuffix);
5584                    repeatedWizardPanel.setAttribute("aria-labelledby", childView.id + Wizard.#tabIdSuffix);
5585                    
5586                    const steppedTabClass = Array.from(navigationTabToBeRepeated.classList).find(cls => cls.includes('--stepped'));
5587                    if (steppedTabClass) {
5588                        navigationTabToBeRepeated.classList.remove(steppedTabClass);
5589                    }
5590                    const steppedWizardPanelClass = Array.from(repeatedWizardPanel.classList).find(cls => cls.includes('--stepped'));
5591                    if (steppedWizardPanelClass) {
5592                        repeatedWizardPanel.classList.remove(steppedWizardPanelClass);
5593            }
5594                    this.refreshActive();
5595                    this.#getTabIndexById();
5596                    if (childView.getInstanceManager().getModel().minOccur != undefined && childView.getInstanceManager().children.length > childView.getInstanceManager().getModel().minOccur) {
5597                        this.#navigateAndFocusTab(this.#getTabIndexById(navigationTabToBeRepeated.id));
5598                    }
5599                }
5600            }
5601
5602            handleChildRemoval(removedInstanceView) {
5603                let removedTabPanelId = removedInstanceView.element.id + Wizard.#wizardPanelIdSuffix;
5604                let removedTabNavId = removedTabPanelId.substring(0, removedTabPanelId.lastIndexOf("__")) + Wizard.#tabIdSuffix;
5605                let wizardPanelElement = this.#getWizardPanelElementById(removedTabPanelId);
5606                let tabNavElement = this.getTabNavElementById(removedTabNavId);
5607
5608                const tabs = this.getCachedTabs();
5609                const currentIndex = Array.from(tabs).findIndex(tab => tab.id === removedTabNavId);
5610                let nextIndex = -1;
5611                
5612                if (currentIndex === 0) {
5613                    // If removing first tab, focus on the next one
5614                    nextIndex = 1;
5615                } else {
5616                    // Look for previous visible tab
5617                    for (let i = currentIndex - 1; i >= 0; i--) {
5618                        nextIndex = i;
5619                        break;
5620                    }
5621                }
5622                
5623                tabNavElement.remove();
5624                wizardPanelElement.remove();
5625                this.children.splice(this.children.indexOf(removedInstanceView), 1);
5626                this.cacheElements(this._elements.self);
5627                this._active = this.getActiveIndex(this.getCachedTabs());
5628                this.refreshActive();
5629
5630                // Focus the next tab after active state is updated
5631                if (nextIndex !== -1 && tabs[nextIndex]) {
5632                    this.#navigateAndFocusTab(nextIndex);    
5633                }
5634            }
5635
5636            addChild(childView) {
5637                super.addChild(childView);
5638                this.#cacheTemplateHTML(childView);
5639                //when all children are available in view
5640                if (this.getCountOfAllChildrenInModel() === this.children.length) {
5641                    this.cacheClosestFieldsInView();
5642                    this.handleHiddenChildrenVisibility();
5643                }
5644                this.#setNavigationRange();
5645                this.#hideUnhideNavButtons(this._active);
5646            }
5647
5648            getChildViewByIndex(index) {
5649                let wizardPanels = this.getCachedWizardPanels();
5650                let fieldId = wizardPanels[index].id.substring(0, wizardPanels[index].id.lastIndexOf("__"));
5651                return this.getChild(fieldId);
5652            }
5653
5654            /**
5655             * Adds unique HTML for added instance corresponding to requirements of different types of repeatableParent
5656             * @param instanceManager of the repeated component
5657             * @param addedModel of the repeated component
5658             * @param htmlElement of the repeated component
5659             */
5660            addRepeatableMarkup(instanceManager, addedModel, htmlElement) {
5661                let elementToEnclose = this._templateHTML[instanceManager.getId()]['targetWizardPanel'].cloneNode(false);
5662                elementToEnclose.id = addedModel.id + Wizard.#wizardPanelIdSuffix;
5663                let result = this.#getBeforeViewElement(instanceManager, addedModel.index);
5664                let beforeViewElement = result.beforeViewElement;
5665                beforeViewElement.after(elementToEnclose);
5666                elementToEnclose.append(htmlElement.querySelector('#' + addedModel.id));
5667                return elementToEnclose;
5668            }
5669
5670            #cacheTemplateHTML(childView) {
5671                if (childView.getInstanceManager() != null && (this._templateHTML == null || this._templateHTML[childView.getInstanceManager().getId()] == null)) {
5672                    let tabId = childView.element.id + Wizard.#tabIdSuffix;
5673                    let wizardPanelId = childView.element.id + Wizard.#wizardPanelIdSuffix;
5674                    let instanceManagerId = childView.getInstanceManager().getId();
5675                    let navigationTabToBeRepeated = this.getTabNavElementById(tabId);
5676                    let wizardPanelToBeRepeated = this.#getWizardPanelElementById(wizardPanelId)
5677                    this._templateHTML[instanceManagerId] = {};
5678                    this._templateHTML[instanceManagerId]['navigationTab'] = navigationTabToBeRepeated;
5679                    this._templateHTML[instanceManagerId]['targetWizardPanel'] = wizardPanelToBeRepeated;
5680                }
5681            }
5682
5683            #getWizardPanelElementById(wizardPanelId) {
5684                let wizardPanels = this.getCachedWizardPanels();
5685                if (wizardPanels) {
5686                    for (let i = 0; i < wizardPanels.length; i++) {
5687                        if (wizardPanels[i].id === wizardPanelId) {
5688                            return wizardPanels[i];
5689                        }
5690                    }
5691                }
5692            }
5693
5694            #getTabIndexById(tabId) {
5695                let tabs = this.getCachedTabs();
5696                if (tabs) {
5697                    for (let i = 0; i < tabs.length; i++) {
5698                        if (tabs[i].id === tabId) {
5699                            return i;
5700                        }
5701                    }
5702                }
5703                return -1;
5704            }
5705
5706            #getBeforeViewElement(instanceManager, instanceIndex) {
5707                let result = {};
5708                let instanceManagerId = instanceManager.getId();
5709                if (instanceIndex == 0) {
5710                    let closestNonRepeatableFieldId = this._templateHTML[instanceManagerId]['closestNonRepeatableFieldId'];
5711                    let closestRepeatableFieldInstanceManagerIds = this._templateHTML[instanceManagerId]['closestRepeatableFieldInstanceManagerIds'];
5712                    let indexToInsert = this.getIndexToInsert(closestNonRepeatableFieldId, closestRepeatableFieldInstanceManagerIds);
5713                    let wizardPanels = this.getCachedWizardPanels();
5714                    if (indexToInsert > 0) {
5715                        result.beforeViewElement = this.#getWizardPanelElementById(wizardPanels[indexToInsert - 1].id);
5716                    } else {
5717                        result.beforeViewElement = this.getPreviousButtonDiv();
5718                    }
5719                } else {
5720                    let previousInstanceElement = this.#getRepeatableElementAt(instanceManager, instanceIndex - 1)
5721                    result.beforeViewElement = previousInstanceElement;
5722                }
5723                return result;
5724            }
5725
5726            #getRepeatableElementAt(instanceManager, index) {
5727                let childId = instanceManager._model.items.find((model) => model.index === index)?.id;
5728                return this.element.querySelector(`#${childId}${Wizard.#wizardPanelIdSuffix}`);
5729            }
5730
5731            updateChildVisibility(visible, state) {
5732                this.updateVisibilityOfNavigationElement(this.getTabNavElementById(state.id + Wizard.#tabIdSuffix), visible);
5733                let activeTabNavElement = this.getCachedTabs()[this._active];
5734                this.#setNavigationRange();
5735                this.#hideUnhideNavButtons(this._active);
5736                if (!visible && activeTabNavElement.id === state.id + Wizard.#tabIdSuffix) {
5737                    let child = this.findFirstVisibleChild(this.getCachedTabs());
5738                    if (child) {
5739                        this.#navigateAndFocusTab(this.#getTabIndexById(child.id));
5740                    }
5741                }
5742            }
5743        }
5744
5745        FormView.Utils.setupField(({element, formContainer}) => {
5746            return new Wizard({element, formContainer})
5747        }, Wizard.selectors.self);
5748    }
5749
5750    if (window.Forms && window.Forms.CoreComponentsCommons && window.Forms.CoreComponentsCommons.WizardMixin) {
5751        onWizardMixinLoaded({ detail: { WizardMixin: window.Forms.CoreComponentsCommons.WizardMixin } });
5752    } else {
5753        window.addEventListener('WizardMixinLoaded', onWizardMixinLoaded);
5754    }
5755
5756}());
5757
5758/*******************************************************************************
5759 * Copyright 2023 Adobe
5760 *
5761 * Licensed under the Apache License, Version 2.0 (the "License");
5762 * you may not use this file except in compliance with the License.
5763 * You may obtain a copy of the License at
5764 *
5765 *     http://www.apache.org/licenses/LICENSE-2.0
5766 *
5767 * Unless required by applicable law or agreed to in writing, software
5768 * distributed under the License is distributed on an "AS IS" BASIS,
5769 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5770 * See the License for the specific language governing permissions and
5771 * limitations under the License.
5772 ******************************************************************************/
5773
5774(function () {
5775
5776    class VerticalTabs extends FormView.FormTabs {
5777        _templateHTML = {};
5778        static NS = FormView.Constants.NS;
5779        static IS = "adaptiveFormVerticalTabs";
5780        static bemBlock = "cmp-verticaltabs";
5781        static selectors = {
5782            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
5783            active: {
5784                tab: "cmp-verticaltabs__tab--active",
5785                tabpanel: "cmp-verticaltabs__tabpanel--active"
5786            },
5787            stepped: {
5788                tab: "cmp-verticaltabs__tab--stepped",
5789                tabpanel: "cmp-verticaltabs__tabpanel--stepped"
5790            },
5791            label: `.${VerticalTabs.bemBlock}__label`,
5792            description: `.${VerticalTabs.bemBlock}__longdescription`,
5793            qm: `.${VerticalTabs.bemBlock}__questionmark`,
5794            tooltipDiv: `.${VerticalTabs.bemBlock}__shortdescription`,
5795            olTabList: `.${VerticalTabs.bemBlock}__tablist`,
5796            widget: `.${VerticalTabs.bemBlock}__tabs-container`
5797        };
5798
5799        constructor(params) {
5800            super(params, VerticalTabs.NS, VerticalTabs.IS, VerticalTabs.selectors);
5801        }
5802
5803        getClass() {
5804            return VerticalTabs.IS;
5805        }
5806
5807        setFocus(id) {
5808            super.setFocus(id);
5809            this.setActive();
5810            if(id) {
5811                this.navigateAndFocusTab(id + '__tab');
5812            }
5813        }
5814
5815        getWidget() {
5816            return this.element.querySelector(VerticalTabs.selectors.widget);
5817        }
5818
5819        getDescription() {
5820            return this.element.querySelector(VerticalTabs.selectors.description);
5821        }
5822
5823        getLabel() {
5824            return this.element.querySelector(VerticalTabs.selectors.label);
5825        }
5826
5827        getErrorDiv() {
5828            return this.element.querySelector(VerticalTabs.selectors.errorDiv);
5829        }
5830
5831        getTooltipDiv() {
5832            return this.element.querySelector(VerticalTabs.selectors.tooltipDiv);
5833        }
5834
5835        getQuestionMarkDiv() {
5836            return this.element.querySelector(VerticalTabs.selectors.qm);
5837        }
5838    }
5839
5840    FormView.Utils.setupField(({element, formContainer}) => {
5841        return new VerticalTabs({element, formContainer})
5842    }, VerticalTabs.selectors.self);
5843
5844}());
5845
5846/*******************************************************************************
5847 * Copyright 2023 Adobe
5848 *
5849 * Licensed under the Apache License, Version 2.0 (the "License");
5850 * you may not use this file except in compliance with the License.
5851 * You may obtain a copy of the License at
5852 *
5853 *     http://www.apache.org/licenses/LICENSE-2.0
5854 *
5855 * Unless required by applicable law or agreed to in writing, software
5856 * distributed under the License is distributed on an "AS IS" BASIS,
5857 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5858 * See the License for the specific language governing permissions and
5859 * limitations under the License.
5860 ******************************************************************************/
5861(function() {
5862
5863    "use strict";
5864    class Recaptcha extends FormView.FormFieldBase {
5865
5866        static NS = FormView.Constants.NS;
5867        static IS = "adaptiveFormRecaptcha";
5868        static bemBlock = 'cmp-adaptiveform-recaptcha';
5869        static selectors  = {
5870            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
5871            widget: `.${Recaptcha.bemBlock}__widget`,
5872            label: `.${Recaptcha.bemBlock}__label`,
5873            errorDiv: `.${Recaptcha.bemBlock}__errormessage`
5874        };
5875
5876        constructor(params) {
5877            super(params);
5878        }
5879
5880        getWidget() {
5881            return this.element.querySelector(Recaptcha.selectors.widget);
5882        }
5883
5884        getDescription() {
5885            return null;
5886        }
5887
5888        getLabel() {
5889            return this.element.querySelector(Recaptcha.selectors.label);
5890        }
5891
5892        getTooltipDiv() {
5893            return null;
5894        }
5895
5896        getErrorDiv() {
5897            return this.element.querySelector(Recaptcha.selectors.errorDiv);
5898        }
5899
5900        getQuestionMarkDiv() {
5901            return null;
5902        }
5903
5904    	initializeWidget() {
5905            this.widgetObject = new RecaptchaWidget(this, this._model, this.getWidget());
5906            this.getWidget().addEventListener('blur', (e) => {
5907                if(this.element) {
5908                    this.setInactive();
5909                }
5910            });
5911
5912        }
5913
5914        setModel(model) {
5915            super.setModel(model);
5916            if (this.widgetObject == null) {
5917                    this.initializeWidget();
5918            } else {
5919                if (this.widget.value !== '') {
5920                    this._model.dispatch(new FormView.Actions.UIChange({'value': this.widget.value}));
5921                }
5922            }
5923        }
5924    }
5925
5926    FormView.Utils.setupField(({element, formContainer}) => {
5927        return new Recaptcha({element, formContainer})
5928    }, Recaptcha.selectors.self);
5929
5930})();
5931
5932/*******************************************************************************
5933 * Copyright 2023 Adobe
5934 *
5935 * Licensed under the Apache License, Version 2.0 (the "License");
5936 * you may not use this file except in compliance with the License.
5937 * You may obtain a copy of the License at
5938 *
5939 *     http://www.apache.org/licenses/LICENSE-2.0
5940 *
5941 * Unless required by applicable law or agreed to in writing, software
5942 * distributed under the License is distributed on an "AS IS" BASIS,
5943 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5944 * See the License for the specific language governing permissions and
5945 * limitations under the License.
5946 ******************************************************************************/
5947
5948/**
5949 * This class is responsible for interacting with the recaptcha widget. It displays Google reCAPTCHA challenge.
5950 */
5951
5952if (typeof window.RecaptchaWidget === 'undefined') {
5953    window.RecaptchaWidget = class {
5954        #widget = null
5955        #model = null // passed by reference
5956        #options = null
5957        #lang = 'en'
5958        static FD_CAPTCHA = "fd:captcha";
5959
5960        constructor(view, model, widget) {
5961            // initialize the widget and model
5962            this.#widget = widget;
5963            this.#model = model;
5964            this.#widget = document.createElement("div");
5965            this.#widget.classList.add("cmp-adaptiveform-recaptcha__widget");
5966            this.#lang = view.formContainer.getModel().lang;
5967
5968            //Always inserting it in body
5969            document.body.appendChild(this.#widget);
5970            this.#options = Object.assign({}, this.#model._jsonModel);
5971
5972            this.#renderRecaptcha(widget);
5973        }
5974
5975        #renderRecaptcha(element) {
5976
5977            var self = this;
5978            var recaptchaConfigData = this.#options;
5979            element.innerHTML = '<div class="g-recaptcha"></div>';
5980            var gcontainer = document.getElementsByClassName("g-recaptcha")[0];
5981            var widgetId;
5982            var url = recaptchaConfigData.properties[RecaptchaWidget.FD_CAPTCHA].config.uri;
5983            if (recaptchaConfigData.properties[RecaptchaWidget.FD_CAPTCHA].config.size == "invisible") {
5984                gcontainer.classList.add('g-recaptcha-invisible');
5985                recaptchaConfigData.required = false;
5986            }
5987
5988            var successCallback = function(response) {
5989                self.setCaptchaModel(response);
5990            };
5991
5992            var expiredCallback = function() {
5993                if (isRecaptchaEnterprise()) {
5994                    grecaptcha.enterprise.reset(widgetId);
5995                } else {
5996                    grecaptcha.reset(widgetId);
5997                }
5998                self.setCaptchaModel("");
5999            };
6000
6001            var onloadCallbackInternal = function() {
6002                widgetId = isRecaptchaEnterprise() ? grecaptcha.enterprise.render(gcontainer, gparameters)
6003                    : grecaptcha.render(gcontainer, gparameters);
6004                return widgetId;
6005            };
6006
6007            var gparameters = {
6008                'sitekey': recaptchaConfigData.properties[RecaptchaWidget.FD_CAPTCHA].config.siteKey,
6009                'size': recaptchaConfigData.properties[RecaptchaWidget.FD_CAPTCHA].config.size,
6010                'theme': recaptchaConfigData.properties[RecaptchaWidget.FD_CAPTCHA].config.theme || 'light',
6011                'type': recaptchaConfigData.properties[RecaptchaWidget.FD_CAPTCHA].config.type || 'image',
6012                'callback': successCallback,
6013                'expired-callback': expiredCallback
6014            };
6015
6016            const isRecaptchaEnterprise = function () {
6017                return recaptchaConfigData.properties[RecaptchaWidget.FD_CAPTCHA].config.version === "enterprise";
6018            }
6019            const isScoreBasedKey = function () {
6020                return isRecaptchaEnterprise() && recaptchaConfigData.properties[RecaptchaWidget.FD_CAPTCHA].config.keyType === "score";
6021            }
6022
6023            window.onloadRecaptchaCallback = onloadCallbackInternal;
6024
6025            var runtimeLocale = this.#lang;
6026
6027            var scr = document.createElement('script');
6028            let queryParams = isScoreBasedKey() ? "?render=" + recaptchaConfigData.properties[RecaptchaWidget.FD_CAPTCHA].config.siteKey
6029                : "?onload=onloadRecaptchaCallback&render=explicit";
6030            queryParams += "&hl=" + runtimeLocale;
6031            scr.src = url + queryParams;
6032            scr.async = true;
6033            element.appendChild(scr);
6034        }
6035
6036        setCaptchaModel = function(response) {
6037            this.#model.dispatch(new FormView.Actions.UIChange({'value': response}));
6038        }
6039    }
6040}
6041
6042/*******************************************************************************
6043 * Copyright 2022 Adobe
6044 *
6045 * Licensed under the Apache License, Version 2.0 (the "License");
6046 * you may not use this file except in compliance with the License.
6047 * You may obtain a copy of the License at
6048 *
6049 *     http://www.apache.org/licenses/LICENSE-2.0
6050 *
6051 * Unless required by applicable law or agreed to in writing, software
6052 * distributed under the License is distributed on an "AS IS" BASIS,
6053 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6054 * See the License for the specific language governing permissions and
6055 * limitations under the License.
6056 ******************************************************************************/
6057(function() {
6058
6059
6060    "use strict";
6061    class CheckBox extends FormView.FormCheckBox {
6062
6063        static NS = FormView.Constants.NS;
6064        /**
6065         * Each FormField has a data attribute class that is prefixed along with the global namespace to
6066         * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be
6067         * data-{NS}-{IS}-x=""
6068         * @type {string}
6069         */
6070        static IS = "adaptiveFormCheckBox";
6071        static bemBlock = 'cmp-adaptiveform-checkbox'
6072        static selectors  = {
6073            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
6074            widget: `.${CheckBox.bemBlock}__widget`,
6075            widgetLabel: `.${CheckBox.bemBlock}__label`,
6076            label: `.${CheckBox.bemBlock}__label`,
6077            description: `.${CheckBox.bemBlock}__longdescription`,
6078            qm: `.${CheckBox.bemBlock}__questionmark`,
6079            errorDiv: `.${CheckBox.bemBlock}__errormessage`,
6080            tooltipDiv: `.${CheckBox.bemBlock}__shortdescription`
6081        };
6082
6083        constructor(params) {
6084            super(params);
6085            this.qm = this.element.querySelector(CheckBox.selectors.qm)
6086            this.widgetLabel = this.element.querySelector(CheckBox.selectors.widgetLabel)
6087        }
6088
6089        getWidget() {
6090            return this.element.querySelector(CheckBox.selectors.widget);
6091        }
6092
6093        getDescription() {
6094            return this.element.querySelector(CheckBox.selectors.description);
6095        }
6096
6097        getLabel() {
6098            return this.element.querySelector(CheckBox.selectors.label);
6099        }
6100
6101        getErrorDiv() {
6102            return this.element.querySelector(CheckBox.selectors.errorDiv);
6103        }
6104
6105        getQuestionMarkDiv() {
6106            return this.element.querySelector(CheckBox.selectors.qm);
6107        }
6108
6109        getTooltipDiv() {
6110            return this.element.querySelector(CheckBox.selectors.tooltipDiv);
6111        }
6112
6113        updateEnabled(enabled, state) {
6114            if (this.widget) {
6115                this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_ENABLED, enabled);
6116                const isDisabled = !enabled || state.readOnly;
6117                if (isDisabled) {
6118                    this.widget.setAttribute("disabled", "disabled");
6119                } else {
6120                    this.widget.removeAttribute("disabled");
6121                }
6122            }
6123        }
6124
6125        updateReadOnly(readonly) {
6126            if (this.widget) {
6127                this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_READONLY, readonly);
6128                if (readonly === true) {
6129                    this.widget.setAttribute(FormView.Constants.HTML_ATTRS.DISABLED, "disabled");
6130                } else {
6131                    this.widget.removeAttribute(FormView.Constants.HTML_ATTRS.DISABLED);
6132                }
6133            }
6134        }
6135    }
6136
6137    FormView.Utils.setupField(({element, formContainer}) => {
6138        return new CheckBox({element, formContainer})
6139    }, CheckBox.selectors.self);
6140
6141})();
6142
6143/*******************************************************************************
6144 * Copyright 2023 Adobe
6145 *
6146 * Licensed under the Apache License, Version 2.0 (the "License");
6147 * you may not use this file except in compliance with the License.
6148 * You may obtain a copy of the License at
6149 *
6150 *     http://www.apache.org/licenses/LICENSE-2.0
6151 *
6152 * Unless required by applicable law or agreed to in writing, software
6153 * distributed under the License is distributed on an "AS IS" BASIS,
6154 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6155 * See the License for the specific language governing permissions and
6156 * limitations under the License.
6157 ******************************************************************************/
6158(function() {
6159
6160    "use strict";
6161    class Fragment extends FormView.FormPanel {
6162
6163        static NS = FormView.Constants.NS;
6164        /**
6165         * Each FormField has a data attribute class that is prefixed along with the global namespace to
6166         * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be
6167         * data-{NS}-{IS}-x=""
6168         * @type {string}
6169         */
6170        static IS = "adaptiveFormFragment";
6171        static bemBlock = 'cmp-adaptiveform-fragment'
6172        static selectors  = {
6173            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
6174            widget: `.${Fragment.bemBlock}__widget`,
6175            label: `.${Fragment.bemBlock}__label`,
6176            description: `.${Fragment.bemBlock}__longdescription`,
6177            qm: `.${Fragment.bemBlock}__questionmark`,
6178            errorDiv: `.${Fragment.bemBlock}__errormessage`,
6179            tooltipDiv: `.${Fragment.bemBlock}__shortdescription`
6180        };
6181
6182        constructor(params) {
6183            super(params);
6184        }
6185
6186        getWidget() {
6187            return this.element.querySelector(Fragment.selectors.widget);
6188        }
6189
6190        getDescription() {
6191            return this.element.querySelector(Fragment.selectors.description);
6192        }
6193
6194        getLabel() {
6195            return this.element.querySelector(Fragment.selectors.label);
6196        }
6197
6198        getErrorDiv() {
6199            return this.element.querySelector(Fragment.selectors.errorDiv);
6200        }
6201
6202        getTooltipDiv() {
6203            return this.element.querySelector(Fragment.selectors.tooltipDiv);
6204        }
6205
6206        getQuestionMarkDiv() {
6207            return this.element.querySelector(Fragment.selectors.qm);
6208        }
6209    }
6210
6211    FormView.Utils.setupField(({element, formContainer}) => {
6212        return new Fragment({element, formContainer})
6213    }, Fragment.selectors.self);
6214
6215})();
6216
6217/*******************************************************************************
6218 * Copyright 2023 Adobe
6219 *
6220 * Licensed under the Apache License, Version 2.0 (the "License");
6221 * you may not use this file except in compliance with the License.
6222 * You may obtain a copy of the License at
6223 *
6224 *     http://www.apache.org/licenses/LICENSE-2.0
6225 *
6226 * Unless required by applicable law or agreed to in writing, software
6227 * distributed under the License is distributed on an "AS IS" BASIS,
6228 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6229 * See the License for the specific language governing permissions and
6230 * limitations under the License.
6231 ******************************************************************************/
6232(function() {
6233
6234
6235    "use strict";
6236    class Switch extends FormView.FormCheckBox {
6237
6238        static NS = FormView.Constants.NS;
6239        static IS = "adaptiveFormSwitch";
6240        static bemBlock = 'cmp-adaptiveform-switch';
6241        static selectors  = {
6242            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
6243            widget: `.${Switch.bemBlock}__widget`,
6244            label: `.${Switch.bemBlock}__label`,
6245            description: `.${Switch.bemBlock}__longdescription`,
6246            errorDiv: `.${Switch.bemBlock}__errormessage`,
6247            qm: `.${Switch.bemBlock}__questionmark`,
6248            tooltipDiv: `.${Switch.bemBlock}__shortdescription`
6249        };
6250
6251        constructor(params) {
6252            super(params);
6253            this.qm = this.element.querySelector(Switch.selectors.qm)
6254        }
6255
6256        getClass() {
6257            return Switch.IS;
6258        }
6259
6260        getWidget() {
6261            return this.element.querySelector(Switch.selectors.widget);
6262        }
6263
6264        getDescription() {
6265            return this.element.querySelector(Switch.selectors.description);
6266        }
6267
6268        getLabel() {
6269            return this.element.querySelector(Switch.selectors.label);
6270        }
6271
6272        getErrorDiv() {
6273            return this.element.querySelector(Switch.selectors.errorDiv);
6274        }
6275
6276        getTooltipDiv() {
6277            return this.element.querySelector(Switch.selectors.tooltipDiv);
6278        }
6279
6280        getQuestionMarkDiv() {
6281            return this.element.querySelector(Switch.selectors.qm);
6282        }
6283    }
6284
6285    FormView.Utils.setupField(({element, formContainer}) => {
6286        return new Switch({element,formContainer})
6287    }, Switch.selectors.self);
6288
6289})();
6290
6291/*******************************************************************************
6292 * Copyright 2023 Adobe
6293 *
6294 * Licensed under the Apache License, Version 2.0 (the "License");
6295 * you may not use this file except in compliance with the License.
6296 * You may obtain a copy of the License at
6297 *
6298 *     http://www.apache.org/licenses/LICENSE-2.0
6299 *
6300 * Unless required by applicable law or agreed to in writing, softw
6300are
6301 * distributed under the License is distributed on an "AS IS" BASIS,
6302 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6303 * See the License for the specific language governing permissions and
6304 * limitations under the License.
6305 ******************************************************************************/
6306
6307(function () {
6308
6309    class TermsAndConditions extends FormView.FormPanel {
6310        static NS = FormView.Constants.NS;
6311        static IS = "adaptiveFormTermsAndConditions";
6312        static bemBlock = 'cmp-adaptiveform-termsandcondition';
6313        static selectors = {
6314            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
6315            label: `.${TermsAndConditions.bemBlock}__label`,
6316            description: `.${TermsAndConditions.bemBlock}__longdescription`,
6317            qm: `.${TermsAndConditions.bemBlock}__questionmark`,
6318            tooltipDiv: `.${TermsAndConditions.bemBlock}__shortdescription`,
6319            tncContentWrapper: `.${TermsAndConditions.bemBlock}__content-container`,
6320            closePopupButton: `.${TermsAndConditions.bemBlock}__close-button`
6321        };
6322
6323        constructor(params) {
6324            super(params);
6325            this.#handleScroll()
6326        }
6327
6328        addChild(childView) {
6329            super.addChild(childView);
6330            if (childView.getModel()._jsonModel.fieldType === 'checkbox-group') {
6331                this.#addLinkClickListener(childView);
6332            }
6333            if (childView.getModel()._jsonModel.fieldType === 'checkbox') {
6334                this.#handlePopup(childView);
6335            }
6336        }
6337
6338        #addLinkClickListener(childView) {
6339            childView.getWidgets().querySelectorAll('label').forEach((item) => {
6340                const checkboxInput = item.querySelector('input');
6341                item.querySelector('a').addEventListener('click', (e) => {
6342                    checkboxInput.click();
6343                })
6344            })
6345        }
6346
6347        #handleScroll() {
6348            const intersection = this.element.querySelector('.cmp-adaptiveform-termsandcondition__text-intersect');
6349            if (intersection) {
6350                const self = this;
6351                const io = new IntersectionObserver(onIntersection, {
6352                    threshold: [1],
6353                })
6354                function onIntersection ([{isIntersecting}]) {
6355                    const isEnabled = self.getModel()?.enabled && !self.getModel()?.readOnly;
6356                    if (isIntersecting) {
6357                        if (isEnabled) {
6358                              self.children.filter(c => c.getModel()._jsonModel.fieldType === 'checkbox').forEach(cb => {
6359                                cb.getModel().enabled = true;
6360                        })}
6361                        io.unobserve(intersection);
6362                    }
6363                }
6364                io.observe(intersection)
6365            }
6366        }
6367
6368        #handlePopup(approvalCheckbox) {
6369            const closePopUpBtn = this.getClosePopupButton();
6370            if (closePopUpBtn) {
6371                closePopUpBtn.addEventListener('click', () => {
6372                    this.toggleAttribute(this.getContentDivWrapper(), false, 'data-cmp-visible', false);
6373                })
6374
6375                approvalCheckbox.label.addEventListener('click', () => {
6376                    const contentDiv = this.getContentDivWrapper();
6377                    if (contentDiv) {
6378                        this.toggleAttribute(this.getContentDivWrapper(), true, 'data-cmp-visible', false);
6379                    }
6380                })
6381            }
6382        }
6383
6384        getContentDivWrapper() {
6385            return this.element.querySelector(TermsAndConditions.selectors.tncContentWrapper);
6386        }
6387
6388        getClosePopupButton() {
6389            return this.element.querySelector(TermsAndConditions.selectors.closePopupButton);
6390        }
6391
6392        getWidget() {
6393            return null;
6394        }
6395
6396        getDescription() {
6397            return this.element.querySelector(TermsAndConditions.selectors.description);
6398        }
6399
6400        getLabel() {
6401            return null;
6402        }
6403
6404        getErrorDiv() {
6405            return null;
6406        }
6407
6408        getTooltipDiv() {
6409            return this.element.querySelector(TermsAndConditions.selectors.tooltipDiv);
6410        }
6411
6412        getQuestionMarkDiv() {
6413            return this.element.querySelector(TermsAndConditions.selectors.qm);
6414        }
6415    }
6416
6417    FormView.Utils.setupField(({element, formContainer}) => {
6418        return new TermsAndConditions({element, formContainer})
6419    }, TermsAndConditions.selectors.self);
6420})();
6421
6422/*******************************************************************************
6423 * Copyright 2024 Adobe
6424 *
6425 * Licensed under the Apache License, Version 2.0 (the "License");
6426 * you may not use this file except in compliance with the License.
6427 * You may obtain a copy of the License at
6428 *
6429 *     http://www.apache.org/licenses/LICENSE-2.0
6430 *
6431 * Unless required by applicable law or agreed to in writing, software
6432 * distributed under the License is distributed on an "AS IS" BASIS,
6433 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6434 * See the License for the specific language governing permissions and
6435 * limitations under the License.
6436 ******************************************************************************/
6437(function() {
6438
6439    "use strict";
6440    class HCaptcha extends FormView.FormFieldBase {
6441
6442        static NS = FormView.Constants.NS;
6443        static IS = "adaptiveFormHCaptcha";
6444        static bemBlock = 'cmp-adaptiveform-hcaptcha';
6445        static selectors  = {
6446            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
6447            widget: `.${HCaptcha.bemBlock}__widget`,
6448            label: `.${HCaptcha.bemBlock}__label`,
6449            errorDiv: `.${HCaptcha.bemBlock}__errormessage`
6450        };
6451
6452        constructor(params) {
6453            super(params);
6454        }
6455
6456        getWidget() {
6457            return this.element.querySelector(HCaptcha.selectors.widget);
6458        }
6459
6460        getDescription() {
6461            return null;
6462        }
6463
6464        getLabel() {
6465            return this.element.querySelector(HCaptcha.selectors.label);
6466        }
6467
6468        getTooltipDiv() {
6469            return null;
6470        }
6471
6472        getErrorDiv() {
6473            return this.element.querySelector(HCaptcha.selectors.errorDiv);
6474        }
6475
6476        getQuestionMarkDiv() {
6477            return null;
6478        }
6479
6480    	initializeWidget() {
6481            this.widgetObject = new HCaptchaWidget(this, this._model, this.getWidget());
6482            this.getWidget().addEventListener('blur', (e) => {
6483                if(this.element) {
6484                    this.setInactive();
6485                }
6486            });
6487
6488        }
6489
6490        setModel(model) {
6491            super.setModel(model);
6492            if (this.widgetObject == null) {
6493                    this.initializeWidget();
6494            } else {
6495                if (this.widget.value !== '') {
6496                    this._model.value = this.widget.value;
6497                }
6498            }
6499        }
6500    }
6501
6502    FormView.Utils.setupField(({element, formContainer}) => {
6503        return new HCaptcha({element, formContainer})
6504    }, HCaptcha.selectors.self);
6505
6506})();
6507
6508/*******************************************************************************
6509 * Copyright 2024 Adobe
6510 *
6511 * Licensed under the Apache License, Version 2.0 (the "License");
6512 * you may not use this file except in compliance with the License.
6513 * You may obtain a copy of the License at
6514 *
6515 *     http://www.apache.org/licenses/LICENSE-2.0
6516 *
6517 * Unless required by applicable law or agreed to in writing, software
6518 * distributed under the License is distributed on an "AS IS" BASIS,
6519 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6520 * See the License for the specific language governing permissions and
6521 * limitations under the License.
6522 ******************************************************************************/
6523
6524/**
6525 * This class is responsible for interacting with the hCaptcha widget. It displays hCaptcha challenge.
6526 */
6527
6528if (typeof window.HCaptchaWidget === 'undefined') {
6529    window.HCaptchaWidget = class {
6530        #widget = null
6531        #model = null // passed by reference
6532        #options = null
6533        #lang = 'en'
6534        static FD_CAPTCHA = "fd:captcha";
6535
6536        constructor(view, model, widget) {
6537            // initialize the widget and model
6538            this.#widget = widget;
6539            this.#model = model;
6540            this.#widget = document.createElement("div");
6541            this.#widget.classList.add("cmp-adaptiveform-hcaptcha__widget");
6542            this.#lang = view.formContainer.getModel().lang;
6543
6544            //Always inserting it in body
6545            document.body.appendChild(this.#widget);
6546            this.#options = Object.assign({}, this.#model._jsonModel);
6547
6548            this.#renderHCaptcha(widget);
6549        }
6550
6551        #renderHCaptcha(element) {
6552
6553            const self = this;
6554            const hCaptchaConfigData = this.#options;
6555            element.innerHTML = '<div class="h-captcha"></div>';
6556            const hcontainer = document.getElementsByClassName("h-captcha")[0];
6557            let widgetId;
6558            const url = hCaptchaConfigData.properties[HCaptchaWidget.FD_CAPTCHA].config.uri;
6559
6560            const successCallback = function(response) {
6561                self.setCaptchaModel(response);
6562            };
6563
6564            const expiredCallback = function() {
6565                hcaptcha.reset(widgetId);
6566                self.setCaptchaModel("");
6567            };
6568
6569            const onloadCallbackInternal = function() {
6570                widgetId = hcaptcha.render(
6571                    hcontainer,
6572                    hparameters
6573                );
6574                return widgetId;
6575            };
6576
6577            const hparameters = {
6578                'sitekey': hCaptchaConfigData.properties[HCaptchaWidget.FD_CAPTCHA].config.siteKey,
6579                'size': hCaptchaConfigData.properties[HCaptchaWidget.FD_CAPTCHA].config.size,
6580                'theme': hCaptchaConfigData.properties[HCaptchaWidget.FD_CAPTCHA].config.theme || 'light',
6581                'callback': successCallback,
6582                'expired-callback': expiredCallback
6583            };
6584
6585            window.onloadHCaptchaCallback = onloadCallbackInternal;
6586
6587            const runtimeLocale = this.#lang;
6588
6589            const scr = document.createElement('script');
6590            scr.src = url + "?onload=onloadHCaptchaCallback&render=explicit&hl=" + runtimeLocale;
6591            scr.async = true;
6592            element.appendChild(scr);
6593        }
6594
6595        setCaptchaModel = function(response) {
6596            this.#model.dispatch(new FormView.Actions.UIChange({'value': response}));
6597        }
6598    }
6599}
6600
6601/*******************************************************************************
6602 * Copyright 2024 Adobe
6603 *
6604 * Licensed under the Apache License, Version 2.0 (the "License");
6605 * you may not use this file except in compliance with the License.
6606 * You may obtain a copy of the License at
6607 *
6608 *     http://www.apache.org/licenses/LICENSE-2.0
6609 *
6610 * Unless required by applicable law or agreed to in writing, software
6611 * distributed under the License is distributed on an "AS IS" BASIS,
6612 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6613 * See the License for the specific language governing permissions and
6614 * limitations under the License.
6615 ******************************************************************************/
6616
6617(function () {
6618
6619  "use strict";
6620  class Review extends FormView.FormFieldBase {
6621
6622    static NS = FormView.Constants.NS;
6623    /**
6624     * Each FormField has a data attribute class that is prefixed along with the global namespace to
6625     * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be
6626     * data-{NS}-{IS}-x=""
6627     * @type {string}
6628     */
6629    static IS = "adaptiveFormReview";
6630    static bemBlock = 'cmp-adaptiveform-review';
6631    static templateAttribute = 'data-cmp-review';
6632    static DATA_ATTRIBUTE_VISIBLE = 'data-cmp-visible';
6633    static FIELD_TYPE = FormView.Constants.FIELD_TYPE;
6634    static HIDE_FIELD_FROM_REVIEW = [Review.FIELD_TYPE.BUTTON, Review.FIELD_TYPE.PLAIN_TEXT, Review.FIELD_TYPE.CAPTCHA, Review.FIELD_TYPE.IMAGE];
6635    static panelModifier = '__panel--repeatable';
6636    static fieldModifier = '__field--';
6637    static selectors = {
6638      self: "[data-" + this.NS + '-is="' + this.IS + '"]',
6639      container: `.${Review.bemBlock}__container`,
6640      templates: "template[data-cmp-review-fieldType]",
6641      label: '[' + Review.templateAttribute + '-label]',
6642      value: '[' + Review.templateAttribute + '-value]',
6643      editButton:'[' + Review.templateAttribute + '-editButton]',
6644      fieldId: Review.templateAttribute + '-fieldId',
6645      fieldType: Review.templateAttribute + '-fieldType',
6646      panelContent:'[' + Review.templateAttribute + '-content]',
6647      labelContainer: `.${Review.bemBlock}__label-container`,
6648      intersection: Review.templateAttribute + "-intersection="
6649    };
6650    static intersectionOptions = {
6651      root: null,
6652      rootMargin: "0px",
6653      threshold: Review.buildThresholdList(),
6654    };
6655    static buildThresholdList() {
6656      let thresholds = [];
6657      let numSteps = 20;
6658      for (let i = 1.0; i <= numSteps; i++) {
6659        thresholds.push(i / numSteps);
6660      }
6661      thresholds.push(0);
6662      return thresholds;
6663    }
6664
6665    static sanitizedValue(value, options) {
6666      if(options){
6667        return window.DOMPurify ?  window.DOMPurify.sanitize(value, options) : value;
6668      }
6669      return window.DOMPurify ?  window.DOMPurify.sanitize(value) : value;
6670    }
6671
6672    static hasChild(element) {
6673      return element && element.children && element.children.length;
6674    }
6675
6676    static addClassModifier(element, item) {
6677      if(item.fieldType !== Review.FIELD_TYPE.PANEL){
6678        element.querySelector('div').classList.add(Review.bemBlock + Review.fieldModifier + item.fieldType);
6679      }
6680      if(item.repeatable){
6681        element.querySelector('div').classList.add(Review.bemBlock + Review.panelModifier);
6682      }
6683      if(item.name){
6684        element.querySelector('div').classList.add(item.name);
6685      }
6686    }
6687
6688    static renderLabel(element, item) {
6689      const label = element.querySelector(Review.selectors.label);
6690      label.innerHTML = item.fieldType === Review.FIELD_TYPE.PLAIN_TEXT ? Review.sanitizedValue(item.value) : Review.sanitizedValue(item?.label?.value, {ALLOWED_TAGS: [] });
6691      if (item.required) {
6692        label.setAttribute('data-cmp-required', item.required);
6693      }
6694    }
6695
6696    static renderValue(element, item) {
6697      const value = element.querySelector(Review.selectors.value);
6698      if (value) {
6699        const plainText = Review.getValue(item, item.value) || '';
6700        value.innerHTML = Review.sanitizedValue(plainText);
6701      }
6702    }
6703
6704    static addAccessibilityAttributes(element, item) {
6705      const container = element.querySelector('div');
6706      const label = element.querySelector(Review.selectors.label);
6707      const value = element.querySelector(Review.selectors.value);
6708      const editButton = element.querySelector(Review.selectors.editButton);
6709      const id = `${item.id}-review-label`;
6710      if(label){
6711        label.setAttribute('id', id);
6712        container.setAttribute('role', 'region');  
6713        container.setAttribute('aria-labelledby', id);
6714      }
6715      if(value){
6716        value.setAttribute('aria-labelledby', id);
6717      }
6718    }
6719
6720    static isRepeatable(item) {
6721      return item.fieldType === Review.FIELD_TYPE.PANEL && item.type === 'array'
6722    }
6723
6724    /* return value of the field, if value is array then return comma separated string and 
6725      if value is file then return file name
6726    */
6727    static getValue(item, value) {
6728      if (value === undefined || value === null) return '';
6729      if (item.fieldType === Review.FIELD_TYPE.FILE_INPUT) {
6730        return Array.isArray(value) ? value.filter(file => file && file.name).map(file => file.name).join(', ') : (value.name || '');
6731      }
6732      if (Array.isArray(item.enumNames)) {
6733        const values = Array.isArray(value) ? value : [value];
6734        return values.reduce((names, val) => {
6735          const index = item.enum.indexOf(val);
6736          if (index >= 0) {
6737            names.push(item.enumNames[index]);
6738          }
6739          return names;
6740        }, []).join(', ');
6741      }
6742      if (Array.isArray(value)) {
6743        return value.join(', ');
6744      }
6745      return value;
6746    }
6747
6748    constructor(params) {
6749      super(params);
6750      this.#attachIntersectionObserver();
6751      this.#attachClickEventOnEdit();
6752      this.#setFieldTemplateMapping();
6753    }
6754    getContainer() {
6755      return this.element.querySelector(Review.selectors.container);
6756    }
6757    getTemplates() {
6758      return this.element.querySelectorAll(Review.selectors.templates);
6759    }
6760    getIntersectionElement() {
6761      return this.element.querySelector("[" + Review.selectors.intersection + this.id + "]");
6762    }
6763    getWidget() { return null }
6764    getDescription() { return null; }
6765    getLabel() { return null; }
6766    getErrorDiv() { return null; }
6767    getTooltipDiv() { return null; }
6768    getQuestionMarkDiv() { return null; }
6769    setModel(model) {
6770      super.setModel(model);
6771    }
6772
6773    // attach intersection observer to the review container for lazy loading
6774    #attachIntersectionObserver() {
6775      let observer = new IntersectionObserver(this.#intersectionObserverHandler.bind(this), Review.intersectionOptions);
6776      const ele = this.getIntersectionElement();
6777      if(ele){
6778        observer.observe(ele);
6779      }
6780    }
6781
6782    // attach click event on edit button to set focus on the field
6783    #attachClickEventOnEdit() {
6784      this.getContainer().addEventListener('click', this.#clickHandler.bind(this))
6785    }
6786
6787    // create template mapping based on field type and use it to render review fields
6788    #setFieldTemplateMapping() {
6789      const templates = this.getTemplates();
6790      let mappings = {};
6791      templates.forEach(template => {
6792        const type = template.getAttribute(Review.selectors.fieldType);
6793        mappings[type || 'default'] = template;
6794      });
6795      this.templateMappings = mappings;
6796    }
6797
6798    // click handler to set focus on the field when use click on edit button
6799    #clickHandler(event) {
6800      if (event?.target?.nodeName === 'BUTTON') {
6801        const id = event.target.getAttribute(Review.selectors.fieldId);
6802        const form = this.formContainer.getModel();;
6803        const field = this.formContainer.getField(id);
6804        if (form && field) {
6805          form.setFocus(field._model);
6806        }
6807      }
6808    }
6809
6810     // if review container is in view port then render review fields
6811    #intersectionObserverHandler(entries) {
6812      entries.forEach(entry => {
6813        if (entry.isIntersecting && this._model) {
6814          const panels = this.#getPanels();
6815          const reviewContainer = this.getContainer();
6816          const children = this.#renderReviewFields(panels);
6817          reviewContainer.innerHTML = '';
6818          reviewContainer.appendChild(children);
6819        }
6820      })
6821    }
6822
6823    // iterate over all the panels or linked panels and render child of each panel
6824    #renderReviewFields(items) {
6825      if (!items) return;
6826      const currentFragment = document.createDocumentFragment();
6827      items.filter(item => item.visible !== false && item.fieldType && item[':type']).forEach(item => {
6828        if (Review.isRepeatable(item)) {
6829          const repeatableItems = this.getModel().form.getElement(item.id).getState();
6830          const repeatablePanel = this.#renderReviewFields(repeatableItems.items);
6831          if (Review.hasChild(repeatablePanel)) {
6832            currentFragment.appendChild(repeatablePanel);
6833          }
6834        } else {
6835          let template = this.templateMappings[item.fieldType] || this.templateMappings['default'];
6836          const cloneNode = template.content.cloneNode(true);
6837          Review.addClassModifier(cloneNode, item);
6838          Review.renderLabel(cloneNode, item);
6839          this.#renderEditButton(cloneNode, item);
6840          if (item.fieldType === Review.FIELD_TYPE.PANEL) {
6841            const fields = this.#renderReviewFields(item.items);
6842            if (Review.hasChild(fields)) {
6843              const labelContainer = cloneNode.querySelector(Review.selectors.labelContainer);
6844              if(item?.label?.visible === false && labelContainer){
6845                labelContainer.remove();
6846              }
6847              Review.addAccessibilityAttributes(cloneNode, item);
6848              const contentElement = cloneNode.querySelector(Review.selectors.panelContent);
6849              if(contentElement){
6850                contentElement.appendChild(fields);
6851              }
6852              currentFragment.appendChild(cloneNode);
6853            }
6854          } else if (!Review.HIDE_FIELD_FROM_REVIEW.includes(item.fieldType) && !item[':type'].endsWith('review')) {
6855            Review.renderValue(cloneNode, item);
6856            Review.addAccessibilityAttributes(cloneNode, item);
6857            currentFragment.appendChild(cloneNode);
6858          }
6859        }
6860      });
6861      return currentFragment;
6862    }
6863
6864    #getPanels() {
6865      const linkedPanels = this.getModel().properties["fd:linkedPanels"] || [];
6866      if (linkedPanels.length) {
6867        return this.#getLinkedPanels([...linkedPanels]);
6868      }
6869      return this.#getAllPanels();
6870    }
6871
6872    // return all top lavel panels if author has not linked any panel
6873    #getAllPanels() {
6874      let state = this.getModel().form.getState();
6875      while (state?.items?.length === 1) {
6876        state = state.items[0];
6877      }
6878      return state.items || [];
6879    }
6880
6881    // return linked panels if author has linked any panel
6882    #getLinkedPanels(linkedPanels) {
6883      let queue = [], result = [];
6884      let state = this.getModel().form.getState();
6885      queue.push(state);
6886      while (queue.length && linkedPanels.length) {
6887        const items = Array.isArray(queue[0]) ? queue[0] : [queue[0]];
6888        items.forEach(item => {
6889          const index = linkedPanels.indexOf(item.name);
6890          if (index > -1) {
6891            result.push(item);
6892            linkedPanels.splice(index, 1);
6893          }
6894          if (item.items) {
6895            queue.push(item.items);
6896          }
6897        })
6898        queue.shift();
6899      }
6900      return result;
6901    }
6902
6903    // render edit button of the field
6904    #renderEditButton(cloneNode, item) {
6905      const editButton = cloneNode.querySelector(Review.selectors.editButton);
6906      if (editButton) {
6907        editButton.setAttribute(Review.selectors.fieldId, item.id);
6908        const currentItemLabel = item?.label?.value;
6909        editButton.setAttribute('aria-label', Granite.I18n.get('Edit') + (currentItemLabel ?  " " + currentItemLabel : ""));
6910        if (item.enabled === false) {
6911          editButton.setAttribute('disabled', true);
6912        }
6913        editButton.setAttribute(Review.DATA_ATTRIBUTE_VISIBLE, this.#isVisibleEditButton(item.fieldType));
6914      }
6915    }
6916    #isVisibleEditButton(fieldType) {
6917      let editModeAction = this.getModel().properties?.['fd:editModeAction'];
6918      if (editModeAction === 'both' ||
6919        (editModeAction === Review.FIELD_TYPE.PANEL && fieldType === Review.FIELD_TYPE.PANEL) ||
6920        (editModeAction === 'field' && fieldType !== Review.FIELD_TYPE.PANEL)) {
6921        return true;
6922      }
6923      return false;
6924    }
6925  }
6926
6927  FormView.Utils.setupField(({ element, formContainer }) => {
6928    return new Review({ element, formContainer })
6929  }, Review.selectors.self);
6930
6931})();
6932
6933/*******************************************************************************
6934 * Copyright 2024 Adobe
6935 *
6936 * Licensed under the Apache License, Version 2.0 (the "License");
6937 * you may not use this file except in compliance with the License.
6938 * You may obtain a copy of the License at
6939 *
6940 *     http://www.apache.org/licenses/LICENSE-2.0
6941 *
6942 * Unless required by applicable law or agreed to in writing, software
6943 * distributed under the License is distributed on an "AS IS" BASIS,
6944 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6945 * See the License for the specific language governing permissions and
6946 * limitations under the License.
6947 ******************************************************************************/
6948(function() {
6949
6950    "use strict";
6951    class Turnstile extends FormView.FormFieldBase {
6952
6953        static NS = FormView.Constants.NS;
6954        static IS = "adaptiveFormTurnstile";
6955        static bemBlock = 'cmp-adaptiveform-turnstile';
6956        static selectors  = {
6957            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
6958            widget: `.${Turnstile.bemBlock}__widget`,
6959            label: `.${Turnstile.bemBlock}__label`,
6960            errorDiv: `.${Turnstile.bemBlock}__errormessage`
6961        };
6962
6963        constructor(params) {
6964            super(params);
6965        }
6966
6967        getWidget() {
6968            return this.element.querySelector(Turnstile.selectors.widget);
6969        }
6970
6971        getDescription() {
6972            return null;
6973        }
6974
6975        getLabel() {
6976            return this.element.querySelector(Turnstile.selectors.label);
6977        }
6978
6979        getTooltipDiv() {
6980            return null;
6981        }
6982
6983        getErrorDiv() {
6984            return this.element.querySelector(Turnstile.selectors.errorDiv);
6985        }
6986
6987        getQuestionMarkDiv() {
6988            return null;
6989        }
6990
6991    	initializeWidget() {
6992            this.widgetObject = new TurnstileWidget(this, this._model, this.getWidget());
6993            this.getWidget().addEventListener('blur', (e) => {
6994                if(this.element) {
6995                    this.setInactive();
6996                }
6997            });
6998
6999        }
7000
7001        setModel(model) {
7002            super.setModel(model);
7003            if (this.widgetObject == null) {
7004                    this.initializeWidget();
7005            } else {
7006                if (this.widget.value !== '') {
7007                    this._model.dispatch(new FormView.Actions.UIChange({'value': this.widget.value}));
7008                }
7009            }
7010        }
7011    }
7012
7013    FormView.Utils.setupField(({element, formContainer}) => {
7014        return new Turnstile({element, formContainer})
7015    }, Turnstile.selectors.self);
7016
7017})();
7018
7019/*******************************************************************************
7020 * Copyright 2024 Adobe
7021 *
7022 * Licensed under the Apache License, Version 2.0 (the "License");
7023 * you may not use this file except in compliance with the License.
7024 * You may obtain a copy of the License at
7025 *
7026 *     http://www.apache.org/licenses/LICENSE-2.0
7027 *
7028 * Unless required by applicable law or agreed to in writing, software
7029 * distributed under the License is distributed on an "AS IS" BASIS,
7030 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7031 * See the License for the specific language governing permissions and
7032 * limitations under the License.
7033 ******************************************************************************/
7034
7035/**
7036 * This class is responsible for interacting with the turnstile widget. It displays turnstile challenge.
7037 */
7038
7039if (typeof window.TurnstileWidget === 'undefined') {
7040    window.TurnstileWidget = class {
7041        #widget = null
7042        #model = null // passed by reference
7043        #options = null
7044        #lang = 'en'
7045        static FD_CAPTCHA = "fd:captcha";
7046
7047        constructor(view, model, widget) {
7048            // initialize the widget and model
7049            this.#widget = widget;
7050            this.#model = model;
7051            this.#widget = document.createElement("div");
7052            this.#widget.classList.add("cmp-adaptiveform-turnstile__widget");
7053            this.#lang = view.formContainer.getModel().lang;
7054
7055            //Always inserting it in body
7056            document.body.appendChild(this.#widget);
7057            this.#options = Object.assign({}, this.#model._jsonModel);
7058
7059            this.#renderTurnstile(widget);
7060        }
7061
7062        #renderTurnstile(turnstileContainer) {
7063
7064            const self = this;
7065            const turnstileConfigData = this.#options;
7066            let widgetId;
7067            const url = turnstileConfigData.properties[TurnstileWidget.FD_CAPTCHA].config.uri;
7068
7069            const successCallback = function(response) {
7070                self.setCaptchaModel(response);
7071            };
7072
7073            const expiredCallback = function() {
7074                turnstile.reset(widgetId);
7075                self.setCaptchaModel("");
7076            };
7077
7078            const onloadCallbackInternal = function() {
7079                widgetId = turnstile.render(
7080                    turnstileContainer,
7081                    turnstileParameters
7082                );
7083                return widgetId;
7084            };
7085
7086            const turnstileParameters = {
7087                'sitekey': this.#model.captchaSiteKey,
7088                'size': turnstileConfigData.properties[TurnstileWidget.FD_CAPTCHA].config.size,
7089                'theme': turnstileConfigData.properties[TurnstileWidget.FD_CAPTCHA].config.theme || 'light',
7090                'callback': successCallback,
7091                'expired-callback': expiredCallback,
7092                'language': this.#lang
7093            };
7094
7095            window.onloadTurnstileCallback = onloadCallbackInternal;
7096            const scr = document.createElement('script');
7097            const queryParams = (this.#model.captchaDisplayMode === 'invisible')
7098                ? "?render=explicit"
7099                : "?onload=onloadTurnstileCallback&render=explicit";
7100            scr.src = url + queryParams;
7101            scr.async = true;
7102            turnstileContainer.appendChild(scr);
7103        }
7104
7105        setCaptchaModel(response) {
7106            this.#model.dispatch(new FormView.Actions.UIChange({'value': response}));
7107        }
7108    }
7109}
7110
7111/*******************************************************************************
7112 * Copyright 2025 Adobe
7113 *
7114 * Licensed under the Apache License, Version 2.0 (the "License");
7115 * you may not use this file except in compliance with the License.
7116 * You may obtain a copy of the License at
7117 *
7118 *     http://www.apache.org/licenses/LICENSE-2.0
7119 *
7120 * Unless required by applicable law or agreed to in writing, software
7121 * distributed under the License is distributed on an "AS IS" BASIS,
7122 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7123 * See the License for the specific language governing permissions and
7124 * limitations under the License.
7125 ******************************************************************************/
7126
7127if(window.GeoLocationQuery === undefined) {
7128        window.GeoLocationQuery = class GeoLocationQuery {
7129        constructor() {
7130            this._active = false;
7131        }
7132
7133        init(success, failure) {
7134            this._successHandler = success;
7135            this._errorHandler = failure;
7136            this._active = true;
7137            return this;
7138        }
7139
7140        _handleSuccess(data) {
7141            if (this._successHandler) {
7142                this._successHandler(data);
7143            }
7144        }
7145
7146        _handleError(err) {
7147            if (this._errorHandler) {
7148                this._errorHandler(err);
7149            }
7150        }
7151
7152        query() {
7153            const onSuccess = (pos) => {
7154                if (this._active) {
7155                    this._handleSuccess(pos);
7156                }
7157                this._active = false;
7158            };
7159
7160            const onError = (err) => {
7161                if (this._active) {
7162                    this._handleError(err);
7163                }
7164                this._active = false;
7165            };
7166
7167            navigator.geolocation.getCurrentPosition(onSuccess, onError, { timeout: 10000 });
7168        }
7169
7170        cancel() {
7171            this._active = false;
7172        }
7173    }
7174}
7175/*******************************************************************************
7176 * Copyright 2025 Adobe
7177 *
7178 * Licensed under the Apache License, Version 2.0 (the "License");
7179 * you may not use this file except in compliance with the License.
7180 * You may obtain a copy of the License at
7181 *
7182 *     http://www.apache.org/licenses/LICENSE-2.0
7183 *
7184 * Unless required by applicable law or agreed to in writing, software
7185 * distributed under the License is distributed on an "AS IS" BASIS,
7186 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7187 * See the License for the specific language governing permissions and
7188 * limitations under the License.
7189 ******************************************************************************/
7190
7191
7192(function() {
7193    "use strict";
7194    /**
7195     * class definition for GeoLocationQueryRequest
7196     * encapsulated success and error handlers
7197    */
7198    class Scribble extends FormView.FormFieldBase {
7199        _geoLocQuery=null;
7200        _signSubmitted=false;
7201        _enforceGeoLoc=!!navigator.userAgent.match(/iPad/i);
7202        existingSign = '';
7203        existingCanvas = '';
7204        lang = "en";
7205        static NS = FormView.Constants.NS;
7206        static IS = "adaptiveFormScribble";
7207        static bemBlock = 'cmp-adaptiveform-scribble';
7208        static selectors  = {
7209            self: `[data-${this.NS}-is="${this.IS}"]`,
7210            scribbleContainer: `.${Scribble.bemBlock}__container`,
7211            scribbleContainerPanel: `.${Scribble.bemBlock}__panel`,
7212            keyboardSignBox: `.${Scribble.bemBlock}__keyboard-sign-box`,
7213            scribbleControlPanel: `.${Scribble.bemBlock}__controlpanel`,
7214            geoCanvas: `.${Scribble.bemBlock}__geocanvas`,
7215            canvasSignedContainer: `.${Scribble.bemBlock}__canvas-signed-container`,
7216            canvas: `.${Scribble.bemBlock}__canvas`,
7217            label: `.${Scribble.bemBlock}__label`,
7218            description: `.${Scribble.bemBlock}__longdescription`,
7219            qm: `.${Scribble.bemBlock}__questionmark`,
7220            errorDiv: `.${Scribble.bemBlock}__errormessage`,
7221            tooltipDiv: `.${Scribble.bemBlock}__shortdescription`,
7222            scribbleCloseButton: `.${Scribble.bemBlock}__button-close`,
7223            brushControl: `.${Scribble.bemBlock}__control-brush`,
7224            scribbleGeoControl: `.${Scribble.bemBlock}__control-geo`,
7225            clearControl: `.${Scribble.bemBlock}__control-clear`,
7226            scribbleTextControl: `.${Scribble.bemBlock}__control-text`,
7227            scribbleMessage: `.${Scribble.bemBlock}__control-message`,
7228            clearSignButton: `.${Scribble.bemBlock}__button--primary`,
7229            cancelClearSignButton: `.${Scribble.bemBlock}__button--secondary`,
7230            clearSignContainer: `.${Scribble.bemBlock}__clearsign-container`,
7231            scribbleSubmitControl: `.${Scribble.bemBlock}__save-button`,
7232            scribbleBrushList: `.${Scribble.bemBlock}__brushlist`,
7233            signCanvases: `.${Scribble.bemBlock}__signcanvases`,
7234            saveCanvas: `.${Scribble.bemBlock}__save-button`,
7235            canvasSignedImage: `.${Scribble.bemBlock}__canvas-signed-image`,
7236            mainCanvas: `.${Scribble.bemBlock}__canvas__main`
7237        };
7238
7239        constructor(params) {
7240            super(params);
7241            this.initializeScribble();
7242        }
7243
7244        setModel(model) {
7245            super.setModel(model);
7246            this.lang = model.lang;
7247        }
7248
7249        initializeScribble() {
7250            this.getCanvasContainer().addEventListener('click', () => this.scribbleContainerClickHandler());
7251            this.initScribbleModal();
7252        }
7253        
7254        getWidget() {
7255            return this.element.querySelector(Scribble.selectors.canvasSignedContainer);
7256        }
7257
7258        getLabel() {
7259            return this.element.querySelector(Scribble.selectors.label);
7260        }
7261
7262        getErrorDiv() {
7263            return this.element.querySelector(Scribble.selectors.errorDiv);
7264        }
7265
7266        getTooltipDiv() {
7267            return this.element.querySelector(Scribble.selectors.tooltipDiv);
7268        }
7269
7270        getQuestionMarkDiv() {
7271            return this.element.querySelector(Scribble.selectors.qm);
7272        }
7273
7274        getScribbleControlPanel() {
7275            return this.element.querySelector(Scribble.selectors.scribbleControlPanel);
7276        }
7277
7278        getScribbleContainer() {
7279            return this.element.querySelector(Scribble.selectors.scribbleContainer);
7280        }
7281
7282        getMessage() {
7283            return this.element.querySelector(Scribble.selectors.scribbleMessage);
7284        }
7285
7286        getClearSignContainer() {
7287            return this.element.querySelector(Scribble.selectors.clearSignContainer);
7288        }
7289
7290        getClearSignButton() {
7291            return this.element.querySelector(Scribble.selectors.clearSignButton);
7292        }
7293
7294        getCancelClearSignButton() {
7295            return this.element.querySelector(Scribble.selectors.cancelClearSignButton);
7296        }
7297
7298        getBrushList() {
7299            return this.element.querySelector(Scribble.selectors.scribbleBrushList);
7300        }
7301
7302        getBrush() {
7303            return this.element.querySelector(Scribble.selectors.brushControl);
7304        }
7305
7306        getClearControl() {
7307            return this.element.querySelector(Scribble.selectors.clearControl);
7308        }
7309
7310        getSaveControl() {
7311            return this.element.querySelector(Scribble.selectors.saveCanvas);
7312        }
7313
7314        getGeoLocationIcon() {
7315            return this.element.querySelector(Scribble.selectors.scribbleGeoControl);
7316        }
7317
7318        getTextSignControl() {
7319            return this.element.querySelector(Scribble.selectors.scribbleTextControl);
7320        }
7321
7322        getScribbleContainerPanel() {
7323            return this.element.querySelector(Scribble.selectors.scribbleContainerPanel);
7324        }
7325
7326        getKeyboardSignBox() {
7327            return this.element.querySelector(Scribble.selectors.keyboardSignBox);
7328        }
7329
7330        getGeoCanvas() {
7331            return this.element.querySelector(Scribble.selectors.geoCanvas);
7332        }
7333
7334        getCanvasContainer() {
7335            return this.element.querySelector(Scribble.selectors.canvasSignedContainer);
7336        }
7337
7338        getScribbleCloseButton() {
7339            return this.element.querySelector(Scribble.selectors.scribbleCloseButton);
7340        }
7341
7342        getCanvas() {
7343            return this.element.querySelector(Scribble.selectors.canvas);
7344        }
7345
7346        getMainCanvas() {
7347            return this.element.querySelector(Scribble.selectors.mainCanvas);
7348        }
7349
7350        getSignCanvasesContainer() {
7351            return this.element.querySelector(Scribble.selectors.signCanvases);
7352        }
7353
7354        getDescription() {
7355            return this.element.querySelector(Scribble.selectors.description);
7356        }
7357
7358        getSignedCanvasImage() {
7359            return this.element.querySelector(Scribble.selectors.canvasSignedImage);
7360        }
7361
7362        showMessage(msg){
7363            if(this._msgTimeout) { clearTimeout(this._msgTimeout); this._msgTimeout=0; }
7364             const scribbleMessage = this.getMessage();
7365             scribbleMessage.innerHTML = msg;
7366             scribbleMessage.style.display = 'block';
7367             this._msgTimeout = window.setTimeout(function(){
7368                scribbleMessage.innerHTML = '';
7369             },15000);
7370        }
7371
7372        openClearSignModal() {
7373            const clearSignContainer = this.getClearSignContainer();
7374            const clearSignButton = this.getClearSignButton();
7375            const cancelClearSignButton = this.getCancelClearSignButton();
7376        
7377            clearSignContainer.style.display = 'inline-block';
7378            // Set focus to the clear sign modal container for accessibility
7379            clearSignContainer.setAttribute('tabindex', '-1');
7380            clearSignContainer.focus();
7381        
7382            const handleClearSign = () => {
7383                this.existingSign = '';
7384                const mainCanvas = this.getMainCanvas();
7385                const existingCanvas = this.existingCanvas;
7386        
7387                if (mainCanvas && existingCanvas) {
7388                    mainCanvas.parentNode.replaceChild(existingCanvas, mainCanvas);
7389                    const ctx = existingCanvas.getContext('2d');
7390                    ctx.clearRect(0, 0, existingCanvas.width, existingCanvas.height);
7391                }
7392        
7393                const geoCanvas = this.getGeoCanvas();
7394                if (geoCanvas) {
7395                    const geoCtx = geoCanvas.getContext('2d');
7396                    geoCtx.clearRect(0, 0, geoCanvas.width, geoCanvas.height);
7397                }
7398        
7399                this.enableControls(['brushes', 'geolocation', 'clearSign', 'textSign', 'save']);
7400        
7401                const signedImage = this.getSignedCanvasImage();
7402                if (signedImage) {
7403                    signedImage.removeAttribute('alt');
7404                    signedImage.removeAttribute('title');
7405                    signedImage.removeAttribute('src');
7406                    signedImage.removeAttribute('style');
7407                    this.element.querySelector('.cmp-adaptiveform-scribble__clear-sign')?.remove();
7408                    clearSignContainer.style.display = 'none';
7409                    this.getKeyboardSignBox().value = '';
7410                }
7411        
7412                this._signSubmitted = false;
7413                this.setModelValue(undefined);
7414            };
7415        
7416            clearSignButton.addEventListener('click', handleClearSign);
7417        
7418            cancelClearSignButton.addEventListener('click', () => {
7419                clearSignContainer.style.display = 'none';
7420            });
7421        }
7422
7423        createCanvas() {
7424            const mainCanvas = document.createElement('canvas');
7425            mainCanvas.classList.add('cmp-adaptiveform-scribble__canvasImage');
7426        }
7427
7428        updateEmptyStatus () {
7429            super.updateEmptyStatus();
7430        }
7431
7432        updateValue(value) {
7433            let that = this;
7434            this._model.serialize().then((files) => {
7435                if (files && files.length > 0 && files[0]) {
7436                    let signatureDataUrl = files[0].data;
7437                    signatureDataUrl = typeof signatureDataUrl === "undefined" ? null : signatureDataUrl;
7438                    const signedImage = that.getSignedCanvasImage();
7439                    if (signedImage && signatureDataUrl) {
7440                        signedImage.src = signatureDataUrl;
7441                        signedImage.setAttribute('alt', FormView.LanguageUtils.getTranslatedString(this.lang, 'signature') || 'Signature');
7442                        signedImage.setAttribute('title', FormView.LanguageUtils.getTranslatedString(this.lang, 'signature') || 'Signature');
7443                        that.updateEmptyStatus();
7444                    }
7445                }
7446            });
7447        }
7448
7449        isCanvasEmpty(canvas) {
7450            const ctx = canvas.getContext('2d');
7451            const width = canvas.width;
7452            const height = canvas.height;
7453            
7454            // Get pixel data from the canvas
7455            const imageData = ctx.getImageData(0, 0, width, height);
7456            
7457            // Check if any pixel is not transparent (not [0, 0, 0, 0] = transparent)
7458            for (let i = 0; i < imageData.data.length; i += 4) {
7459                if (imageData.data[i + 3] > 0) {
7460                    return false; // Found non-transparent pixel
7461                }
7462            }
7463            
7464            return true; // No non-transparent pixels found
7465        }
7466
7467        submitSign() {
7468            if (!this.isCanvasEmpty(this.canvas)) {
7469                const mainCanvas = this.createMainCanvas();
7470                const sigCnv = this.getCanvas(); // Get the sign canvas
7471                const geoCnv = this.getGeoCanvas(); // Get the geo canvas
7472        
7473                this.drawCanvasesOnMainCanvas(mainCanvas, sigCnv, geoCnv);
7474        
7475                this.existingCanvas = sigCnv;
7476                sigCnv.height = mainCanvas.height;
7477                sigCnv.parentNode.replaceChild(mainCanvas, sigCnv);
7478        
7479                let submitData = mainCanvas.toDataURL("image/png");
7480                submitData = submitData.replace("data:image/png;base64,", "data:image/png;name=fd_type_signature.png;base64,")
7481                this.existingSign = mainCanvas;
7482        
7483                this.updateSignedImage(submitData);
7484                this.setModelValue(submitData);
7485                this.addClearSignButton();
7486        
7487                if (this._geoLocQuery) {
7488                    this._geoLocQuery.cancel(); // Cancel the current geo loc request
7489                }
7490        
7491                this.closeEditModal();
7492                this._signSubmitted = true;
7493            }
7494        }
7495
7496        createMainCanvas() {
7497            const mainCanvas = document.createElement('canvas');
7498            mainCanvas.classList.add('cmp-adaptiveform-scribble__canvas__main');
7499            mainCanvas.ariaLabel = FormView.LanguageUtils.getTranslatedString(this.lang, "SignatureCanvas");
7500            return mainCanvas;
7501        }
7502
7503        drawCanvasesOnMainCanvas(mainCanvas, sigCnv, geoCnv) {
7504            const ctx = mainCanvas.getContext('2d');
7505            if (geoCnv && geoCnv.width > 0 && geoCnv.height > 0) {
7506                // Set the dimensions of the mainCanvas to accommodate both canvases vertically
7507                mainCanvas.width = Math.max(sigCnv.width, geoCnv.width);
7508                mainCanvas.height = sigCnv.height + geoCnv.height;
7509                // Draw the sign canvas on the main canvas
7510                ctx.drawImage(sigCnv, 0, 0);
7511                // Draw the geo canvas below the sign canvas
7512                ctx.drawImage(geoCnv, 0, sigCnv.height, geoCnv.width, geoCnv.height);
7513            } else {
7514                mainCanvas.width = sigCnv.width;
7515                mainCanvas.height = sigCnv.height;
7516                ctx.drawImage(sigCnv, 0, 0);
7517            }
7518        }
7519
7520        updateSignedImage(newData) {
7521            const img = this.getSignedCanvasImage();
7522            img.src = newData;
7523            img.style.width = '100%';
7524            img.style.height = '150px';
7525        }
7526
7527        addClearSignButton() {
7528            const clearSignButton = document.createElement('div');
7529            clearSignButton.setAttribute('role', 'button');
7530            clearSignButton.setAttribute('tabindex', '0');
7531            clearSignButton.setAttribute('aria-label', FormView.LanguageUtils.getTranslatedString(this.lang, 'clearSign') || 'Clear Signature');
7532            clearSignButton.classList.add('cmp-adaptiveform-scribble__clear-sign');
7533
7534            const mainCanvasImageContainer = this.getCanvasContainer();
7535            mainCanvasImageContainer.appendChild(clearSignButton);
7536
7537            clearSignButton.addEventListener('click', (e) => {
7538                e.stopPropagation();
7539                this.openClearSignModal();
7540            });
7541            // Keyboard accessibility: allow Enter/Space to trigger clear
7542            clearSignButton.addEventListener('keydown', (e) => {
7543                if (e.key === 'Enter' || e.key === ' ') {
7544                    e.preventDefault();
7545                    this.openClearSignModal();
7546                }
7547            });
7548        }
7549
7550        geoQueryErrorHandler(err){
7551            this.showMessage('errorFetchGeoLocation');
7552        }
7553
7554        renderBrushList() {
7555            [2,3,4,5,6,7,8,9,10].forEach((brush) => {
7556                var divel = document.createElement('div');
7557                var cnv = document.createElement('canvas');
7558                var ctx = cnv.getContext('2d');
7559                cnv.style.border='1px solid #AAAAAA';
7560                cnv.width=100;
7561                cnv.height=20;
7562                cnv.style.backgroundColor = 'white';
7563                cnv.ariaLabel = FormView.LanguageUtils.getTranslatedString(this.lang, "brushSize") + brush;
7564                ctx.lineWidth=brush;
7565                ctx.beginPath();
7566                ctx.moveTo(10,cnv.height/2);
7567                ctx.lineTo(cnv.width-10,cnv.height/2);
7568                ctx.stroke();
7569                divel.appendChild(cnv);
7570                divel.addEventListener('click', (e) => {
7571                    e.stopPropagation();
7572                    this.context.lineWidth=brush;
7573                    this.toggleBrushList();
7574                })
7575                this.getBrushList().append(divel);
7576             });
7577        }
7578
7579        resizeCanvas(percentage) {
7580            const signCanvas = this.getCanvas();
7581            const ctx = signCanvas.getContext('2d', { willReadFrequently: true });
7582            const container = this.getCanvasContainer();
7583            this.getSignCanvasesContainer().style.width = `${percentage}%`;
7584            
7585            // Ensure the canvas has valid dimensions
7586            if (signCanvas.width === 0 || signCanvas.height === 0) {
7587                return;
7588            }
7589            
7590            // Save the content of the canvas if it has valid dimensions
7591            let imgData = null;
7592            if (signCanvas.width > 0 && signCanvas.height > 0) {
7593                imgData = ctx.getImageData(0, 0, signCanvas.width, signCanvas.height);
7594            }
7595            // Calculate the new width based on the percentage of the container's width
7596            const newWidth = container.offsetWidth * (percentage / 100);
7597            // Set the new width and height of the canvas
7598            signCanvas.width = newWidth;
7599            // Restore the content back to the resized canvas if it has valid content
7600            if (imgData) {
7601                ctx.putImageData(imgData, 0, 0);
7602            }
7603        }
7604
7605        geoQuerySuccessHandler(position) {
7606            if (position && position.coords) {
7607                this.showMessage('');
7608                const { latitude, longitude } = position.coords;
7609                const latStr = `Latitude: ${latitude}`;
7610                const longStr = `Longitude: ${longitude}`;
7611                const dateObj = new Date();
7612                const tZone = (dateObj.getTimezoneOffset() / 60) * -1;
7613                const timeStr = `${dateObj.getTime()}: ${(dateObj.getMonth() + 1)}/${dateObj.getDate()}/${dateObj.getFullYear()} ${dateObj.getHours()}:${dateObj.getMinutes()}:${dateObj.getSeconds()}${tZone > 0 ? ' +' : ' '}${tZone}`;
7614                this.updateGeoCanvas(latStr, longStr, timeStr);
7615            }
7616        }
7617
7618        updateGeoCanvas(latStr, longStr, timeStr) {
7619            const geoCanvas = this.getGeoCanvas();
7620            geoCanvas.style.height = '50px';
7621            geoCanvas.style.width = '200px';
7622            geoCanvas.style.display = 'block';
7623
7624            if (geoCanvas) {
7625                const ctx = geoCanvas.getContext('2d');
7626                geoCanvas.width = geoCanvas.offsetWidth;
7627                geoCanvas.height = geoCanvas.offsetHeight;
7628
7629                ctx.font = 'bold 10px Arial'; // Font size and type
7630                ctx.fillStyle = 'black'; // Text color
7631                ctx.measureText("m").width * 1.5;
7632                let x = 0;
7633                let y = 15;
7634
7635                // Draw the text on the canvas
7636                ctx.fillText(latStr, x, y);
7637                ctx.fillText(longStr, x, y + 15);
7638                ctx.fillText(timeStr, x, y + 30);
7639            }
7640        }
7641
7642        handleGeoLocation() {
7643            if (navigator.geolocation) {
7644                this._geoLocQuery = new GeoLocationQuery();
7645                this._geoLocQuery.init(
7646                    this.geoQuerySuccessHandler.bind(this),
7647                    this.geoQueryErrorHandler.bind(this)
7648                );
7649                this._geoLocQuery.query();
7650                var message = FormView.LanguageUtils.getTranslatedString(this.lang, 'geoLocationFetch');
7651                this.showMessage(message);
7652            }
7653        }
7654
7655        geoQueryErrorHandler(err) {
7656            var message = FormView.LanguageUtils.getTranslatedString(this.lang, 'geoLocationError')
7657            this.showMessage(message);
7658        }
7659
7660        enableControls(controls) {
7661            controls.forEach(control => {
7662                const element = this.element.querySelector('[data-cmp-scribble-button="'+ control +'"]');
7663                element?.classList.remove('disable_button');
7664                element?.removeAttribute('disabled');
7665            });
7666        }
7667
7668        disableControl(controls) {
7669            controls.forEach(control => {
7670                const element = this.element.querySelector('[data-cmp-scribble-button="'+ control +'"]');
7671                element?.classList.add('disable_button');
7672                element?.setAttribute('disabled', 'true');
7673            });
7674        }
7675
7676        toggleBrushList(event) {
7677            var brushList = this.getBrushList();
7678            if(getComputedStyle(brushList).display === 'none') {
7679                brushList.style.display = 'block';
7680            } else {
7681                brushList.style.display = 'none';
7682            }
7683        }
7684
7685        controlPanelClickHandler(event) {
7686            const scribbleButton = event.target.getAttribute('data-cmp-scribble-button');
7687            switch(scribbleButton){
7688                case 'save':
7689                    this.submitSign();
7690                    break;
7691                case 'close':
7692                    this.closeEditModal();
7693                    break;
7694                case 'clearSign':
7695                    this.eraseSignature();
7696                    this.widget.value = '';
7697                    break;
7698                case 'textSign':
7699                    this.enableSignatureTextBox();
7700                    break;
7701                case 'geolocation':
7702                    this.handleGeoLocation();
7703                    break;
7704                case 'brushes':
7705                    this.handleBrush(event);
7706                    this.toggleBrushList();
7707                    break;
7708            }
7709        }
7710
7711        closeEditModal() {
7712            if(this.getCanvas()) this.getCanvas().style.display = 'block';
7713            if(!this._signSubmitted) {
7714                this.eraseSignature()
7715            }
7716            this.hideScribbleModal();
7717        }
7718
7719        handleBrush(evt){
7720            this.getKeyboardSignBox().style.display = 'none';
7721            if (this.canvas.style.display == "none") {
7722                this.canvas.style.display = "block";
7723                this.context.clearRect(0, 0, this.canvas?.width, this.canvas?.height);
7724                this.eraseSignature();
7725                this.initializeCanvas();
7726            }
7727        }
7728        initScribbleModal() {
7729            const controlPanel = this.getScribbleControlPanel();
7730            const toggleBrushListIcon = this.getBrush();
7731            const brushList = this.getBrushList();
7732            const keyboardSignBox = this.getKeyboardSignBox();
7733        
7734            this.renderBrushList();
7735        
7736            this.addEventListeners(controlPanel, 'click', this.controlPanelClickHandler.bind(this));
7737        
7738            keyboardSignBox.addEventListener('input', (event) => {
7739                if (event?.target?.value) {
7740                    this.enableControls(['save', 'clearSign']);
7741                } else {
7742                    this.disableControl(['save', 'clearSign']);
7743                }
7744            });
7745        
7746            keyboardSignBox.addEventListener('keyup', () => {
7747                this.updateKeyboardSignBoxFont(keyboardSignBox);
7748            });
7749        
7750            document.addEventListener('click', (event) => {
7751                if (!brushList.contains(event.target) && !toggleBrushListIcon.contains(event.target)) {
7752                    brushList.style.display = 'none';
7753                }
7754            });
7755        }
7756        
7757        addEventListeners(element, eventType, handler, checkDisabled = false) {
7758            if (element) {
7759                element.addEventListener(eventType, (event) => {
7760                    if (!checkDisabled || element.getAttribute('disabled') !== 'true') {
7761                        handler(event);
7762                    }
7763                });
7764            }
7765        }
7766        
7767        updateKeyboardSignBoxFont(keyboardSignBox) {
7768            const fontFamily = "sans-serif, Georgia";
7769            const fontStyle = "italic";
7770            keyboardSignBox.style.font = `${fontStyle} 2rem ${fontFamily}`;
7771            const value = keyboardSignBox.value;
7772            const canvas = this.getCanvas();
7773            const ctx = this.context;
7774            const maxFontSize = 10; // rem
7775            const minFontSize = 1;  // rem
7776            // Set to max font size to measure
7777            ctx.clearRect(0, 0, canvas.width, canvas.height);
7778            // Find the largest font size that fits the text within the canvas width
7779            let fontSize = maxFontSize;
7780            ctx.font = `${fontStyle} ${fontSize}rem ${fontFamily}`;
7781            let textWidth = ctx.measureText(value).width;
7782            const canvasWidth = canvas.width;
7783            while (fontSize > minFontSize && textWidth > canvasWidth) {
7784                fontSize -= 0.5;
7785                ctx.font = `${fontStyle} ${fontSize}rem ${fontFamily}`;
7786                textWidth = ctx.measureText(value).width;
7787            }
7788            fontSize = Math.max(minFontSize, fontSize);
7789            ctx.font = `${fontStyle} ${fontSize}rem ${fontFamily}`;
7790            ctx.fillText(value, 0, canvas.height / 2);
7791        }
7792
7793        enableSignatureTextBox() {
7794            this.eraseSignature();
7795            this.getKeyboardSignBox().style.display = "inline-block";
7796            this.getCanvas().style.display = "none";
7797        }
7798
7799        eraseSignature() {
7800            this.context?.clearRect(0, 0, this.canvas?.width, this.canvas?.height);
7801            const geoCnv = this.getGeoCanvas();
7802            if(geoCnv) {
7803                const geoCanvasContext = geoCnv?.getContext('2d');
7804                geoCanvasContext?.clearRect(0, 0, geoCnv.width, geoCnv.height);
7805                geoCnv.style.display = 'none';
7806            }
7807            this.getKeyboardSignBox().value='';
7808            this.disableControl(['clearSign','save']);
7809        }
7810
7811        resizeAndFixCanvas() {
7812            const dpr = window.devicePixelRatio || 1;
7813            let imgData = null;
7814            if (this.canvas.width > 0 && this.canvas.height > 0) {
7815                imgData = this.context.getImageData(0, 0, this.canvas.width, this.canvas.height);
7816            }
7817            this.canvas.width = this.canvas.offsetWidth * dpr;
7818            this.canvas.height = this.canvas.offsetHeight * dpr;
7819            if (imgData) {
7820                this.context.putImageData(imgData, 0, 0);
7821            }
7822        }
7823
7824        handleCanvasEvent(event) {
7825            switch (event.type) {
7826                case 'mousedown':
7827                case 'touchstart':
7828                    this.startDrawing(event);
7829                    break;
7830                case 'mousemove':
7831                case 'touchmove':
7832                    this.draw(event);
7833                    break;
7834                case 'mouseup':
7835                case 'mouseleave':
7836                case 'touchend':
7837                case 'touchcancel':
7838                    this.stopDrawing();
7839                    break;
7840            }
7841        }
7842
7843        addCanvasEventListeners() {
7844            const events = ['mousedown', 'mousemove', 'mouseup', 'mouseleave', 'touchstart', 'touchmove', 'touchend', 'touchcancel'];
7845            events.forEach(event => {
7846                this.canvas.addEventListener(event, this.handleCanvasEvent.bind(this));
7847            });
7848        }
7849
7850        initializeCanvas() {
7851            if(this.existingSign) {
7852                this.getCanvasContainer().style.width = '100%';
7853                this.getMainCanvas().style.border = '1px solid black';
7854                this.getKeyboardSignBox().style.display = 'none';
7855                this.disableControl(['brushes','geolocation','clearSign','textSign','save']);
7856            } else {
7857                this.canvas = this.getCanvas();
7858                this.canvas.style.display = 'block';
7859                this.context = this.canvas.getContext('2d', { willReadFrequently: true });
7860                this.resizeCanvas(100);
7861                this.resizeAndFixCanvas();
7862                if (this.canvas) {
7863                    this.canvas.style.border = '1px dashed #AAAAAA';
7864                    this.getKeyboardSignBox().style.display = 'none';
7865                    this.addCanvasEventListeners();
7866                    this.isDrawing = false;
7867                }
7868            }
7869            // Add event listener for window resize to make the canvas responsive
7870            window.addEventListener('resize', this.resizeAndFixCanvas.bind(this));
7871        // }
7872        }
7873
7874        showScribbleModal() {
7875            if(window.getComputedStyle(this.getScribbleContainer()).display !== 'block') {
7876                this.disableControl(['clearSign','save']);
7877            }
7878            const container = this.getScribbleContainer();
7879            container.style.display = 'block';
7880            // Set focus to the modal container for accessibility
7881            container.setAttribute('tabindex', '-1');
7882            container.focus();
7883        }
7884
7885        hideScribbleModal() {
7886            this.getScribbleContainer().style.display = 'none';
7887        }
7888
7889        scribbleContainerClickHandler() {
7890            this.showScribbleModal();
7891            this.initializeCanvas();
7892        }
7893        
7894        startDrawing(event) {
7895            // Ensure the context is initialized
7896            if (!this.context) {
7897                return;
7898            }
7899        
7900            // Normalize event coordinates for touch events
7901            const { offsetX, offsetY } = this.getEventCoordinates(event);
7902        
7903            this.isDrawing = true;
7904            this.context.beginPath();
7905            this.context.moveTo(offsetX, offsetY);
7906        }
7907
7908        getMousePos(event) {
7909            const rect = this.canvas.getBoundingClientRect();
7910            const offsetX = event.clientX - rect.left;
7911            const offsetY = event.clientY - rect.top;
7912            return { offsetX, offsetY };
7913        }
7914
7915        getEventCoordinates(event) {
7916            const rect = this.canvas.getBoundingClientRect();
7917            const dpr = window.devicePixelRatio || 1;
7918            if (event.touches && event.touches.length > 0) {
7919                const touch = event.touches[0];
7920                return {
7921                    offsetX: (touch.clientX - rect.left) * dpr,
7922                    offsetY: (touch.clientY - rect.top) * dpr
7923                };
7924            } else {
7925                return {
7926                    offsetX: (event.clientX - rect.left) * dpr,
7927                    offsetY: (event.clientY - rect.top) * dpr
7928                };
7929            }
7930        }
7931
7932        draw(event) {
7933            if (!this.isDrawing) return;
7934            const { offsetX, offsetY } = this.getEventCoordinates(event);
7935            this.context.lineTo(offsetX, offsetY);
7936            this.context.stroke();
7937            this.enableControls(['clearSign','save']);
7938        }
7939
7940        stopDrawing() {
7941            if (this.isDrawing) {
7942                this.context.closePath();
7943                this.isDrawing = false;
7944            }
7945        }
7946    }
7947
7948    FormView.Utils.setupField(({element, formContainer}) => {
7949        return new Scribble({element, formContainer})
7950    }, Scribble.selectors.self);
7951})();
7952
7953/*******************************************************************************
7954 * Copyright 2025 Adobe
7955 *
7956 * Licensed under the Apache License, Version 2.0 (the "License");
7957 * you may not use this file except in compliance with the License.
7958 * You may obtain a copy of the License at
7959 *
7960 *     http://www.apache.org/licenses/LICENSE-2.0
7961 *
7962 * Unless required by applicable law or agreed to in writing, software
7963 * distributed under the License is distributed on an "AS IS" BASIS,
7964 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7965 * See the License for the specific language governing permissions and
7966 * limitations under the License.
7967 ******************************************************************************/
7968(function() {
7969
7970    "use strict";
7971    class Datetime extends FormView.FormFieldBase {
7972
7973        static NS = FormView.Constants.NS;
7974        /**
7975         * Each FormField has a data attribute class that is prefixed along with the global namespace to
7976         * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be
7977         * data-{NS}-{IS}-x=""
7978         * @type {string}
7979         */
7980        static IS = "adaptiveFormDatetime";
7981        static bemBlock = 'cmp-adaptiveform-datetime'
7982        static selectors  = {
7983            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
7984            widget: `.${Datetime.bemBlock}__widget`,
7985            label: `.${Datetime.bemBlock}__label`,
7986            description: `.${Datetime.bemBlock}__longdescription`,
7987            qm: `.${Datetime.bemBlock}__questionmark`,
7988            errorDiv: `.${Datetime.bemBlock}__errormessage`,
7989            tooltipDiv: `.${Datetime.bemBlock}__shortdescription`,
7990            eyeIcon: `.${Datetime.bemBlock}__eyeicon`
7991        };
7992
7993        constructor(params) {
7994            super(params);
7995        }
7996
7997        getWidget() {
7998            return this.element.querySelector(Datetime.selectors.widget);
7999        }
8000
8001        getDescription() {
8002            return this.element.querySelector(Datetime.selectors.description);
8003        }
8004
8005        getLabel() {
8006            return this.element.querySelector(Datetime.selectors.label);
8007        }
8008
8009        getErrorDiv() {
8010            return this.element.querySelector(Datetime.selectors.errorDiv);
8011        }
8012
8013        getTooltipDiv() {
8014            return this.element.querySelector(Datetime.selectors.tooltipDiv);
8015        }
8016
8017        getQuestionMarkDiv() {
8018            return this.element.querySelector(Datetime.selectors.qm);
8019        }
8020
8021        setModel(model) {
8022            super.setModel(model);
8023            if (this.widget.value !== '') {
8024                this._model.value = this.widget.value;
8025            }
8026            this.widget.addEventListener('blur', (e) => {
8027                this._model.value = e.target.value;
8028                this.setInactive();
8029            });
8030            this.widget.addEventListener('focus', (e) => {
8031                this.setActive();
8032            });
8033        }
8034
8035    }
8036
8037    FormView.Utils.setupField(({element, formContainer}) => {
8038        return new Datetime({element, formContainer})
8039    }, Datetime.selectors.self);
8040
8041})();
8042
8043/*******************************************************************************
8044 * Copyright 2026 Adobe
8045 *
8046 * Licensed under the Apache License, Version 2.0 (the "License");
8047 * you may not use this file except in compliance with the License.
8048 * You may obtain a copy of the License at
8049 *
8050 *     http://www.apache.org/licenses/LICENSE-2.0
8051 *
8052 * Unless required by applicable law or agreed to in writing, software
8053 * distributed under the License is distributed on an "AS IS" BASIS,
8054 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8055 * See the License for the specific language governing permissions and
8056 * limitations under the License.
8057 ******************************************************************************/
8058(function() {
8059
8060    "use strict";
8061    class ImageChoice extends FormView.FormOptionFieldBase {
8062
8063        static NS = FormView.Constants.NS;
8064        static IS = "adaptiveFormImageChoice";
8065        static bemBlock = 'cmp-adaptiveform-imagechoice';
8066        static selectors  = {
8067            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
8068            widgets: `.${ImageChoice.bemBlock}__widget`,
8069            widget: `.${ImageChoice.bemBlock}__option__widget`,
8070            label: `.${ImageChoice.bemBlock}__label`,
8071            description: `.${ImageChoice.bemBlock}__longdescription`,
8072            qm: `.${ImageChoice.bemBlock}__questionmark`,
8073            errorDiv: `.${ImageChoice.bemBlock}__errormessage`,
8074            tooltipDiv: `.${ImageChoice.bemBlock}__shortdescription`,
8075            option: `.${ImageChoice.bemBlock}__option`,
8076            optionLabel: `.${ImageChoice.bemBlock}__option-label`,
8077            optionImage: `.${ImageChoice.bemBlock}__option-image`,
8078            optionText: `.${ImageChoice.bemBlock}__option-text`
8079        };
8080
8081        constructor(params) {
8082            super(params);
8083            this.qm = this.element.querySelector(ImageChoice.selectors.qm);
8084            this._selectionType = this.element.getAttribute('data-cmp-selection-type') || 'single';
8085        }
8086
8087        get isMultiSelect() {
8088            return this._selectionType === 'multi';
8089        }
8090
8091        getWidgets() {
8092            return this.element.querySelector(ImageChoice.selectors.widgets);
8093        }
8094
8095        getWidget() {
8096            return this.element.querySelectorAll(ImageChoice.selectors.widget);
8097        }
8098
8099        getDescription() {
8100            return this.element.querySelector(ImageChoice.selectors.description);
8101        }
8102
8103        getLabel() {
8104            return this.element.querySelector(ImageChoice.selectors.label);
8105        }
8106
8107        getQuestionMarkDiv() {
8108            return this.element.querySelector(ImageChoice.selectors.qm);
8109        }
8110
8111        getTooltipDiv() {
8112            return this.element.querySelector(ImageChoice.selectors.tooltipDiv);
8113        }
8114
8115        getErrorDiv() {
8116            return this.element.querySelector(ImageChoice.selectors.errorDiv);
8117        }
8118
8119        getOptions() {
8120            return this.element.querySelectorAll(ImageChoice.selectors.option);
8121        }
8122
8123        #addWidgetListeners(optionWidget) {
8124            optionWidget.addEventListener('change', (e) => {
8125                if (this.isMultiSelect) {
8126                    this.#updateMultiValue();
8127                } else {
8128                    this.setModelValue(e.target.value);
8129                }
8130            });
8131            optionWidget.addEventListener('focus', (e) => {
8132                this.setActive();
8133            });
8134            optionWidget.addEventListener('blur', (e) => {
8135                this.setInactive();
8136            });
8137        }
8138
8139        setModel(model) {
8140            super.setModel(model);
8141            this.widget.forEach(optionWidget => {
8142                this.#addWidgetListeners(optionWidget);
8143            });
8144            if (this.isMultiSelect) {
8145                this.#updateMultiValue();
8146            }
8147        }
8148
8149        #updateMultiValue() {
8150            let value = [];
8151            this.widget.forEach(widget => {
8152                if (widget.checked) {
8153                    value.push(widget.value);
8154                }
8155            }, this);
8156            if (value.length !== 0 || this._model.value != null) {
8157                this.setModelValue(value);
8158            }
8159        }
8160
8161        updateEnabled(enabled, state) {
8162            this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_ENABLED, enabled);
8163            this.widget.forEach(widget => {
8164                if (enabled === false) {
8165                    if (state.readOnly === false) {
8166                        widget.setAttribute(FormView.Constants.HTML_ATTRS.DISABLED, "disabled");
8167                    }
8168                } else if (state.readOnly === false) {
8169                    widget.removeAttribute(FormView.Constants.HTML_ATTRS.DISABLED);
8170                }
8171            });
8172        }
8173
8174        updateReadOnly(readonly) {
8175            this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_READONLY, readonly);
8176            this.widget.forEach(widget => {
8177                if (readonly === true) {
8178                    widget.setAttribute(FormView.Constants.HTML_ATTRS.DISABLED, "disabled");
8179                    widget.setAttribute("aria-readonly", true);
8180                } else {
8181                    widget.removeAttribute(FormView.Constants.HTML_ATTRS.DISABLED);
8182                    widget.removeAttribute("aria-readonly");
8183                }
8184            });
8185        }
8186
8187        updateValidity(validity) {
8188            if (validity.valid === undefined) {
8189                this.element.removeAttribute(FormView.Constants.DATA_ATTRIBUTE_VALID);
8190                this.widget.forEach(widget => widget.removeAttribute(FormView.Constants.ARIA_INVALID));
8191            } else {
8192                this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_VALID, validity.valid);
8193                this.widget.forEach(widget => widget.setAttribute(FormView.Constants.ARIA_INVALID, !validity.valid));
8194            }
8195        }
8196
8197        updateValue(modelValue) {
8198            if (this.isMultiSelect) {
8199                modelValue = [].concat(modelValue);
8200                let selectedWidgetValues = modelValue.map(String);
8201                this.widget.forEach(widget => {
8202                    if (selectedWidgetValues.includes(widget.value)) {
8203                        widget.checked = true;
8204                        widget.setAttribute(FormView.Constants.HTML_ATTRS.CHECKED, FormView.Constants.HTML_ATTRS.CHECKED);
8205                    } else {
8206                        widget.checked = false;
8207                        widget.removeAttribute(FormView.Constants.HTML_ATTRS.CHECKED);
8208                    }
8209                }, this);
8210            } else {
8211                this.widget.forEach(widget => {
8212                    if (modelValue != null && widget.value != null && (modelValue.toString() == widget.value.toString())) {
8213                        widget.checked = true;
8214                        widget.setAttribute(FormView.Constants.HTML_ATTRS.CHECKED, FormView.Constants.HTML_ATTRS.CHECKED);
8215                    } else {
8216                        widget.checked = false;
8217                        widget.removeAttribute(FormView.Constants.HTML_ATTRS.CHECKED);
8218                    }
8219                }, this);
8220            }
8221            super.updateEmptyStatus();
8222        }
8223
8224        #createOption(value, itemLabel) {
8225            let inputType = this.isMultiSelect ? 'checkbox' : 'radio';
8226            let richScreenReaderText = `${this._model.label.value}:  ${itemLabel}`;
8227            let plainScreenReaderText = window.DOMPurify ? window.DOMPurify.sanitize(richScreenReaderText, { ALLOWED_TAGS: [] }) : richScreenReaderText;
8228
8229            const optionDiv = document.createElement('div');
8230            optionDiv.className = ImageChoice.selectors.option.slice(1);
8231
8232            const label = document.createElement('label');
8233            label.className = ImageChoice.selectors.optionLabel.slice(1);
8234
8235            const input = document.createElement('input');
8236            input.type = inputType;
8237            input.name = this._model.name;
8238            input.className = ImageChoice.selectors.widget.slice(1);
8239            input.value = value;
8240            input.setAttribute('aria-label', plainScreenReaderText);
8241            input.tabIndex = 0;
8242            if (this._model.readOnly === true || this._model.enabled === false) {
8243                input.setAttribute('disabled', 'true');
8244                if (this._model.readOnly === true) {
8245                    input.setAttribute('aria-readonly', 'true');
8246                }
8247            }
8248
8249            const imageSpan = document.createElement('span');
8250            imageSpan.className = ImageChoice.selectors.optionImage.slice(1);
8251
8252            // Look up image by finding the index of this value in the model's enum array
8253            let layout = this._model.properties && this._model.properties['afs:layout'];
8254            let imageSrcArray = layout && layout.imageSrc;
8255            let enumArray = this._model.enum;
8256            if (imageSrcArray && enumArray) {
8257                let idx = enumArray.indexOf(value);
8258                if (idx === -1) {
8259                    idx = enumArray.findIndex(e => String(e) === String(value));
8260                }
8261                if (idx >= 0 && imageSrcArray[idx]) {
8262                    let altText = window.DOMPurify ? window.DOMPurify.sanitize(itemLabel, { ALLOWED_TAGS: [] }) : itemLabel;
8263                    const img = document.createElement('img');
8264                    img.src = imageSrcArray[idx];
8265                    img.alt = altText;
8266                    img.className = 'cmp-adaptiveform-imagechoice__image';
8267                    imageSpan.appendChild(img);
8268                }
8269            }
8270
8271            const textSpan = document.createElement('span');
8272            textSpan.className = ImageChoice.selectors.optionText.slice(1);
8273            let purifiedLabel = window.DOMPurify ? window.DOMPurify.sanitize(itemLabel) : itemLabel;
8274            textSpan.innerHTML = purifiedLabel;
8275
8276            label.appendChild(input);
8277            label.appendChild(imageSpan);
8278            label.appendChild(textSpan);
8279            optionDiv.appendChild(label);
8280
8281            this.#addWidgetListeners(input);
8282            return optionDiv;
8283        }
8284
8285        updateEnum(newEnums) {
8286            super.updateEnumForRadioButtonAndCheckbox(newEnums, this.#createOption);
8287            this.widget = this.getWidget();
8288        }
8289
8290        updateEnumNames(newEnumNames) {
8291            // Override parent behavior: parent's updateEnumNamesForRadioButtonAndCheckbox
8292            // does option.querySelector('span') which grabs the __option-image span (first span)
8293            // and overwrites its innerHTML with text, destroying the <img>.
8294            // Instead, target the __option-text span specifically.
8295            let options = [...this.getOptions()];
8296            if (options.length === 0) {
8297                newEnumNames.forEach((enumName, index) => {
8298                    const enumValue = this._model.enum?.[index] ?? enumName;
8299                    this.getWidgets().appendChild(this.#createOption(enumValue, enumName));
8300                });
8301            } else {
8302                options.forEach((option, index) => {
8303                    let textSpan = option.querySelector(ImageChoice.selectors.optionText);
8304                    let input = option.querySelector(ImageChoice.selectors.widget);
8305                    if (index < newEnumNames.length) {
8306                        let purifiedValue = window.DOMPurify ? window.DOMPurify.sanitize(newEnumNames[index]) : newEnumNames[index];
8307                        if (textSpan) {
8308                            textSpan.innerHTML = purifiedValue;
8309                        }
8310                        if (input && input.hasAttribute("aria-label")) {
8311                            let richScreenReaderText = `${this._model.label.value}:  ${purifiedValue}`;
8312                            let plainScreenReaderText = window.DOMPurify ? window.DOMPurify.sanitize(richScreenReaderText, { ALLOWED_TAGS: [] }) : richScreenReaderText;
8313                            input.setAttribute("aria-label", plainScreenReaderText);
8314                        }
8315                    }
8316                });
8317            }
8318            this.widget = this.getWidget();
8319        }
8320
8321        updateRequired(required, state) {
8322            if (this.widget) {
8323                this.element.toggleAttribute("required", required);
8324                this.element.setAttribute("data-cmp-required", required);
8325                this.element.setAttribute("aria-required", required);
8326                let widgetsContainer = this.getWidgets();
8327                if (widgetsContainer) {
8328                    widgetsContainer.setAttribute("aria-required", required);
8329                }
8330            }
8331        }
8332
8333        syncMarkupWithModel() {
8334            // Do NOT call super.syncMarkupWithModel() which rebuilds options
8335            // from enum/enumNames and destroys the server-rendered images.
8336            // Only sync widget names with the model.
8337            this.#syncWidgetName();
8338        }
8339
8340        #syncWidgetName() {
8341            const name = this.getModel()?.name;
8342            this.widget.forEach(widget => {
8343                widget.setAttribute("name", `${this.id}_${name}`);
8344            });
8345        }
8346    }
8347
8348    FormView.Utils.setupField(({element, formContainer}) => {
8349        return new ImageChoice({element, formContainer});
8350    }, ImageChoice.selectors.self);
8351
8352})();
8353
8354/*******************************************************************************
8355 * Copyright 2026 Adobe
8356 *
8357 * Licensed under the Apache License, Version 2.0 (the "License");
8358 * you may not use this file except in compliance with the License.
8359 * You may obtain a copy of the License at
8360 *
8361 *     http://www.apache.org/licenses/LICENSE-2.0
8362 *
8363 * Unless required by applicable law or agreed to in writing, software
8364 * distributed under the License is distributed on an "AS IS" BASIS,
8365 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8366 * See the License for the specific language governing permissions and
8367 * limitations under the License.
8368 ******************************************************************************/
8369(function () {
8370    "use strict";
8371
8372    class Table extends FormView.FormPanel {
8373
8374        static NS = FormView.Constants.NS;
8375        static IS = "adaptiveFormTable";
8376        static bemBlock = 'cmp-adaptiveform-table';
8377        static selectors = {
8378            self: "[data-" + this.NS + '-is="' + this.IS + '"]',
8379            widget: `.${Table.bemBlock}__widget`,
8380            description: `.${Table.bemBlock}__longdescription`,
8381            qm: `.${Table.bemBlock}__questionmark`,
8382            tooltipDiv: `.${Table.bemBlock}__shortdescription`
8383        };
8384
8385        constructor(params) {
8386            super(params);
8387            this.children = [];
8388            /** @type {{ col: number, dir: 'asc'|'desc' }|null} */
8389            this._tableSortState = null;
8390        }
8391
8392        setModel(model) {
8393            super.setModel(model);
8394            queueMicrotask(() => {
8395                this.#initColumnSortingIfEnabled();
8396            });
8397        }
8398
8399        getClass() {
8400            return Table.IS;
8401        }
8402
8403        getWidget() {
8404            return null;
8405        }
8406
8407        getDescription() {
8408            return this.element.querySelector(Table.selectors.description);
8409        }
8410
8411        getLabel() {
8412            return this.element.querySelector(`.${Table.bemBlock}__title`);
8413        }
8414
8415        getErrorDiv() {
8416            return null;
8417        }
8418
8419        getTooltipDiv() {
8420            return this.element.querySelector(Table.selectors.tooltipDiv);
8421        }
8422
8423        getQuestionMarkDiv() {
8424            return this.element.querySelector(Table.selectors.qm);
8425        }
8426
8427        setFocus(id) {
8428            super.setFocus(id);
8429            this.setActive();
8430        }
8431
8432        getWidgetId() {
8433            return this.getId();
8434        }
8435
8436        /**
8437         * Override updateLabel to handle the table's specific HTML structure.
8438         * The table uses __title instead of __label-container > __label.
8439         * @param {Object} label - The label state object.
8440         */
8441        updateLabel(label) {
8442            const labelElement = this.getLabel();
8443            if (labelElement) {
8444                if (label.hasOwnProperty("value")) {
8445                    labelElement.innerHTML = label.value;
8446                }
8447                if (label.hasOwnProperty("visible")) {
8448                    if (label.visible === false) {
8449                        labelElement.setAttribute("aria-hidden", "true");
8450                    } else {
8451                        labelElement.removeAttribute("aria-hidden");
8452                    }
8453                    labelElement.setAttribute("data-cmp-visible", label.visible);
8454                }
8455            }
8456        }
8457
8458        /**
8459         * Override applyState to use the table's specific updateLabel.
8460         * @param {Object} state - The state to be applied.
8461         */
8462        applyState(state) {
8463            this.updateVisible(state.visible);
8464            this.updateEnabled(state.enabled);
8465            this.initializeHelpContent(state);
8466            this.updateLabel(state.label);
8467        }
8468
8469        /**
8470         * Get the <tbody> element for row insertion.
8471         */
8472        #getTableBody() {
8473            return this.element.querySelector(`.${Table.bemBlock}__body`) ||
8474                   this.element.querySelector('tbody');
8475        }
8476
8477        /**
8478         * Inserts a new table row into the <tbody> at the correct position.
8479         * This is called by InstanceManager.handleAddition() when repeatableParentView is set.
8480         * Foundation-style approach: insert <tr> directly as sibling within single <tbody>.
8481         *
8482         * @param {Object} instanceManager - The instance manager
8483         * @param {Object} addedModel - The model of the added row
8484         * @param {HTMLElement} htmlElement - The cloned row element (<tr>)
8485         * @returns {HTMLElement} The inserted element
8486         */
8487        addRepeatableMarkup(instanceManager, addedModel, htmlElement) {
8488            const tbody = this.#getTableBody();
8489            if (!tbody) {
8490                console.error('Table: No tbody found for row insertion');
8491                return htmlElement;
8492            }
8493
8494            const instanceIndex = addedModel.index;
8495            const children = instanceManager.children;
8496
8497            if (children.length === 0) {
8498                tbody.appendChild(htmlElement);
8499            } else if (instanceIndex === 0) {
8500                const firstChild = children[0];
8501                if (firstChild && firstChild.element && firstChild.element.isConnected) {
8502                    tbody.insertBefore(htmlElement, firstChild.element);
8503                } else {
8504                    tbody.insertBefore(htmlElement, tbody.firstElementChild);
8505                }
8506            } else {
8507                const prevIndex = instanceIndex - 1;
8508                const prevChild = children.find(c => c.getModel && c.getModel().index === prevIndex);
8509                if (prevChild && prevChild.element) {
8510                    prevChild.element.after(htmlElement);
8511                } else {
8512                    const items = instanceManager._model.items || [];
8513                    const prevModel = items.find(m => m.index === prevIndex);
8514                    if (prevModel) {
8515                        const prevElement = document.getElementById(prevModel.id);
8516                        if (prevElement) {
8517                            prevElement.after(htmlElement);
8518                        } else {
8519                            tbody.appendChild(htmlElement);
8520                        }
8521                    } else {
8522                        tbody.appendChild(htmlElement);
8523                    }
8524                }
8525            }
8526
8527            // Utils.updateId only patches id attributes, not data-cmp-hook-* attrs.
8528            // Without this, cloned rows keep the template's stale row ID on their
8529            // add/remove buttons, causing every dynamically-added row to dispatch
8530            // the wrong model index when clicked.
8531            this.#syncTableRowHooks(htmlElement, addedModel.id);
8532
8533            return htmlElement;
8534        }
8535
8536        /**
8537         * Patches data-cmp-hook-add-instance / data-cmp-hook-remove-instance on a
8538         * freshly cloned row so they reference the row's own model ID.
8539         */
8540        #syncTableRowHooks(rowElement, rowId) {
8541            const addBtn = rowElement.querySelector('[data-cmp-hook-add-instance]');
8542            if (addBtn) {
8543                addBtn.setAttribute('data-cmp-hook-add-instance', rowId);
8544            }
8545            const removeBtn = rowElement.querySelector('[data-cmp-hook-remove-instance]');
8546            if (removeBtn) {
8547                removeBtn.setAttribute('data-cmp-hook-remove-instance', rowId);
8548            }
8549        }
8550
8551        /**
8552         * Repeatable table rows: align add/remove control visibility with minOccur / maxOccur.
8553         */
8554        handleChildAddition(childView) {
8555            this.#syncTableRowRepeatableControls(childView.getInstanceManager());
8556        }
8557
8558        handleChildRemoval(removedInstanceView) {
8559            this.#syncTableRowRepeatableControls(removedInstanceView.getInstanceManager());
8560        }
8561
8562        #syncTableRowRepeatableControls(instanceManager) {
8563            if (!instanceManager || !instanceManager.children || instanceManager.children.length === 0) {
8564                return;
8565            }
8566            const model = instanceManager._model;
8567            const items = model.items || [];
8568            const activeIds = new Set(items.map((item) => item.id));
8569            const minOccur = (typeof model.minOccur === 'number' && model.minOccur >= 0) ? model.minOccur : 0;
8570            const maxOccur = (typeof model.maxOccur === 'number' && model.maxOccur >= 0) ? model.maxOccur : -1;
8571            const dataVisible = FormView.Constants.DATA_ATTRIBUTE_VISIBLE;
8572            instanceManager.children.forEach((childView) => {
8573                if (!activeIds.has(childView.id)) {
8574                    return;
8575                }
8576                const rowElement = childView.element;
8577                if (!rowElement) {
8578                    return;
8579                }
8580                const addBtn = rowElement.querySelector("[data-cmp-hook-add-instance]");
8581                const removeBtn = rowElement.querySelector("[data-cmp-hook-remove-instance]");
8582                if (addBtn) {
8583                    addBtn.setAttribute(dataVisible, !(items.length === maxOccur && maxOccur !== -1));
8584                }
8585                if (removeBtn) {
8586                    removeBtn.setAttribute(dataVisible, items.length > minOccur);
8587                }
8588            });
8589        }
8590
8591        #initColumnSortingIfEnabled() {
8592            const widget = this.element.querySelector(Table.selectors.widget);
8593            if (!widget) {
8594                return;
8595            }
8596            const thead = widget.querySelector("thead");
8597            const tbody = widget.querySelector("tbody");
8598            if (!thead || !tbody) {
8599                return;
8600            }
8601            thead.querySelectorAll("th.cmp-adaptiveform-tablehead").forEach((th, index) => {
8602                const btn = th.querySelector(".cmp-adaptiveform-table__sort-button");
8603                if (!btn) {
8604                    return;
8605                }
8606                btn.addEventListener("click", (e) => {
8607                    e.preventDefault();
8608                    e.stopPropagation();
8609                    this.#sortTableByColumn(tbody, thead, index);
8610                });
8611            });
8612        }
8613
8614        /**
8615         * @param {HTMLTableSectionElement} tbody
8616         * @param {HTMLTableSectionElement} thead
8617         * @param {number} colIndex
8618         */
8619        #sortTableByColumn(tbody, thead, colIndex) {
8620            const rows = Array.from(tbody.querySelectorAll(":scope > tr"));
8621            if (rows.length <= 1) {
8622                return;
8623            }
8624            let dir = "asc";
8625            if (this._tableSortState && this._tableSortState.col === colIndex) {
8626                dir = this._tableSortState.dir === "asc" ? "desc" : "asc";
8627            }
8628            this._tableSortState = { col: colIndex, dir: dir };
8629            const mult = dir === "asc" ? 1 : -1;
8630            const sorted = rows.slice().sort((a, b) => {
8631                const va = this.#getCellSortValue(a.cells[colIndex]);
8632                const vb = this.#getCellSortValue(b.cells[colIndex]);
8633                return mult * va.localeCompare(vb, undefined, { numeric: true, sensitivity: "base" });
8634            });
8635            sorted.forEach((r) => tbody.appendChild(r));
8636            this.#syncInstanceManagerOrderAfterSort(sorted);
8637            const headerCells = thead.querySelectorAll("th.cmp-adaptiveform-tablehead");
8638            headerCells.forEach((th) => {
8639                th.removeAttribute("aria-sort");
8640                const b = th.querySelector(".cmp-adaptiveform-table__sort-button");
8641                if (b) {
8642                    b.classList.remove("cmp-adaptiveform-table__sort-button--asc");
8643                    b.classList.remove("cmp-adaptiveform-table__sort-button--desc");
8644                }
8645            });
8646            const activeTh = headerCells[colIndex];
8647            const activeBtn = activeTh && activeTh.querySelector(".cmp-adaptiveform-table__sort-button");
8648            if (activeTh && activeBtn) {
8649                activeBtn.classList.add(
8650                    dir === "asc" ? "cmp-adaptiveform-table__sort-button--asc" : "cmp-adaptiveform-table__sort-button--desc"
8651                );
8652                activeTh.setAttribute("aria-sort", dir === "asc" ? "ascending" : "descending");
8653            }
8654        }
8655
8656        /**
8657         * Keep repeatable row views aligned with DOM order after a sort.
8658         * @param {HTMLTableRowElement[]} sortedRows
8659         */
8660        #syncInstanceManagerOrderAfterSort(sortedRows) {
8661            const firstId = sortedRows[0] && sortedRows[0].id;
8662            if (!firstId || !this.formContainer || !this.formContainer.getField) {
8663                return;
8664            }
8665            const firstView = this.formContainer.getField(firstId);
8666            const im = firstView && typeof firstView.getInstanceManager === "function" ? firstView.getInstanceManager() : null;
8667            if (!im || !im.children || im.children.length !== sortedRows.length) {
8668                return;
8669            }
8670            const byId = new Map(im.children.map((cv) => [cv.getId(), cv]));
8671            const reordered = sortedRows.map((r) => byId.get(r.id)).filter(Boolean);
8672            if (reordered.length === im.children.length) {
8673                im.children = reordered;
8674            }
8675        }
8676
8677        /**
8678         * @param {HTMLTableCellElement|undefined} cell
8679         * @returns {string}
8680         */
8681        #getCellSortValue(cell) {
8682            if (!cell) {
8683                return "";
8684            }
8685            const control = cell.querySelector("input:not([type='hidden']):not([type='button']), select, textarea");
8686            if (control) {
8687                if (control.type === "checkbox" || control.type === "radio") {
8688                    return control.checked ? "1" : "0";
8689                }
8690                if (typeof control.value === "string") {
8691                    return control.value.trim();
8692                }
8693            }
8694            return cell.innerText.replace(/\s+/g, " ").trim();
8695        }
8696    }
8697
8698    FormView.Utils.setupField(({element, formContainer}) => {
8699        return new Table({element, formContainer})
8700    }, Table.selectors.self);
8701})();
8702
8703/*******************************************************************************
8704 * Copyright 2026 Adobe
8705 *
8706 * Licensed under the Apache License, Version 2.0 (the "License");
8707 * you may not use this file except in compliance with the License.
8708 * You may obtain a copy of the License at
8709 *
8710 *     http://www.apache.org/licenses/LICENSE-2.0
8711 *
8712 * Unless required by applicable law or agreed to in writing, software
8713 * distributed under the License is distributed on an "AS IS" BASIS,
8714 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8715 * See the License for the specific language governing permissions and
8716 * limitations under the License.
8717 ******************************************************************************/
8718(function () {
8719    "use strict";
8720
8721    class TableRow extends FormView.FormPanel {
8722
8723        static NS = FormView.Constants.NS;
8724        static IS = "adaptiveFormTableRow";
8725        static bemBlock = 'cmp-adaptiveform-tablerow';
8726        static selectors = {
8727            self: "[data-" + this.NS + '-is="' + this.IS + '"]'
8728        };
8729
8730        constructor(params) {
8731            super(params);
8732            this.children = [];
8733        }
8734
8735        /**
8736         * For table rows in a single tbody, the row element is the repeatable unit.
8737         * In edit mode with div wrappers, return the Sling wrapper div.
8738         * @returns {HTMLElement}
8739         */
8740        getRepeatableDomWrapper() {
8741            const parent = this.element.parentElement;
8742            if (parent && parent.classList && parent.classList.contains(TableRow.bemBlock)) {
8743                return parent;
8744            }
8745            return this.element;
8746        }
8747
8748        /**
8749         * Container where sibling rows are inserted — the {@code <tbody>} or div.table__body.
8750         * @returns {HTMLElement}
8751         */
8752        getRepeatableInstancesContainerElement() {
8753            const tableBody = this.element.closest(".cmp-adaptiveform-table__body") ||
8754                this.element.closest("tbody");
8755            return tableBody || this.element.parentElement;
8756        }
8757
8758        getClass() {
8759            return TableRow.IS;
8760        }
8761
8762        getWidget() {
8763            return null;
8764        }
8765
8766        getDescription() {
8767            return null;
8768        }
8769
8770        getLabel() {
8771            return null;
8772        }
8773
8774        getErrorDiv() {
8775            return null;
8776        }
8777
8778        getTooltipDiv() {
8779            return null;
8780        }
8781
8782        getQuestionMarkDiv() {
8783            return null;
8784        }
8785
8786        setFocus(id) {
8787            super.setFocus(id);
8788            this.setActive();
8789        }
8790
8791        getWidgetId() {
8792            return this.getId();
8793        }
8794
8795        /**
8796         * Override updateLabel to handle the table row's specific HTML structure.
8797         * Table rows don't have labels in the traditional sense.
8798         * @param {Object} label - The label state object.
8799         */
8800        updateLabel(label) {
8801            // Table rows don't have visible labels, so this is a no-op
8802        }
8803
8804        /**
8805         * Override applyState for table row's specific structure.
8806         * @param {Object} state - The state to be applied.
8807         */
8808        applyState(state) {
8809            this.updateVisible(state.visible);
8810            this.updateEnabled(state.enabled);
8811            this.initializeHelpContent(state);
8812            this.updateLabel(state.label);
8813        }
8814    }
8815
8816    FormView.Utils.setupField(({element, formContainer}) => {
8817        return new TableRow({element, formContainer})
8818    }, TableRow.selectors.self);
8819})();
8820
8821/*******************************************************************************
8822 * Copyright 2026 Adobe
8823 *
8824 * Licensed under the Apache License, Version 2.0 (the "License");
8825 * you may not use this file except in compliance with the License.
8826 * You may obtain a copy of the License at
8827 *
8828 *     http://www.apache.org/licenses/LICENSE-2.0
8829 *
8830 * Unless required by applicable law or agreed to in writing, software
8831 * distributed under the License is distributed on an "AS IS" BASIS,
8832 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8833 * See the License for the specific language governing permissions and
8834 * limitations under the License.
8835 ******************************************************************************/
8836(function () {
8837    "use strict";
8838
8839    class TableHeader extends FormView.FormPanel {
8840
8841        static NS = FormView.Constants.NS;
8842        static IS = "adaptiveFormTableHeader";
8843        static bemBlock = 'cmp-adaptiveform-tableheader';
8844        static selectors = {
8845            self: "[data-" + this.NS + '-is="' + this.IS + '"]'
8846        };
8847
8848        constructor(params) {
8849            super(params);
8850            this.children = [];
8851        }
8852
8853        getClass() {
8854            return TableHeader.IS;
8855        }
8856
8857        getWidget() {
8858            return null;
8859        }
8860
8861        getDescription() {
8862            return null;
8863        }
8864
8865        getLabel() {
8866            return null;
8867        }
8868
8869        getErrorDiv() {
8870            return null;
8871        }
8872
8873        getTooltipDiv() {
8874            return null;
8875        }
8876
8877        getQuestionMarkDiv() {
8878            return null;
8879        }
8880
8881        setFocus(id) {
8882            super.setFocus(id);
8883            this.setActive();
8884        }
8885
8886        getWidgetId() {
8887            return this.getId();
8888        }
8889
8890        /**
8891         * Override updateLabel to handle the table header's specific HTML structure.
8892         * Table headers don't have labels in the traditional sense.
8893         * @param {Object} label - The label state object.
8894         */
8895        updateLabel(label) {
8896            // Table headers don't have visible labels, so this is a no-op
8897        }
8898
8899        /**
8900         * Override applyState for table header's specific structure.
8901         * @param {Object} state - The state to be applied.
8902         */
8903        applyState(state) {
8904            this.updateVisible(state.visible);
8905            this.updateEnabled(state.enabled);
8906            this.initializeHelpContent(state);
8907            this.updateLabel(state.label);
8908        }
8909    }
8910
8911    FormView.Utils.setupField(({element, formContainer}) => {
8912        return new TableHeader({element, formContainer})
8913    }, TableHeader.selectors.self);
8914})();

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.