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)),c=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 d{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"){return this._callbacks[t]=this._callbacks[t]||[],this._callbacks[t].push(e),{unsubscribe:()=>{this._callbacks[t]=this._callbacks[t].filter((t=>t!==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))}));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){const t=new d(e,this);this.form.getEventQueue().queue(this,t,["valid","invalid"].indexOf(t.type)>-1)}dispatch(e){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),(this._callbacks[e.type]||[]).forEach((t=>{this.withDependencyTrackingControl(!0,(()=>{t(new d(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),c.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.`)}return n&&(this.isContainer||s===u.default||n===u.default||(n=null==n?void 0:n.$convertToDataValue(),s.$addDataNode(r,n,!0)),null==n||n.$bindToField(this),this._data=n),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(;
1null!=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.__esModule?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.__esMo
1dule?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},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),c=["readOnly","enabled"];class d 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(;
1null!=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()}_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)}
1this.items.forEach((e=>{e.reset()}))}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&&"array"===this.type&&Array.isArray(e)){const i=new l.default(this._data.$name,e,this._data.$type,this._data.parent);try{null===(t=this._data.parent)||void 0===t||t.$addDataNode(i.$name,i,!0)}catch(e){return void this.form.logger.error(`unable to setItems for ${this.qualifiedName} : ${e}`)}this._data=i,this.syncDataAndFormModel(i);const n=this.items.length;for(let e=0;e<n;e+=1)this._children[e].dispatch(new o.ExecuteRule)}else void 0===this._data&&console.warn(`Data node is null, hence importData did not work for panel "${this.name}". Check if parent has a dataRef set to null.`)}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 d;){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&&c.includes(t.propertyName)&&this.items.forEach((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)()],d.prototype,"maxItems",null),n([(0,u.dependencyTracked)()],d.prototype,"minItems",null),n([(0,u.dependencyTracked)()],d.prototype,"activeChild",null),t.default=d},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 c(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 d 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=c(this._jsonModel.editFormat),this._jsonModel.displayFormat?this._jsonModel.displayFormat=c(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=d},3260: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(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)},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),c=i(3332),d=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 d.default{constructor(e,t){super(e,t),n.add(this),this._ruleNodeReference=[],this._hasValueBeenSet=!1,"restore"!==t.mode&&(this._applyDefaults(),this.queueEvent(new c.Initialize),"deps"===this.form.changeEventBehaviour?this.queueEvent(new c.Change({changes:[]})):this.queueEvent(new c.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.forEac
1h((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)||("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=new c.Change({changes:t.concat(Object.values(s)),eventSource:this._eventSource});this.dispatch(a)}}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 c.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)();return(null===(t=this._jsonModel.constraintMessages)||void 0===t?void 0:t["exclusiveMaximum"===i?"maximum":"exclusiveMinimum"===i?"minimum":i])||(0,_.replaceTemplatePlaceholders)(s[n],[this._jsonModel[i]])}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,c=Math.abs(o-l)%a<.001;let d,h;return c||(d=(Math.ceil(u)*a+l)/r,h=(d-a)/r),{valid:c,next:d,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"
1: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&&(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 c.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,c.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,editValue: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 c.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 c.Valid):this.dispatch(new c.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.depen
1dencyTracked)()],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),c=s(i(8224));function d(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:d(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;return(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!==c.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,c=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())}))},d=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 c(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}}resolveQualifiedName(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 d(this,n,"m",u).call(this,e),void d(this,n,"m",a).call(this,e);const i=(null==e?void 0:e.isContainer)?e:e.parent,r=d(this,n,"m",s).call(this,i.items);let c=i.activeChild,h=null!==c?r.indexOf(c):-1;if(null===i.activeChild)return d(this,n,"m",a).call(this,r[0]),void(h=0);t===E.FocusOption.NEXT_ITEM?c=d(this,n,"m",o).call(this,h,r):t===E.FocusOption.PREVIOUS_ITEM&&(c=d(this,n,"m",l).call(this,h,r)),null!==c&&d(this,n,"m",a).call(this,c)}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"}
1isTransparent(){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"),e.subscribe((e=>{const t=this._invalidFields.indexOf(e.target.id);t>-1&&this._invalidFields.splice(t,1)}),"valid"),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)}}))}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=d(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);d(this,n,"m",u).call(this,t);const i=t.activeChild||d(this,n,"m",r).call(this,t);null!==i?d(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);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.__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())}))}
1,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),c=i(372),d=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 d.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 d.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 d.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 d.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,c.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)=>{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);
1this.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],c=l[u];l[u]=t,this.host._jsonModel.properties=a;const d=(0,n.propertyChange)(`properties.${e}`,t,c);this.host.notifyDependents(d)}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];"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]||[]}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(){return this._node.id+"__"+this.event.type}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 c=r(i(6764));t.EmailInput=c.default;const d=r(i(3968));t.Captcha=d.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),c=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),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=d(o))),"text/plain"===t&&(g=String(o))}const y=(t,i,n)=>{const r=c(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=c(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 d=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 c=a;const d=yield(0,o.readAttachments)(e.form,!0);"object"==typeof c&&null!=c||(c=e.form.exportData(d));let p=r;const f=Object.assign({data:c},u);let m=f;(Object.keys(d).length>0||"multipart/form-data"===r)&&(m=h(f,d),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,n)=>{const s={form:n.globals.$form,field:n.globals.$field,event:n.globals.$event,functions:{setProperty:(e,t)=>{const s=[e,"custom:setProperty",t];return f.getInstance().getFunctions().dispatchEvent._func.call(void 0,s,i,n)},reset:e=>{const t=[e=e||"reset","reset"];return n.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,n)},validate:e=>{const t=[e];return f.getInstance().getFunctions().validate._func.call(void 0,t,i,n)},importData:(e,t)=>{const s=[e,t];return f.getInstance().getFunctions().importData._func.call(void 0,s,i,n)},exportData:()=>f.getInstance().getFunctions().exportData._func.call(void 0,e,i,n),submitForm:(e,t,s)=>{const r=[e,t,s||"multipart/form-data"];return f.getInstance().getFunctions().submitForm._func.call(void 0,r,i,n)},markFieldAsInvalid:(e,t,i)=>{var s,r;!i||i.useId?null===(s=n.globals.form.getElement(e))||void 0===s||s.markAsInvalid(t):i&&i.useDataRef?n.globals.form.visit((function(i){i.dataRef===e&&i.markAsInvalid(t)})):i&&i.useQualifiedName&&(null===(r=n.globals.form.resolveQualifiedName(e))||void 0===r||r.markAsInvalid(t))},setFocus:(e,t)=>{const s=[e,t];return f.getInstance().getFunctions().setFocus._func.call(void 0,s,i,n)},dispatchEvent:(e,t,s,r)=>{const a=[e,t,s,r];return f.getInstance().getFunctions().dispatchEvent._func.call(void 0,a,i,n)},getFiles:e=>{const t={};e||n.globals.form.visit((function(e){"file-input"===e.fieldType&&e.value&&(t[e.qualifiedName]=e.serialize())}));const i=n.globals.form.resolveQualifiedName(e);return"file-input"===(null==i?void 0:i.fieldType)&&(null==i?void 0:i.value)&&(t[e]=i.serialize()),t}}};return t(...e,s)},_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,c,d;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===(c=null===(l=_.captcha.properties["fd:captcha"])||void 0===l?void 0:l.config)||void 0===c?void 0:c.keyType))){if("function"!=typeof(null===(d=a.runtime.functionTable.fetchCaptchaToken)||void 0===d?void 0:d._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,c,d={};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,d=t.headers||{},u=e(n[3]),c=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]),c=e(n[4])):(d=e(n[3]),u=e(n[4]),c=e(n[5]));return(0,t.request)(r.globals,a,o,l,u,c,d)},_signature:[]},requestWithRetry:{_func:(s,r,a)=>{const o=i(s[0]),l=i(s[1]);let u,c,d=e(s[2]);return"string"==typeof s[3]&&5===s.length?(u=e(s[3]),c=e(s[4])):"string"==typeof s[4]&&6===s.length&&(u=e(s[4]),c=e(s[5])),e=>n(this,void 0,void 0,(function*(){try{d instanceof Promise&&(d=yield d)}catch(e){throw console.error("Error resolving payload Promise:",e),e}let i={},n={},r=null;5===s.length?(n=d.body||{},i=d.headers||{},r=d.cryptoMetadata):(n=d||{},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,c,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:[]},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,c,d,h,p,f,m,g,_,v;const{formula:y,ast:b}=e,E=this._context;let T;this._context=i;try{T=y.run(b,t,"en-US",i)}catch(e){if(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.error(e),null===(u=this._context)||void 0===u?void 0:u.form){const t=null===(c=this._context)||void 0===c?void 0:c.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===(h=null===(d=this._context)||void 0===d?void 0:d.$event)||void 0===h?void 0:h.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===(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.warn(`Form rule expression string: ${s}`);this.debugInfo.length>0;)null===(v=null===(_=null===(g=this._context)||void 0===g?void 0:g.form)||void 0===_?void 0:_.logger)||void 0===v||v.warn(this.debugInfo.pop());let M=T;return n&&"object"==typeof T&&null!==T&&(M=Object.getPrototypeOf(T).valueOf.call(T)),this._context=E,M}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.",[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],c=(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},d=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(;d(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,!d(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(c(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 c=(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=c(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=c(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)),c=n(i(6884)),d=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 c.default(e,n):(0,a.isDateTimeField)(e)?new d.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],c={};for(const e of u)c[e]=JSON.parse(JSON.stringify(l));return[o,c]}},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}},c=e=>null==e||e instanceof Array?e:[e],d=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=c(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=c(t);break;case"number":n=l(t),i=n.value,s=n.valid;break;case"boolean":n=d(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,d),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=[],c=(d=t,"هـ"===(null===(h=new Intl.DateTimeFormat(d,{era:"short"}).formatToParts(new Date).find((e=>"era"===e.type)))||void 0===h?void 0:h.value)?"islamic":"gregory");var d,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"===c&&(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,c)?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 c=a||"";r.push(["@",u-c.length]),i.minimumSignificantDigits=u-c.length,i.maximumSignificantDigits=u,r.push(["digit",c.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:c,TYPE_EXPREF:d,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",[c]:"boolean",[d]:"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 c;case"[object Null]":return h;case"[object Object]":return i.jmespathType===_?d:u;default:return u}}function b(e){return[y(e),y(e,!1)]}function E(e,t,i,n,s,d){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,d)}return e}if([r,o,h,c].includes(t))return[E(e,[t],i,n,s,d)]}else{if(T===r)return[o,c,h].includes(_)?s(i):0;if(T===o)return _===h||_===u?"":d(i);if(T===c)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:P,TOK_NE:D,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===D)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===P)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:K,TOK_RPAREN:H,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:ce,TOK_GT:de,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,"]":K,"(":Me,")":H,"@":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,H,B,Y,K].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:de,value:">",start:t}:"="===e[this._current]?(this._current+=1,{type:ce,value:"==",start:t}):{type:ce,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:Pe,TOK_UNQUOTEDIDENTIFIER:De,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:Ke,TOK_FIELD:He,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:ct,TOK_FILTER:dt,TOK_DOT:ht,TOK_NOT:pt,TOK_LBRACE:ft,TOK_LBRACKET:mt,TOK_LPAREN:gt}=s,_t={[Pe]:0,[De]:0,[Fe]:0,[Le]:0,[ke]:0,[$e]:0,[Ve]:0,[Be]:0,[Ye]:0,[Ke]:0,[He]: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,[ct]:20,[dt]: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)!==Pe){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:Pe,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 De: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 ct:return t={type:"Identity"},i=this._lookahead(0)===Le?{type:"Identity"}:this._parseProjectionRHS(_t.Star),{type:"ValueProjection",children:[t,i]};case dt: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)===ct&&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 Ke:return{type:Ke,name:e.name};case He:return{type:He};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,c;switch(e){case Ue:return n=this.expression(_t.Concatenate),{type:"ConcatenateExpression",children:[t,n]};case ht:return l=_t.Dot,this._lookahead(0)!==ct?(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 dt: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]},c=this._parseProjectionRHS(_t.Flatten),{type:"Projection",children:[u,c]};case nt:case lt:case st:case at:case rt:case ot:return this._parseComparator(t,e);case mt:return this._lookahead(0)===ct&&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[De,Fe,ct].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)===dt)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=[De,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:c,TYPE_STRING:d,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:[d,h]},{types:[c]}]},endsWith:{_func:e=>{const t=a(e[0]),i=a(e[1]);return-1!==t.indexOf(i,t.length-i.length)},_signature:[{types:[d]},{types:[d]}]},floor:{_func:e=>Math.floor(e[0]),_signature:[{types:[u]}]},join:{_func:e=>{const t=e[0];return e[1].join(t)},_signature:[{types:[d]},{types:[v]}]},keys:{_func:e=>null===e[0]?[]:Object.keys(e[0]),_signature:[{types:[c]}]},length:{_func:e=>{const n=a(e[0]);return t(n)?Object.keys(n).length:i(n)?n.length:o(n).length},_signature:[{types:[d,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,d]);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,d]);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:[c],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:[c],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:[c],optional:!0}]},{})},_signature:[{types:[d]},{types:[m]}]},reverse:{_func:e=>{const t=a(e[0]);if(r(t)===d){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:[d,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,d].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:[d]},{types:[d]}]},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:[c]}]},toNumber:{_func:e=>{const t=r(e[0]);return t===u?e[0]:t===d?s(e[0]):null},_signature:[{types:[c]}]},toString:{_func:e=>r(e[0])===d?e[0]:JSON.stringify(e[0]),_signature:[{types:[c]}]},type:{_func:e=>({[u]:"number",[d]:"string",[h]:"array",[p]:"object",[f]:"boolean",[m]:"expref",[g]:"null"}[r(e[0])]),_signature:[{types:[c]}]},values:{_func:e=>{const t=a(e[0]);return null===t?[]:Object.values(t)},_signature:[{types:[c]}]},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 c=o.getDate()-a.getDate();if("y"===r){let e=l;return u<0&&(e-=1),0===u&&c<0&&(e-=1),e}if("m"===r)return 12*l+u+(c<0?-1:0);if("ym"===r)return c<0&&(u-=1),u<=0&&l>0?12+u:u;if("yd"===r)return c<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,c=e.length>7?t(e[7]):null;let d=new Date(n,s-1,r,a,o,l,u);return c&&(d=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)}(d,c)),d.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],c=void 0,a.includes(Et)&&null!==(c=u)&&!Array.isArray(c)&&"Object"!==c.constructor.name||a.includes(Tt)||(o=b(t[n]),t[n]=E(o,a,t[n],e,this.toNumber,Mt));var u,c}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:()=>d,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=`${d.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){window.alert(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){let i,n=[];const r=t.properties["fd:customFunctionsUrl"];i=r?await s.getJson(r):await s.getCustomFunctionConfig(t.id),console.debug("Fetched custom functions: "+JSON.stringify(i)),i&&i.clientSideParsingEnabled?n=this.extractFunctionNames(t):i&&i.customFunction&&(n=i.customFunction);const a=n.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:",a),e.FunctionRuntime.registerFunctions(a)}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])};e.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 c{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.forEac
1h((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));c.#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(c.#s).forEach((function(i){let n=c.#n[i];const s=e.querySelectorAll(n.fieldSelector);c.#r(s,n.fieldCreator,t)}))}static setupField(e,t,i){t in c.#n||c.#s.push(t),c.#n[t]={fieldCreator:e,fieldSelector:t,fieldClass:i}}static initializeAllFields(e){console.debug("Initializing field views ",e),Object.values(c.#s).forEach((function(t){const{fieldSelector:i,fieldCreator:n,fieldClass:s}=c.#n[t];console.debug("Initializing all fields of field selector ",i);let r=document.querySelectorAll(i);c.#r(r,n,e),c.registerMutationObserver(e,n,i,s)}))}static#a(e,t){e&&e.getAllFields()&&delete e.getAllFields()[t]}static#o(e,t){let i=e.children;if(i)for(let e=0;e<i.length;e++)c.#o(i[e]);e.getInstanceManager&&e.getInstanceManager()&&c.#a(t,e.getInstanceManager().id),c.#a(t,e.id)}static removeFieldReferences(e,t){let i=e.children;if(i)for(let e=0;e<i.length;e++)c.#o(i[e]);c.#a(t,e.id)}static updateId(e,t,i){let n=e.querySelectorAll("#"+t)[0];n&&(n.id=i)}static setContextPath(e){null!=c.#i&&0!==c.#i.length||(c.#i=e)}static getContextPath(){return c.#i}static _clearState(){c.#i="",c.#n={},c.#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=c.readData(a[e],r),o=n.customFunctionsModuleUrl,d=n.path,h=n.pageLang;if("contextPath"in n&&c.setContextPath(n.contextPath),null==d)console.error(`data-${t.NS}-${r}-path attribute is not present in the HTML element. Form cannot be initialized`);else{let n,r;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(d,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("&")),_=_||{},_=c.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:d,_element:a[e]});"function"==typeof r&&r(v.getModel()),c.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 d=c,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.#c()}#c(){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)}#d(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.#d(e.payload)}),"validationComplete")}},f=class{constructor(e){this.formContainer=e.formContainer,this.element=e.element,this.options=d.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),d.createFieldsForAddedElement(n,this.formContainer)):null==t?this.#j(e.getModel()):e.getId()!=t.id&&(n=this.#S(t,i),d.createFieldsForAddedElement(n,this.formContainer),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&&d.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&&d.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;this._templateHTML=t.cloneNode(!0);let i=e.getModel();i||(i=this.formContainer.getModel(e.getId())),this.#R(this._templateHTML,i,"temp_0")}#P(e,t,i){const n=new CustomEvent(t);i&&(n.payload=i),this.getModel().dispatch(n)}#S(e,t){if(this._templateHTML)return this.handleAddition(e,t);console.error("Panel needs to have templateHTML to support repeatability.")}#j(e){const i=e.index;let n=this.children[i];-1==i&&(n=this.formContainer.getField(e.id)),d.removeFieldReferences(n,this.formContainer),this.handleRemoval(n),this.children.splice(i,1);const s=new CustomEvent(t.PANEL_INSTANCE_REMOVED,{detail:n});this.formContainer.getFormElement().dispatchEvent(s)}addInstance(e,t){this.#P(e,"addInstance",t)}removeInstance(e,t){this.#P(e,"removeInstance",t)}#D(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);d.registerClickHandler(i,t.DATA_HOOK_ADD_INSTANCE,(e=>{const i=e.currentTarget.getAttribute(t.DATA_HOOK_ADD_INSTANCE);i?this.#D(i,"addInstance",1,e):this.addInstance(e)})),d.registerClickHandler(i,t.DATA_HOOK_REMOVE_INSTANCE,(e=>{const i=e.currentTarget.getAttribute(t.DATA_HOOK_REMOVE_INSTANCE);i?this.#D(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){this.repeatableParentView&&"function"==typeof this.repeatableParentView.handleChildRemoval&&this.repeatableParentView.handleChildRemoval(e),e.element.parentElement.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)}subscribe(){this.getModel().subscribe((e=>{let t=e.target.getState();
1e.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=[]}instantiateInstanceManager(){return new g({formContainer:this.formContainer,model:this._model.parent,parentElement:this.element.parentElement.parentElement})}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 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.#K(s),this.#k=this.getActiveTabId(this.#H()),this.#q(),this.#G()}#q(){var e=this.#z(),i=this.#H();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.#H();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)}))}}#K(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.#H(),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.#H();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.#H()).replace(this.#B,"");this.focusToFirstVisibleField(t)}}#Q(e){var t=this.#H();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.#H(),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.#H(),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.#H()[a-1].after(t)}else{var l=e.getInstanceManager().children[i-1].element.id+this.#B;this.#Q(l).after(t)}this.#K(this._elements.self);var u=this.#te(e.id+this.#Y);u.setAttribute("aria-labelledby",e.id+this.#B);const c=Array.from(t.classList).find((e=>e.includes("--stepped")));c&&t.classList.remove(c);const d=Array.from(u.classList).find((e=>e.includes("--stepped")));d&&u.classList.remove(d),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.#H()).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.#H(),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.#K(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.#H(),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}#H(){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.#H());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.invalidMimeType||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,c){let d=!1,h=!1,p=!1;if(t=a.name.split("\\").pop(),a.size/1024/1024>parseFloat(this.options.maxFileSize))o=d=!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;d||h||p?e.push(c):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]}}}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{#ce={};#de=[];#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.#ce[t.getPath()]=t,i.#fe(t.getPath())}))}#fe(e){this.#de.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.#ce[this.#he]?this.#ce[this.#he].getModel():null;{const e=this.#me();return this.#he=e,this.#ce[e]?this.#ce[e].getModel():null}}#me(){let e=this.#he;if(!e)for(let t in this.#ce)this.#ce.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.#de.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.#ce[i]:this.#ce[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.#ce[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.#ce[t]){const e=this.#ce[t];i=e.getFormElement(),"function"==typeof e._disconnectMutationObservers&&e._disconnectMutationObservers()}window.formBridge&&"function"==typeof window.formBridge.destroyForm&&window.formBridge.destroyForm(),1===Object.keys(this.#ce).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()))})),d._clearState(),window.xfalib&&window.xfalib.ut&&(window.xfalib.ut=null)),i&&i.remove(),delete this.#ce[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 active: `${HamburgerMenu.bemBlock}-item--active`, 52 activeParent: `${HamburgerMenu.bemBlock}-item--activeparent`, 53 hamburgerMenuWidget: { 54 hamburgerMenu: `${HamburgerMenu.bemBlock}-dropdown`, 55 hamburgerSubMenu: `${HamburgerMenu.bemBlock}-submenu`, 56 hamburgerMenuNavLink: `${HamburgerMenu.bemBlock}-link`, 57 hamburgerMenuCloseNavButton: `${HamburgerMenu.bemBlock}-button--close`, 58 hamburgerMenuOpenNavButton: `${HamburgerMenu.bemBlock}-button--open`, 59 }, 60 } 61 62 constructor(formContainer) { 63 this.formContainer = formContainer; 64 formContainer._model.subscribe((action) => { 65 const { payload } = action; 66 const { changes, field } = payload; 67 const { items } = field; 68 if (changes && changes.length > 0) { 69 changes.forEach((change) => { 70 switch (change.propertyName) { 71 case "activeChild": 72 this.#handleActiveItem(field); 73 break; 74 case "items": 75 this.#handleItemsChange(change, items); 76 break; 77 case "visible": 78 this.#updateAttribute(field.id, 'data-panel-visible', field.visible); 79 break; 80 case "enabled": 81 this.#updateAttribute(field.id, 'data-panel-enabled', field.enabled); 82 break; 83 } 84 }); 85 } 86 }, "fieldChanged"); 87 } 88 89 #updateAttribute(id, attributeName, value) {
90 const element = document.querySelector(`[data-panel-id='${id}']`); 91 if (attributeName === 'data-panel-enabled' && element) { 92 if (value === 'false') { 93 element.setAttribute('disabled', 'true'); 94 } else { 95 element.removeAttribute('disabled'); 96 } 97 } 98 if (element) { 99 element.setAttribute(attributeName, value); 100 } 101 } 102 103 #createListItem(item) { 104 const li = document.createElement('li'); 105 const link = document.createElement('a'); 106 const textSpan = document.createElement('span'); 107 link.href = "#"; 108 textSpan.textContent = item?.label?.value; 109 textSpan.setAttribute('tabindex', "0"); 110 link.appendChild(textSpan); 111 li.appendChild(link); 112 li.setAttribute('data-panel-id', item?.id); 113 li.setAttribute('data-panel-visible', item?.visible); 114 li.setAttribute('data-panel-enabled', item?.enabled); 115 return li; 116 } 117 118 #handleItemsChange(change, items) { 119 if (change?.prevValue !== null) {
120 document.querySelector(`[data-panel-id='${change?.prevValue?.id}']`)?.remove(); 121 } else { 122 items.forEach((item) => { 123 if (item.id === change.currentValue.id) { 124 const prevListItem = document.querySelector(`[data-panel-id='${items[change.currentValue.index - 1]?.id}']`); 125 const newListItem = this.#createListItem(change.currentValue); 126 prevListItem?.parentNode?.insertBefore(newListItem, prevListItem?.nextSibling); 127 } 128 }); 129 } 130 } 131 132 133 #handleActiveItem(field) { 134 const menu = document.querySelector(HamburgerMenu.selectors.hamburgerMenuWidget.hamburgerMenu); 135 if (field !== null && field) { 136 const activeListItem = document.querySelector(`[data-panel-id='${field.id}']`); 137 if(activeListItem && activeListItem.tagName === 'LI') { 138 const menuItems = document.querySelectorAll(HamburgerMenu.selectors.hamburgerMenuWidget.hamburgerMenu + ' li'); 139 const fieldModel = this.formContainer?.getField(activeListItem?.getAttribute('data-panel-id'))?.getModel(); 140 const elementID = this.#checkFirstNonPanel(fieldModel); 141 const targetElement = menu.querySelector("[data-panel-id='"+ elementID + "']"); 142 this.#resetMenuItems(menuItems); 143 this.#activateCurrentItem(targetElement); 144 const anchorElement = targetElement?.querySelector('a'); 145 anchorElement?.classList.add(HamburgerMenu.cssClasses.active); 146 anchorElement?.querySelector('button')?.classList?.toggle(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuCloseNavButton); 147 this.#updateSelectedPanelTitle(anchorElement); 148 this.#highlightMenuTree(anchorElement); 149 this.#renderBreadCrumbs(menu); 150 } 151 } 152 } 153 154 #updateSelectedPanelTitle(anchorElement, clickedAnchorElement) { 155 const activeItemTitleContent = anchorElement?.innerText; 156 const clickedAnchorElementText = clickedAnchorElement?.innerText; 157 const activeItemTitle = document.querySelector(HamburgerMenu.selectors.hamburgerMenuBottomContainer.hamburgerMenuActiveItemTitle); 158 activeItemTitle.innerText = activeItemTitleContent || clickedAnchorElementText || ''; 159 } 160 161 #checkFirstNonPanel(fieldModel) { 162 if(fieldModel && fieldModel._children && fieldModel._children[0]) { 163 if(fieldModel._children[0]?.fieldType !== 'panel') { 164 return fieldModel._children[0].parent.id; 165 } 166 return this.#checkFirstNonPanel(fieldModel?._children[0]) 167 } 168 return fieldModel?.id; 169 } 170 171 #clickHandler(event) { 172 const menu = document.querySelector(HamburgerMenu.selectors.hamburgerMenuWidget.hamburgerMenu); 173 event.stopPropagation(); 174 let targetElement = event.target.closest('li'); 175 if(targetElement?.getAttribute('data-panel-enabled') === 'false') { 176 return; 177 } 178 if(event.target.tagName === "BUTTON" && (event.target.classList.contains(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuCloseNavButton) || event.target.classList.contains(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuOpenNavButton))) { 179 const isExpanded = event.target.getAttribute('aria-expanded') === 'true'; 180 event.target.classList.toggle(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuCloseNavButton); 181 event.target.setAttribute('aria-expanded', !isExpanded); 182 return; 183 } 184 const menuItems = document.querySelectorAll(HamburgerMenu.selectors.hamburgerMenuWidget.hamburgerMenu + ' li'); 185 const fieldModel = this.formContainer?.getModel().getElement(targetElement?.getAttribute('data-panel-id')); 186 const elementID = this.#checkFirstNonPanel(fieldModel) || targetElement?.getAttribute('data-panel-id'); 187 188 const parentAnchorElement = targetElement?.querySelector('a'); 189 targetElement = menu.querySelector("[data-panel-id='"+ elementID + "']"); 190 this.#resetMenuItems(menuItems); 191 this.#activateCurrentItem(targetElement); 192 const anchorElement = targetElement?.querySelector('a'); 193 anchorElement?.classList.add(HamburgerMenu.cssClasse
193s.active); 194 anchorElement?.querySelector('button')?.classList?.toggle(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuCloseNavButton); 195 const isExpanded = anchorElement?.querySelector('button')?.getAttribute('aria-expanded') === 'true'; 196 anchorElement?.querySelector('button')?.setAttribute('aria-expanded', !isExpanded); 197 this.#updateSelectedPanelTitle(anchorElement, parentAnchorElement); 198 this.#highlightMenuTree(anchorElement, parentAnchorElement); 199 200 this.formContainer.getModel().getElement('accordion-9fbafbc6e6'); 201 202 const itemId = targetElement?.getAttribute('data-panel-id') || HamburgerMenu.activeItemId; 203 const form = this.formContainer?.getModel(); 204 const field = form?.getElement(itemId); 205 menu.style.display = menu.style.display === 'flex' ? 'none' : 'flex'; 206 this.#renderBreadCrumbs(menu); 207 if (form && field) { 208 form.setFocus(field); 209 } 210 } 211 212 #resetMenuItems(menuItems) { 213 menuItems.forEach(item => { 214 const subMenu = item.querySelector(HamburgerMenu.selectors.hamburgerMenuWidget.hamburgerSubMenu); 215 if (subMenu) { 216 subMenu.style.display = 'none'; 217 subMenu.setAttribute('aria-hidden', true); 218 } 219 const link = item.querySelector('a'); 220 if(link) { 221 link?.querySelector('button')?.classList.remove(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuCloseNavButton); 222 link?.querySelector('button')?.classList.add(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuOpenNavButton); 223 link?.classList.remove(HamburgerMenu.cssClasses.active, HamburgerMenu.cssClasses.activeParent); 224 link.style.fontWeight = 'normal'; 225 } 226 }); 227 } 228 229 #activateCurrentItem(currentItem) { 230 while (currentItem) { 231 const subMenu = currentItem.querySelector(HamburgerMenu.selectors.hamburgerMenuWidget.hamburgerSubMenu); 232 if (subMenu) { 233 subMenu.style.display = 'block'; 234 subMenu.setAttribute('aria-hidden', false); 235 } 236 currentItem = currentItem.parentElement.closest('li'); 237 } 238 } 239 240 #menuItemClickHandler(event, subMenu, li, link) { 241 event.preventDefault(); 242 if (li.getAttribute('data-panel-enabled') === 'false') { 243 return; 244 } 245 const expanded = link.getAttribute('aria-expanded') === 'true'; 246 link.setAttribute('aria-expanded', !expanded); 247 if (subMenu.style.display === 'flex' || subMenu.style.display === 'block') { 248 subMenu.style.display = 'none'; 249 subMenu.setAttribute('aria-hidden', true); 250 } else { 251 subMenu.style.display = 'flex'; 252 subMenu.setAttribute('aria-hidden', false); 253 } 254 } 255 256 #createDownArrowButton() { 257 const downArrowButton = document.createElement('button'); 258 downArrowButton.type='button'; 259 downArrowButton.classList.add(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuOpenNavButton); 260 downArrowButton.setAttribute('aria-expanded', false); 261 return downArrowButton; 262 } 263 264 #createHamburgerMenu(items, counter = 0) { 265 if (counter >= HamburgerMenu.nestingSupport) { 266 return; 267 } 268 if (!items?.length) return; 269 const ul = document.createElement('ul'); 270 let activeItemTitleUpdated = false; 271 items.forEach((item) => { 272 if (item?.fieldType !== "panel") return; 273 274 if (!activeItemTitleUpdated) { 275 const activeItemTitle = document.querySelector(HamburgerMenu.selectors.hamburgerMenuBottomContainer.hamburgerMenuActiveItemTitle); 276 if(activeItemTitle) { 277 activeItemTitle.innerText = item?.label?.value; 278 activeItemTitleUpdated = true; 279 } 280 } 281 282 const li = document.createElement('li'); 283 const link = document.createElement('a'); 284 link.setAttribute('role', 'menuitem'); 285 link.setAttribute('aria-expanded', 'false'); 286 const textSpan = document.createElement('span'); 287 textSpan.setAttribute('tabindex', "0"); 288 link.href = "#"; 289 textSpan.textContent = item?.label?.value; 290 link.appendChild(textSpan); 291 link.style.visibility = item?.label?.visible ? 'visible' : 'hidden'; 292 li.appendChild(link); 293 294 li.setAttribute('data-panel-id', item?.id); 295 li.setAttribute('data-panel-visible', item?.visible); 296 li.setAttribute('data-panel-enabled', item?.enabled); 297 const children = this.formContainer?.getModel()?.getElement(item.id)?._children; 298 let flag = false;
299 300 // setting an attibute(data-panel-has-input) if the item is having an input field 301 if(children) { 302 for(let i = 0; i< children.length; i++) { 303 if(children[i].fieldType !== 'panel') { 304 flag = true; 305 } 306 } 307 } 308 if(flag) { 309 li.setAttribute('data-panel-has-input', flag); 310 } 311 312 link.classList.add(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuNavLink); 313 if (item?.repeatable) { 314 const subMenu = this.#createHamburgerMenu(item.items, counter + 1); 315 subMenu?.childNodes.forEach(child => ul.appendChild(child)); 316 } else if (Array.isArray(item.items) && item.items.length > 0) { 317 const subMenu = this.#createHamburgerMenu(item.items, counter + 1); 318 if (subMenu?.childNodes?.length) { 319 subMenu.classList.add(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerSubMenu); 320 li.appendChild(subMenu); 321 link.insertBefore(this.#createDownArrowButton(), link.firstChild); 322 link.addEventListener('click', (event) => { 323 this.#menuItemClickHandler(event, subMenu, li, link) 324 }); 325 link.addEventListener('keydown', (event) => { 326 if(event.key === 'Enter' || event.key === ' ') { 327 this.#menuItemClickHandler(event, subMenu, li, link); 328 } 329 }); 330 } 331 } 332 ul.appendChild(li); 333 }); 334 335 return ul; 336 } 337 338 // Function to find the currently active li 339 #findActiveLi() { 340 return document.querySelector(HamburgerMenu.selectors.active).parentElement; 341 } 342 343 #highlightMenuTree(element, parentAnchorElement) { 344 const closestLI = element?.closest('li'); 345 const clickedClosestLI = parentAnchorElement?.closest('li'); 346 347 const li = closestLI || clickedClosestLI; 348 349 if (!li || li === document.body) { 350 return; 351 } 352 let anchorElement = li?.querySelector('a'); 353 354 if(anchorElement) { 355 anchorElement?.classList.add(HamburgerMenu.cssClasses.activeParent); 356 anchorElement?.querySelector('button')?.classList.add(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuCloseNavButton); 357 if(anchorElement?.querySelector('button')?.classList.contains(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenuCloseNavButton)) { 358 anchorElement?.querySelector('button')?.setAttribute('aria-expanded', true); 359 } 360 if(li.parentElement.classList.contains(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenu)) { 361 anchorElement.style.fontWeight = 'bold' 362 } 363 this.#highlightMenuTree(li.parentElement); 364 } 365 } 366 367 #isEligible(element, direction) { 368 if (element && element?.getAttribute('data-panel-visible') === 'false' || element?.getAttribute('data-panel-enabled') === 'false' || (direction === 'prev' && element?.getAttribute('data-panel-has-input') !== 'true')) { 369 return false; 370 } else if (element && element.parentNode && element.parentNode !== document) { 371 return this.#isEligible(element.parentNode); 372 } else { 373 return true; 374 } 375 } 376 377 #moveTo(menuListItems, direction) { 378 const currentActive = this.#findActiveLi(); 379 if (!currentActive) return; 380 381 let newActiveItemIndex = -1; 382 menuListItems.forEach((item, index) => { 383 if (item.getAttribute('data-panel-id') === currentActive.getAttribute('data-panel-id')) { 384 newActiveItemIndex = direction === 'prev' ? index - 1 : index + 1; 385 } 386 }); 387 388 if (direction === 'prev' && newActiveItemIndex < 0) { 389 newActiveItemIndex = menuListItems.length - 1; 390 } 391 while (!this.#isEligible(menuListItems[newActiveItemIndex], direction)) { 392 if(direction === 'prev') { 393 newActiveItemIndex = (newActiveItemIndex - 1) % menuListItems.length; 394 if(newActiveItemIndex<=0) { 395 newActiveItemIndex = 0; 396 break; 397 } 398 } else { 399 newActiveItemIndex = (newActiveItemIndex + 1) % menuListItems.length; 400 } 401 } 402 const newActiveItem = menuListItems[newActiveItemIndex]; 403 HamburgerMenu.activeItemId = newActiveItem?.getAttribute('data-panel-id'); 404 newActiveItem?.click(); 405 } 406 407 #movePrev(menuListItems) { 408 this.#moveTo(menuListItems, 'prev'); 409 } 410 411 #moveNext(menuListItems) { 412 this.#moveTo(menuListItems, 'next'); 413 } 414 415 #addEventsToNavigationButtons() { 416 const previousNavButton = document.querySelector(HamburgerMenu.selectors.hamburgerMenuBottomContainer.hamburgerMenuPreviousNavButton); 417 const nextNavButton = document.querySelector(HamburgerMenu.selectors.hamburgerMenuBottomContainer.hamburgerMenuNextNavButton); 418 const menuListItems = document.querySelector(HamburgerMenu.selectors.hamburgerMenuWidget.hamburgerMenu).querySelectorAll('li'); 419 previousNavButton.addEventListener('click', () => this.#movePrev(menuListItems)); 420 nextNavButton.addEventListener('click', () => this.#moveNext(menuListItems)); 421 } 422 423 #generateBreadcrumbs(breadcrumbs) { 424 const container = document.createElement('nav'); 425 container.setAttribute('aria-label', 'Breadcrumb'); 426 const list = document.createElement('ul'); 427 list.style.listStyleType = 'none'; 428 list.style.padding = '0'; 429 list.style.margin = '0'; 430 if(breadcrumbs && breadcrumbs.length) {
431 [...breadcrumbs].forEach((breadcrumb, index) => { 432 const listItem = document.createElement('li'); 433 listItem.style.display = 'inline'; 434 const span = document.createElement('span'); 435 span.textContent = breadcrumb.innerText; 436 listItem.appendChild(span); 437 if (index < breadcrumbs.length - 1) { 438 const separator = document.createElement('span'); 439 separator.textContent = ' > '; 440 separator.style.margin = '0 5px'; 441 listItem.appendChild(separator); 442 } 443 if(index === breadcrumbs?.length-1) { 444 listItem.style.fontWeight = 'bold'; 445 } 446 list.appendChild(listItem); 447 }); 448 } 449 container.appendChild(list); 450 return container; 451 } 452 453 #renderBreadCrumbs(menu) { 454 const selectedPanels = menu.getElementsByClassName(HamburgerMenu.cssClasses.activeParent); 455 const breadCrumbsContainer = document.querySelector(HamburgerMenu.selectors.hamburgerMenuMiddleContainer); 456 breadCrumbsContainer.innerHTML = ''; 457 const breadCrumbs = this.#generateBreadcrumbs(selectedPanels) 458 breadCrumbsContainer.appendChild(breadCrumbs); 459 breadCrumbsContainer.scrollLeft = breadCrumbs.scrollWidth; 460 } 461 462 #renderHamburgerItems(panels) { 463 const parentContainer = document.querySelector(HamburgerMenu.selectors.hamburgerMenuTopContainer.self); 464 const hamburgerIcon = document.querySelector(HamburgerMenu.selectors.hamburgerMenuTopContainer.hamburgerMenuIcon); 465 const hamburgerMenuIconContainer = document.querySelector(HamburgerMenu.selectors.hamburgerMenuTopContainer.hamburgerMenuIconContainer); 466 467 const menu = this.#createHamburgerMenu(panels); 468 if(menu) { 469 menu.classList.add(HamburgerMenu.cssClasses.hamburgerMenuWidget.hamburgerMenu); 470 menu.setAttribute('role', 'menu'); 471 menu.setAttribute('id', 'hamburger-menu'); 472 473 this.#attachHamburgerEventListeners(hamburgerIcon, menu); 474 this.#attachOutsideClickHandler(hamburgerIcon, menu); 475 this.#attachMenuEventListeners(menu); 476 this.#styleSubmenuItems(menu); 477 parentContainer.innerHTML=''; 478 parentContainer.appendChild(hamburgerMenuIconContainer); 479 parentContainer.appendChild(menu); 480 481 // Add events to navigation buttons 482 this.#addEventsToNavigationButtons(); 483 484 // Automatically click the first root list item if it exists 485 const rootListItems = menu.querySelectorAll(HamburgerMenu.selectors.hamburgerMenuWidget.hamburgerMenu + ' > li'); 486 if (rootListItems[0] && rootListItems[0].tagName === 'LI') { 487 rootListItems[0].click(); 488 menu.style.display = 'none'; 489 } 490 } 491 } 492 493 #attachMenuEventListeners(menu) { 494 menu.addEventListener('click', (event) => this.#clickHandler(event)); 495 menu.addEventListener('keydown', (event) => { 496 if (event.key === 'Enter' || event.key === ' ') { 497 event.preventDefault(); 498 this.#clickHandler(event); 499 } 500 }); 501 menu.addEventListener('ontouchstart', (event) => this.#clickHandler(event)); 502 } 503 504 #attachHamburgerEventListeners(hamburgerIcon, menu) { 505 const toggleMenuVisibility = () => { 506 menu.style.display = menu.style.display === 'flex' ? 'none' : 'flex'; 507 }; 508 hamburgerIcon?.addEventListener('click', toggleMenuVisibility); 509 hamburgerIcon?.addEventListener('ontouchstart', toggleMenuVisibility); 510 } 511 512 #styleSubmenuItems(menu) { 513 const rootListItems = menu.querySelectorAll(HamburgerMenu.selectors.hamburgerMenuWidget.hamburgerMenu + ' > li');
514 rootListItems.forEach((item) => { 515 let padding = 30; 516 const submenus = item.querySelectorAll(HamburgerMenu.selectors.hamburgerMenuWidget.hamburgerSubMenu); 517 submenus.forEach((submenu) => { 518 const links = submenu.querySelectorAll('a'); 519 links.forEach((link) => { 520 if(link.querySelector('button')) { 521 link.style.paddingInlineStart = `${padding}px`; 522 } else { 523 link.style.paddingInlineStart = `${padding + 30}px`; 524 } 525 }); 526 padding += 15; 527 }); 528 }); 529 } 530 531 #attachOutsideClickHandler(hamburger, menu) { 532 window.addEventListener('click', (e) => { 533 if (!hamburger.contains(e.target) && !menu.contains(e.target) && menu.style.display === 'flex') { 534 menu.style.display = 'none'; 535 } 536 }); 537 } 538 539 #getAllPanels() { 540 let items = this.formContainer?._model.getItemsState() || []; 541 const panels = items.filter(item => item?.fieldType === "panel"); 542 return panels; 543 } 544 545 init() { 546 if(this.formContainer?.getModel()?.properties?.['fd:isHamburgerMenuEnabled']) { 547 document.querySelector('.cmp-adaptiveform-container')?.setAttribute('data-cmp-hamburger-menu-enabled', 'true'); 548 const panels = this.#getAllPanels(); 549 this.#renderHamburgerItems(panels); 550 } 551 } 552 } 553} 554/******************************************************************************* 555 * Copyright 2024 Adobe 556 * 557 * Licensed under the Apache License, Version 2.0 (the "License"); 558 * you may not use this file except in compliance with the License. 559 * You may obtain a copy of the License at 560 * 561 * http://www.apache.org/licenses/LICENSE-2.0 562 * 563 * Unless required by applicable law or agreed to in writing, software 564 * distributed under the License is distributed on an "AS IS" BASIS, 565 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 566 * See the License for the specific language governing permissions and 567 * limitations under the License. 568 ******************************************************************************/ 569 570(function() { 571 572 "use strict"; 573 class FormContainerV2 extends FormView.FormContainer { 574 static NS = FormView.Constants.NS; 575 static IS = "adaptiveFormContainer"; 576 static bemBlock = 'cmp-adaptiveform-container'; 577 static selectors = { 578 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 579 }; 580 static loadingClass = `${FormContainerV2.bemBlock}--loading`; 581 #hamburgerMenuInstance = ''; 582 583 constructor(params) { 584 super(params); 585 let self = this; 586 this.#hamburgerMenuInstance = new HamburgerMenu(this); 587 // CoPA Customization - to add the loading class 588 const addLoadingClass = (formId) => { 589 const formContainer = document.querySelector(`[data-cmp-adaptiveform-container-loader='${formId}']`); 590 if (formContainer) { 591 formContainer.classList.add('cmp-adaptiveform-container--loading'); 592 } 593 }; 594 // CoPA Customization - to remove the loading class 595 const removeLoadingClass = (formId) => { 596 const formContainer = document.querySelector(`[data-cmp-adaptiveform-container-loader='${formId}']`); 597 if (formContainer) { 598 formContainer.classList.remove('cmp-adaptiveform-container--loading'); 599 } 600 }; 601 this._model.subscribe((action) => { 602 // CoPA Customization - only if there is no validation errors show the loading icon 603 if (action?.payload?.length === 0) { 604 if(document.getElementById("form-wizard-submit-button")!=undefined){ 605 document.getElementById("form-wizard-submit-button").setAttribute("style"," pointer-events: none;opacity: 0.4;"); 606 } 607 addLoadingClass(action.target.id); 608 } 609 }, "validationComplete"); 610 this._model.subscribe((action) => { 611 let state = action.target.getState(); 612 const errorMessage = document.getElementsByClassName('form-error-message')?.[0]; 613 if(errorMessage){ 614 errorMessage.remove(); 615 } 616 // CoPA Customization - execute the handler only if there are no rules configured on submitSuccess event. 617 if (!state.events.submitSuccess || state.events.submitSuccess.length === 0) { 618 const globals = { 619 form: self.getModel().getRuleNode(), 620 event: { 621 type: action.type, 622 payload: action.payload, 623 } 624 }; 625 // CoPA Customization - comment OOTB FormView.customFunctions. 626 // FormView.customFunctions.defaultSubmitSuccessHandler(globals); 627 const event = globals.event; 628 const submitSuccessResponse = event?.payload?.body; 629 const form = globals.form; 630 // CoPA Customization - Added submitSuccessResponse. 631 if (submitSuccessResponse) { 632 if (submitSuccessResponse.redirectUrl) { 633 // removeLoadingClass(self.getModel().id); 634 window.location.href = encodeURI(submitSuccessResponse.redirectUrl); 635 } else if (submitSuccessResponse.thankYouMessage) { 636 let formContainerElement = document.getElementById(`${form.$id}`); 637 let thankYouMessage = document.createElement("div"); 638 thankYouMessage.setAttribute("class", "tyMessage"); 639 thankYouMessage.setAttribute("tabindex", "-1"); 640 thankYouMessage.setAttribute("role","alertdialog"); 641 // Sanitize HTML for XSS A03:2021-Injection issue raised by security team. 642 thankYouMessage.innerHTML = DOMPurify.sanitize(submitSuccessResponse.thankYouMessage, { 643 ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'br', 'p', 'ul', 'ol', 'li', 'a', 'span'], 644 ALLOWED_ATTR: ['href', 'title', 'target', 'class'], 645 ALLOWED_URI_REGEXP: /^https?:|^mailto:|^tel:/ 646 }); 647 //thankYouMessage.innerHTML = submitSuccessResponse.thankYouMessage; 648 removeLoadingClass(self.getModel().id); 649 formContainerElement.replaceWith(thankYouMessage); 650 thankYouMessage.focus(); 651 } 652 } 653 } 654 }, "submitSuccess"); 655 this._model.subscribe((action) => { 656 // CoPA Customization - enable submit btn 657 if(document.getElementById("form-wizard-submit-button")!=undefined){ 658 document.getElementById("form-wizard-submit-button").setAttribute("style",""); 659 } 660 removeLoadingClass(self.getModel().id); 661 let state = action.target.getState(); 662 // execute the handler only if there are no rules configured on submitError event. 663 if (!state.events.submitError || state.events.submitError.length === 0) { 664 let defaultSubmissionError = FormView.LanguageUtils.getTranslatedString(self.getLang(), "InternalFormSubmissionError"); 665 const globals = { 666 form: self.getModel().getRuleNode(), 667 event: { 668 type: action.type, 669 payload: action.payload, 670 } 671 }; 672 // CoPA Customization - Show error message if form submission fails only for dgs form 673 if(window.location.href.includes('dgs/calendar')){ 674 const form = document.getElementsByClassName('cmp-adaptiveform-container')?.[0]; 675 const errorMessage = document.getElementsByClassName('form-error-message')?.[0]; 676 if(form && !errorMessage){ 677 const div = document.createElement('div'); 678 div.textContent = 'Some fields in the form contain incorrect or incomplete information. Please review your entries, correct any errors, and submit the form again'; 679 div.style.color ='red'; 680 div.classList.add('form-error-message'); 681 form.appendChild(div); 682 } 683 } 684 else { 685 FormView.customFunctions.defaultSubmitErrorHandler(defaultSubmissionError, globals); 686 } 687 } 688 }, "submitError"); 689 this._model.subscribe((action) => { 690 let state = action.target.getState(); 691 // execute the handler only if there are no rules configured on custom:saveSuccess event. 692 if (!state.events['custom:saveSuccess'] || state.events['custom:saveSuccess'].length === 0) { 693 console.log("Draft id = " + action?.payload?.body?.draftId); 694 window.alert(FormView.LanguageUtils.getTranslatedString(self.getLang(), "saveDraftSuccessMessage")); 695 } 696 }, "saveSuccess"); 697 this._model.subscribe((action) => { 698 let state = action.target.getState(); 699 // execute the handler only if there are no rules configured on custom:saveError event. 700 if (!state.events['custom:saveError'] || state.events['custom:saveError'].length === 0) { 701 window.alert(FormView.LanguageUtils.getTranslatedString(self.getLang(), "saveDraftErrorMessage")); 702 } 703 }, "saveError"); 704 this.#setupAutoSave(self.getModel()); 705 } 706 707 initialiseHamburgerMenu() { 708 this.#hamburgerMenuInstance.init(); 709 } 710 711 /** 712 * Register time based auto save 713 * @param formModel. 714 */ 715 #setupAutoSave(formModel) { 716 const autoSaveProperties = formModel?.properties?.['fd:autoSave']; 717 const enableAutoSave = this.#getAutoSaveAttribute(); 718 if (enableAutoSave) { 719 const autoSaveStrategyType = autoSaveProperties['fd:autoSaveStrategyType']; 720 const autoSaveInterval = autoSaveProperties['fd:autoSaveInterval']; 721 const saveEndPoint = FormView.Utils.getContextPath() + '/adobe/forms/af/save/' + formModel.id; 722 if (autoSaveStrategyType === 'time' && autoSaveInterval) { 723 console.log("Registering time based auto save"); 724 setInterval(() => { 725 formModel.dispatch(new FormView.Actions.Save({ 726 'action': saveEndPoint 727 })); 728 }, parseInt(autoSaveInterval) * 1000); 729 } 730 } 731 } 732 733 #getAutoSaveAttribute() { 734 return this.getFormElement()?.getAttribute('data-cmp-auto-save') === 'true'; 735 } 736 } 737 738 async function onDocumentReady() { 739 const startTime = new Date().getTime(); 740 let elements = document.querySelectorAll(FormContainerV2.selectors.self); 741 742 for (let i = 0; i < elements.length; i++) { 743 let loaderToAdd = document.querySelector("[data-cmp-adaptiveform-container-loader='"+ elements[i].id + "']"); 744 if(loaderToAdd){ 745 loaderToAdd.classList.add(FormContainerV2.loadingClass); 746 } 747 console.debug("Form loading started", elements[i].id); 748 } 749 function onInit(e) { 750 let formContainer = e.detail; 751 let formEl = formContainer.getFormElement(); 752 formContainer.initialiseHamburgerMenu(); 753 setTimeout(() => { 754 let loaderToRemove = document.querySelector("[data-cmp-adaptiveform-container-loader='"+ formEl.id + "']"); 755 if(loaderToRemove){ 756 loaderToRemove.classList.remove(FormContainerV2.loadingClass); 757 } 758 const timeTaken = new Date().getTime() - startTime; 759 console.debug("Form loading complete", formEl.id, timeTaken); 760 }, 10); 761 } 762 document.addEventListener(FormView.Constants.FORM_CONTAINER_INITIALISED, onInit); 763 await FormView.Utils.setupFormContainer(async ({ 764 _formJson, _prefillData, _path, _element 765 }) => { 766 let formContainer = new FormContainerV2({_formJson, _prefillData, _path, _element}); 767 // before initializing the form container load all the locale specific json resources 768 // for runtime 769 const formLanguage = formContainer.getLang(); 770 const aemLangUrl = `/etc.clientlibs/core/fd/af-clientlibs/core-forms-components-runtime-all/resources/i18n/${formLanguage}.json`; 771 await FormView.LanguageUtils.loadLang(formLanguage, aemLangUrl, true); 772 formContainer.subscribe(); 773 return formContainer; 774 }, FormContainerV2.selectors.self, FormContainerV2.IS); 775 } 776 777 // This is to ensure that the there is no WCM Mode cookie when Form Container is rendered. 778 // max-age=0 ensures that the cookie is deleted. 779 document.cookie="wcmmode=disabled; max-age=0; path=/"; 780 781 if (document.readyState !== "loading") { 782 onDocumentReady(); 783 } else { 784 document.addEventListener("DOMContentLoaded", onDocumentReady); 785 } 786})(); 787 788/******************************************************************************* 789 * Copyright 2023 Adobe 790 * 791 * Licensed under the Apache License, Version 2.0 (the "License");
792 * you may not use this file except in compliance with the License. 793 * You may obtain a copy of the License at 794 * 795 * http://www.apache.org/licenses/LICENSE-2.0 796 * 797 * Unless required by applicable law or agreed to in writing, software 798 * distributed under the License is distributed on an "AS IS" BASIS, 799 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 800 * See the License for the specific language governing permissions and 801 * limitations under the License. 802 ******************************************************************************/ 803(function() { 804 805 "use strict"; 806 class Cache { 807 808 store = {}; 809 810 put(el, key, value) { 811 this.store[el.id ] = {}; 812 this.store[el.id][key] = value; 813 } 814 815 get(el, key) { 816 return this.store[el.id][key]; 817 } 818 } 819 window.afCache = new Cache(); 820})(); 821 822/******************************************************************************* 823 * Copyright 2022 Adobe 824 * 825 * Licensed under the Apache License, Version 2.0 (the "License"); 826 * you may not use this file except in compliance with the License. 827 * You may obtain a copy of the License at 828 * 829 * http://www.apache.org/licenses/LICENSE-2.0 830 * 831 * Unless required by applicable law or agreed to in writing, software 832 * distributed under the License is distributed on an "AS IS" BASIS, 833 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 834 * See the License for the specific language governing permissions and 835 * limitations under the License. 836 ******************************************************************************/ 837(function() { 838 839 "use strict"; 840 class DatePicker extends FormView.FormFieldBase { 841 842 static NS = FormView.Constants.NS; 843 static IS = "adaptiveFormDatePicker"; 844 static bemBlock = 'cmp-adaptiveform-datepicker'; 845 static selectors = { 846 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 847 widget: `.${DatePicker.bemBlock}__widget`, 848 label: `.${DatePicker.bemBlock}__label`, 849 description: `.${DatePicker.bemBlock}__longdescription`, 850 qm: `.${DatePicker.bemBlock}__questionmark`, 851 errorDiv: `.${DatePicker.bemBlock}__errormessage`, 852 tooltipDiv: `.${DatePicker.bemBlock}__shortdescription` 853 }; 854 855 constructor(params) { 856 super(params); 857 } 858 859 getWidget() { 860 return this.element.querySelector(DatePicker.selectors.widget); 861 } 862 863 getDescription() { 864 return this.element.querySelector(DatePicker.selectors.description); 865 } 866 867 getLabel() { 868 return this.element.querySelector(DatePicker.selectors.label); 869 } 870 871 getErrorDiv() { 872 return this.element.querySelector(DatePicker.selectors.errorDiv); 873 } 874 875 getQuestionMarkDiv() { 876 return this.element.querySelector(DatePicker.selectors.qm); 877 } 878 879 getTooltipDiv() { 880 return this.element.querySelector(DatePicker.selectors.tooltipDiv); 881 } 882 883 updateValue(value) { 884 if (this.widgetObject) { 885 if (this.isActive()) { 886 // Replacing undefined / null with empty string on reset 887 this.widgetObject.setValue(value || ''); 888 } else { 889 // Replacing undefined / null with empty string on reset 890 this.widgetObject.setDisplayValue(value || ''); 891 } 892 } else { 893 // Replacing undefined / null with empty string on reset 894 super.updateValue(value || ''); 895 } 896 } 897 898 updateReadOnly(readOnly, state) { 899 super.updateReadOnly(readOnly, state); 900 if (this.widgetObject != null) { 901 this.widgetObject.markAsReadOnly(readOnly); 902 } 903 } 904 905 906 setModel(model) { 907 super.setModel(model); 908 if (!this.#noFormats()) { 909 if (this.widgetObject == null) { 910 this.widgetObject = new DatePickerWidget(this, this.getWidget(), model); 911 } 912 if (this.isActive()) { 913 this.widgetObject.setValue(model.value); 914 } else { 915 this.widgetObject.setDisplayValue(model.value); 916 } 917 this.widgetObject.addEventListener('blur', (e) => { 918 this.setModelValue(this.widgetObject.getValue()) 919 //setDisplayValue is required for cases where value remains same while focussing in and out. 920 this.widgetObject.setDisplayValue(this._model.value); 921 this.widgetObject.setCalendarWidgetValue(this._model.value); 922 this.setInactive(); 923 this.triggerExit(); 924 }, this.getWidget()); 925 this.widgetObject.addEventListener('focus', (e) => { 926 this.widgetObject.setValue(e.target.value); 927 this.setActive(); 928 this.triggerEnter(); 929 }, this.getWidget()); 930 this.widgetObject.addEventListener('input', (e) => { 931 if( e.target.value === '') { 932 // clear the value if user manually empties the value in date input box 933 this.setModelValue(""); 934 } 935 }, this.getWidget()); 936 } else { 937 if (this.widget.value !== '') { 938 this.setModelValue(this.widget.value); 939 } 940 this.widget.addEventListener('blur', (e) => { 941 this.setModelValue(e.target.value); 942 this.setInactive(); 943 this.triggerExit(); 944 }); 945 this.widget.addEventListener('focus', (e) => { 946 this.setActive(); 947 this.triggerEnter(); 948 }); 949 } 950 } 951 952 #noFormats() { 953 return (this._model.editFormat == null || this._model.editFormat === 'date|short') && 954 (this._model.displayFormat == null || this._model.displayFormat === 'date|short') && (this._model.displayValueExpression == null) 955 } 956 } 957 958 FormView.Utils.setupField(({element, formContainer}) => { 959 return new DatePicker({element, formContainer}) 960 }, DatePicker.selectors.self); 961})(); 962 963/******************************************************************************* 964 * Copyright 2023 Adobe 965 * 966 * Licensed under the Apache License, Version 2.0 (the "License");
967 * you may not use this file except in compliance with the License. 968 * You may obtain a copy of the License at 969 * 970 * http://www.apache.org/licenses/LICENSE-2.0 971 * 972 * Unless required by applicable law or agreed to in writing, software 973 * distributed under the License is distributed on an "AS IS" BASIS, 974 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 975 * See the License for the specific language governing permissions and 976 * limitations under the License. 977 ******************************************************************************/ 978 979if (typeof window.DatePickerWidget === 'undefined') { 980 981 window.DatePickerWidget = class { 982 983 #widget = null; 984 #model = null // passed by reference 985 #options = null 986 987 #lang = "en"; 988 989 #dp = null; 990 #curInstance = null; 991 #calendarIcon = null; 992 #documentTouchListener = null; 993 static #visible = false; 994 static #clickedWindow; 995 996 /** default configuration options 997 * 998 * yearsPerView: number of years to show in the yearset view 999 * 1000 * width: with of the widget 1001 * 1002 * viewHeight: Height of the month,year and yearset view. This doesn't include 1003 * the height of the header 1004 * 1005 * locale: locale information for the locale in which to show the datepicker which comprises of 1006 * days: day names to display in the monthview 1007 * months: month names to display in the yearview 1008 * zero: string representation of zero in the locale. Numbers will be 1009 * displayed in that locale only 1010 * clearText: Text to display for the reset button 1011 * name: name of the locale 1012 * 1013 * format: input format for the datepicker (not implemented) 1014 * 1015 * pickerType: type of the datetimepicker (date, datetime and time) 1016 * 1017 * positioning: element around which datepicker will be displayed. if null then it 1018 * will be displayed around the input element 1019 * 1020 * showCalendarIcon: to show the Calendar on the right of the text field or not 1021 */ 1022 #defaultOptions = { 1023 yearsPerView: 16, 1024 width: 340, 1025 viewHeight: 248, 1026 locale: { 1027 days: ["S","M","T","W","T","F","S"], 1028 months: ["January","February","March","April","May","June","July","August","September","October","November","December"], 1029 zero: "0", 1030 clearText: "Clear", 1031 name: "en_US" 1032 }, 1033 format: "YYYY-MM-DD", 1034 pickerType: "date", 1035 positioning: null, 1036 showCalendarIcon: true 1037 } 1038 1039 #dates = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] 1040 /* 1041 * Actions to perform when clicked on the datepicker buttons 1042 * for different views 1043 * caption: view to show when clicked on caption 1044 * (Year/YearSet/Month/null) null means don't change the view 1045 * li: view to show when clicked on date, month or year element 1046 * upDown: add(up key) or subtract(down key) current date (for monthview), 1047 * month(Year View) or year(YearSetView) with the number provided 1048 * key: identifies the key that needs to be changed for that view 1049 */ 1050 #viewAction = { 1051 Month: { 1052 caption: 'Year', 1053 li: null, 1054 key: "day", 1055 upDown: 7 1056 }, 1057 Year: { 1058 caption: "Yearset", 1059 li: "Month", 1060 key: "month", 1061 upDown: 3 1062 }, 1063 Yearset: { 1064 caption: null, 1065 li: "Year", 1066 key: "year", 1067 upDown: 4 1068 } 1069 } 1070 1071 selectedDay = 0; 1072 selectedMonth = 0; 1073 selectedYear = 0; 1074 currentDay = 0; 1075 currentMonth = 0; 1076 currentYear = 0; 1077 //view="Month"; 1078 #touchSupported = !!("ontouchstart" in window || window.DocumentTouch 1079 && document instanceof DocumentTouch); 1080 #defaultView = "Month"; 1081 #keysEnabled = false; 1082 #focusedOnLi = false; 1083 #keyboardAccessibility = true; 1084 #scriptFocus; 1085 1086 /* template for the clear Button */ 1087 #clearButtonTemplate = '<div class="dp-clear">' + 1088 '<a></a>' + 1089 '</div>'; 1090 1091 /* template for the calendar 1092 * header contains the navigation icons (left and right arrows) 1093 * and the current caption (which can be date, year or month) 1094 * 1095 * monthview displays the grid for showing the dates for a particular 1096 * month 1097 * 1098 * yearview displays all the months of that year 1099 * 1100 * yearsetview displays a grid of 16 years. This can be configured
1101 * through the option: yearsPerView 1102 * 1103 */ 1104 #calendarTemplate = '<div class="dp-header">' + 1105 '<div class="dp-leftnav"></div>' + 1106 '<div class="dp-caption"></div>' + 1107 '<div class="dp-rightnav"></div>' + 1108 '</div>' + 1109 '<div class="view dp-monthview"></div>' + 1110 '<div class="view dp-yearview"></div>' + 1111 '<div class="view dp-yearsetview"></div>'; 1112 1113 constructor(view, widget, model) { 1114 this.#model = model; 1115 this.#lang = view.getModel().lang; 1116 let editValFn = () => { 1117 return model.editValue; 1118 }; 1119 let displayValueFn = () => { 1120 return model.displayValue; 1121 }; 1122 this.#localizeDateElements(this.#defaultOptions, this.#lang); 1123 this.#options = Object.assign( 1124 {editValue: editValFn, displayValue: displayValueFn}, 1125 this.#defaultOptions, this.#model._jsonModel); 1126 1127 this.#initialiseCalenderElement(); 1128 1129 //update widget markup to have input type=text element. 1130 let newDatePickerElement = widget.cloneNode(true); 1131 newDatePickerElement.setAttribute("type", "text"); 1132 newDatePickerElement.id = model.id + '-widget'; 1133 1134 widget.parentNode.replaceChild(newDatePickerElement, widget); 1135 this.#widget = view.getWidget(); 1136 this.#attachField(view.getWidget(), this.#options); 1137 } 1138 1139 #initialiseCalenderElement() { 1140 let self = this, 1141 html = ""; 1142 if (this.#options.pickerType.match(/date/)) { 1143 html += this.#calendarTemplate; 1144 } 1145 html += this.#clearButtonTemplate; 1146 1147 if (!this.#dp) { 1148 this.#dp = document.createElement("div"); 1149 this.#dp.classList.add("datetimepicker", "datePickerTarget"); 1150 this.#dp.innerHTML = html; 1151 //Always inserting it in body 1152 document.body.appendChild(this.#dp); 1153 } 1154 // attach click event on entire datePicker popup 1155 this.#dp.addEventListener("click", 1156 function (evnt) { 1157 //focus only if the device doesn't support touch 1158 // input otherwise on screen keyboard will popup 1159 if (!self.#touchSupported) { 1160 if (self.#curInstance) { 1161 self.#curInstance.$field.focus(); 1162 } 1163 } 1164 }, false); 1165 "touchstart mousedown".split(" ").forEach(function (e) { 1166 self.#dp.addEventListener(e, function (evt) { 1167 self.#checkWindowClicked(evt) 1168 }, false); 1169 }); 1170 1171 this.$month = this.#dp.getElementsByClassName("dp-monthview")[0]; 1172 this.$year = this.#dp.getElementsByClassName("dp-yearview")[0]; 1173 this.$yearset = this.#dp.getElementsByClassName("dp-yearsetview")[0]; 1174 1175 this.clear = this.#dp.getElementsByClassName( 1176 "dp-clear")[0].getElementsByTagName("a")[0]; 1177 this.clear.addEventListener("click", function (evnt) { 1178 if (self.view && self.#curInstance) { 1179 self.#clearDate(self.view); 1180 } 1181 }); 1182 this.prevNavWidthBtn = this.#dp.getElementsByClassName("dp-leftnav")[0]; 1183 this.prevNavWidthBtn.addEventListener("click", 1184 function (evnt) { 1185 if (self.view && self.#curInstance) { 1186 self.#adjustDate(-1, self.view, false) 1187 } 1188 }); 1189 this.nextNavWidthBtn = this.#dp.getElementsByClassName("dp-rightnav")[0]; 1190 this.nextNavWidthBtn.addEventListener("click", 1191 function (evnt) { 1192 if (self.view && self.#curInstance) { 1193 self.#adjustDate(1, self.view, false) 1194 } 1195 }); 1196 this.caption = this.#dp.getElementsByClassName("dp-caption")[0]; 1197 this.caption.addEventListener("click", 1198 function (evnt) { 1199 if (self.view && self.#curInstance) { 1200 if (!self.caption.classList.contains("disabled")) { 1201 self.#layout(self.#viewAction[self.view].caption); 1202 } 1203 } 1204 }); 1205 if (this.#keyboardAccessibility) { 1206 [this.prevNavWidthBtn, this.caption, this.nextNavWidthBtn, 1207 this.clear].forEach(function (elem, i) { 1208 elem.setAttribute("tabIndex", i + 1); 1209 }); 1210 } 1211 1212 } 1213 1214 /* 1215 * attaches the date picker to the field. This is a one time operation 1216 * First creates a configuration object and stores it in the field data attributes 1217 * then attaches event handlers on click, focus (to show the picker) and blur
1217(to hide) events 1218 */ 1219 #attachField(widget, options) { 1220 let inst = this.#newInst(widget, options), 1221 self = this, 1222 activateField = function (evnt) { 1223 if (!self.#curInstance) { 1224 self.#activateField(evnt); 1225 } 1226 1227 if (self.#options.showCalendarIcon) { 1228 if (evnt.type === self.#getEvent()) { 1229 if (self._iconClicked) { 1230 self._iconClicked = false; 1231 if (DatePickerWidget.#visible) { 1232 self.#hide(); // hide the calendar popup if visible when calendar icon is clicked 1233 self.#curInstance.$field.focus(); // bring back focus in field 1234 } else { 1235 self.#show(); //// show the calendar popup if not visible when calendar icon is clicked 1236 } 1237 } 1238 } 1239 } else { 1240 /*show the popup only if 1241 1. click/touch event 1242 2. focus event in case of non-touch devices and focus is not done using script 1243 */ 1244 if (evnt.type === self.#getEvent() || (evnt.type === "focus" 1245 && !self.#touchSupported && !self.#scriptFocus)) { 1246 self.#show(evnt); 1247 } 1248 } 1249 1250 DatePickerWidget.#clickedWindow = true; 1251 self.#scriptFocus = false; 1252 }, 1253 deactivateField = function (evnt) { 1254 //deactivate only if clicked outside window 1255 // on touch devices only keyboard or calendar should be active at once, touching keyboard should deactivate calendar 1256 if ((DatePickerWidget.#clickedWindow && !self.#focusedOnLi) 1257 && (self.#options.showCalendarIcon || !self.#touchSupported)) { 1258 self.#hide(); 1259 self.#deactivateField(); 1260 DatePickerWidget.#clickedWindow = true; 1261 } 1262 }; 1263 1264 window.afCache.put(widget, "datetimepicker", inst); 1265 1266 widget.addEventListener(this.#getEvent(), activateField); 1267 widget.onfocus = activateField; 1268 widget.onblur = deactivateField; 1269 1270 if (options.showCalendarIcon) { 1271 let existingCalendarIcons = widget.parentNode.querySelectorAll('.cmp-adaptiveform-datepicker__calendar-icon'); 1272 existingCalendarIcons.forEach(icon => icon.remove()); 1273 1274 let calendarIcon = document.createElement("div"); 1275 calendarIcon.classList.add("cmp-adaptiveform-datepicker__calendar-icon"); 1276 1277 widget.parentNode.insertBefore(calendarIcon, widget.nextSibling); 1278 1279 if (this.#keyboardAccessibility) { 1280 calendarIcon.setAttribute("tabindex", 0); 1281 } 1282 calendarIcon.addEventListener(this.#getEvent(), function (evnt) { 1283 self._iconClicked = true; 1284 widget.click(); 1285 }); 1286 calendarIcon.addEventListener("keydown", function (event) { 1287 if (event.keyCode === 32 || event.keyCode === 13) { 1288 event.preventDefault(); 1289 event.stopPropagation(); 1290 self._iconClicked = true; 1291 widget.click(); 1292 } 1293 }); 1294 this.#calendarIcon = calendarIcon; 1295 if (options.readOnly) { 1296 this.markAsReadOnly(true) 1297 } 1298 } 1299 } 1300 1301 markAsReadOnly(readonly) { 1302 if (readonly) { 1303 this.#calendarIcon.style.display = "none"; 1304 } else { 1305 this.#calendarIcon.style.display = ""; 1306 } 1307 } 1308 1309 #newInst(widget, options) { 1310 return { 1311 $field: widget, 1312 locale: options.locale, 1313 positioning: options.positioning || widget, 1314 access: options.access, 1315 selectedDate: options.value, 1316 editValue: options.editValue, 1317 displayValue: options.displayValue, 1318 minValidDate: options.minimum, 1319 maxValidDate: options.maximum, 1320 exclMinDate: options.exclusiveMinimum, 1321 exclMaxDate: options.exclusiveMaximum 1322 } 1323 } 1324 1325 /* 1326 * To check where the click happened, if happened outside the datepicker 1327 * then hide the picker. This is checked whether any ancestor of clicked target 1328 * has a class datePickerTarget. This class is added to the attached element as well 1329 */ 1330 #checkWindowClicked(evnt) { 1331 let self = this; 1332 if (self.#curInstance) { 1333 // datepickerTarget class depicts that the component is a part of the Date Field 1334 // and on click of that class, we should not hide the datepicker or fire exit events. 1335 if (!evnt.target.closest(".datePickerTarget")) { 1336 //non-touch devices do not deactivate on blur. Hence needs to be done here 1337 if (self.#touchSupported) { 1338 self.#hide(); 1339 //clicking outside a field doesn't blur the field in IPad. Doing it by script 1340 self.#curInstance.$field.blur(); 1341 self.#deactivateField(); 1342 } else { 1343 DatePickerWidget.#clickedWindow = true; 1344 } 1345 } else { 1346 DatePickerWidget.#clickedWindow = false;
1347 } 1348 } 1349 } 1350 1351 /* 1352 * handling of key strokes. All the key strokes prevent the default browser action 1353 * unless specified otherwise 1354 * tab: set focus on calendar icon when dateinput field is active, navigates through date picker buttons when datepicker is open, 1355 * otherwise perform default browser action 1356 * escape: hides the datepicker 1357 * down arrow key: navigate the picker downwards by the number specified in actionView.upDown of the current View 1358 * up arrow key: navigate the picker upwards by the number specified in actionView.upDown of the current View 1359 * left arrow key: navigate the picker one unit of that view backward 1360 * right arrow key: navigate the picker one unit of that view forward 1361 * shift + up: perform the action that happens on clicking the caption (as specified in actionView.caption) 1362 * shift + left: perform the action that happens on clicking the left navigation button 1363 * shift + right: perform the action that happens on clicking the right navigation button 1364 * space/enter: triggers the click event for the current focused element from datepicker/ opens datepicker when calendar icon is focused. 1365 */ 1366 #hotKeys(evnt) { 1367 var handled = false, date; 1368 switch (evnt.keyCode) { 1369 case 9: //tab 1370 // CQ-4239352 : Setting clickedWindow property to true on tabbing so that deactivateField logic gets executed 1371 // When clicking on "x" on input field in in IE and when selecting the content and releasing the mouse select outside the field 1372 // the click event is not trigerred on the field and hence activateField is not executed, so clickedWindow remains as false 1373 DatePickerWidget.#clickedWindow = true; 1374 handled = false; 1375 break; 1376 case 27://escape 1377 if (DatePickerWidget.#visible) { 1378 this.#hide(); 1379 this.#curInstance.$field.focus(); 1380 this.#deactivateField(); 1381 handled = true; 1382 } 1383 break; 1384 case 32: //space 1385 case 13: // enter 1386 if (evnt.target.classList.contains("cmp-adaptiveform-datepicker__calendar-icon")) { 1387 if (!DatePickerWidget.#visible) { 1388 this.#show(); 1389 handled = true; 1390 } else { 1391 this.$focusedDate.classList.add("dp-focus"); 1392 handled = true; 1393 } 1394 } 1395 break; 1396 case 40: //down arrow key 1397 if (!DatePickerWidget.#visible) { 1398 this.#show(); 1399 return; 1400 } 1401 this.$focusedDate.classList.add("dp-focus"); 1402 break; 1403 } 1404 1405 if (DatePickerWidget.#visible && this.#keysEnabled) { 1406 var v = this.#viewAction[this.view].key, 1407 updown = this.#viewAction[this.view].upDown; 1408 switch (evnt.keyCode) { 1409 case 9: // tab 1410 if (evnt.shiftKey) { 1411 if (evnt.target.classList.contains("dp-leftnav") 1412 || evnt.target.classList.contains("dp-focus")) { 1413 this.#hide(); 1414 this.#curInstance.$field.focus(); 1415 handled = true; 1416 } else { 1417 handled = false; 1418 } 1419 } else { 1420 const buttonTabindex = evnt.target.getAttribute("tabindex"); 1421 if (buttonTabindex === '0') { 1422 if (evnt.target.tagName.toLocaleLowerCase() === "input") { 1423 this.#hide(); 1424 handled = false; 1425 } else { 1426 this.prevNavWidthBtn.focus(); 1427 handled = true; 1428 } 1429 } else if (buttonTabindex === '4') { 1430 this.#hide(); 1431 this.#curInstance.$field.focus(); 1432 handled = true; 1433 } else { 1434 handled = false; 1435 } 1436 } 1437 break; 1438 case 32: //select on space 1439 case 13: // select on enter 1440 this.hotKeyPressed = true; 1441 this.#focusedOnLi = false; 1442 if (!this.#focusedOnLi) { 1443 evnt.target.click(); 1444 } else { 1445 if (this.$focusedDate) { 1446 this.$focusedDate.click() //todo 1447 } 1448 } 1449 this.hotKeyPressed = false;
1450 handled = true; 1451 break; 1452 case 37: //left arrow key 1453 if (evnt.shiftKey) { 1454 this.prevNavWidthBtn.click(); 1455 } else { 1456 this.#adjustDate(-1, v, true); 1457 } 1458 handled = true; 1459 break; 1460 case 38: //up arrow key 1461 if (evnt.shiftKey) { 1462 this.caption.click(); 1463 } else { 1464 this.#adjustDate(-updown, v, true); 1465 } 1466 handled = true; 1467 break; 1468 case 39: //right arrow key 1469 if (evnt.shiftKey) { 1470 this.nextNavWidthBtn.click(); 1471 } else { 1472 this.#adjustDate(+1, v, true); 1473 } 1474 handled = true; 1475 break; 1476 case 40: //down arrow key 1477 this.#adjustDate(updown, v, true); 1478 handled = true; 1479 break; 1480 default: 1481 } 1482 } 1483 if (handled) { 1484 evnt.preventDefault(); 1485 } 1486 } 1487 1488 /* 1489 * show the datepicker. //TODO: migrate this to vanilla js 1490 */ 1491 #show() { 1492 this.#options.locale = this.#curInstance.locale; 1493 if (!DatePickerWidget.#visible) { 1494 let date = new Date(), 1495 validDate, 1496 parsedDate; 1497 if (this.#curInstance.selectedDate) { 1498 validDate = this.#curInstance.selectedDate; 1499 } else if (this.#model.valid) { 1500 validDate = this.#model.value; 1501 } 1502 if (validDate) { 1503 parsedDate = validDate ? new Date(validDate) : null; 1504 date = (parsedDate == null || parsedDate == 'Invalid Date') ? date : parsedDate; 1505 } 1506 const timezoneOffset = date.getTimezoneOffset(); 1507 date.setMinutes(date.getMinutes() + timezoneOffset); 1508 this.selectedDay = this.currentDay = date.getDate(); 1509 this.selectedMonth = this.currentMonth = date.getMonth(); 1510 this.selectedYear = this.currentYear = date.getFullYear(); 1511 this.maxValidDate = this.#options.maximum ? new Date( 1512 this.#curInstance.maxValidDate) : null; 1513 this.minValidDate = this.#options.minimum ? new Date( 1514 this.#curInstance.minValidDate) : null; 1515 this.exclMaxDate = this.#curInstance.exclMaxDate; 1516 this.exclMinDate = this.#curInstance.exclMinDate; 1517 this.#dp.getElementsByClassName("dp-clear")[0].getElementsByTagName( 1518 "a")[0].innerText = this.#options.locale.clearText; 1519 this.#layout(this.#defaultView); 1520 this.#dp.style.display = "flex"; 1521 this.#focusedOnLi = false; 1522 DatePickerWidget.#visible = true; 1523 this.#position(); 1524 1525 // Add document touch listener for mobile to close datepicker when tapping outside 1526 if (this.#touchSupported && !this.#documentTouchListener) { 1527 this.#documentTouchListener = (evt) => { 1528 if (DatePickerWidget.#visible && this.#curInstance) { 1529 this.#checkWindowClicked(evt); 1530 } 1531 }; 1532 document.addEventListener("touchstart", this.#documentTouchListener, false); 1533 } 1534 1535 if (this.#options.showCalendarIcon) { 1536 this.#curInstance.$field.setAttribute('readonly', true); // when the datepicker is active, deactivate the field 1537 } 1538 } 1539 1540 // Disabling the focus on ipad due to a bug where value of 1541 // date picker is not being set 1542 // Removing this code will only hamper one use case 1543 // where on ipad if you click on the calander then 1544 // the field becomes read only so 1545 // there is no indication where the current focus is 1546 // And if you remove this foucs code all together 1547 // then what happens is that on desktop MF in iframe the exit event 1548 // is not getting called hence calander getting remained open even 1549 // when you click somewhere on window or focus into some other field 1550 if (this.#options.showCalendarIcon && !this.#touchSupported) { 1551 this.#curInstance.$field.focus(); // field loses focus after being marked readonly, causing blur event not to be fired later 1552 } 1553 } 1554 1555 /* 1556 * position the datepicker around the positioning element //TODO: migrate this to vanilla js 1557 * provided in the options 1558 */ 1559 #position() { 1560 let $elem = this.#curInstance.positioning, 1561 windowScrollX = window.scrollX, 1562 windowScrollY = window.scrollY, 1563 windowInnerHeight = window.innerHeight, 1564 windowInnerWidth = window.innerWidth, 1565 inputRect = $elem.getBoundingClientRect(), 1566 height = $elem.offsetHeight, 1567 top = this.#getOffset($elem).top + height, 1568 left = this.#getOffset($elem).left, 1569 styles = {"top": (top + "px"), "left": (left + "px")}, 1570 diffBottom = top + this.#dp.offsetHeight - windowInnerHeight - windowScrollY, //this.#dp.offsetHeight is the widget's height 1571 newLeft, 1572 newTop; 1573 if (diffBottom > 0) { 1574 //can't appear at the bottom 1575 //check top 1576 newTop = top - height - this.#dp.offsetHeight - 20; 1577 if (newTop < windowScrollY) { 1578 //can't appear at the top as well ... the datePicker pop up overlaps the date field 1579 newTop = top - diffBottom; 1580 } 1581 styles.top = newTop + "px"; 1582 } 1583 if (left + this.#dp.offsetWidth > windowScrollX + windowInnerWidth) { 1584 //align with the right edge 1585 newLeft = windowScrollX + windowInnerWidth - this.#dp.offsetWidth - 20; 1586 styles.left = newLeft + "px"; 1587 } 1588 this.#dp.style.top = styles.top; 1589 this.#dp.style.left = styles.left; 1590 const localeObj = new Intl.Locale(this.#lang); 1591 if(localeObj?.textInfo?.direction == "rtl") { 1592 let right = windowInnerWidth - (left + inputRect.width); // Calculate right offset 1593 if (right + this.#dp.offsetWidth > windowInnerWidth) { // this.#dp.offsetWidth is the widget's width 1594 // Align with the right edge of the viewport 1595 right = windowScrollX + windowInnerWidth - this.#dp.offsetWidth - 20;
1595 // Adjust with a 20px margin 1596 } 1597 this.#dp.style.right = right + "px"; 1598 this.#dp.style.left = "unset" 1599 } 1600 return this; 1601 } 1602 1603 #getOffset(elem) { 1604 let box = elem.getBoundingClientRect(); 1605 return { 1606 top: box.top + window.scrollY, 1607 left: box.left + window.scrollX 1608 }; 1609 } 1610 1611 /* 1612 * layout the nextView. if nextView is null return 1613 * 1614 */ 1615 #layout(nextView) { 1616 if (nextView == null) { 1617 this.#hide(); 1618 } else { 1619 if (this.view) { 1620 this['$' + this.view.toLowerCase()].style.display = "none"; 1621 } 1622 this.view = nextView; 1623 this.caption.classList.toggle("disabled", 1624 !this.#viewAction[this.view].caption); 1625 this['$' + this.view.toLowerCase()].style.display = "block"; 1626 this["show" + this.view](); 1627 } 1628 return this; 1629 } 1630 1631 /* 1632 * show the month view 1633 */ 1634 showMonth() { 1635 var self = this, 1636 curDate = new Date(this.currentYear, this.currentMonth), 1637 maxDay = this.#maxDate(this.currentMonth), 1638 prevMaxDay = this.#maxDate((this.currentMonth + 11) % 12), 1639 day1 = new Date(this.currentYear, this.currentMonth, 1).getDay(), 1640 data, display; 1641 var localizedYear = this.#getLocalizedYear(curDate); 1642 1643 this.#tabulateView( 1644 { 1645 caption: this.#options.locale.months[this.currentMonth] + ", " 1646 + this.#convertNumberToLocale(localizedYear), 1647 header: this.#options.locale.days, 1648 numRows: 7, 1649 numColumns: 7, 1650 elementAt: function (row, col) { 1651 var day = (row - 1) * 7 + col - day1 + 1; 1652 var monthVal = self.currentMonth + 1; 1653 let gridId = "day-" + day; 1654 display = self.#convertNumberToLocale(day); 1655 data = day; 1656 if (day < 1) { 1657 display = self.#convertNumberToLocale(prevMaxDay + day); 1658 data = -1; 1659 monthVal = self.currentMonth; 1660 } else if (day > maxDay) { 1661 display = self.#convertNumberToLocale(day - maxDay); 1662 data = -1; 1663 monthVal = self.currentMonth + 2; 1664 } else { 1665 curDate.setDate(day); 1666 // check if the currentdate is valid based on max and min valid date 1667 if (self.#compareVal(curDate, self.maxValidDate, 1668 self.exclMaxDate) || self.#compareVal(self.minValidDate, 1669 curDate, self.exclMinDate)) { 1670 data = -1; 1671 } 1672 } 1673 return { 1674 data: data, 1675 gridId: gridId, 1676 display: display, 1677 ariaLabel: self.#options.editValue( 1678 self.currentYear + "-" + self.#pad2(monthVal) 1679 + "-" + self.#pad2(display)) 1680 }; 1681 } 1682 }); 1683 } 1684 1685 /**
1686 * returns boolean based on val1, val2, checkEqual 1687 * For comparing date, use date object 1688 */ 1689 #compareVal(val1, val2, checkEqual) { 1690 if (!val1 || !val2) { 1691 return false; 1692 } 1693 1694 if (checkEqual) { 1695 return val1 >= val2; 1696 } else { 1697 return val1 > val2; 1698 } 1699 } 1700 1701 /* 1702 * show the year view 1703 */ 1704 showYear() { 1705 var self = this, 1706 minDate = this.minValidDate ? new Date( 1707 this.minValidDate.getFullYear(), this.minValidDate.getMonth()) 1708 : null, 1709 maxDate = this.maxValidDate ? new Date( 1710 this.maxValidDate.getFullYear(), this.maxValidDate.getMonth()) 1711 : null, 1712 curDate = new Date(this.currentYear, 0), //can't omit month, if only one param present it is treated as millisecond 1713 data, 1714 month; 1715 var localizedYear = this.#getLocalizedYear(curDate); 1716 this.#tabulateView( 1717 { 1718 caption: this.#convertNumberToLocale(localizedYear), 1719 numRows: 4, 1720 numColumns: 3, 1721 elementAt: function (row, col) { 1722 data = month = row * 3 + col; 1723 let gridId = "month-" + data; 1724 curDate.setMonth(month); 1725 if ((minDate && curDate < minDate) || (maxDate && curDate 1726 > maxDate)) { 1727 data = -1; 1728 } 1729 return { 1730 data: data, 1731 gridId: gridId, 1732 display: self.#options.locale.months[month], 1733 ariaLabel: self.#options.locale.months[month] + " " 1734 + self.currentYear 1735 }; 1736 } 1737 }); 1738 } 1739 1740 #getLocalizedYear(date) { 1741 /* 1742 // Only Thai language return year according to Buddhist calendar, rest all languages follows gregorian calendar in practice. 1743 // The Buddhist Year in 2024 = 543 + 2024 = B.E. 2567 (reference https://wesak.org.my/calculating-b-e/) 1744 // Intl.DateTimeFormat#formatToParts returns number (2024) for all languages except for Thai (2567) & for Persian ('Û±Û´Û°Û³') 1745 // For Persian ('Û±Û´Û°Û³'), returned year is not in numbers that is breaking next flow. 1746 */ 1747 if(this.#lang === 'th') { 1748 const dateFormat = new Intl.DateTimeFormat(this.#lang, { 1749 year: 'numeric' 1750 }); 1751 const dateParts = dateFormat.formatToParts(date); 1752 const yearObject = dateParts.find(yearObject => yearObject.type === "year"); 1753 const localizedYear = yearObject.value; 1754 return Number(localizedYear); 1755 } 1756 else { 1757 return Number(date.getFullYear()); 1758 } 1759 } 1760 1761 /* 1762 * show the year set view 1763 */ 1764 showYearset() { 1765 var year, 1766 minDate = this.minValidDate ? new Date( 1767 this.minValidDate.getFullYear(), 0) : null, 1768 maxDate = this.maxValidDate ? new Date( 1769 this.maxValidDate.getFullYear() + 1, 0) : null, 1770 curDate = new Date(), 1771 data, 1772 self = this; 1773 var localizedYear = this.#getLocalizedYear(new Date(this.currentYear, 0)), 1774 localizedYearSet = this.#getLocalizedYear(new Date(self.currentYear, 0)); 1775 1776 this.#tabulateView( 1777 { 1778 caption: this.#convertNumberToLocale( 1779 localizedYear - this.#options.yearsPerView / 2) + "-" 1780 + this.#convertNumberToLocale( 1781 localizedYear - this.#options.yearsPerView / 2 1782 + this.#options.yearsPerView - 1), 1783 numRows: 4, 1784 numColumns: 4, 1785 elementAt: function (row, col) { 1786 data = year = localizedYearSet - 8 + (row * 4 + col); 1787 let gridId = "year-" + data; 1788 curDate.setFullYear(year); 1789 if ((minDate && curDate < minDate) || (maxDate && curDate 1790 > maxDate)) { 1791 data = -1; 1792 } 1793 return { 1794 "data": data, 1795 "gridId": gridId, 1796 "display": self.#convertNumberToLocale(year), 1797 ariaLabel: year 1798 }; 1799 } 1800 }); 1801 } 1802 1803 insertRow(rowNum, rowArray, isHeader, elementAt) { 1804 let $view = this["$" + this.view.toLowerCase()], 1805 $row = $view.getElementsByTagName("ul")[rowNum], 1806 items, $li, element, $tmp, 1807 self = this; 1808 if (!$row) { 1809 let rowEl = document.createElement("ul"); 1810 rowEl.removeAttribute("aria-label"); 1811 rowEl.classList.toggle("header", isHeader); 1812 $row = $view.appendChild(rowEl); 1813 } 1814 items = $row.getElementsByTagName("li").length; 1815 while (items++ < rowArray.length) { 1816 let listItemEl = document.createElement("li"); 1817 listItemEl.id = "li-" + elementAt(rowNum, items).gridId; 1818 $tmp = $row.appendChild(listItemEl); 1819 if (!isHeader) { 1820 let cb = function (evnt) { 1821 self.#selectDate(evnt); 1822 }; 1823 $tmp.addEventListener("click", cb); 1824 } 1825 } 1826 1827 rowArray.forEach(function (el, index) { 1828 $li = $row.getElementsByTagName("li")[index]; 1829 if (isHeader) { 1830 $li.innerText = rowArray[index]; 1831 } else { 1832 element = rowArray[index]; 1833 window.afCache.put($li, "value", element.data); 1834 if (self.#checkDateIsFocussed(element.data)) { 1835 if (self.$focusedDate) { 1836 self.$focusedDate.classList.remove("dp-focus"); 1837 self.$focusedDate.setAttribute("tabindex", "-1"); 1838 } 1839 self.$focusedDate = $li; 1840 if (self.#keysEnabled) { 1841 self.$focusedDate.classList.add("dp-focus") 1842 } 1843 } 1844 $li.setAttribute("title", element.ariaLabel); 1845 $li.setAttribute("aria-label", element.ariaLabel); 1846 $li.setAttribute("tabindex", -1); 1847 $li.classList.toggle("dp-selected", 1848 self.#checkDateIsSelected(element.data)); 1849 $li.classList.toggle("disabled", element.data === -1); 1850 $li.innerText = element.display; 1851 } 1852 }); 1853 return $row; 1854 } 1855 1856 /* 1857 * creates a tabular view based on the options provided. The options that can be passed are 1858 * numRows: number of rows that needs rendering
1859 * numCols: number of columns that needs rendering 1860 * caption: text for the datepickers caption element 1861 * header: an array of elements that identifies the header row 1862 * elementAt: a function(row, column) that returns an object (data: <data>, display: <display>) where 1863 * <data> is the value to set for that view when the element at (row,column) is clicked and 1864 * <display> is the value that will be visible to the user 1865 */ 1866 #tabulateView(options) { 1867 var r = 0, rows = 0, 1868 row = [], 1869 c; 1870 this.caption.innerHTML = options.caption; 1871 if (options.header) { 1872 this.insertRow(r++, options.header, true, options.elementAt); 1873 } 1874 while (r < options.numRows) { 1875 c = 0; 1876 while (c < options.numColumns) { 1877 row[c] = options.elementAt(r, c); 1878 c++; 1879 } 1880 this.insertRow(r++, row, false, options.elementAt); 1881 } 1882 } 1883 1884 #hotKeysCallBack = this.#hotKeys.bind(this); 1885 1886 #activateField(evnt) { 1887 let self = this; 1888 this.#curInstance = window.afCache.get(evnt.target, "datetimepicker"); 1889 // Issue LC-7049: 1890 // datepickerTarget should be added when activate the field and should be removed 1891 // after the fields gets deactivated. 1892 if (this.#options.showCalendarIcon) { 1893 this.#curInstance.$field.parentNode.classList.add("datePickerTarget"); 1894 } 1895 //enable hot keys only for non touch devices 1896 if (!this.#touchSupported && !this.#keysEnabled) { 1897 document.addEventListener("keydown", self.#hotKeysCallBack); 1898 this.#keysEnabled = true; 1899 } 1900 } 1901 1902 #deactivateField() { 1903 let self = this; 1904 if (self.#curInstance) { 1905 if (this.#keysEnabled) { 1906 document.removeEventListener("keydown", self.#hotKeysCallBack); 1907 this.#keysEnabled = false; 1908 } 1909 // Remove document touch listener if it exists 1910 if (this.#documentTouchListener) { 1911 document.removeEventListener("touchstart", this.#documentTouchListener); 1912 this.#documentTouchListener = null; 1913 } 1914 // Issue LC-7049: 1915 // datepickerTarget should be added when activate the field and should be removed 1916 // after the fields gets deactivated. Otherwise clicking on any other datefield 1917 // will not hide the existing datepicker 1918 if (this.#options.showCalendarIcon) { 1919 self.#curInstance.$field.parentNode.classList.remove( 1920 "datePickerTarget"); 1921 } 1922 self.#curInstance = null; 1923 this.#hideAllViews(); 1924 } 1925 } 1926 1927 #hide() { 1928 if (DatePickerWidget.#visible) { 1929 this.#dp.style.display = "none"; 1930 this.#hideAllViews(); 1931 DatePickerWidget.#visible = false; 1932 if (this.#options.showCalendarIcon) { 1933 this.#curInstance.$field.removeAttribute('readonly'); // when the datepicker is deactivated, activate the field 1934 } 1935 } 1936 } 1937 1938 #hideAllViews() { 1939 this['$month'].replaceChildren(); 1940 this['$year'].replaceChildren(); 1941 this['$yearset'].replaceChildren(); 1942 this['$month'].style.display = "none"; 1943 this['$year'].style.display = "none"; 1944 this['$yearset'].style.display = "none"; 1945 } 1946 1947 #adjustDate(step, view, focus) { 1948 let maxDate, prevMaxDate; 1949 let _focus = focus || false; 1950 switch (view.toLowerCase()) { 1951 case "day": 1952 this.currentDay += step; 1953 maxDate = this.#maxDate(this.currentMonth) 1954 if (this.currentDay < 1) { 1955 prevMaxDate = this.#maxDate((this.currentMonth - 1 + 12) % 12); 1956 this.currentDay = prevMaxDate + this.currentDay; 1957 return this.#adjustDate(-1, "month", _focus); 1958 } 1959 if (this.currentDay > maxDate) { 1960 this.currentDay -= maxDate; 1961 return this.#adjustDate(+1, "month", _focus); 1962 } 1963 break; 1964 case "month": 1965 this.currentMonth += step; 1966 if (this.currentMonth > 11) { 1967 this.currentYear++; 1968 this.currentMonth = 0; 1969 } 1970 if (this.currentMonth < 0) { 1971 this.currentYear--; 1972 this.currentMonth = 11; 1973 } 1974 break; 1975 case "year": 1976 this.currentYear += step; 1977 break;
1978 case "yearset": 1979 this.currentYear += step * this.#options.yearsPerView; 1980 break; 1981 } 1982 this.#layout(this.view); 1983 if (_focus) { 1984 this.#focusedOnLi = true; 1985 this.$focusedDate.setAttribute("tabindex", 0); 1986 this.$focusedDate.focus(); 1987 } 1988 } 1989 1990 #checkDateIsSelected(data) { 1991 switch (this.view.toLowerCase()) { 1992 case "month": 1993 return this.currentYear === this.selectedYear && this.currentMonth 1994 === this.selectedMonth && data === this.selectedDay; 1995 case "year": 1996 return this.currentYear === this.selectedYear && this.selectedMonth 1997 === data; 1998 case "yearset": 1999 return this.selectedYear === data; 2000 } 2001 } 2002 2003 #checkDateIsFocussed(data) { 2004 switch (this.view.toLowerCase()) { 2005 case "month": 2006 return data === this.currentDay; 2007 case "year": 2008 return this.currentMonth === data; 2009 case "yearset": 2010 return this.currentYear === data; 2011 } 2012 } 2013 2014 #convertNumberToLocale(number) { 2015 const zeroCode = this.#options.locale.zero.charCodeAt(0); 2016 number += ""; 2017 let newNumber = []; 2018 for (let i = 0; i < number.length; i++) { 2019 newNumber.push( 2020 String.fromCharCode(zeroCode + parseInt(number.charAt(i)))); 2021 } 2022 return newNumber.join(""); 2023 } 2024 2025 #clearDate(view) { 2026 this.#model.dispatch(new FormView.Actions.UIChange({'value': ''})); 2027 let existingSelectedItem = this['$' + view.toLowerCase()].getElementsByClassName("dp-selected")[0]; 2028 if (existingSelectedItem) { 2029 existingSelectedItem.classList.remove("dp-selected"); 2030 } 2031 } 2032 2033 #getEvent() { 2034 return "click";//this.#touchSupported ? "touchstart" : "click"; 2035 } 2036 2037 #pad2(m) { 2038 return m = m < 10 ? "0" + m : m; 2039 } 2040 2041 toString() { 2042 if(this.selectedYear === -1 || this.selectedMonth === -1 || this.selectedDay === -1){ 2043 return ""; 2044 } 2045 const formattedDate = `${this.selectedYear}-${this.#pad2(this.selectedMonth + 1)}-${this.#pad2(this.selectedDay)}`; 2046 return formattedDate; 2047 } 2048 2049 #selectDate(evnt) { 2050 let val = window.afCache.get(evnt.target, "value"), 2051 nextView = this.#viewAction[this.view].li; 2052 2053 //disabled dates have a value of -1. Do nothing in that case 2054 if (val === -1) { 2055 return; 2056 } 2057 switch (this.view.toLowerCase()) { 2058 case "month": 2059 this.selectedMonth = this.currentMonth; 2060 this.selectedYear = this.currentYear; 2061 this.selectedDay = val; 2062 this.setValue(this.toString()); 2063 this.#model.dispatch(new FormView.Actions.UIChange({'value': this.toString()})); // updating model value to the latest when calender is changed 2064 this.#curInstance.$field.focus(); 2065 let existingSelectedElement = this['$' 2066 + this.view.toLowerCase()].getElementsByClassName("dp-selected")[0]; 2067 if (existingSelectedElement) { 2068 existingSelectedElement.classList.remove("dp-selected"); 2069 } 2070 evnt.target.classList.add("dp-selected"); 2071 break; 2072 case "year": 2073 this.currentMonth = val; 2074 break;
2075 case "yearset": 2076 this.currentYear = val; 2077 break; 2078 } 2079 this.#layout(nextView); 2080 //manually focus on the field if clicked on the popup buttons for non-touch device 2081 if (!this.#touchSupported) { 2082 //No need to focus if selection is made by pressing space. 2083 if (!this.hotKeyPressed) { 2084 this.#scriptFocus = true; 2085 } 2086 } else if (nextView == null) { 2087 //For touch devices, deactivate the field if a selection is made 2088 this.#deactivateField() 2089 } 2090 } 2091 2092 #leapYear() { 2093 return this.currentYear % 400 === 0 || (this.currentYear % 100 !== 0 2094 && this.currentYear % 4 === 0); 2095 } 2096 2097 #maxDate(m) { 2098 if (this.#leapYear() && m === 1) { 2099 return 29; 2100 } else { 2101 return this.#dates[m]; 2102 } 2103 } 2104 2105 #localizeDateElements(defaultOptions, locale) { 2106 var calendarSymbols = FormView.LanguageUtils.getTranslatedString(locale, "calendarSymbols"); 2107 if (calendarSymbols && calendarSymbols.abbrdayNames) { 2108 defaultOptions.locale.days = calendarSymbols.abbrdayNames; 2109 } 2110 if (calendarSymbols && calendarSymbols.abbrdayNames) { 2111 defaultOptions.locale.months = calendarSymbols.monthNames; 2112 } 2113 var clearText = FormView.LanguageUtils.getTranslatedString(locale, "clearText"); 2114 if (clearText) { 2115 defaultOptions.locale.clearText = clearText; 2116 } 2117 var zero = FormView.LanguageUtils.getTranslatedString(locale, "0"); 2118 if (zero) { 2119 defaultOptions.locale.zero = zero; 2120 } 2121 } 2122 2123 #isEditValueOrDisplayValue(value) { 2124 return (this.#model.editValue === value || this.#model.displayValue 2125 === value); 2126 } 2127 2128 /** 2129 * returns the original value of format YYYY-MM-DD 2130 * @returns {*|string} 2131 */ 2132 getValue() { 2133 if (this.#isEditValueOrDisplayValue(this.#widget.value)) { 2134 return this.#model.value; // if the widget has edit/display value thiss method should return model value 2135 } 2136 return this.#widget.value; 2137 } 2138 2139 /** 2140 * Sets the formatted display value on the widget. 2141 * value should be in YYYY-MM-DD format 2142 * @param value 2143 */ 2144 setDisplayValue(value) { 2145 if (this.#curInstance != null) { 2146 this.#curInstance.$field.value = this.#curInstance.displayValue( 2147 this.toString()) || value; 2148 } else { 2149 this.#widget.value = this.#model.displayValue || value; 2150 } 2151 } 2152 2153 setCalendarWidgetValue(value) { 2154 if (this.#curInstance === null && this.#widget != null) { 2155 this.#curInstance = window.afCache.get(this.#widget, "datetimepicker"); 2156 } 2157 if (this.#curInstance != null) { 2158 // also change the date of the calendar widget 2159 this.#curInstance.selectedDate = value; 2160 } 2161 } 2162 2163 /** 2164 * Sets the formatted edit value on the widget 2165 * @param value 2166 */ 2167 2168 setValue(value) { 2169 let currDate; 2170 if (value instanceof Date && !isNaN(value)) { 2171 // If value is already a Date object and it's valid, use it as is 2172 currDate = value; 2173 } else { 2174 // Check if value is empty 2175 if (!value || value.trim() === '') { 2176 currDate = new Date(); 2177 } else { 2178 let displayFormat = this.#model._jsonModel?.displayFormat; 2179 // If displayFormat is null/undefined, use default parsing 2180 if (!displayFormat) { 2181 currDate = new Date(value); 2182 } else { 2183 // Use FormView.Formatters.parseDate for custom formats 2184 currDate = FormView.Formatters.parseDate(value, this.#lang || 'en', displayFormat); 2185 // If parseDate failed (returned null), fallback to default parsing 2186 if (currDate === null) { 2187 currDate = new Date(value); 2188 } 2189 const timezoneOffset = currDate.getTimezoneOffset(); 2190 currDate.setMinutes(currDate.getMinutes() + timezoneOffset); 2191 } 2192 } 2193 } 2194 2195 if (!isNaN(currDate) && value != null) { 2196 //in case the value is directly updated from the field without using calendar widget 2197 this.selectedMonth = currDate.getMonth(); 2198 this.selectedYear = currDate.getFullYear(); 2199 this.selectedDay = currDate.getDate(); 2200 } else { 2201 this.selectedYear 2202 = this.selectedMonth 2203 = this.selectedDay 2204 = -1; 2205 } 2206 if (this.#curInstance != null) { 2207 if (!this.#isEditValueOrDisplayValue(value)) { 2208 this.#curInstance.selectedDate = value; // prevent edit/display value from getting set in calender 2209 } 2210 this.#curInstance.$field.value = this.#curInstance.editValue() || value; 2211 } else { 2212 this.#widget.value = value; 2213 } 2214 } 2215 2216 addEventListener(event, handler, widget) { 2217 let inst = window.afCache.get(widget, "datetimepicker"); 2218 inst.$field.addEventListener(event, function (e) { 2219 switch (e.type) { 2220 case 'blur': 2221 if (!DatePickerWidget.#visible) { 2222 handler(e); 2223 } 2224 break; 2225 case 'focus': 2226 handler(e); 2227 break; 2228 case 'input': 2229 handler(e); 2230 break; 2231 2232 } 2233 }); 2234 } 2235 2236 } 2237} 2238/******************************************************************************* 2239 * Copyright 2022 Adobe 2240 * 2241 * Licensed under the Apache License, Version 2.0 (the "License");
2242 * you may not use this file except in compliance with the License. 2243 * You may obtain a copy of the License at 2244 * 2245 * http://www.apache.org/licenses/LICENSE-2.0 2246 * 2247 * Unless required by applicable law or agreed to in writing, software 2248 * distributed under the License is distributed on an "AS IS" BASIS, 2249 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2250 * See the License for the specific language governing permissions and 2251 * limitations under the License. 2252 ******************************************************************************/ 2253(function() { 2254 2255 "use strict"; 2256 class TextInput extends FormView.FormFieldBase { 2257 2258 static NS = FormView.Constants.NS; 2259 /** 2260 * Each FormField has a data attribute class that is prefixed along with the global namespace to 2261 * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be 2262 * data-{NS}-{IS}-x="" 2263 * @type {string} 2264 */ 2265 static IS = "adaptiveFormTextInput"; 2266 static bemBlock = 'cmp-adaptiveform-textinput' 2267 static selectors = { 2268 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 2269 widget: `.${TextInput.bemBlock}__widget`, 2270 label: `.${TextInput.bemBlock}__label`, 2271 description: `.${TextInput.bemBlock}__longdescription`, 2272 qm: `.${TextInput.bemBlock}__questionmark`, 2273 errorDiv: `.${TextInput.bemBlock}__errormessage`, 2274 tooltipDiv: `.${TextInput.bemBlock}__shortdescription` 2275 }; 2276 2277 constructor(params) { 2278 super(params); 2279 } 2280 2281 getWidget() { 2282 return this.element.querySelector(TextInput.selectors.widget); 2283 } 2284 2285 getDescription() { 2286 return this.element.querySelector(TextInput.selectors.description); 2287 } 2288 2289 getLabel() { 2290 return this.element.querySelector(TextInput.selectors.label); 2291 } 2292 2293 getErrorDiv() { 2294 return this.element.querySelector(TextInput.selectors.errorDiv); 2295 } 2296 2297 getTooltipDiv() { 2298 return this.element.querySelector(TextInput.selectors.tooltipDiv); 2299 } 2300 2301 getQuestionMarkDiv() { 2302 return this.element.querySelector(TextInput.selectors.qm); 2303 } 2304 2305 setModel(model) { 2306 super.setModel(model); 2307 if (this.widget.value !== '') { 2308 this.setModelValue(this.widget.value); 2309 } 2310 this.widget.addEventListener('blur', (e) => { 2311 this.setModelValue(e.target.value); 2312 this.setWidgetValueToDisplayValue(); 2313 this.setInactive(); 2314 this.triggerExit(); 2315 }); 2316 this.widget.addEventListener('focus', (e) => { 2317 this.setActive(); 2318 this.setWidgetValueToModelValue(); 2319 this.triggerEnter(); 2320 }); 2321 if (model.fieldType === "multiline-input") { 2322 this.widget.addEventListener('keydown', (event) => { 2323 if (event.key === 'Enter') { 2324 // Prevent default action of Enter key to avoid form submission 2325 event.preventDefault(); 2326 // Add a newline character to the widget value 2327 let cursorPosition = this.widget.selectionStart; 2328 let textBefore = this.widget.value.substring(0, cursorPosition); 2329 let textAfter = this.widget.value.substring(this.widget.selectionEnd); 2330 this.widget.value = textBefore + '\n' + textAfter; 2331 this.widget.selectionStart = this.widget.selectionEnd = cursorPosition + 1; 2332 } 2333 }); 2334 } 2335 } 2336 } 2337 2338 FormView.Utils.setupField(({element, formContainer}) => { 2339 return new TextInput({element, formContainer}) 2340 }, TextInput.selectors.self); 2341 2342})(); 2343 2344/******************************************************************************* 2345 * Copyright 2022 Adobe 2346 * 2347 * Licensed under the Apache License, Version 2.0 (the "License");
2348 * you may not use this file except in compliance with the License. 2349 * You may obtain a copy of the License at 2350 * 2351 * http://www.apache.org/licenses/LICENSE-2.0 2352 * 2353 * Unless required by applicable law or agreed to in writing, software 2354 * distributed under the License is distributed on an "AS IS" BASIS, 2355 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2356 * See the License for the specific language governing permissions and 2357 * limitations under the License. 2358 ******************************************************************************/ 2359(function() { 2360 2361 "use strict"; 2362 class TelephoneInput extends FormView.FormFieldBase { 2363 2364 static NS = FormView.Constants.NS; 2365 /** 2366 * Each FormField has a data attribute class that is prefixed along with the global namespace to 2367 * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be 2368 * data-{NS}-{IS}-x="" 2369 * @type {string} 2370 */ 2371 static IS = "adaptiveFormTelephoneInput"; 2372 static bemBlock = 'cmp-adaptiveform-telephoneinput' 2373 static selectors = { 2374 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 2375 widget: `.${TelephoneInput.bemBlock}__widget`, 2376 label: `.${TelephoneInput.bemBlock}__label`, 2377 description: `.${TelephoneInput.bemBlock}__longdescription`, 2378 qm: `.${TelephoneInput.bemBlock}__questionmark`, 2379 errorDiv: `.${TelephoneInput.bemBlock}__errormessage`, 2380 tooltipDiv: `.${TelephoneInput.bemBlock}__shortdescription` 2381 }; 2382 2383 constructor(params) { 2384 super(params); 2385 } 2386 2387 getWidget() { 2388 return this.element.querySelector(TelephoneInput.selectors.widget); 2389 } 2390 2391 getDescription() { 2392 return this.element.querySelector(TelephoneInput.selectors.description); 2393 } 2394 2395 getLabel() { 2396 return this.element.querySelector(TelephoneInput.selectors.label); 2397 } 2398 2399 getErrorDiv() { 2400 return this.element.querySelector(TelephoneInput.selectors.errorDiv); 2401 } 2402 2403 getTooltipDiv() { 2404 return this.element.querySelector(TelephoneInput.selectors.tooltipDiv); 2405 } 2406 2407 getQuestionMarkDiv() { 2408 return this.element.querySelector(TelephoneInput.selectors.qm); 2409 } 2410 2411 setModel(model) { 2412 super.setModel(model); 2413 if (this.widget.value !== '') { 2414 this.setModelValue(this.widget.value); 2415 } 2416 this.widget.addEventListener('blur', (e) => { 2417 this.setModelValue(e.target.value); 2418 this.setWidgetValueToDisplayValue(); 2419 this.setInactive(); 2420 this.triggerExit(); 2421 }); 2422 this.widget.addEventListener('focus', (e) => { 2423 this.setActive(); 2424 this.setWidgetValueToModelValue(); 2425 this.triggerEnter(); 2426 }); 2427 } 2428 } 2429 2430 FormView.Utils.setupField(({element, formContainer}) => { 2431 return new TelephoneInput({element, formContainer}) 2432 }, TelephoneInput.selectors.self); 2433 2434})(); 2435 2436/******************************************************************************* 2437 * Copyright 2022 Adobe 2438 * 2439 * Licensed under the Apache License, Version 2.0 (the "License"); 2440 * you may not use this file except in compliance with the License. 2441 * You may obtain a copy of the License at 2442 * 2443 * http://www.apache.org/licenses/LICENSE-2.0 2444 * 2445 * Unless required by applicable law or agreed to in writing, software 2446 * distributed under the License is distributed on an "AS IS" BASIS, 2447 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2448 * See the License for the specific language governing permissions and 2449 * limitations under the License. 2450 ******************************************************************************/ 2451(function() { 2452 2453 "use strict"; 2454 class EmailInput extends FormView.FormFieldBase { 2455 2456 static NS = FormView.Constants.NS; 2457 /** 2458 * Each FormField has a data attribute class that is prefixed along with the global namespace to 2459 * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be 2460 * data-{NS}-{IS}-x="" 2461 * @type {string} 2462 */ 2463 static IS = "adaptiveFormEmailInput"; 2464 static bemBlock = 'cmp-adaptiveform-emailinput' 2465 static selectors = { 2466 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 2467 widget: `.${EmailInput.bemBlock}__widget`, 2468 label: `.${EmailInput.bemBlock}__label`, 2469 description: `.${EmailInput.bemBlock}__longdescription`, 2470 qm: `.${EmailInput.bemBlock}__questionmark`, 2471 errorDiv: `.${EmailInput.bemBlock}__errormessage`, 2472 tooltipDiv: `.${EmailInput.bemBlock}__shortdescription` 2473 }; 2474 2475 constructor(params) { 2476 super(params); 2477 } 2478 2479 getWidget() { 2480 return this.element.querySelector(EmailInput.selectors.widget); 2481 } 2482 2483 getDescription() { 2484 return this.element.querySelector(EmailInput.selectors.description); 2485 } 2486 2487 getLabel() { 2488 return this.element.querySelector(EmailInput.selectors.label); 2489 } 2490 2491 getErrorDiv() { 2492 return this.element.querySelector(EmailInput.selectors.errorDiv); 2493 } 2494 2495 getTooltipDiv() { 2496 return this.element.querySelector(EmailInput.selectors.tooltipDiv); 2497 } 2498 2499 getQuestionMarkDiv() { 2500 return this.element.querySelector(EmailInput.selectors.qm); 2501 } 2502 2503 setModel(model) { 2504 super.setModel(model); 2505 if (this.widget.value !== '') { 2506 this.setModelValue(this.widget.value); 2507 } 2508 this.widget.addEventListener('blur', (e) => { 2509 this.setModelValue(e.target.value); 2510 this.setWidgetValueToDisplayValue(); 2511 this.setInactive(); 2512 this.triggerExit(); 2513 }); 2514 this.widget.addEventListener('focus', (e) => { 2515 this.setActive(); 2516 this.setWidgetValueToModelValue(); 2517 this.triggerEnter(); 2518 }); 2519 } 2520 } 2521 2522 FormView.Utils.setupField(({element, formContainer}) => { 2523 return new EmailInput({element, formContainer}) 2524 }, EmailInput.selectors.self); 2525 2526})(); 2527 2528/******************************************************************************* 2529 * Copyright 2022 Adobe 2530 * 2531 * Licensed under the Apache License, Version 2.0 (the "License");
2532 * you may not use this file except in compliance with the License. 2533 * You may obtain a copy of the License at 2534 * 2535 * http://www.apache.org/licenses/LICENSE-2.0 2536 * 2537 * Unless required by applicable law or agreed to in writing, software 2538 * distributed under the License is distributed on an "AS IS" BASIS, 2539 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2540 * See the License for the specific language governing permissions and 2541 * limitations under the License. 2542 ******************************************************************************/ 2543(function() { 2544 2545 "use strict"; 2546 class TextInput extends FormView.FormFieldBase { 2547 2548 static NS = FormView.Constants.NS; 2549 /** 2550 * Each FormField has a data attribute class that is prefixed along with the global namespace to 2551 * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be 2552 * data-{NS}-{IS}-x="" 2553 * @type {string} 2554 */ 2555 // CoPA Customization - adaptiveFormTextInputWithCounter,counterSpan 2556 static IS = "adaptiveFormTextInputWithCounter"; 2557 static bemBlock = 'cmp-adaptiveform-textinput' 2558 static selectors = { 2559 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 2560 widget: `.${TextInput.bemBlock}__widget`, 2561 label: `.${TextInput.bemBlock}__label`, 2562 description: `.${TextInput.bemBlock}__longdescription`, 2563 qm: `.${TextInput.bemBlock}__questionmark`, 2564 errorDiv: `.${TextInput.bemBlock}__errormessage`, 2565 tooltipDiv: `.${TextInput.bemBlock}__shortdescription`, 2566 counterSpan: `.${TextInput.bemBlock}__charcount` 2567 }; 2568 2569 constructor(params) { 2570 super(params); 2571 } 2572 2573 getWidget() { 2574 return this.element.querySelector(TextInput.selectors.widget); 2575 } 2576 2577 getDescription() { 2578 return this.element.querySelector(TextInput.selectors.description); 2579 } 2580 2581 getLabel() { 2582 return this.element.querySelector(TextInput.selectors.label); 2583 } 2584 2585 getErrorDiv() { 2586 return this.element.querySelector(TextInput.selectors.errorDiv); 2587 } 2588 2589 getTooltipDiv() { 2590 return this.element.querySelector(TextInput.selectors.tooltipDiv); 2591 } 2592 2593 getQuestionMarkDiv() { 2594 return this.element.querySelector(TextInput.selectors.qm); 2595 } 2596 // CoPA Customization - Start 2597 getCounterSpan() { 2598 return this.element.querySelector(TextInput.selectors.counterSpan); 2599 } 2600 2601 updateValue(value) { 2602 super.updateValue(value); 2603 const counterSpan = this.getCounterSpan(); 2604 if (counterSpan) { 2605 const currentValue = this.widget.value || ''; 2606 counterSpan.textContent = currentValue.length; 2607 } 2608 } 2609 2610 updateCharacterCounter() { 2611 const currentValue = this.widget.value || ''; 2612 const counterSpan = this.getCounterSpan(); 2613 if (counterSpan) { 2614 if(currentValue !== undefined) 2615 counterSpan.textContent = currentValue.length; 2616 } 2617 } 2618 2619 newLineUpdateEvent(event){ 2620 event.preventDefault(); 2621 let cursorPosition = this.widget.selectionStart; 2622 let textBefore = this.widget.value.substring(0, cursorPosition); 2623 let textAfter = this.widget.value.substring(this.widget.selectionEnd); 2624 this.widget.value = textBefore + '\n' + textAfter; 2625 this.widget.selectionStart = this.widget.selectionEnd = cursorPosition + 1; 2626 } 2627 // CoPA Customization - End 2628 setModel(model) { 2629 // CoPA Customization - dataset 2630 let dataset = document.querySelector("#"+this.id).dataset; 2631 super.setModel(model); 2632 if (this.widget.value !== '') { 2633 this.setModelValue(this.widget.value); 2634 } 2635 this.widget.addEventListener('blur', (e) => { 2636 this.setModelValue(e.target.value); 2637 this.setWidgetValueToDisplayValue(); 2638 this.setInactive(); 2639 // CoPA Customization 2640 if (model.fieldType === "text-input" && dataset.cmpMask !== undefined && dataset.cmpMask === "true"){ 2641 this.widget.setAttribute("type","password"); 2642 } 2643 this.triggerExit(); 2644 }); 2645 this.widget.addEventListener('focus', (e) => { 2646 this.setActive(); 2647 this.setWidgetValueToModelValue(); 2648 // CoPA Customization 2649 if (model.fieldType === "text-input" && dataset.cmpMask !== undefined && dataset.cmpMask === "true"){ 2650 this.widget.setAttribute("type","text"); 2651 } 2652 this.triggerEnter(); 2653 }); 2654 // CoPA Customization 2655 this.widget.addEventListener('input', (e) => { 2656 this.updateCharacterCounter(); 2657 }); 2658 if (model.fieldType === "multiline-input") { 2659 this.widget.addEventListener('keydown', (event) => { 2660 // CoPA Customization - Start 2661 let currentVal = this.widget.value || ''; 2662 if (currentVal !== '' && currentVal !== undefined){ 2663 currentVal = currentVal.length + 1; 2664 } else { 2665 currentVal = 0; 2666 } 2667 let maxChar = this.widget.maxLength; 2668 if (maxChar && maxChar !== -1) { 2669 if (event.key === 'Enter' && currentVal <= maxChar) { 2670 this.newLineUpdateEvent(event); 2671 this.updateCharacterCounter(); 2672 } 2673 } else { 2674 if (event.key === 'Enter') { 2675 this.newLineUpdateEvent(event); 2676 // CoPA Customization - End 2677 /* OOTB code 2678 // Prevent default action of Enter key to avoid form submission 2679 event.preventDefault(); 2680 // Add a newline character to the widget value 2681 let cursorPosition = this.widget.selectionStart; 2682 let textBefore = this.widget.value.substring(0, cursorPosition); 2683 let textAfter = this.widget.value.substring(this.widget.selectionEnd); 2684 this.widget.value = textBefore + '\n' + textAfter; 2685 this.widget.selectionStart = this.widget.selectionEnd = cursorPosition + 1; 2686 */ 2687 } 2688 2689 2690 2691 } 2692 }); 2693 } 2694 this.setupCharacterCounter(); 2695 } 2696 2697 2698 setupCharacterCounter() { 2699 this.updateCharacterCounter(); // Set the initial character count 2700 } 2701 } 2702 2703 FormView.Utils.setupField(({element, formContainer}) => { 2704 return new TextInput({element, formContainer}) 2705 }, TextInput.selectors.self); 2706 2707})(); 2708 2709/******************************************************************************* 2710 * Copyright 2022 Adobe 2711 * 2712 * Licensed under the Apache License, Version 2.0 (the "License");
2713 * you may not use this file except in compliance with the License. 2714 * You may obtain a copy of the License at 2715 * 2716 * http://www.apache.org/licenses/LICENSE-2.0 2717 * 2718 * Unless required by applicable law or agreed to in writing, software 2719 * distributed under the License is distributed on an "AS IS" BASIS, 2720 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2721 * See the License for the specific language governing permissions and 2722 * limitations under the License. 2723 ******************************************************************************/ 2724 2725/** 2726 * This class is responsible for interacting with the numeric input widget. It implements edit/display format 2727 * for numeric input, along with the following features 2728 * - Convert's input type number to text to support display/edit format (for example `$` symbol) 2729 * - One cannot type or paste alphabets in the html input element 2730 */ 2731 2732 if (typeof window.NumericInputWidget === 'undefined') { 2733 2734 window.NumericInputWidget = class { 2735 #widget=null 2736 #model=null // passed by reference 2737 #options=null 2738 #defaultOptions={ 2739 value : null, 2740 curValue: null, 2741 pos: 0, 2742 lengthLimitVisible: true, 2743 zero:"0", 2744 decimal:".", 2745 minus:"-" 2746 } 2747 //TODO: to support writing in different locales \d should be replaced by [0-9] for different locales 2748 #matchArray ={ 2749 "integer":"^[+-]?{digits}*$" 2750 } 2751 #regex=null 2752 #processedValue=null 2753 #engRegex=null 2754 #writtenInLocale=false 2755 #previousCompositionVal="" 2756 2757 #toLatinForm (halfOrFullWidthStr) { 2758 // refer http://www.fileformat.info/info/unicode/block/halfwidth_and_fullwidth_forms/utf8test.htm 2759 return halfOrFullWidthStr.replace( 2760 /[\uff00-\uffef]/g, 2761 function(ch) { return String.fromCharCode(ch.charCodeAt(0) - 0xfee0); } 2762 ); 2763 } 2764 2765 constructor(widget, model) { 2766 // initialize the widget and model 2767 this.#widget = widget; 2768 this.#model = model; 2769 // initialize options for backward compatibility 2770 this.#options = Object.assign({}, this.#defaultOptions, this.#model._jsonModel); 2771 let matchStr = this.#matchArray[this.#options.type]; 2772 if(matchStr) { 2773 let ld = this.#options.leadDigits, 2774 fd = this.#options.fracDigits, 2775 ldstr = ld && ld !== -1 ? "{0,"+ld+"}" 2776 : "*", 2777 fdstr = fd && fd !== -1 ? "{0,"+fd+"}" 2778 : "*"; 2779 matchStr = matchStr.replace("{leading}",ldstr) 2780 .replace("{fraction}",fdstr); 2781 let localeStr = matchStr.replace(/{digits}/g,this.#getDigits()) 2782 .replace("{decimal}",this.#escape(this.#options.decimal)), 2783 engStr = matchStr.replace(/{digits}/g,"[0-9]") 2784 .replace("{decimal}","\\.") 2785 this.#processedValue = !(this.#getDigits() === "[0123456789]" && this.#options.decimal === ".") 2786 this.#regex = new RegExp(localeStr, "g"); 2787 this.#engRegex = new RegExp(engStr, "g"); 2788 } 2789 2790 // change the input type to text for patterns 2791 this.#widget.setAttribute("type", "text"); 2792 this.#attachEventHandlers(widget); 2793 } 2794 2795 #attachEventHandlers(widget, model) { 2796 widget.addEventListener('keydown', (e)=> { 2797 this.#handleKeyDown(e); 2798 }); 2799 widget.addEventListener('keypress', (e)=> { 2800 this.#handleKeyPress(e); 2801 }); 2802 widget.addEventListener('focus', (e)=> { 2803 this.#widget.value = this.#model.value; 2804 }); 2805 widget.addEventListener('paste', (e)=> { 2806 this.#handlePaste(e); 2807 }); 2808 widget.addEventListener('cut', (e)=> { 2809 this.#handleCut(e); 2810 }); 2811 widget.addEventListener('blur', (e) => { 2812 this.#model.dispatch(new FormView.Actions.UIChange({'value': this.getValue(e.target.value)})); 2813 this.#widget.value = this.#model.displayValue; 2814 }); 2815 // IME specific handling, to handle japanese languages max limit 2816 this.#attachCompositionEventHandlers(widget); 2817 } 2818 2819 #attachCompositionEventHandlers(widget) { 2820 let isComposing = false; // IME Composing going on 2821 let hasCompositionJustEnded = false; // Used to swallow keyup event related to compositionend 2822 // IME specific handling, to handle japanese languages max limit 2823 // since enter can also be invoked during composing, a special handling is done here 2824 let that = this, 2825 changeCaratPosition = function() { 2826 // change the carat selection position to further limit input of characters 2827 let range = window.getSelection(); 2828 range.selectAllChildren(widget); 2829 range.collapseToEnd(); 2830 }; 2831 widget.addEventListener('keyup', function(event) { 2832 if (/*isComposing || */hasCompositionJustEnded) { 2833 if (that.#compositionUpdateCallback(event)) { 2834 changeCaratPosition(); 2835 } 2836 // IME composing fires keydown/keyup events 2837 hasCompositionJustEnded = false;
2838 } 2839 }); 2840 widget.addEventListener('compositionstart', 2841 function(event) { 2842 isComposing = true; 2843 }); 2844 widget.addEventListener("compositionupdate", 2845 function(event) { 2846 // event.originalEvent.data refers to the actual content 2847 if (that.#compositionUpdateCallback(event)) { 2848 changeCaratPosition(); 2849 } 2850 }); 2851 widget.addEventListener("compositionend", 2852 function(event) { 2853 isComposing = false; 2854 // some browsers (IE, Firefox, Safari) send a keyup event after 2855 // compositionend, some (Chrome, Edge) don't. This is to swallow 2856 // the next keyup event, unless a keydown event happens first 2857 hasCompositionJustEnded = true; 2858 }); 2859 widget.addEventListener("keydown", 2860 function(event) { 2861 // Safari on OS X may send a keydown of 229 after compositionend 2862 if (event.which !== 229) { 2863 hasCompositionJustEnded = false; 2864 } 2865 }); 2866 } 2867 2868 #getDigits() { 2869 let zeroCode = this.#options.zero.charCodeAt(0), 2870 digits = ""; 2871 for(let i = 0;i < 10;i++) { 2872 digits += String.fromCharCode(zeroCode + i); 2873 } 2874 return "["+digits+"]" 2875 } 2876 2877 #escape(str) { 2878 return str.replace(".", "\\.") 2879 } 2880 2881 2882 getValue(value) { 2883 // we support full width, half width and locale specific numbers 2884 value = this.#toLatinForm(value); 2885 if(value.length > 0 && this.#processedValue && !value.match(this.#engRegex)) { 2886 this.#writtenInLocale = true; 2887 value = this.#convertValueFromLocale(value); 2888 } else { 2889 this.#writtenInLocale = false 2890 } 2891 if(value && value.length >= this.#options.combCells ) 2892 value = value.slice(0,this.#options.combCells); 2893 this.#previousCompositionVal = value; 2894 return value; 2895 } 2896 2897 #compositionUpdateCallback(event) { 2898 let that = this; 2899 let flag = false; 2900 let leadDigits = that.#options.leadDigits; 2901 let fracDigits = that.#options.fracDigits; 2902 // we don't check use-case where just fracDigits is set since in case of composition update, the value to update is not known 2903 if (leadDigits !== -1) { 2904 let val = this.#widget.value; 2905 if (event.type === "compositionupdate" && event.originalEvent.data) { 2906 val = val + event.originalEvent.data.substr(event.originalEvent.data.length - 1); 2907 } 2908 // can't use the existing regex (since current regex checks for english digits), rather doing leadDigit compare 2909 let totalLength = leadDigits + (fracDigits !== -1 ? (fracDigits + that.#options.decimal.length) : 0); 2910 if (val.indexOf(that.#options.decimal) === -1) { 2911 totalLength = leadDigits; 2912 } 2913 let latinVal = this.#toLatinForm(val); 2914 // match both since we support full width, half width and locale specific input 2915 let match = latinVal.match(that.#regex)|| latinVal.match(this.#engRegex); 2916 flag = !match; 2917 if (match === null) { 2918 // entered invalid character, revert to previous value 2919 that.#widget.value = that.#previousCompositionVal; 2920 flag = true; 2921 } else if (flag) { 2922 // if max reached 2923 let newVal = val.substr(0, totalLength); 2924 that.#widget.value = newVal; 2925 that.#previousCompositionVal = newVal; 2926 flag = true; 2927 } else { 2928 that.#previousCompositionVal = val; 2929 } 2930 } 2931 return flag; 2932 } 2933 2934 trigger(event, detail) { 2935 if (!this.#widget) { 2936 return this; 2937 } 2938 const eventName = event.split('.')[0]; 2939 const isNativeEvent = 2940 typeof document.body[`on${eventName}`] !== 'undefined'; 2941 if (isNativeEvent) {
2942 this.#widget.dispatchEvent(new Event(eventName)); 2943 return this; 2944 } 2945 const customEvent = new CustomEvent(eventName, { 2946 detail: detail || null, 2947 }); 2948 this.#widget.dispatchEvent(customEvent); 2949 return this; 2950 } 2951 2952 getHTMLSupportedAttr(domElement, attr){ 2953 try{ 2954 return domElement[attr]; 2955 } 2956 catch (err){ 2957 return undefined; 2958 } 2959 } 2960 2961 #handleKeyInput(event, character, code){ 2962 if(event.ctrlKey && !(['paste', 'cut'].includes(event.type))) { 2963 return true; 2964 } 2965 2966 this.#handleKeyDown(arguments); 2967 this.#options.lengthLimitVisible = true; 2968 let val = this.#widget.value, 2969 // if selectionStart attribute isn't supported then its value will be undefined 2970 selectionStart = this.getHTMLSupportedAttr(this.#widget, "selectionStart") || 0, 2971 isSelectionAttrSupported = !(selectionStart === undefined || selectionStart === null), 2972 selectionEnd = this.getHTMLSupportedAttr(this.#widget, "selectionEnd") || 0, 2973 combCells = parseInt(this.#options.combCells) || 0, 2974 current, 2975 change = character; 2976 2977 if (combCells > 0 ) { 2978 change = character.substr(0, combCells - val.length + selectionEnd - selectionStart); 2979 } 2980 2981 // CQ-4245407 : selectionStart and selectionEnd attributes aren't supported in case of input type = number 2982 // it is used for providing native HTML5 implementation for numeric field, so no further processing is required 2983 // As it is specific to AF and AF doesn't support change event on each keypress, so this change should be fine 2984 if (!isSelectionAttrSupported) { 2985 return true; 2986 } 2987 2988 current = val.substr(0, selectionStart) + change + val.substr(selectionEnd); 2989 // done to handle support for both full width, half width or mixed input in number field 2990 let latinCurrentValue = this.#toLatinForm(current); 2991 2992 if (!(this.#regex == null || latinCurrentValue.match(this.#regex) || latinCurrentValue.match(this.#engRegex))) { 2993 event.preventDefault(); 2994 return false; 2995 } 2996 if (!(['keydown', 'cut'].includes(event.type)) && combCells && (val.length >= combCells || current.length > combCells) && selectionStart === selectionEnd) { 2997 event.preventDefault(); 2998 return false; 2999 } 3000 3001 this.#options.curValue = val; 3002 this.#previousCompositionVal = val; 3003 this.#options.pos = selectionStart; 3004 } 3005 3006 #handleKeyDown(event){ 3007 if (event) { 3008 let code = event.charCode || event.which || event.keyCode || 0; 3009 if(code === 8 || code === 46) // backspace and del 3010 this.#handleKeyInput(event, "", code); 3011 else if(code === 32) { // suppress space 3012 event.preventDefault(); 3013 return false; 3014 } 3015 } 3016 } 3017 3018 #isValidChar(character) { 3019 character = this.#toLatinForm(character); 3020 let lastSingleDigitChar = String.fromCharCode(this.#options.zero.charCodeAt(0) + 9); 3021 // we only full width, half width and also locale specific if customer has overlayed the i18n file 3022 return (character >= "0" && character <= "9") || (character>=this.#options.zero && character<=lastSingleDigitChar) || character===this.#options.decimal || character===this.#options.minus; 3023 } 3024 3025 isNonPrintableKey(key) { 3026 return (key // In IE, event.key returns words instead of actual characters for some keys. 3027 && !['MozPrintableKey','Divide','Multiply','Subtract','Add','Enter','Decimal','Spacebar','Del'].includes(key) 3028 && key.length !== 1 ) 3029 } 3030 3031 #handleKeyPress(event){ 3032 if (event) { 3033 let code = event.charCode || event.which || event.keyCode || 0, 3034 character = String.fromCharCode(code); 3035 3036 if(this.isNonPrintableKey(event.key)) { // mozilla also generates a keypress, along with keydown 3037 return true; // for all keys, so only handling printable keys in keypress 3038 } 3039 3040 if (this.#isValidChar(character)) 3041 this.#handleKeyInput(event, character, code); 3042 else if (!event.ctrlKey){ 3043 event.preventDefault(); 3044 return false;
3045 } 3046 } 3047 } 3048 3049 #handlePaste(event){ 3050 if (event) { 3051 // get the contents 3052 let pastedChar = undefined; 3053 if (window.clipboardData && window.clipboardData.getData) { // IE 3054 pastedChar = window.clipboardData.getData('Text'); 3055 } else if ((event.originalEvent || event).clipboardData && (event.originalEvent || event).clipboardData.getData) { 3056 pastedChar = (event.originalEvent || event).clipboardData.getData('text/plain'); 3057 } 3058 3059 if(pastedChar) { 3060 let allPastedCharsValid = pastedChar.split('').every(function (character) { 3061 return this.#isValidChar(character); 3062 }, this); 3063 if (allPastedCharsValid) { 3064 // during paste we support both half width, full width and locale specific numbers 3065 pastedChar = this.#toLatinForm(pastedChar); 3066 this.#handleKeyInput(event, pastedChar, 0); 3067 } 3068 else if (!event.ctrlKey) { 3069 event.preventDefault(); 3070 return false; 3071 } 3072 } 3073 } 3074 } 3075 3076 #handleCut(event) { 3077 if (event) { 3078 this.#handleKeyInput(event, "", 0); 3079 } 3080 } 3081 3082 #convertValueToLocale(val) { 3083 let zeroCode = this.#options.zero.charCodeAt(0); 3084 return val.map(function(c) { 3085 if(c === ".") { 3086 return this.#options.decimal; 3087 } else if(c === "-") { 3088 return this.#options.minus; 3089 } else { 3090 return String.fromCharCode(parseInt(c) + zeroCode); 3091 } 3092 },this).join(""); 3093 } 3094 3095 #convertValueFromLocale(val) { 3096 val = this.#toLatinForm(val); 3097 let zeroCode = this.#options.zero.charCodeAt(0); 3098 return val.map(function(c) { 3099 if(c === this.#options.decimal) { 3100 return "."; 3101 } else if(c === this.#options.minus) { 3102 return "-"; 3103 } else { 3104 return (c.charCodeAt(0) - zeroCode).toString(); 3105 } 3106 },this).join(""); 3107 } 3108 3109 /** 3110 * Checks if the edit value is same as value present in the user control(html form element) 3111 * @returns {boolean} 3112 */ 3113 #isValueSame() { 3114 return (((this.#model.value === null) && (this.#widget.value === "")) || (this.#model.value === this.#widget.value)); 3115 } 3116 3117 setValue(value) { 3118 // if the value is same, don't do anything 3119 if(!this.#isValueSame()){ 3120 if(value && this.#writtenInLocale) { 3121 this.#widget.value = this.#convertValueToLocale(value); 3122 } else { 3123 this.#widget.value= this.#model.displayValue; 3124 } 3125 } 3126 } 3127 } 3128 } 3129 3130 3131/******************************************************************************* 3132 * Copyright 2022 Adobe 3133 * 3134 * Licensed under the Apache License, Version 2.0 (the "License"); 3135 * you may not use this file except in compliance with the License. 3136 * You may obtain a copy of the License at 3137 * 3138 * http://www.apache.org/licenses/LICENSE-2.0 3139 * 3140 * Unless required by applicable law or agreed to in writing, software 3141 * distributed under the License is distributed on an "AS IS" BASIS, 3142 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3143 * See the License for the specific language governing permissions and 3144 * limitations under the License. 3145 ******************************************************************************/ 3146(function() { 3147 3148 "use strict"; 3149 class NumberInput extends FormView.FormFieldBase { 3150 3151 static NS = FormView.Constants.NS; 3152 static IS = "adaptiveFormNumberInput"; 3153 static bemBlock = 'cmp-adaptiveform-numberinput'; 3154 static selectors = { 3155 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 3156 widget: `.${NumberInput.bemBlock}__widget`, 3157 label: `.${NumberInput.bemBlock}__label`, 3158 description: `.${NumberInput.bemBlock}__longdescription`, 3159 errorDiv: `.${NumberInput.bemBlock}__errormessage`, 3160 qm: `.${NumberInput.bemBlock}__questionmark`, 3161 tooltipDiv: `.${NumberInput.bemBlock}__shortdescription` 3162 }; 3163 3164 constructor(params) { 3165 super(params); 3166 } 3167 3168 getClass() { 3169 return NumberInput.IS; 3170 } 3171 3172 getWidget() { 3173 return this.element.querySelector(NumberInput.selectors.widget); 3174 } 3175 3176 getDescription() { 3177 return this.element.querySelector(NumberInput.selectors.description); 3178 } 3179 3180 getLabel() { 3181 return this.element.querySelector(NumberInput.selectors.label); 3182 } 3183 3184 getErrorDiv() { 3185 return this.element.querySelector(NumberInput.selectors.errorDiv); 3186 } 3187 3188 getTooltipDiv() { 3189 return this.element.querySelector(NumberInput.selectors.tooltipDiv); 3190 } 3191 3192 getQuestionMarkDiv() { 3193 return this.element.querySelector(NumberInput.selectors.qm); 3194 } 3195 3196 initializeWidget() {
3197 this.widgetObject = new NumericInputWidget(this.getWidget(), this._model); 3198 this.getWidget().addEventListener('blur', (e) => { 3199 if(this.element) { 3200 this.setInactive(); 3201 } 3202 }); 3203 } 3204 3205 updateValue(value) { 3206 if (this.widgetObject == null && (this._model._jsonModel.editFormat || this._model._jsonModel.displayFormat || FormView.Utils.isUserAgent('safari'))) { 3207 this.initializeWidget(); 3208 } 3209 if (this.widgetObject) { 3210 this.widgetObject.setValue(value); 3211 super.updateEmptyStatus(); 3212 } else { 3213 super.updateValue(value); 3214 } 3215 } 3216 3217 setModel(model) { 3218 super.setModel(model); 3219 // only initialize if patterns are set 3220 if (this._model._jsonModel.editFormat || this._model._jsonModel.displayFormat || this._model._jsonModel.displayValueExpression 3221 || this._model._jsonModel.type === 'integer' || FormView.Utils.isUserAgent('safari')) { 3222 if (this.widgetObject == null) { 3223 this.initializeWidget(); 3224 } 3225 } else { 3226 if (this.widget.value !== '') { 3227 this.setModelValue(this.widget.value); 3228 } 3229 this.getWidget().addEventListener('blur', (e) => { 3230 this.setModelValue(e.target.value); 3231 if(this.element) { 3232 this.setInactive(); 3233 this.triggerExit(); 3234 } 3235 }); 3236 } 3237 this.getWidget().addEventListener('focus', (e) => { 3238 if (this.element) { 3239 this.setActive(); 3240 this.triggerEnter(); 3241 } 3242 }); 3243 } 3244 } 3245 3246 FormView.Utils.setupField(({element, formContainer}) => { 3247 return new NumberInput({element,formContainer}) 3248 }, NumberInput.selectors.self); 3249})(); 3250 3251/******************************************************************************* 3252 * Copyright 2022 Adobe 3253 * 3254 * Licensed under the Apache License, Version 2.0 (the "License"); 3255 * you may not use this file except in compliance with the License. 3256 * You may obtain a copy of the License at 3257 * 3258 * http://www.apache.org/licenses/LICENSE-2.0 3259 * 3260 * Unless required by applicable law or agreed to in writing, software 3261 * distributed under the License is distributed on an "AS IS" BASIS, 3262 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3263 * See the License for the specific language governing permissions and 3264 * limitations under the License. 3265 ******************************************************************************/ 3266(function () { 3267 3268 class Panel extends FormView.FormPanel { 3269 3270 _templateHTML = {}; 3271 #childIdMap = {} 3272 3273 static NS = FormView.Constants.NS; 3274 static IS = "adaptiveFormPanel"; 3275 static bemBlock = 'cmp-container'; 3276 static selectors = { 3277 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 3278 label: `.${Panel.bemBlock}__label`, 3279 description: `.${Panel.bemBlock}__longdescription`, 3280 qm: `.${Panel.bemBlock}__questionmark`, 3281 tooltipDiv: `.${Panel.bemBlock}__shortdescription` 3282 }; 3283 3284 constructor(params) { 3285 super(params); 3286 } 3287 3288 getClass() { 3289 return Panel.IS; 3290 } 3291 3292 setFocus(id) { 3293 super.setFocus(id); 3294 this.setActive(); 3295 } 3296 3297 getWidgetId(){ 3298 return this.getId(); 3299 } 3300 3301 getWidget() { 3302 return null; 3303 } 3304 3305 getDescription() { 3306 return this.element.querySelector(Panel.selectors.description); 3307 } 3308 3309 getLabel() { 3310 return this.element.querySelector(Panel.selectors.label); 3311 } 3312 3313 getErrorDiv() { 3314 //error div is not defined 3315 //return this.element.querySelector(Panel.selectors.errorDiv); 3316 return null; 3317 } 3318 3319 getTooltipDiv() { 3320 return this.element.querySelector(Panel.selectors.tooltipDiv); 3321 } 3322 3323 getQuestionMarkDiv() { 3324 return this.element.querySelector(Panel.selectors.qm); 3325 } 3326 3327 addChild(childView) { 3328 super.addChild(childView); 3329 if (this.getCountOfAllChildrenInModel() === this.children.length) { 3330 this.#cacheElements(this.element); 3331 this.#cacheDivToAppendChildMarkup(); 3332 this.cacheClosestFieldsInView(); 3333 } else if (childView.getInstanceManager() != null) { 3334 // this is for cases when repeatable instances are added after first initialisation 3335 this.#cacheElements(this.element); 3336 } 3337 } 3338 3339 getChildViewByIndex(index) { 3340 if (this.#getCachedElements()[index] != null) { 3341 return this.getChild(this.#getCachedElements()[index].id) 3342 } 3343 } 3344 3345 /** 3346 * Adds unique HTML for added instance corresponding to requirements of different types of repeatableParent 3347 * @param instanceManager of the repeated component 3348 * @param addedModel of the repeated component 3349 * @param htmlElement of the repeated component 3350 */ 3351 addRepeatableMarkup(instanceManager, addedModel, htmlElement) { 3352 let result = this.#getBeforeViewElement(instanceManager, addedModel.index); 3353 if (result.beforeViewElement != null) { 3354 result.beforeViewElement.after(htmlElement); 3355 } else if (result.parentElement != null) { 3356 if (result.parentElement.children.length == 0) { 3357 result.parentElement.append(htmlElement); 3358 } else { 3359 result.parentElement.insertBefore(htmlElement, result.parentElement.firstElementChild); 3360 } 3361 } 3362 return htmlElement; 3363 } 3364 3365 handleChildRemoval(removedInstanceView) { 3366 this.children.splice(this.children.indexOf(removedInstanceView), 1); 3367 this.#cacheElements(this._elements.self); 3368 } 3369 3370 handleChildAddition(childView) { 3371 //can't initiate cacheElement From here as children property of the panel is not updated at this point, 3372 // hence cacheElement is called from addChild method which ensures panel's addChild is called first and children 3373 // property is updated 3374 } 3375 3376 #cacheElements(wrapper) { 3377 this._elements = {}; 3378 this._elements.self = wrapper; 3379 this._elements.items = []; 3380 this.#childIdMap = {}; 3381 for (let i = 0; i < this.children.length; i++) { 3382 this.#childIdMap[this.children[i].id] = this.children[i]; 3383 } 3384 let components = this._elements.self.querySelectorAll("[data-cmp-is]"); 3385 for (let i = 0; i < components.length; i++) { 3386 //only consider this panel's child and not children of some child panel. 3387 if (this.#childIdMap.hasOwnProperty(components[i].id)) { 3388 this._elements.items.push(components[i]); 3389 } 3390 } 3391 } 3392 3393 #getCachedElements() { 3394 return this._elements.items; 3395 } 3396 3397 #getCachedElementById(id) { 3398 for (let i = 0; i < this.#getCachedElements().length; i++) { 3399 if (this.#getCachedElements()[i].id == id) { 3400 return this.#getCachedElements()[i]; 3401 } 3402 } 3403 } 3404 3405 #cacheDivToAppendChildMarkup() { 3406 if (this.children.length > 0 && this._templateHTML['divToAppendChild'] === undefined) { 3407 var fieldView = this.children[0]; 3408 //because htmlElement cached for repeating is element.parentElement in instanceManager 3409 this._templateHTML['divToAppendChild'] = fieldView.element.parentElement.parentElement; 3410 } 3411 } 3412 3413 #getBeforeViewElement(instanceManager, instanceIndex) { 3414 var result = {}; 3415 var instanceManagerId = instanceManager.getId(); 3416 if (instanceIndex == 0) { 3417 var closestNonRepeatableFieldId = this._templateHTML[instanceManagerId]['closestNonRepeatableFieldId']; 3418 var closestRepeatableFieldInstanceManagerIds = this._templateHTML[instanceManagerId]['closestRepeatableFieldInstanceManagerIds']; 3419 var indexToInsert = this.getIndexToInsert(closestNonRepeatableFieldId, closestRepeatableFieldInstanceManagerIds); 3420 if (indexToInsert > 0) { 3421 result.beforeViewElement = this.#getCachedElements()[indexToInsert - 1].parentElement; 3422 } else { 3423 result.parentElement = this._templateHTML['divToAppendChild']; 3424 } 3425 } else { 3426 let previousInstanceItemDiv = instanceManager.getElementAt(instanceIndex - 1); 3427 result.beforeViewElement = previousInstanceItemDiv; 3428 } 3429 return result; 3430 } 3431 } 3432 3433 FormView.Utils.setupField(({element, formContainer}) => { 3434 return new Panel({element, formContainer}) 3435 }, Panel.selectors.self); 3436})(); 3437 3438/******************************************************************************* 3439 * Copyright 2022 Adobe 3440 * 3441 * Licensed under the Apache License, Version 2.0 (the "License");
3442 * you may not use this file except in compliance with the License. 3443 * You may obtain a copy of the License at 3444 * 3445 * http://www.apache.org/licenses/LICENSE-2.0 3446 * 3447 * Unless required by applicable law or agreed to in writing, software 3448 * distributed under the License is distributed on an "AS IS" BASIS, 3449 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3450 * See the License for the specific language governing permissions and 3451 * limitations under the License. 3452 ******************************************************************************/ 3453(function() { 3454 "use strict"; 3455 3456 class Text extends FormView.FormFieldBase { 3457 3458 static NS = FormView.Constants.NS; 3459 static IS = "adaptiveFormText"; 3460 static bemBlock = 'cmp-adaptiveform-text'; 3461 3462 static selectors = { 3463 self: "[data-" + this.NS + '-is="' + this.IS + '"]' 3464 }; 3465 3466 constructor(params) { 3467 super(params); 3468 } 3469 3470 getWidget() { 3471 return null; 3472 } 3473 3474 getDescription() { 3475 return null; 3476 } 3477 3478 getLabel() { 3479 return null; 3480 } 3481 3482 getErrorDiv() { 3483 return null; 3484 } 3485 3486 getTooltipDiv() { 3487 return null; 3488 } 3489 3490 getQuestionMarkDiv() { 3491 return null; 3492 } 3493 3494 getClass() { 3495 return Text.IS; 3496 } 3497 3498 setFocus() { 3499 const fieldType = this.parentView?.getModel()?.fieldType; 3500 if (fieldType !== 'form' && this.parentView.setFocus) { 3501 this.parentView.setFocus(this.getId()); 3502 } 3503 this.setActive(); 3504 this.element.scrollIntoView({ behavior: 'smooth', block: 'start' }); 3505 } 3506 3507 updateValue(value) { 3508 // html sets undefined value as undefined string in input value, hence this check is added 3509 let actualValue = typeof value === "undefined" ? "" : value; 3510 3511 // Custom configuration for DOMPurify for RTE content 3512 const cleanHTML = (dirtyHTML) => { 3513 // Specify the allowed tags and attributes 3514 const allowedTags = [ 3515 'b', 'strong', 'caption', 'i', 'em', 'u', 3516 'sub', 'sup', 'small', 'blockquote', 3517 'ul', 'ol', 'li', 'a', 'img', 3518 'table', 'tbody', 'tr', 'td', 'th', 3519 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 3520 'br', 'p', 'span' 3521 ]; 3522 const allowedAttributes = [ 3523 'href', 'target', 'rel', '_rte_href', 3524 'src', 'alt' , 'style', '_rte_a_id_repl', 3525 'class', 'id', 'title', 'colspan', 'rowspan', 3526 'cellPadding', 'cellSpacing', 'border', 'width', 'height', 'scope' 3527 ]; 3528 3529 // Sanitize the HTML 3530 const sanitizedHTML = window.DOMPurify ? window.DOMPurify.sanitize(dirtyHTML, { 3531 ALLOWED_TAGS: allowedTags, 3532 ALLOWED_ATTR: allowedAttributes, 3533 }) : dirtyHTML; 3534 3535 return sanitizedHTML; 3536 }; 3537 3538 const sanitizedValue = cleanHTML(actualValue); 3539 3540 // since there is no widget for textview, the innerHTML is being changed 3541 if (this.element.children[0]) { 3542 this.element.children[0].innerHTML = sanitizedValue; 3543 } else { 3544 this.element.innerHTML = sanitizedValue; 3545 } 3546 } 3547 } 3548 3549 FormView.Utils.setupField(({element, formContainer}) => { 3550 return new Text({element, formContainer}) 3551 }, Text.selectors.self); 3552})(); 3553 3554/******************************************************************************* 3555 * Copyright 2022 Adobe 3556 * 3557 * Licensed under the Apache License, Version 2.0 (the "License");
3558 * you may not use this file except in compliance with the License. 3559 * You may obtain a copy of the License at 3560 * 3561 * http://www.apache.org/licenses/LICENSE-2.0 3562 * 3563 * Unless required by applicable law or agreed to in writing, software 3564 * distributed under the License is distributed on an "AS IS" BASIS, 3565 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3566 * See the License for the specific language governing permissions and 3567 * limitations under the License. 3568 ******************************************************************************/ 3569(function() { 3570 3571 3572 "use strict"; 3573 class CheckBoxGroup extends FormView.FormOptionFieldBase { 3574 3575 static NS = FormView.Constants.NS; 3576 /** 3577 * Each FormField has a data attribute class that is prefixed along with the global namespace to 3578 * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be 3579 * data-{NS}-{IS}-x="" 3580 * @type {string} 3581 */ 3582 static IS = "adaptiveFormCheckBoxGroup"; 3583 static bemBlock = 'cmp-adaptiveform-checkboxgroup' 3584 static checkboxBemBlock = 'cmp-adaptiveform-checkbox' 3585 static selectors = { 3586 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 3587 widgets: `.${CheckBoxGroup.bemBlock}__widget`, 3588 widget: `.${CheckBoxGroup.bemBlock}__option__widget`, 3589 widgetLabel: `.${CheckBoxGroup.bemBlock}__label`, 3590 label: `.${CheckBoxGroup.bemBlock}__label`, 3591 description: `.${CheckBoxGroup.bemBlock}__longdescription`, 3592 qm: `.${CheckBoxGroup.bemBlock}__questionmark`, 3593 errorDiv: `.${CheckBoxGroup.bemBlock}__errormessage`, 3594 tooltipDiv: `.${CheckBoxGroup.bemBlock}__shortdescription`, 3595 item: `.${CheckBoxGroup.bemBlock}-item`, 3596 optionLabel: `${CheckBoxGroup.bemBlock}__option-label`, 3597 optionLink: `${CheckBoxGroup.bemBlock}__links` 3598 }; 3599 3600 constructor(params) { 3601 super(params); 3602 this.qm = this.element.querySelector(CheckBoxGroup.selectors.qm) 3603 this.widgetLabel = this.element.querySelector(CheckBoxGroup.selectors.widgetLabel) 3604 } 3605 3606 getWidgets() { 3607 return this.element.querySelector(CheckBoxGroup.selectors.widgets); 3608 } 3609 3610 getWidget() { 3611 return this.element.querySelectorAll(CheckBoxGroup.selectors.widget); 3612 } 3613 3614 getDescription() { 3615 return this.element.querySelector(CheckBoxGroup.selectors.description); 3616 } 3617 3618 getLabel() { 3619 return this.element.querySelector(CheckBoxGroup.selectors.label); 3620 } 3621 3622 getErrorDiv() { 3623 return this.element.querySelector(CheckBoxGroup.selectors.errorDiv); 3624 } 3625 3626 getQuestionMarkDiv() { 3627 return this.element.querySelector(CheckBoxGroup.selectors.qm); 3628 } 3629 3630 getTooltipDiv() { 3631 return this.element.querySelector(CheckBoxGroup.selectors.tooltipDiv); 3632 } 3633 3634 getOptions() { 3635 return this.element.querySelectorAll(CheckBoxGroup.selectors.item); 3636 } 3637 3638 #addWidgetListeners(optionWidget) { 3639 optionWidget.addEventListener('change', (e) => { 3640 this.#updateModelValue(optionWidget); 3641 }); 3642 optionWidget.addEventListener('focus', (e) => { 3643 this.setActive(); 3644 }); 3645 optionWidget.addEventListener('blur', (e) => { 3646 this.setInactive(); 3647 }); 3648 } 3649 3650 setModel(model) { 3651 super.setModel(model); 3652 this.widget.forEach(optionWidget => { 3653 this.#addWidgetListeners(optionWidget); 3654 }); 3655 let optionLinks = this.element.querySelectorAll(`.${CheckBoxGroup.selectors.optionLink}`); 3656 const actionKeys = ['Enter', ' ', 'Spacebar', 'Space']; 3657 optionLinks.forEach(optionLink => { 3658 optionLink.addEventListener('keydown', (e)=>{ 3659 if(actionKeys.includes(e.key)) { 3660 optionLink.click(); 3661 } 3662 }); 3663 }); 3664 this.#updateModelValue(); 3665 } 3666 3667 #updateModelValue() { 3668 let value = []; 3669 this.widget.forEach(widget => { 3670 if (widget.checked) { 3671 value.push(widget.value) 3672 } 3673 }, this); 3674 if (value.length !== 0 || this._model.value != null) { 3675 this.setModelValue(value) 3676 } 3677 } 3678
3679 updateValidity(validity) { 3680 if(validity.valid === undefined) { 3681 this.element.removeAttribute(FormView.Constants.DATA_ATTRIBUTE_VALID); 3682 this.widget.forEach(widget => widget.removeAttribute(FormView.Constants.ARIA_INVALID)); 3683 } else { 3684 this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_VALID, validity.valid); 3685 this.widget.forEach(widget => widget.setAttribute(FormView.Constants.ARIA_INVALID, !validity.valid)); 3686 } 3687 } 3688 3689 updateValue(modelValue) { 3690 modelValue = [].concat(modelValue); 3691 let selectedWidgetValues = modelValue.map(String); 3692 this.widget.forEach(widget => { 3693 if (selectedWidgetValues.includes((widget.value))) { 3694 widget.checked = true 3695 widget.setAttribute(FormView.Constants.HTML_ATTRS.CHECKED, FormView.Constants.HTML_ATTRS.CHECKED); 3696 } else { 3697 widget.checked = false 3698 widget.removeAttribute(FormView.Constants.HTML_ATTRS.CHECKED); 3699 } 3700 }, this) 3701 super.updateEmptyStatus(); 3702 } 3703 3704 #createCheckBoxItem(value, itemLabel) { 3705 // This doesn't cater for optionLink __links as toggelablelink component is hidden 3706 let richScreenReaderText = `${this._model.label.value}: ${itemLabel}`; 3707 let plainScreenReaderText = window.DOMPurify ? window.DOMPurify.sanitize(richScreenReaderText, { ALLOWED_TAGS: [] }) : richScreenReaderText; 3708 const optionTemplate = ` 3709 <div class="${CheckBoxGroup.selectors.item.slice(1)}"> 3710 <label class="${CheckBoxGroup.selectors.optionLabel}"> 3711 <input type="checkbox" class="${CheckBoxGroup.selectors.widget.slice(1)}" name="${this._model.name}" value="${value}" aria-label="${plainScreenReaderText}" tabindex="0"> 3712 <span>${itemLabel}</span> 3713 </label> 3714 </div>`; 3715 3716 const container = document.createElement('div'); // Create a container element to hold the template 3717 container.innerHTML = optionTemplate; 3718 let addedOptionWidget = container.querySelector(CheckBoxGroup.selectors.widget); 3719 if(this._model.readOnly === true || this._model.enabled === false) { 3720 addedOptionWidget.setAttribute("disabled", true); 3721 if(this._model.readOnly === true) { 3722 addedOptionWidget.setAttribute("aria-readonly", true); 3723 } 3724 } 3725 this.#addWidgetListeners(addedOptionWidget); 3726 return container.firstElementChild; // Return the first child, which is the created option 3727 } 3728 updateEnum(newEnums) { 3729 super.updateEnumForRadioButtonAndCheckbox(newEnums, this.#createCheckBoxItem); 3730 // refresh the widget references, to dynamically added options 3731 this.widget = this.getWidget(); 3732 } 3733 3734 updateEnumNames(newEnumNames) { 3735 super.updateEnumNamesForRadioButtonAndCheckbox(newEnumNames, this.#createCheckBoxItem); 3736 // refresh the widget references, to dynamically added options 3737 this.widget = this.getWidget(); 3738 } 3739 3740 updateEnabled(enabled, state) { 3741 this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_ENABLED, enabled); 3742 let widgets = this.widget; 3743 widgets.forEach(widget => { 3744 if (enabled === false) { 3745 if(state.readOnly === false){ 3746 widget.setAttribute(FormView.Constants.HTML_ATTRS.DISABLED, "disabled"); 3747 } 3748 } else if (state.readOnly === false) { 3749 widget.removeAttribute(FormView.Constants.HTML_ATTRS.DISABLED); 3750 } 3751 }); 3752 } 3753 3754 updateReadOnly(readonly) { 3755 let widgets = this.widget; 3756 this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_READONLY, readonly); 3757 widgets.forEach(widget => { 3758 if (readonly === true) { 3759 widget.setAttribute(FormView.Constants.HTML_ATTRS.DISABLED, "disabled"); 3760 widget.setAttribute("aria-readonly", true); 3761 } else { 3762 widget.removeAttribute(FormView.Constants.HTML_ATTRS.DISABLED); 3763 widget.removeAttribute("aria-readonly"); 3764 } 3765 }); 3766 } 3767 updateRequired(required, state) { 3768 if (this.widget) { 3769 this.element.toggleAttribute("required", required); 3770 this.element.setAttribute("data-cmp-required", required); 3771 } 3772 } 3773 3774 syncMarkupWithModel() { 3775 super.syncMarkupWithModel(); 3776 this.updateEnum(this._model.enum); 3777 this.updateEnumNames(this._model.enumNames); 3778 } 3779 } 3780 3781 FormView.Utils.setupField(({element, formContainer}) => { 3782 return new CheckBoxGroup({element, formContainer}) 3783 }, CheckBoxGroup.selectors.self); 3784 3785})(); 3786 3787/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3788 ~ Copyright 2024 Adobe 3789 ~ 3790 ~ Licensed under the Apache License, Version 2.0 (the "License");
3791 ~ you may not use this file except in compliance with the License. 3792 ~ You may obtain a copy of the License at 3793 ~ 3794 ~ http://www.apache.org/licenses/LICENSE-2.0 3795 ~ 3796 ~ Unless required by applicable law or agreed to in writing, software 3797 ~ distributed under the License is distributed on an "AS IS" BASIS, 3798 ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3799 ~ See the License for the specific language governing permissions and 3800 ~ limitations under the License. 3801 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ 3802(function() { 3803 3804 "use strict"; 3805 class Button extends FormView.FormFieldBase { 3806 3807 static NS = FormView.Constants.NS; 3808 /** 3809 * Each FormField has a data attribute class that is prefixed along with the global namespace to 3810 * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be 3811 * data-{NS}-{IS}-x="" 3812 * @type {string} 3813 */ 3814 static IS = "adaptiveFormButton"; 3815 static bemBlock = 'cmp-adaptiveform-button'; 3816 static selectors = { 3817 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 3818 widget: `.${Button.bemBlock}__widget`, 3819 label: `.${Button.bemBlock}__text`, 3820 description: `.${Button.bemBlock}__longdescription`, 3821 qm: `.${Button.bemBlock}__questionmark`, 3822 tooltipDiv: `.${Button.bemBlock}__shortdescription` 3823 }; 3824 3825 constructor(params) { 3826 super(params); 3827 const formModel = this.formContainer?.getModel?.(); 3828 if (!formModel) { return; } 3829 3830 formModel.subscribe((action) => { // hide loader if validation fails (no submit performed) 3831 const errors = action?.payload; 3832 if (Array.isArray(errors) && errors.length > 0) { 3833 this._hideLoader(); 3834 } 3835 }, 'validationComplete'); 3836 3837 formModel.subscribe(() => { // hide loader on submit success 3838 this._hideLoader(); 3839 }, 'submitSuccess'); 3840 3841 formModel.subscribe(() => { // hide loader on submit error 3842 this._hideLoader(); 3843 }, 'submitError'); 3844 } 3845 3846 _container = null; 3847 3848 _getContainer() { 3849 if (this._container) return this._container; 3850 const container = this.formContainer?.getFormElement?.(); 3851 if (container) this._container = container; 3852 return this._container; 3853 } 3854 3855 _showLoader() { 3856 const container = this._getContainer(); 3857 if (container) { 3858 container.classList.add('cmp-adaptiveform-container--submitting'); 3859 } 3860 } 3861 3862 _hideLoader() { 3863 const container = this._getContainer(); 3864 if (container) { 3865 container.classList.remove('cmp-adaptiveform-container--submitting'); 3866 } 3867 } 3868 3869 getQuestionMarkDiv() { 3870 return this.element.querySelector(Button.selectors.qm); 3871 } 3872 3873 getLabel() { 3874 return this.element.querySelector(Button.selectors.label); 3875 } 3876 3877 getWidget() { 3878 return this.element.querySelector(Button.selectors.widget); 3879 } 3880 3881 /** 3882 * Return the description element. 3883 * @returns {HTMLElement} 3884 */ 3885 getDescription() { 3886 return this.element.querySelector(Button.selectors.description); 3887 } 3888 3889 getErrorDiv() { 3890 return null; 3891 } 3892 3893 getTooltipDiv() { 3894 return this.element.querySelector(Button.selectors.tooltipDiv); 3895 } 3896 3897 setModel(model) { 3898 super.setModel(model); 3899 this.getWidget().addEventListener("click", (event) => { 3900 if (this.widget.type === 'submit' || this.widget.type === 'reset') { 3901 event.preventDefault(); 3902 } 3903 if (this.widget.type === 'submit') { 3904 this._showLoader(); 3905 } 3906 this._model.dispatch(new FormView.Actions.Click()); 3907 }); 3908 } 3909 } 3910 3911 FormView.Utils.setupField(({element, formContainer}) => { 3912 return new Button({element, formContainer}) 3913 }, Button.selectors.self); 3914 3915})(); 3916/******************************************************************************* 3917 * Copyright 2022 Adobe 3918 * 3919 * Licensed under the Apache License, Version 2.0 (the "License");
3920 * you may not use this file except in compliance with the License. 3921 * You may obtain a copy of the License at 3922 * 3923 * http://www.apache.org/licenses/LICENSE-2.0 3924 * 3925 * Unless required by applicable law or agreed to in writing, software 3926 * distributed under the License is distributed on an "AS IS" BASIS, 3927 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3928 * See the License for the specific language governing permissions and 3929 * limitations under the License. 3930 ******************************************************************************/ 3931(function(document) { 3932 3933 "use strict"; 3934 class Image extends FormView.FormFieldBase { 3935 3936 static NS = FormView.Constants.NS; 3937 static IS = "adaptiveFormImage"; 3938 static bemBlock = 'cmp-image'; 3939 3940 static selectors = { 3941 self: "[data-" + this.NS + '-is="' + this.IS + '"]' 3942 }; 3943 3944 constructor(params) { 3945 super(params); 3946 } 3947 3948 getClass() { 3949 return Image.IS; 3950 } 3951 3952 getWidget() { 3953 return null; 3954 } 3955 3956 getDescription() { 3957 return null; 3958 } 3959 3960 getLabel() { 3961 return null; 3962 } 3963 3964 getErrorDiv() { 3965 return null; 3966 } 3967 3968 getTooltipDiv() { 3969 return null; 3970 } 3971 3972 getQuestionMarkDiv() { 3973 return null; 3974 } 3975 3976 setFocus() { 3977 this.setActive(); 3978 } 3979 3980 updateValue(value) { 3981 if (this.element) { 3982 this.element.setAttribute('data-cmp-src', value); 3983 const imgElement = this.element.querySelector('img'); 3984 if (imgElement) { 3985 imgElement.setAttribute('src', value); 3986 } 3987 } 3988 } 3989 } 3990 3991 FormView.Utils.setupField(({element, formContainer}) => { 3992 return new Image({element, formContainer}) 3993 }, Image.selectors.self); 3994})(); 3995 3996/******************************************************************************* 3997 * Copyright 2022 Adobe 3998 * 3999 * Licensed under the Apache License, Version 2.0 (the "License"); 4000 * you may not use this file except in compliance with the License. 4001 * You may obtain a copy of the License at 4002 * 4003 * http://www.apache.org/licenses/LICENSE-2.0 4004 * 4005 * Unless required by applicable law or agreed to in writing, software 4006 * distributed under the License is distributed on an "AS IS" BASIS, 4007 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4008 * See the License for the specific language governing permissions and 4009 * limitations under the License. 4010 ******************************************************************************/ 4011(function() { 4012 4013 "use strict"; 4014 class DropDown extends FormView.FormOptionFieldBase { 4015 4016 static NS = FormView.Constants.NS; 4017 /** 4018 * Each FormField has a data attribute class that is prefixed along with the global namespace to 4019 * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be 4020 * data-{NS}-{IS}-x="" 4021 * @type {string} 4022 */ 4023 static IS = "adaptiveFormDropDown"; 4024 static bemBlock = 'cmp-adaptiveform-dropdown'; 4025 static selectors = { 4026 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 4027 widget: `.${DropDown.bemBlock}__widget`, 4028 options: `.${DropDown.bemBlock}__option`, 4029 label: `.${DropDown.bemBlock}__label`, 4030 description: `.${DropDown.bemBlock}__longdescription`, 4031 qm: `.${DropDown.bemBlock}__questionmark`, 4032 errorDiv: `.${DropDown.bemBlock}__errormessage`, 4033 tooltipDiv: `.${DropDown.bemBlock}__shortdescription` 4034 }; 4035 4036 constructor(params) { 4037 super(params); 4038 this.qm = this.element.querySelector(DropDown.selectors.qm); 4039 } 4040 4041 getWidget() { 4042 return this.element.querySelector(DropDown.selectors.widget); 4043 } 4044 4045 getDescription() { 4046 return this.element.querySelector(DropDown.selectors.description); 4047 } 4048 4049 getLabel() { 4050 return this.element.querySelector(DropDown.selectors.label); 4051 } 4052 4053 getErrorDiv() { 4054 return this.element.querySelector(DropDown.selectors.errorDiv); 4055 } 4056 4057 getQuestionMarkDiv() { 4058 return this.element.querySelector(DropDown.selectors.qm); 4059 } 4060 4061 getTooltipDiv() { 4062 return this.element.querySelector(DropDown.selectors.tooltipDiv); 4063 } 4064 4065 getOptions() { 4066 return this.element.querySelectorAll(DropDown.selectors.options); 4067 } 4068 4069 #checkIfEqual = function(value, optionValue, multiSelect) { 4070 if(multiSelect) { 4071 let isPresent = false;
4072 value.forEach((saveValue) => { 4073 if(String(saveValue) === optionValue) // save value can be number and boolean also. 4074 isPresent = true; 4075 }) 4076 return isPresent; 4077 } 4078 return String(value) === optionValue; 4079 } 4080 4081 updateEnabled(enabled, state) { 4082 this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_ENABLED, enabled); 4083 let widget = this.widget; 4084 if (enabled === false) { 4085 if(state.readOnly === false){ 4086 widget.setAttribute(FormView.Constants.HTML_ATTRS.DISABLED, "disabled"); 4087 } 4088 } else if (state.readOnly === false) { 4089 widget.removeAttribute(FormView.Constants.HTML_ATTRS.DISABLED); 4090 } 4091 } 4092 4093 updateReadOnly(readonly) { 4094 let widget = this.widget; 4095 this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_READONLY, readonly); 4096 if (readonly === true) { 4097 widget.setAttribute(FormView.Constants.HTML_ATTRS.DISABLED, "disabled"); 4098 widget.setAttribute("aria-readonly", true); 4099 } else { 4100 widget.removeAttribute(FormView.Constants.HTML_ATTRS.DISABLED); 4101 widget.removeAttribute("aria-readonly"); 4102 } 4103 } 4104 4105 updateValue(value) { 4106 if(value == null) { // if undefined or null, reset the widget 4107 this.widget.selectedIndex = -1; 4108 return; 4109 } 4110 let isMultiSelect = this._model.isArrayType(); 4111 [...this.widget].forEach((option) => { 4112 // clear of any selection, and re-add selection (otherwise HTML shows stale state if it already existed) 4113 option.removeAttribute('selected'); 4114 if(this.#checkIfEqual(value, option.value, isMultiSelect)) { 4115 option.setAttribute('selected', 'selected'); 4116 } 4117 }); 4118 super.updateEmptyStatus(); 4119 } 4120 4121 #createDropDownOptions(value, label) { 4122 const optionTemplate = `<option value="${value}" class="${DropDown.selectors.options.slice(1)}">${label}</option>`; 4123 const container = document.createElement('div'); // Create a container element to hold the template 4124 container.innerHTML = optionTemplate; 4125 return container.firstElementChild; // Return the first child, which is the created option 4126 } 4127 4128 #removeAllOptions() { 4129 while(this.getOptions().length !== 0) { 4130 this.getWidget().remove(this.getOptions().length) // not removing the blank option 4131 } 4132 } 4133 4134 /** 4135 * @override 4136 * Method for updating the saved value in the option field. 4137 * It contains the logic for updating the 'enum' value. 4138 * 4139 * @param {Array} newEnums - An array of primitive values to be saved in the option field. 4140 */ 4141 updateEnum(newEnums) { 4142 let options = this.getOptions(); 4143 let currentEnumSize = options.length; 4144 let startIndex = options[0] && options[0].value === '' ? 1 : 0; // Check if the first option is a blank option 4145 4146 // Update existing options and add new options in the same loop 4147 newEnums.forEach((value, index) => { 4148 if (index + startIndex < currentEnumSize) { 4149 // Update existing option 4150 options[index + startIndex].value = value; 4151 } else { 4152 // Add new option 4153 this.getWidget().add(this.#createDropDownOptions(value, value)); 4154 } 4155 }); 4156 4157 // Remove extra options, but never remove the first option 4158 while (currentEnumSize > newEnums.length + startIndex) { 4159 this.getWidget().remove(currentEnumSize--); 4160 } 4161 } 4162 4163 /** 4164 * @override 4165 * Method for updating the display value in the option field. 4166 * It contains the logic for updating the 'enumNames' value. 4167 * 4168 * @param {Array} newEnumNames - An array of primitive values to be displayed in the option field. 4169 */ 4170 updateEnumNames(newEnumNames) { 4171 let options = this.getOptions(); 4172 let currentEnumNameSize = options.length; 4173 if(currentEnumNameSize === 0) { // case 1: Create all dropdown new options
4174 newEnumNames.forEach((value) => { 4175 this.getWidget().add(this.#createDropDownOptions(value, value)); 4176 }) 4177 } else if(currentEnumNameSize > newEnumNames.length) { // case 2: Replace existing enumNames, remaining enumNames = enums 4178 newEnumNames.forEach((value, index) => { 4179 options[index].text = value; 4180 }); 4181 4182 options.forEach((option, index) => { 4183 if(index >= newEnumNames.length) { 4184 option.text = option.value; 4185 } 4186 }) 4187 } else { // case 3: Replace all existing enumNames 4188 options.forEach((option, index) => { 4189 option.text = newEnumNames[index]; 4190 }); 4191 } 4192 } 4193 4194 setModel(model) { 4195 super.setModel(model); 4196 if (this.widget.value !== '') { 4197 this.#updateModelValue(this.widget); 4198 } 4199 this.widget.addEventListener('change', (e) => { 4200 this.#updateModelValue(e.target); 4201 }); 4202 this.widget.addEventListener('focus', (e) => { 4203 this.setActive(); 4204 this.triggerEnter(); 4205 }); 4206 this.widget.addEventListener('blur', (e) => { 4207 this.setInactive(); 4208 this.triggerExit(); 4209 }); 4210 } 4211 4212 #updateModelValue(widget) { 4213 if(this._model.isArrayType()) { 4214 let valueArray = []; 4215 [...this.widget].forEach((option) => { 4216 if(option.selected) { 4217 valueArray.push(option.value); 4218 } 4219 }); 4220 if (valueArray.length !== 0 || this._model.value != null) { 4221 this.setModelValue(valueArray); 4222 } 4223 } else { 4224 this.setModelValue(widget.value); 4225 } 4226 } 4227 } 4228 4229 FormView.Utils.setupField(({element, formContainer}) => { 4230 return new DropDown({element, formContainer}) 4231 }, DropDown.selectors.self); 4232 4233})(); 4234 4235/******************************************************************************* 4236 * Copyright 2022 Adobe 4237 * 4238 * Licensed under the Apache License, Version 2.0 (the "License"); 4239 * you may not use this file except in compliance with the License. 4240 * You may obtain a copy of the License at 4241 * 4242 * http://www.apache.org/licenses/LICENSE-2.0 4243 * 4244 * Unless required by applicable law or agreed to in writing, software 4245 * distributed under the License is distributed on an "AS IS" BASIS, 4246 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4247 * See the License for the specific language governing permissions and 4248 * limitations under the License. 4249 ******************************************************************************/ 4250(function () { 4251 4252 function onAccordionMixinLoaded(event) { 4253 const AccordionMixin = event.detail.AccordionMixin; 4254 4255 class Accordion extends AccordionMixin(FormView.FormPanel) { 4256 4257 static NS = FormView.Constants.NS; 4258 static DATA_ATTRIBUTE_VISIBLE = 'data-cmp-visible'; 4259 _templateHTML = {}; 4260 static selectors = { 4261 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 4262 widget: `.${Accordion.bemBlock}__widget`, 4263 description: `.${Accordion.bemBlock}__longdescription`, 4264 qm: `.${Accordion.bemBlock}__questionmark`, 4265 tooltipDiv: `.${Accordion.bemBlock}__shortdescription`, 4266 label: `.${Accordion.bemBlock}__label`, 4267 item: `.${Accordion.bemBlock}__item` 4268 }; 4269 4270 static keyCodes = { 4271 ENTER: 13, 4272 SPACE: 32, 4273 END: 35, 4274 HOME: 36, 4275 ARROW_LEFT: 37, 4276 ARROW_UP: 38, 4277 ARROW_RIGHT: 39, 4278 ARROW_DOWN: 40 4279 }; 4280 4281 constructor(params) { 4282 super(params); 4283 const {element} = params; 4284 this.cacheElements(element); 4285 if (this.getCachedItems()) { 4286 var expandedItems = this.getExpandedItems(); 4287 // multiple expanded items annotated, display the last item open. 4288 if (expandedItems.length > 1) { 4289 var lastExpandedItem = expandedItems[expandedItems.length - 1] 4290 this.expandItem(lastExpandedItem);
4291 this.collapseAllOtherItems(lastExpandedItem.id); 4292 } 4293 this.refreshItems(); 4294 this.#bindEvents(); 4295 } 4296 } 4297 4298 getClass() { 4299 return Accordion.IS; 4300 } 4301 4302 getWidget() { 4303 return null; 4304 } 4305 4306 getDescription() { 4307 return this.element.querySelector(Accordion.selectors.description); 4308 } 4309 4310 getLabel() { 4311 return this.element.querySelector(Accordion.selectors.label); 4312 } 4313 4314 getErrorDiv() { 4315 return null; 4316 } 4317 4318 getTooltipDiv() { 4319 return this.element.querySelector(Accordion.selectors.tooltipDiv); 4320 } 4321 4322 getQuestionMarkDiv() { 4323 return this.element.querySelector(Accordion.selectors.qm); 4324 } 4325 4326 setFocus(id) { 4327 super.setFocus(id); 4328 this.setActive(); 4329 this.#collapseAllItems(); 4330 const item = this.getItemById(id + '-item'); 4331 this.expandItem(item) 4332 } 4333 4334 #collapseAllItems() { 4335 var items = this.getCachedItems(); 4336 if (items) { 4337 for (var i = 0; i < items.length; i++) { 4338 if (this.isItemExpanded(items[i])) { 4339 this.collapseItem(items[i]) 4340 } 4341 } 4342 } 4343 } 4344 4345 /** 4346 * Binds Accordion event handling. 4347 * 4348 * @private 4349 */ 4350 #bindEvents() { 4351 var buttons = this.getCachedButtons(); 4352 if (buttons) { 4353 var _self = this; 4354 for (var i = 0; i < buttons.length; i++) { 4355 (function (index) { 4356 buttons[index].addEventListener("click", function (event) { 4357 var itemDivId = _self.#convertToItemDivId(buttons[index].id); 4358 _self.toggle(itemDivId); 4359 _self.collapseAllOtherItems(itemDivId); 4360 _self.#focusButton(buttons[index].id); 4361 }); 4362 buttons[index].addEventListener("keydown", function (event) { 4363 _self.#onButtonKeyDown(event, buttons[index].id); 4364 }); 4365 })(i); 4366 } 4367 } 4368 } 4369 4370 /** 4371 * Binds Accordion event handling. 4372 * 4373 * @private 4374 */ 4375 #bindEventsToAddedChild(addedChildId) { 4376 var _self = this; 4377 var buttonId = addedChildId + Accordion.idSuffixes.button; 4378 var button = this.#getButtonById(buttonId); 4379 button.addEventListener("click", function (event) { 4380 var itemDivId = _self.#convertToItemDivId(buttonId); 4381 _self.toggle(itemDivId); 4382 _self.collapseAllOtherItems(itemDivId); 4383 _self.#focusButton(buttonId); 4384 }); 4385 button.addEventListener("keydown", function (event) { 4386 _self.#onButtonKeyDown(event, buttonId); 4387 }); 4388 } 4389 4390 /** 4391 * Handles button keydown events. 4392 * 4393 * @private 4394 * @param {Object} event The keydown event 4395 * @param {Number} id The id of the button triggering the event 4396 */ 4397 #onButtonKeyDown(event, id) { 4398 var buttons = this.getCachedButtons(); 4399 var lastIndex = buttons.length - 1; 4400 var index = this.#getButtonIndexById(id); 4401 4402 switch (event.keyCode) { 4403 case Accordion.keyCodes.ARROW_LEFT: 4404 case Accordion.keyCodes.ARROW_UP: 4405 event.preventDefault(); 4406 if (index > 0) { 4407 this.#focusButton(buttons[index - 1].id); 4408 } 4409 break; 4410 case Accordion.keyCodes.ARROW_RIGHT: 4411 case Accordion.keyCodes.ARROW_DOWN: 4412 event.preventDefault(); 4413 if (index < lastIndex) { 4414 this.#focusButton(buttons[index + 1].id); 4415 } 4416 break; 4417 case Accordion.keyCodes.HOME: 4418 event.preventDefault(); 4419 this.#focusButton(buttons[0].id); 4420 break; 4421 case Accordion.keyCodes.END: 4422 event.preventDefault(); 4423 this.#focusButton(buttons[lastIndex].id); 4424 break;
4425 case Accordion.keyCodes.ENTER: 4426 case Accordion.keyCodes.SPACE: 4427 event.preventDefault(); 4428 var itemDivId = this.#convertToItemDivId(buttons[index].id); 4429 this.toggle(itemDivId); 4430 this.collapseAllOtherItems(itemDivId); 4431 this.#focusButton(buttons[index].id); 4432 break; 4433 default: 4434 return; 4435 } 4436 } 4437 4438 /** 4439 * Focuses the button at the provided index. 4440 * 4441 * @private 4442 * @param {Number} id The id of the button to focus 4443 */ 4444 #focusButton(id) { 4445 var button = this.#getButtonById(id); 4446 button.focus(); 4447 } 4448 4449 addChild(childView) { 4450 super.addChild(childView); 4451 this.#cacheTemplateHTML(childView); 4452 if (this.getCountOfAllChildrenInModel() === this.children.length) { 4453 this.cacheClosestFieldsInView(); 4454 this.handleHiddenChildrenVisibility(); 4455 } 4456 } 4457 4458 /** 4459 * Adds unique HTML for added instance corresponding to requirements of different types of repeatableParent 4460 * @param instanceManager of the repeated component 4461 * @param addedModel of the repeated component 4462 * @param htmlElement of the repeated component 4463 */ 4464 addRepeatableMarkup(instanceManager, addedModel, htmlElement) { 4465 var accordionItemDivToBeRepeated = this.#prepareAccordionMarkupToBeAdded(instanceManager, addedModel, htmlElement); 4466 let result = this.#getBeforeViewElement(instanceManager, addedModel.index); 4467 if (result.beforeViewElement != null) { 4468 result.beforeViewElement.after(accordionItemDivToBeRepeated); 4469 } else if (result.parentElement != null) { 4470 var firstChildAccordionItem = result.parentElement.querySelector(Accordion.selectors.item); 4471 if (firstChildAccordionItem != null) { 4472 result.parentElement.insertBefore(accordionItemDivToBeRepeated, firstChildAccordionItem); 4473 } else { 4474 result.parentElement.append(accordionItemDivToBeRepeated); 4475 } 4476 } 4477 this.#showHideRepeatableButtons(instanceManager); 4478 return accordionItemDivToBeRepeated; 4479 } 4480 4481 focusOnRepeatableInstances(id) { 4482 const panelId = id.replace(Accordion.idSuffixes.item, ""); 4483 const form = this.formContainer.getModel(); 4484 const tab = this.getModel().getState().items.find(item => item.type === 'array')?.items?.find(subItem => subItem.id === panelId) 4485 const field = form.getElement(tab?.id); 4486 if (field) { 4487 setTimeout(() => {form.setFocus(field)}, 0); 4488 } 4489 } 4490 4491 handleChildAddition(childView) { 4492 var itemDivToExpand; 4493 this.cacheElements(this._elements.self); 4494 this.#bindEventsToAddedChild(childView.id); 4495 if (childView.getInstanceManager().getModel().minOccur != undefined && childView.getInstanceManager().children.length > childView.getInstanceManager().getModel().minOccur) { 4496 itemDivToExpand = this.getItemById(childView.id + Accordion.idSuffixes.item); 4497 } else { 4498 //this will run at initial runtime loading when the repeatable panel is being added minOccur no of times. 4499 // in this case we want the focus to stay at first tab 4500 itemDivToExpand = this.findFirstVisibleChild(this.getCachedItems()); 4501 } 4502 this.expandItem(itemDivToExpand); 4503 this.collapseAllOtherItems(itemDivToExpand.id); 4504 4505 const cachedItems = this.getCachedItems();
4506 const newIndex = cachedItems.indexOf(itemDivToExpand); 4507 this.getCachedButtons()[newIndex].classList.remove(this.constructor.cssClasses.button.stepped); 4508 this.getCachedPanels()[newIndex].classList.remove(this.constructor.cssClasses.panel.stepped); 4509 4510 this.focusOnRepeatableInstances(itemDivToExpand.id); 4511 4512 this.#showHideRepeatableButtons(childView.getInstanceManager()); 4513 } 4514 4515 handleChildRemoval(removedInstanceView) { 4516 var removedAccordionItemDivId = removedInstanceView.element.id + Accordion.idSuffixes.item; 4517 var removedAccordionItemDiv = this.getItemById(removedAccordionItemDivId); 4518 4519 // Find the previous item before removing the current one 4520 var cachedItems = this.getCachedItems(); 4521 var currentIndex = cachedItems.indexOf(removedAccordionItemDiv); 4522 var itemDivToExpand = null; 4523 4524 // If there are items and current item is found 4525 if (cachedItems && cachedItems.length > 0 && currentIndex > -1) { 4526 // If there's a previous item, use it 4527 if (currentIndex > 0) { 4528 itemDivToExpand = cachedItems[currentIndex - 1]; 4529 } else { 4530 // If we're removing the first item, use the next one if available 4531 itemDivToExpand = cachedItems[1] || null; 4532 } 4533 } 4534 4535 // Now remove the item 4536 removedAccordionItemDiv.remove(); 4537 this.children.splice(this.children.indexOf(removedInstanceView), 1); 4538 this.cacheElements(this._elements.self); 4539 4540 // Expand the target item if found 4541 if (itemDivToExpand) { 4542 this.expandItem(itemDivToExpand); 4543 this.collapseAllOtherItems(itemDivToExpand.id); 4544 this.focusOnRepeatableInstances(itemDivToExpand.id) 4545 } 4546 4547 this.#showHideRepeatableButtons(removedInstanceView.getInstanceManager()); 4548 } 4549 4550 #syncLabel() { 4551 let labelElement = typeof this.getLabel === 'function' ? this.getLabel() : null; 4552 if (labelElement) { 4553 labelElement.setAttribute('for', this.getId()); 4554 } 4555 } 4556 4557 syncMarkupWithModel() { 4558 super.syncMarkupWithModel(); 4559 this.#syncLabel(); 4560 for (var itemDiv of this.getCachedItems()) { 4561 this.#syncAccordionMarkup(itemDiv); 4562 } 4563 } 4564 4565 getChildViewByIndex(index) { 4566 var accordionPanels = this.getCachedPanels(); 4567 var fieldId = accordionPanels[index].id.substring(0, accordionPanels[index].id.lastIndexOf("-")); 4568 return this.getChild(fieldId); 4569 } 4570 4571 #getBeforeViewElement(instanceManager, instanceIndex) { 4572 var result = {}; 4573 var instanceManagerId = instanceManager.getId(); 4574 if (instanceIndex == 0) { 4575 var closestNonRepeatableFieldId = this._templateHTML[instanceManagerId]['closestNonRepeatableFieldId']; 4576 var closestRepeatableFieldInstanceManagerIds = this._templateHTML[instanceManagerId]['closestRepeatableFieldInstanceManagerIds']; 4577 var indexToInsert = this.getIndexToInsert(closestNonRepeatableFieldId, closestRepeatableFieldInstanceManagerIds); 4578 if (indexToInsert > 0) { 4579 result.beforeViewElement = this.getCachedItems()[indexToInsert - 1]; 4580 } else { 4581 result.parentElement = this.element; 4582 } 4583 } else { 4584 let previousInstanceElement = this.#getRepeatableElementAt(instanceManager, instanceIndex - 1); 4585 result.beforeViewElement = previousInstanceElement; 4586 } 4587 return result; 4588 } 4589 4590 #getRepeatableElementAt(instanceManager, index) { 4591 let childId = instanceManager._model.items.find((model) => model.index === index)?.id; 4592 return this.element.querySelector(`#${childId}${Accordion.idSuffixes.item}`); 4593 } 4594 4595 #prepareAccordionMarkupToBeAdded(instanceManager, addedModel, htmlElement) { 4596 var accordionItemDivToBeRepeated = this._templateHTML[instanceManager.getId()]['accordionItemDiv'].cloneNode(true); 4597 var itemDivId = accordionItemDivToBeRepeated.id; 4598 var accordionPanelId = this.#convertToPanelId(itemDivId); 4599 var accordionPanelToBeRepeated = accordionItemDivToBeRepeated.querySelector('#' + accordionPanelId); 4600 while (accordionPanelToBeRepeated.hasChildNodes()) { 4601 accordionPanelToBeRepeated.removeChild(accordionPanelToBeRepeated.firstChild); 4602 } 4603 accordionPanelToBeRepeated.append(htmlElement); 4604 this.#syncAccordionMarkup(accordionItemDivToBeRepeated); 4605 return accordionItemDivToBeRepeated; 4606 } 4607 4608 #syncAccordionMarkup(accordionItemDiv) { 4609 var accordionItemDivId = accordionItemDiv.id; 4610 var accordionPanelId = this.#convertToPanelId(accordionItemDivId); 4611 var accordionButtonId = this.#convertToButtonId(accordionItemDivId); 4612 var accordionButton = accordionItemDiv.querySelector('#' + accordionButtonId); 4613 var accordionPanelDiv = accordionItemDiv.querySelector('#' + accordionPanelId); 4614 var childViewId = accordionItemDiv.querySelector("[data-cmp-is]").id; 4615 accordionItemDiv.id = childViewId + Accordion.idSuffixes.item; 4616 accordionButton.id = childViewId + Accordion.idSuffixes.button; 4617 accordionPanelDiv.id = childViewId + Accordion.idSuffixes.panel; 4618 accordionButton.setAttribute("aria-controls", childViewId + Accordion.idSuffixes.panel); 4619 accordionPanelDiv.setAttribute("aria-labelledby", childViewId + Accordion.idSuffixes.button); 4620 var accordionAdd = accordionItemDiv.querySelector(".cmp-accordion__add-button"); 4621 if (accordionAdd) { 4622 accordionAdd.setAttribute('data-cmp-hook-add-instance',
4622childViewId); 4623 } 4624 var accordionRemove = accordionItemDiv.querySelector(".cmp-accordion__remove-button"); 4625 if (accordionRemove) { 4626 accordionRemove.setAttribute('data-cmp-hook-remove-instance', childViewId); 4627 } 4628 } 4629 4630 #cacheTemplateHTML(childView) { 4631 if (childView.getInstanceManager() != null && (this._templateHTML == null || this._templateHTML[childView.getInstanceManager().getId()] == null)) { 4632 var accordionItemDivId = childView.element.id + Accordion.idSuffixes.item; 4633 var instanceManagerId = childView.getInstanceManager().getId(); 4634 var accordionItemDiv = this.getItemById(accordionItemDivId); 4635 this._templateHTML[instanceManagerId] = {}; 4636 this._templateHTML[instanceManagerId]['accordionItemDiv'] = accordionItemDiv; 4637 } 4638 } 4639 4640 #getButtonById(buttonId) { 4641 var buttons = this.getCachedButtons(); 4642 if (buttons) { 4643 for (var i = 0; i < buttons.length; i++) { 4644 if (buttons[i].id === buttonId) { 4645 return buttons[i]; 4646 } 4647 } 4648 } 4649 } 4650 4651 #getButtonIndexById(buttonId) { 4652 var buttons = this.getCachedButtons(); 4653 if (buttons) { 4654 for (var i = 0; i < buttons.length; i++) { 4655 if (buttons[i].id === buttonId) { 4656 return i; 4657 } 4658 } 4659 } 4660 return -1; 4661 } 4662 4663 /** 4664 * Changes provided panel or buttonId to ItemId 4665 * 4666 * @private 4667 * @param {Number} id The id of the panel/button to convert to corresponding item div 4668 */ 4669 #convertToItemDivId(idToConvert) { 4670 return idToConvert.substring(0, idToConvert.lastIndexOf("-")) + Accordion.idSuffixes.item; 4671 } 4672 4673 /** 4674 * Changes provided panel or item id to Button Id 4675 * 4676 * @private 4677 * @param {Number} id The id of the panel/item to convert to corresponding button id 4678 */ 4679 #convertToButtonId(idToConvert) { 4680 return idToConvert.substring(0, idToConvert.lastIndexOf("-")) + Accordion.idSuffixes.button; 4681 } 4682 4683 /** 4684 * Changes provided button or item id to Panel Id 4685 * 4686 * @private 4687 * @param {Number} id The id of the button/item to convert to corresponding button id 4688 */ 4689 #convertToPanelId(idToConvert) { 4690 return idToConvert.substring(0, idToConvert.lastIndexOf("-")) + Accordion.idSuffixes.panel; 4691 } 4692 4693 updateChildVisibility(visible, state) { 4694 this.updateVisibilityOfNavigationElement(this.getItemById(state.id + Accordion.idSuffixes.item), visible); 4695 if (!visible) { 4696 var expandedItems = this.getExpandedItems(); 4697 for (let i = 0; i < expandedItems.length; i++) { 4698 if (expandedItems[i].getAttribute(Accordion.DATA_ATTRIBUTE_VISIBLE) === 'false') { 4699 this.collapseItem(expandedItems[i]); 4700 } 4701 } 4702 let child = this.findFirstVisibleChild(this.getCachedItems()); 4703 if (child) { 4704 this.expandItem(child); 4705 } 4706 } 4707 } 4708 4709 getRepeatableRootElement(childView) { 4710 return this.element.querySelector('#' + childView.id + '-item div[data-cmp-hook-adaptiveFormAccordion="repeatableButton"]') 4711 } 4712 4713 #showHideRepeatableButtons(instanceManager) { 4714 const {_model: {minOccur, maxOccur, items = []} = {}, children} = instanceManager;
4715 children.forEach(child => { 4716 const addButtonElement = this.element.querySelector('#' + child.id + '-item')?.querySelector('[data-cmp-hook-add-instance]'); 4717 const removeButtonElement = this.element.querySelector('#' + child.id + '-item')?.querySelector('[data-cmp-hook-remove-instance]'); 4718 if (addButtonElement) { 4719 addButtonElement.setAttribute(Accordion.DATA_ATTRIBUTE_VISIBLE, !(items.length === maxOccur && maxOccur != -1)) 4720 } 4721 if (removeButtonElement) { 4722 removeButtonElement.setAttribute(Accordion.DATA_ATTRIBUTE_VISIBLE, items.length > minOccur && minOccur != -1) 4723 } 4724 }); 4725 } 4726 } 4727 4728 FormView.Utils.setupField(({element, formContainer}) => { 4729 return new Accordion({element, formContainer}) 4730 }, Accordion.selectors.self); 4731 } 4732 4733 if (window.Forms && window.Forms.CoreComponentsCommons && window.Forms.CoreComponentsCommons.AccordionMixin) { 4734 onAccordionMixinLoaded({ detail: { AccordionMixin: window.Forms.CoreComponentsCommons.AccordionMixin } }); 4735 } else { 4736 window.addEventListener('AccordionMixinLoaded', onAccordionMixinLoaded); 4737 } 4738})(); 4739 4740/******************************************************************************* 4741 * Copyright 2022 Adobe 4742 * 4743 * Licensed under the Apache License, Version 2.0 (the "License"); 4744 * you may not use this file except in compliance with the License. 4745 * You may obtain a copy of the License at 4746 * 4747 * http://www.apache.org/licenses/LICENSE-2.0 4748 * 4749 * Unless required by applicable law or agreed to in writing, software 4750 * distributed under the License is distributed on an "AS IS" BASIS, 4751 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4752 * See the License for the specific language governing permissions and 4753 * limitations under the License. 4754 ******************************************************************************/ 4755 4756(function () { 4757 4758 class Tabs extends FormView.FormTabs { 4759 _templateHTML = {}; 4760 static NS = FormView.Constants.NS; 4761 static IS = "adaptiveFormTabs"; 4762 static bemBlock = "cmp-tabs"; 4763 static selectors = { 4764 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 4765 active: { 4766 tab: "cmp-tabs__tab--active", 4767 tabpanel: "cmp-tabs__tabpanel--active" 4768 }, 4769 stepped: { 4770 tab: "cmp-tabs__tab--stepped", 4771 tabpanel: "cmp-tabs__tabpanel--stepped" 4772 }, 4773 label: `.${Tabs.bemBlock}__label`, 4774 description: `.${Tabs.bemBlock}__longdescription`, 4775 qm: `.${Tabs.bemBlock}__questionmark`, 4776 tooltipDiv: `.${Tabs.bemBlock}__shortdescription`, 4777 olTabList: `.${Tabs.bemBlock}__tablist`, 4778 widget: `.${Tabs.bemBlock}__tablist` 4779 }; 4780 4781 constructor(params) { 4782 super(params, Tabs.NS, Tabs.IS, Tabs.selectors); 4783 } 4784 4785 4786 getClass() { 4787 return Tabs.IS; 4788 } 4789 4790 setFocus(id) { 4791 super.setFocus(id); 4792 this.setActive(); 4793 if (id) { 4794 this.navigateAndFocusTab(id + '__tab'); 4795 } 4796 } 4797 4798 getWidget() { 4799 return this.element.querySelector(Tabs.selectors.widget); 4800 } 4801 4802 getDescription() { 4803 return this.element.querySelector(Tabs.selectors.description); 4804 } 4805 4806 getLabel() { 4807 return this.element.querySelector(Tabs.selectors.label); 4808 } 4809 4810 getErrorDiv() { 4811 return this.element.querySelector(Tabs.selectors.errorDiv); 4812 } 4813 4814 getTooltipDiv() { 4815 return this.element.querySelector(Tabs.selectors.tooltipDiv); 4816 } 4817 4818 getQuestionMarkDiv() { 4819 return this.element.querySelector(Tabs.selectors.qm); 4820 } 4821 } 4822 4823 FormView.Utils.setupField(({element, formContainer}) => { 4824 return new Tabs({element, formContainer}) 4825 }, Tabs.selectors.self); 4826 4827}()); 4828 4829/******************************************************************************* 4830 * Copyright 2023 Adobe 4831 * 4832 * Licensed under the Apache License, Version 2.0 (the "License");
4833 * you may not use this file except in compliance with the License. 4834 * You may obtain a copy of the License at 4835 * 4836 * http://www.apache.org/licenses/LICENSE-2.0 4837 * 4838 * Unless required by applicable law or agreed to in writing, software 4839 * distributed under the License is distributed on an "AS IS" BASIS, 4840 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4841 * See the License for the specific language governing permissions and 4842 * limitations under the License. 4843 ******************************************************************************/ 4844 4845(function () { 4846 4847 class VerticalTabs extends FormView.FormTabs { 4848 _templateHTML = {}; 4849 static NS = FormView.Constants.NS; 4850 static IS = "adaptiveFormVerticalTabs"; 4851 static bemBlock = "cmp-verticaltabs"; 4852 static selectors = { 4853 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 4854 active: { 4855 tab: "cmp-verticaltabs__tab--active", 4856 tabpanel: "cmp-verticaltabs__tabpanel--active" 4857 }, 4858 stepped: { 4859 tab: "cmp-verticaltabs__tab--stepped", 4860 tabpanel: "cmp-verticaltabs__tabpanel--stepped" 4861 }, 4862 label: `.${VerticalTabs.bemBlock}__label`, 4863 description: `.${VerticalTabs.bemBlock}__longdescription`, 4864 qm: `.${VerticalTabs.bemBlock}__questionmark`, 4865 tooltipDiv: `.${VerticalTabs.bemBlock}__shortdescription`, 4866 olTabList: `.${VerticalTabs.bemBlock}__tablist`, 4867 widget: `.${VerticalTabs.bemBlock}__tabs-container` 4868 }; 4869 4870 constructor(params) { 4871 super(params, VerticalTabs.NS, VerticalTabs.IS, VerticalTabs.selectors); 4872 } 4873 4874 getClass() { 4875 return VerticalTabs.IS; 4876 } 4877 4878 setFocus(id) { 4879 super.setFocus(id); 4880 this.setActive(); 4881 if(id) { 4882 this.navigateAndFocusTab(id + '__tab'); 4883 } 4884 } 4885 4886 getWidget() { 4887 return this.element.querySelector(VerticalTabs.selectors.widget); 4888 } 4889 4890 getDescription() { 4891 return this.element.querySelector(VerticalTabs.selectors.description); 4892 } 4893 4894 getLabel() { 4895 return this.element.querySelector(VerticalTabs.selectors.label); 4896 } 4897 4898 getErrorDiv() { 4899 return this.element.querySelector(VerticalTabs.selectors.errorDiv); 4900 } 4901 4902 getTooltipDiv() { 4903 return this.element.querySelector(VerticalTabs.selectors.tooltipDiv); 4904 } 4905 4906 getQuestionMarkDiv() { 4907 return this.element.querySelector(VerticalTabs.selectors.qm); 4908 } 4909 } 4910 4911 FormView.Utils.setupField(({element, formContainer}) => { 4912 return new VerticalTabs({element, formContainer}) 4913 }, VerticalTabs.selectors.self); 4914 4915}()); 4916 4917/******************************************************************************* 4918 * Copyright 2023 Adobe 4919 * 4920 * Licensed under the Apache License, Version 2.0 (the "License"); 4921 * you may not use this file except in compliance with the License. 4922 * You may obtain a copy of the License at 4923 * 4924 * http://www.apache.org/licenses/LICENSE-2.0 4925 * 4926 * Unless required by applicable law or agreed to in writing, software 4927 * distributed under the License is distributed on an "AS IS" BASIS, 4928 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4929 * See the License for the specific language governing permissions and 4930 * limitations under the License. 4931 ******************************************************************************/ 4932(function() { 4933 4934 "use strict"; 4935 class Recaptcha extends FormView.FormFieldBase { 4936 4937 static NS = FormView.Constants.NS; 4938 static IS = "adaptiveFormRecaptcha"; 4939 static bemBlock = 'cmp-adaptiveform-recaptcha'; 4940 static selectors = { 4941 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 4942 widget: `.${Recaptcha.bemBlock}__widget`, 4943 label: `.${Recaptcha.bemBlock}__label`, 4944 errorDiv: `.${Recaptcha.bemBlock}__errormessage` 4945 }; 4946 4947 constructor(params) { 4948 super(params); 4949 } 4950 4951 getWidget() { 4952 return this.element.querySelector(Recaptcha.selectors.widget); 4953 } 4954 4955 getDescription() { 4956 return null; 4957 } 4958 4959 getLabel() { 4960 return this.element.querySelector(Recaptcha.selectors.label); 4961 } 4962 4963 getTooltipDiv() { 4964 return null; 4965 } 4966 4967 getErrorDiv() { 4968 return this.element.querySelector(Recaptcha.selectors.errorDiv); 4969 } 4970 4971 getQuestionMarkDiv() { 4972 return null; 4973 } 4974 4975 initializeWidget() { 4976 this.widgetObject = new RecaptchaWidget(this, this._model, this.getWidget()); 4977 this.getWidget().addEventListener('blur', (e) => { 4978 if(this.element) { 4979 this.setInactive(); 4980 } 4981 }); 4982 4983 } 4984 4985 setModel(model) { 4986 super.setModel(model); 4987 if (this.widgetObject == null) { 4988 this.initializeWidget(); 4989 } else { 4990 if (this.widget.value !== '') { 4991 this._model.dispatch(new FormView.Actions.UIChange({'value': this.widget.value})); 4992 } 4993 } 4994 } 4995 } 4996 4997 FormView.Utils.setupField(({element, formContainer}) => { 4998 return new Recaptcha({element, formContainer}) 4999 }, Recaptcha.selectors.self); 5000 5001})(); 5002 5003/******************************************************************************* 5004 * Copyright 2023 Adobe 5005 * 5006 * Licensed under the Apache License, Version 2.0 (the "License");
5007 * you may not use this file except in compliance with the License. 5008 * You may obtain a copy of the License at 5009 * 5010 * http://www.apache.org/licenses/LICENSE-2.0 5011 * 5012 * Unless required by applicable law or agreed to in writing, software 5013 * distributed under the License is distributed on an "AS IS" BASIS, 5014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5015 * See the License for the specific language governing permissions and 5016 * limitations under the License. 5017 ******************************************************************************/ 5018 5019/** 5020 * This class is responsible for interacting with the recaptcha widget. It displays Google reCAPTCHA challenge. 5021 */ 5022 5023if (typeof window.RecaptchaWidget === 'undefined') { 5024 window.RecaptchaWidget = class { 5025 #widget = null 5026 #model = null // passed by reference 5027 #options = null 5028 #lang = 'en' 5029 static FD_CAPTCHA = "fd:captcha"; 5030 5031 constructor(view, model, widget) { 5032 // initialize the widget and model 5033 this.#widget = widget; 5034 this.#model = model; 5035 this.#widget = document.createElement("div"); 5036 this.#widget.classList.add("cmp-adaptiveform-recaptcha__widget"); 5037 this.#lang = view.formContainer.getModel().lang; 5038 5039 //Always inserting it in body 5040 document.body.appendChild(this.#widget); 5041 this.#options = Object.assign({}, this.#model._jsonModel); 5042 5043 this.#renderRecaptcha(widget); 5044 } 5045 5046 #renderRecaptcha(element) { 5047 5048 var self = this; 5049 var recaptchaConfigData = this.#options; 5050 element.innerHTML = '<div class="g-recaptcha"></div>'; 5051 var gcontainer = document.getElementsByClassName("g-recaptcha")[0]; 5052 var widgetId; 5053 var url = recaptchaConfigData.properties[RecaptchaWidget.FD_CAPTCHA].config.uri; 5054 if (recaptchaConfigData.properties[RecaptchaWidget.FD_CAPTCHA].config.size == "invisible") { 5055 gcontainer.classList.add('g-recaptcha-invisible'); 5056 recaptchaConfigData.required = false; 5057 } 5058 5059 var successCallback = function(response) { 5060 self.setCaptchaModel(response); 5061 }; 5062 5063 var expiredCallback = function() { 5064 if (isRecaptchaEnterprise()) { 5065 grecaptcha.enterprise.reset(widgetId); 5066 } else { 5067 grecaptcha.reset(widgetId); 5068 } 5069 self.setCaptchaModel(""); 5070 }; 5071 5072 var onloadCallbackInternal = function() { 5073 widgetId = isRecaptchaEnterprise() ? grecaptcha.enterprise.render(gcontainer, gparameters) 5074 : grecaptcha.render(gcontainer, gparameters); 5075 return widgetId; 5076 }; 5077 5078 var gparameters = { 5079 'sitekey': recaptchaConfigData.properties[RecaptchaWidget.FD_CAPTCHA].config.siteKey, 5080 'size': recaptchaConfigData.properties[RecaptchaWidget.FD_CAPTCHA].config.size, 5081 'theme': recaptchaConfigData.properties[RecaptchaWidget.FD_CAPTCHA].config.theme || 'light', 5082 'type': recaptchaConfigData.properties[RecaptchaWidget.FD_CAPTCHA].config.type || 'image', 5083 'callback': successCallback, 5084 'expired-callback': expiredCallback 5085 }; 5086 5087 const isRecaptchaEnterprise = function () { 5088 return recaptchaConfigData.properties[RecaptchaWidget.FD_CAPTCHA].config.version === "enterprise"; 5089 } 5090 const isScoreBasedKey = function () { 5091 return isRecaptchaEnterprise() && recaptchaConfigData.properties[RecaptchaWidget.FD_CAPTCHA].config.keyType === "score"; 5092 } 5093 5094 window.onloadRecaptchaCallback = onloadCallbackInternal; 5095 5096 var runtimeLocale = this.#lang; 5097 5098 var scr = document.createElement('script'); 5099 let queryParams = isScoreBasedKey() ? "?render=" + recaptchaConfigData.properties[RecaptchaWidget.FD_CAPTCHA].config.siteKey 5100 : "?onload=onloadRecaptchaCallback&render=explicit"; 5101 queryParams += "&hl=" + runtimeLocale; 5102 scr.src = url + queryParams; 5103 scr.async = true; 5104 element.appendChild(scr); 5105 } 5106 5107 setCaptchaModel = function(response) { 5108 this.#model.dispatch(new FormView.Actions.UIChange({'value': response})); 5109 } 5110 } 5111} 5112 5113/******************************************************************************* 5114 * Copyright 2022 Adobe 5115 * 5116 * Licensed under the Apache License, Version 2.0 (the "License");
5117 * you may not use this file except in compliance with the License. 5118 * You may obtain a copy of the License at 5119 * 5120 * http://www.apache.org/licenses/LICENSE-2.0 5121 * 5122 * Unless required by applicable law or agreed to in writing, software 5123 * distributed under the License is distributed on an "AS IS" BASIS, 5124 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5125 * See the License for the specific language governing permissions and 5126 * limitations under the License. 5127 ******************************************************************************/ 5128(function() { 5129 5130 5131 "use strict"; 5132 class CheckBox extends FormView.FormCheckBox { 5133 5134 static NS = FormView.Constants.NS; 5135 /** 5136 * Each FormField has a data attribute class that is prefixed along with the global namespace to 5137 * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be 5138 * data-{NS}-{IS}-x="" 5139 * @type {string} 5140 */ 5141 static IS = "adaptiveFormCheckBox"; 5142 static bemBlock = 'cmp-adaptiveform-checkbox' 5143 static selectors = { 5144 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 5145 widget: `.${CheckBox.bemBlock}__widget`, 5146 widgetLabel: `.${CheckBox.bemBlock}__label`, 5147 label: `.${CheckBox.bemBlock}__label`, 5148 description: `.${CheckBox.bemBlock}__longdescription`, 5149 qm: `.${CheckBox.bemBlock}__questionmark`, 5150 errorDiv: `.${CheckBox.bemBlock}__errormessage`, 5151 tooltipDiv: `.${CheckBox.bemBlock}__shortdescription` 5152 }; 5153 5154 constructor(params) { 5155 super(params); 5156 this.qm = this.element.querySelector(CheckBox.selectors.qm) 5157 this.widgetLabel = this.element.querySelector(CheckBox.selectors.widgetLabel) 5158 } 5159 5160 getWidget() { 5161 return this.element.querySelector(CheckBox.selectors.widget); 5162 } 5163 5164 getDescription() { 5165 return this.element.querySelector(CheckBox.selectors.description); 5166 } 5167 5168 getLabel() { 5169 return this.element.querySelector(CheckBox.selectors.label); 5170 } 5171 5172 getErrorDiv() { 5173 return this.element.querySelector(CheckBox.selectors.errorDiv); 5174 } 5175 5176 getQuestionMarkDiv() { 5177 return this.element.querySelector(CheckBox.selectors.qm); 5178 } 5179 5180 getTooltipDiv() { 5181 return this.element.querySelector(CheckBox.selectors.tooltipDiv); 5182 } 5183 5184 updateEnabled(enabled, state) { 5185 if (this.widget) { 5186 this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_ENABLED, enabled); 5187 const isDisabled = !enabled || state.readOnly; 5188 if (isDisabled) { 5189 this.widget.setAttribute("disabled", "disabled"); 5190 } else { 5191 this.widget.removeAttribute("disabled"); 5192 } 5193 } 5194 } 5195 5196 updateReadOnly(readonly) { 5197 if (this.widget) { 5198 this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_READONLY, readonly); 5199 if (readonly === true) { 5200 this.widget.setAttribute(FormView.Constants.HTML_ATTRS.DISABLED, "disabled"); 5201 } else { 5202 this.widget.removeAttribute(FormView.Constants.HTML_ATTRS.DISABLED); 5203 } 5204 } 5205 } 5206 } 5207 5208 FormView.Utils.setupField(({element, formContainer}) => { 5209 return new CheckBox({element, formContainer}) 5210 }, CheckBox.selectors.self); 5211 5212})(); 5213 5214/******************************************************************************* 5215 * Copyright 2023 Adobe 5216 * 5217 * Licensed under the Apache License, Version 2.0 (the "License"); 5218 * you may not use this file except in compliance with the License. 5219 * You may obtain a copy of the License at 5220 * 5221 * http://www.apache.org/licenses/LICENSE-2.0 5222 * 5223 * Unless required by applicable law or agreed to in writing, software 5224 * distributed under the License is distributed on an "AS IS" BASIS, 5225 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5226 * See the License for the specific language governing permissions and 5227 * limitations under the License. 5228 ******************************************************************************/ 5229(function() { 5230 5231 "use strict"; 5232 class Fragment extends FormView.FormPanel { 5233 5234 static NS = FormView.Constants.NS; 5235 /** 5236 * Each FormField has a data attribute class that is prefixed along with the global namespace to 5237 * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be 5238 * data-{NS}-{IS}-x="" 5239 * @type {string} 5240 */ 5241 static IS = "adaptiveFormFragment";
5242 static bemBlock = 'cmp-adaptiveform-fragment' 5243 static selectors = { 5244 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 5245 widget: `.${Fragment.bemBlock}__widget`, 5246 label: `.${Fragment.bemBlock}__label`, 5247 description: `.${Fragment.bemBlock}__longdescription`, 5248 qm: `.${Fragment.bemBlock}__questionmark`, 5249 errorDiv: `.${Fragment.bemBlock}__errormessage`, 5250 tooltipDiv: `.${Fragment.bemBlock}__shortdescription` 5251 }; 5252 5253 constructor(params) { 5254 super(params); 5255 } 5256 5257 getWidget() { 5258 return this.element.querySelector(Fragment.selectors.widget); 5259 } 5260 5261 getDescription() { 5262 return this.element.querySelector(Fragment.selectors.description); 5263 } 5264 5265 getLabel() { 5266 return this.element.querySelector(Fragment.selectors.label); 5267 } 5268 5269 getErrorDiv() { 5270 return this.element.querySelector(Fragment.selectors.errorDiv); 5271 } 5272 5273 getTooltipDiv() { 5274 return this.element.querySelector(Fragment.selectors.tooltipDiv); 5275 } 5276 5277 getQuestionMarkDiv() { 5278 return this.element.querySelector(Fragment.selectors.qm); 5279 } 5280 } 5281 5282 FormView.Utils.setupField(({element, formContainer}) => { 5283 return new Fragment({element, formContainer}) 5284 }, Fragment.selectors.self); 5285 5286})(); 5287 5288/******************************************************************************* 5289 * Copyright 2023 Adobe 5290 * 5291 * Licensed under the Apache License, Version 2.0 (the "License"); 5292 * you may not use this file except in compliance with the License. 5293 * You may obtain a copy of the License at 5294 * 5295 * http://www.apache.org/licenses/LICENSE-2.0 5296 * 5297 * Unless required by applicable law or agreed to in writing, software 5298 * distributed under the License is distributed on an "AS IS" BASIS, 5299 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5300 * See the License for the specific language governing permissions and 5301 * limitations under the License. 5302 ******************************************************************************/ 5303(function() { 5304 5305 5306 "use strict"; 5307 class Switch extends FormView.FormCheckBox { 5308 5309 static NS = FormView.Constants.NS; 5310 static IS = "adaptiveFormSwitch"; 5311 static bemBlock = 'cmp-adaptiveform-switch'; 5312 static selectors = { 5313 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 5314 widget: `.${Switch.bemBlock}__widget`, 5315 label: `.${Switch.bemBlock}__label`, 5316 description: `.${Switch.bemBlock}__longdescription`, 5317 errorDiv: `.${Switch.bemBlock}__errormessage`, 5318 qm: `.${Switch.bemBlock}__questionmark`, 5319 tooltipDiv: `.${Switch.bemBlock}__shortdescription` 5320 }; 5321 5322 constructor(params) { 5323 super(params); 5324 this.qm = this.element.querySelector(Switch.selectors.qm) 5325 } 5326 5327 getClass() { 5328 return Switch.IS; 5329 } 5330 5331 getWidget() { 5332 return this.element.querySelector(Switch.selectors.widget); 5333 } 5334 5335 getDescription() { 5336 return this.element.querySelector(Switch.selectors.description); 5337 } 5338 5339 getLabel() { 5340 return this.element.querySelector(Switch.selectors.label); 5341 } 5342 5343 getErrorDiv() { 5344 return this.element.querySelector(Switch.selectors.errorDiv); 5345 } 5346 5347 getTooltipDiv() { 5348 return this.element.querySelector(Switch.selectors.tooltipDiv); 5349 } 5350 5351 getQuestionMarkDiv() { 5352 return this.element.querySelector(Switch.selectors.qm); 5353 } 5354 } 5355 5356 FormView.Utils.setupField(({element, formContainer}) => { 5357 return new Switch({element,formContainer}) 5358 }, Switch.selectors.self); 5359 5360})(); 5361 5362/******************************************************************************* 5363 * Copyright 2023 Adobe 5364 * 5365 * Licensed under the Apache License, Version 2.0 (the "License"); 5366 * you may not use this file except in compliance with the License. 5367 * You may obtain a copy of the License at 5368 * 5369 * http://www.apache.org/licenses/LICENSE-2.0 5370 * 5371 * Unless required by applicable law or agreed to in writing, softw
5371are 5372 * distributed under the License is distributed on an "AS IS" BASIS, 5373 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5374 * See the License for the specific language governing permissions and 5375 * limitations under the License. 5376 ******************************************************************************/ 5377 5378(function () { 5379 5380 class TermsAndConditions extends FormView.FormPanel { 5381 static NS = FormView.Constants.NS; 5382 static IS = "adaptiveFormTermsAndConditions"; 5383 static bemBlock = 'cmp-adaptiveform-termsandcondition'; 5384 static selectors = { 5385 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 5386 label: `.${TermsAndConditions.bemBlock}__label`, 5387 description: `.${TermsAndConditions.bemBlock}__longdescription`, 5388 qm: `.${TermsAndConditions.bemBlock}__questionmark`, 5389 tooltipDiv: `.${TermsAndConditions.bemBlock}__shortdescription`, 5390 tncContentWrapper: `.${TermsAndConditions.bemBlock}__content-container`, 5391 closePopupButton: `.${TermsAndConditions.bemBlock}__close-button` 5392 }; 5393 5394 constructor(params) { 5395 super(params); 5396 this.#handleScroll() 5397 } 5398 5399 addChild(childView) { 5400 super.addChild(childView); 5401 if (childView.getModel()._jsonModel.fieldType === 'checkbox-group') { 5402 this.#addLinkClickListener(childView); 5403 } 5404 if (childView.getModel()._jsonModel.fieldType === 'checkbox') { 5405 this.#handlePopup(childView); 5406 } 5407 } 5408 5409 #addLinkClickListener(childView) { 5410 childView.getWidgets().querySelectorAll('label').forEach((item) => { 5411 const checkboxInput = item.querySelector('input'); 5412 item.querySelector('a').addEventListener('click', (e) => { 5413 checkboxInput.click(); 5414 }) 5415 }) 5416 } 5417 5418 #handleScroll() { 5419 const intersection = this.element.querySelector('.cmp-adaptiveform-termsandcondition__text-intersect'); 5420 if (intersection) { 5421 const self = this; 5422 const io = new IntersectionObserver(onIntersection, { 5423 threshold: [1], 5424 }) 5425 function onIntersection ([{isIntersecting}]) { 5426 const isEnabled = self.getModel()?.enabled && !self.getModel()?.readOnly; 5427 if (isIntersecting) { 5428 if (isEnabled) { 5429 self.children.filter(c => c.getModel()._jsonModel.fieldType === 'checkbox').forEach(cb => { 5430 cb.getModel().enabled = true; 5431 })} 5432 io.unobserve(intersection); 5433 } 5434 } 5435 io.observe(intersection) 5436 } 5437 } 5438 5439 #handlePopup(approvalCheckbox) { 5440 const closePopUpBtn = this.getClosePopupButton(); 5441 if (closePopUpBtn) { 5442 closePopUpBtn.addEventListener('click', () => { 5443 this.toggleAttribute(this.getContentDivWrapper(), false, 'data-cmp-visible', false); 5444 }) 5445 5446 approvalCheckbox.label.addEventListener('click', () => { 5447 const contentDiv = this.getContentDivWrapper(); 5448 if (contentDiv) { 5449 this.toggleAttribute(this.getContentDivWrapper(), true, 'data-cmp-visible', false); 5450 } 5451 }) 5452 } 5453 } 5454 5455 getContentDivWrapper() { 5456 return this.element.querySelector(TermsAndConditions.selectors.tncContentWrapper); 5457 } 5458 5459 getClosePopupButton() { 5460 return this.element.querySelector(TermsAndConditions.selectors.closePopupButton); 5461 } 5462 5463 getWidget() { 5464 return null; 5465 } 5466 5467 getDescription() { 5468 return this.element.querySelector(TermsAndConditions.selectors.description); 5469 } 5470 5471 getLabel() { 5472 return null; 5473 } 5474 5475 getErrorDiv() { 5476 return null; 5477 } 5478 5479 getTooltipDiv() { 5480 return this.element.querySelector(TermsAndConditions.selectors.tooltipDiv); 5481 } 5482 5483 getQuestionMarkDiv() { 5484 return this.element.querySelector(TermsAndConditions.selectors.qm); 5485 } 5486 } 5487 5488 FormView.Utils.setupField(({element, formContainer}) => { 5489 return new TermsAndConditions({element, formContainer}) 5490 }, TermsAndConditions.selectors.self); 5491})(); 5492 5493(function() { 5494 "use strict"; 5495 const gb = window.guideBridge; 5496 const wizardLabelContainer = document.getElementsByClassName('cmp-adaptiveform-wizard__label-container'); 5497 const el = document.querySelector(".reviewformcontent"); 5498 if (!el) return; 5499 if (!gb) { return; } 5500 5501 gb.connect(async function () { 5502 function updateSummary() { 5503 5504 const panelCount = document.querySelectorAll('[role="tabpanel"]').length; 5505 const wizardComponentPath = "copapwp-adaptive-form-components/components/form/wizard/v1/wizard"; 5506 let panelArray = []; // define panel array 5507 let fieldArray = []; // define field array 5508 let labelCounterGlobal = 1; 5509 5510 gb.getFormModel().visit(function(cmp) { 5511 if(cmp.fieldType === "panel" && cmp.visible && cmp.label.value !== wizardLabelContainer[0].innerHTML 5512 && (cmp.index + 1) < panelCount && cmp.parent._jsonModel[":type"] === wizardComponentPath) { 5513 labelCounterGlobal = 1; 5514 if (fieldArray.length === 0) { 5515 // Don't add to final array if fieldArray is empty 5516 } else { 5517 // Add to final array if fieldArray is not empty 5518 panelArray.push(fieldArray); 5519 fieldArray.unshift({ 5520 "name": cmp.name, 5521 "title": cmp.label.value, 5522 "type": cmp.fieldType, 5523 "id": cmp.id, 5524 "cmp": cmp 5525 }); 5526 } 5527 5528 fieldArray = []; // Create an empty array whenever we encounter a panel 5529 5530 } else if ((cmp.fieldType === "panel" && cmp.parent.repeatable)||(!cmp.repeatable && (cmp.name === undefined || !cmp.visible || cmp.fieldType === "captcha" || cmp.label.value === undefined || cmp.label.value === "" || cmp.fieldType === "button"))) { 5531 // Don't include these form fields. 5532 } else { 5533 if(cmp.fieldType === "panel" && cmp.parent._jsonModel[":type"] !== wizardComponentPath && !cmp.repeatable && !cmp.parent.repeatable){ 5534 fieldArray.push({ 5535 "name":cmp.name, 5536 "title": cmp.label.value, 5537 "value":cmp.value, 5538 "type":"child-panel", 5539 "cmp": cmp 5540 }); 5541 } else if (cmp.fieldType === "panel" && cmp.repeatable){ 5542 labelCounterGlobal++; 5543 fieldArray.push({ 5544 "name":cmp.name, 5545 "title": cmp.label.value, 5546 "value":cmp.value, 5547 "type":"repeated-panel", 5548 "cmp": cmp, 5549 "repeatable":cmp.repeatable 5550 }); 5551 } else if(cmp.fieldType !== "panel" && cmp.parent.repeatable) { 5552 5553 // Push fields info to fieldArray 5554 let labelVisible = false;
5555 if (cmp.parent.label.visible === undefined && cmp.parent.label.value !== undefined) 5556 { 5557 labelVisible = true; 5558 }else{ 5559 labelVisible = cmp.parent.label.visible; 5560 } 5561 let labelTitle = cmp.parent.label.value; 5562 if (cmp.parent._jsonModel["appliedCssClassNames"] !== undefined && cmp.parent._jsonModel["appliedCssClassNames"] === "updateRootPanelLabel") { 5563 labelTitle = panelStyle(cmp.parent.label.value, labelCounterGlobal); 5564 } 5565 fieldArray.push({ 5566 "name":cmp.name, 5567 "title": cmp.label.value, 5568 "value":cmp.value, 5569 "type":cmp.fieldType, 5570 "cmp": cmp, 5571 "repeatableparent":labelTitle, 5572 "repeatablepaneltitlevisible":labelVisible 5573 }); 5574 } 5575 5576 else { 5577 // Push fields info to fieldArray 5578 fieldArray.push({ 5579 "name":cmp.name, 5580 "title": cmp.label.value, 5581 "value":cmp.value, 5582 "type":cmp.fieldType, 5583 "cmp": cmp 5584 }); 5585 } 5586 } 5587 }); 5588 5589 populateSummaryContent(panelArray); 5590 linkPanels(panelArray); 5591 } 5592 5593 function panelStyle(originalValue, valueToApend){ 5594 let result = originalValue.replace(/(<\/.*?>)$/, `${valueToApend}$1`); 5595 return result; 5596 } 5597 5598 function goToPanel(cmp, panelNumber, panelTitle){ 5599 const panelNumberText = document.getElementsByClassName("cmp-adaptiveform-wizard__guideActiveIndex"); 5600 const panelTitleText = document.getElementsByClassName("cmp-adaptiveform-wizard__singleActiveTitleDiv"); 5601 panelNumberText[0].innerHTML = panelNumber; 5602 panelTitleText[0].innerHTML = panelTitle; 5603 gb.getFormModel().setFocus(cmp); 5604 window.scrollTo(0, 0); 5605 } 5606 5607 function linkPanels(panelList) { 5608 const panelEditButtons = document.querySelectorAll('.step-summary__edit'); 5609 const submitButton = document.getElementById("form-wizard-submit-button"); 5610 panelEditButtons.forEach((el) => { 5611 el.addEventListener("click", (event) => { 5612 const panelId = event.currentTarget.getAttribute("data-panel-id"); 5613 for (let i = 0; i < panelList.length; i++) { 5614 for (let j = 0; j < panelList[i].length; j++) { 5615 if(panelList[i][j].id === panelId) { 5616 // Get panel with this ID and go to first child form field 5617 goToPanel(panelList[i][j + 1].cmp, (i + 1), panelList[i][j].title); 5618 if(submitButton !== null) { 5619 if(submitButton.getAttribute("data-cmp-visible") === "true") { 5620 submitButton.setAttribute("data-cmp-visible", "false") 5621 } 5622 } 5623 } 5624 } 5625 } 5626 }); 5627 }); 5628 } 5629 5630 function populateSummaryContent(panelList) { 5631 const formsReviewSubmitContainer = document.querySelector(".forms__review-submit"); // Static HTML node found on the page to be replaced with the dynamic container to be populated 5632 let rowHTML = ""; 5633 5634 let repeatablePanelLabel = ""; 5635 let repeatablePanelValSet = false; 5636 5637 // Iterate fieldArray array 5638 for (let i = 0; i < panelList.length; i++) { 5639 rowHTML = rowHTML + "<div class='step-summary'>"; 5640 repeatablePanelValSet = false;
5641 repeatablePanelLabel = ""; 5642 for (let j = 0; j < panelList[i].length; j++) { 5643 // Depending on field type detected, create a field specific version of the row for the summary 5644 5645 switch (panelList[i][j].type) { 5646 // Panel details 5647 case "panel": 5648 rowHTML = rowHTML + "<div class='step-summary__title'><h2>" + panelList[i][j].title + "</h2>"; 5649 rowHTML = rowHTML + "<div class='step-summary__button'><button type='button' class='step-summary__edit' data-panel-id='" + panelList[i][j].id + "' aria-label='Edit " + panelList[i][j].title + "'><span>Edit</span></button></div>"; 5650 rowHTML = rowHTML + "</div>"; 5651 break; 5652 // Repeated panel 5653 case "repeated-panel": 5654 repeatablePanelValSet = false; 5655 break; 5656 // Text Box 5657 case "text-input": 5658 if ( panelList[i][j].repeatablepaneltitlevisible !== undefined && panelList[i][j].repeatablepaneltitlevisible && !repeatablePanelValSet && panelList[i][j].repeatableparent !== undefined ) { 5659 repeatablePanelValSet = true; 5660 repeatablePanelLabel = panelList[i][j].repeatableparent; 5661 rowHTML = rowHTML + "<div class='step-summary__item label-input'><div class='step-summary__label repeated-panel-label'>"+repeatablePanelLabel +"</div></div>"; 5662 5663 } 5664 const labelText = "<div class='step-summary__label'>" + panelList[i][j].title + "</div>"; 5665 let valueTextEl = ""; 5666 if ( panelList[i][j].cmp.properties.mask ) { 5667 valueTextEl = (panelList[i][j].value === undefined || panelList[i][j].value === null ) ? "--" : panelList[i][j].value.replaceAll("<", "").replaceAll(">", "").replace(/./g, "*"); 5668 } else { 5669 valueTextEl = (panelList[i][j].value === undefined || panelList[i][j].value === null ) ? "--" : panelList[i][j].value.replaceAll("<", "").replaceAll(">", "").replaceAll("\n","<br/>"); 5670 } 5671 const valueText = "<div class='step-summary__value'>" + valueTextEl + "</div>"; 5672 rowHTML = rowHTML + "<div class='step-summary__item "+ panelList[i][j].type + "'>" + labelText + valueText + "</div>"; 5673 break; 5674 5675 //number input 5676 case "number-input": 5677 if ( panelList[i][j].repeatablepaneltitlevisible !== undefined && panelList[i][j].repeatablepaneltitlevisible && !repeatablePanelValSet && panelList[i][j].repeatableparent !== undefined ) { 5678 repeatablePanelValSet = true; 5679 repeatablePanelLabel = panelList[i][j].repeatableparent; 5680 rowHTML = rowHTML + "<div class='step-summary__item label-input'><div class='step-summary__label repeated-panel-label'>"+repeatablePanelLabel +"</div></div>"; 5681 5682 } 5683 const labelTextNum = "<div class='step-summary__label'>" + panelList[i][j].title + "</div>"; 5684 const valueTextElNum = (panelList[i][j].value === undefined || panelList[i][j].value === null ) ? "--" : panelList[i][j].value; 5685 const valueTextNum = "<div class='step-summary__value'>" + valueTextElNum + "</div>"; 5686 rowHTML = rowHTML + "<div class='step-summary__item "+ panelList[i][j].type + "'>" + labelTextNum + valueTextNum+ "</div>"; 5687 break; 5688 5689 // Text Area 5690 case "multiline-input": 5691 if ( panelList[i][j].repeatablepaneltitlevisible !== undefined && panelList[i][j].repeatablepaneltitlevisible && !repeatablePanelValSet && panelList[i][j].repeatableparent !== undefined ) { 5692 repeatablePanelValSet = true; 5693 repeatablePanelLabel = panelList[i][j].repeatableparent; 5694 rowHTML = rowHTML + "<div class='step-summary__item label-input'><div class='step-summary__label repeated-panel-label'>"+repeatablePanelLabel +"</div></div>"; 5695 5696 } 5697 const labelTextArea = "<div class='step-summary__label'>" + panelList[i][j].title + "</div>"; 5698 const valueTextAreaEl = (panelList[i][j].value === undefined || panelList[i][j].value === null ) ? "--" : panelList[i][j].value.replaceAll("<", "").replaceAll(">", "").replaceAll("\n","<br/>"); 5699 const valueTextArea = "<div class='step-summary__value'>" + valueTextAreaEl + "</div>"; 5700 rowHTML = rowHTML + "<div class='step-summary__item "+ panelList[i][j].type + "'>" + labelTextArea + valueTextArea + "</div>"; 5701 break; 5702 5703 // Email 5704 case "email": 5705 if ( panelList[i][j].repeatablepaneltitlevisible !== undefined && panelList[i][j].repeatablepaneltitlevisible && !repeatablePanelValSet && panelList[i][j].repeatableparent !== undefined ) { 5706 repeatablePanelValSet = true; 5707 repeatablePanelLabel = panelList[i][j].repeatableparent; 5708 rowHTML = rowHTML + "<div class='step-summary__item label-input'><div class='step-summary__label repeated-panel-label'>"+repeatablePanelLabel +"</div></div>"; 5709 5710 } 5711 const labelEmail = "<div class='step-summary__label'>" + panelList[i][j].title + "</div>"; 5712 const valueEmailEl = (panelList[i][j].value === undefined || panelList[i][j].value === null ) ? "--" : panelList[i][j].value; 5713 const valueEmail = "<div class='step-summary__value'>" + valueEmailEl + "</div>"; 5714 rowHTML = rowHTML + "<div class='step-summary__item "+ panelList[i][j].type + "'>" + labelEmail + valueEmail + "</div>"; 5715 break; 5716 5717 // Drop-Down 5718 case "drop-down": 5719 if ( panelList[i][j].repeatablepaneltitlevisible !== undefined && panelList[i][j].repeatablepaneltitlevisible && !repeatablePanelValSet && panelList[i][j].repeatableparent !== undefined ) { 5720 repeatablePanelValSet = true; 5721 repeatablePanelLabel = panelList[i][j].repeatableparent; 5722 rowHTML = rowHTML + "<div class='step-summary__item label-input'><div class='step-summary__label repeated-panel-label'>"+repeatablePanelLabel +"</div></div>"; 5723 5724 } 5725 const labelSelect = "<div class='step-summary__label'>" + panelList[i][j].title + "</div>"; 5726 const valueSelectEl = (panelList[i][j].value === undefined || panelList[i][j].value === null) ? "--" : panelList[i][j].value; 5727 let valueSelect = "<div class='step-summary__value'>--</div>"; 5728 5729 const dropdownGroupOptions = (panelList[i][j].value === undefined || panelList[i][j].value === null) ? "--" : panelList[i][j].cmp.enum; 5730 //For county & county entity, options in the list are dynamic. Using enum instead of enumnames 5731 if((panelList[i][j].name === 'county' || panelList[i][j].name === 'countyentity') && dropdownGroupOptions.length && valueSelectEl !== "--"){ 5732 valueSelect = "<div class='step-summary__value'>" + panelList[i][j].cmp.enum[dropdownGroupOptions.indexOf(valueSelectEl)] + "</div>"; 5733 } 5734 else if(dropdownGroupOptions.length && valueSelectEl !== "--") { 5735 valueSelect = "<div class='step-summary__value'>" + panelList[i][j].cmp.enumNames[dropdownGroupOptions.indexOf(valueSelectEl)] + "</div>"; 5736 } 5737 5738 rowHTML = rowHTML + "<div class='step-summary__item'>" + labelSelect + valueSelect + "</div>"; 5739 break; 5740 5741 // Datepicker
5742 case "date-input": 5743 if ( panelList[i][j].repeatablepaneltitlevisible !== undefined && panelList[i][j].repeatablepaneltitlevisible && !repeatablePanelValSet && panelList[i][j].repeatableparent !== undefined ) { 5744 repeatablePanelValSet = true; 5745 repeatablePanelLabel = panelList[i][j].repeatableparent; 5746 rowHTML = rowHTML + "<div class='step-summary__item label-input'><div class='step-summary__label repeated-panel-label'>"+repeatablePanelLabel +"</div></div>"; 5747 5748 } 5749 const labelDate = "<div class='step-summary__label'>" + panelList[i][j].title + "</div>"; 5750 const valueDateEl = (panelList[i][j].value === undefined || panelList[i][j].value === null ) ? "--" : panelList[i][j].value; 5751 const valueDate = "<div class='step-summary__value'>" + valueDateEl + "</div>"; 5752 rowHTML = rowHTML + "<div class='step-summary__item'>" + labelDate + valueDate + "</div>"; 5753 break; 5754 5755 // File Upload & Scribble 5756 case "file-input": 5757 if ( panelList[i][j].repeatablepaneltitlevisible !== undefined && panelList[i][j].repeatablepaneltitlevisible && !repeatablePanelValSet && panelList[i][j].repeatableparent !== undefined ) { 5758 repeatablePanelValSet = true; 5759 repeatablePanelLabel = panelList[i][j].repeatableparent; 5760 rowHTML = rowHTML + "<div class='step-summary__item label-input'><div class='step-summary__label repeated-panel-label'>"+repeatablePanelLabel +"</div></div>"; 5761 5762 } 5763 if (panelList[i][j].cmp.properties["fd:viewType"] === "signature") { 5764 const labelText = "<div class='step-summary__label'>" + panelList[i][j].title + "</div>"; 5765 const valueSelectEl = "--"; 5766 let valueText = ""; 5767 if (panelList[i][j].value === undefined || panelList[i][j].value === null) { 5768 valueText = "<div class='step-summary__value'>" + valueSelectEl + " </div>"; 5769 } else { 5770 panelList[i][j].cmp.serialize().then((files) => { 5771 let signatureDataUrl; 5772 if (files && files.length > 0 && files[0]) { 5773 signatureDataUrl = files[0].data; 5774 document.querySelector("#signature_" + panelList[i][j].cmp.id).src = signatureDataUrl; 5775 } 5776 }); 5777 valueText = "<div class='step-summary__value'><img id='signature_" + panelList[i][j].cmp.id + "' alt='"+panelList[i][j].cmp._jsonModel["label"].value+"'></img> </div>"; 5778 } 5779 5780 rowHTML = rowHTML + "<div class='step-summary__item "+ panelList[i][j].type + "'>" + labelText + valueText +"</div>"; 5781 } else { 5782 const labelFile = "<div class='step-summary__label'>Attachments</div>"; 5783 rowHTML = rowHTML + "<div class='step-summary__item step-summary__file'>" + labelFile + "</div>"; 5784 const attachmentName = (panelList[i][j].value === undefined || panelList[i][j].value === null) ? "--" : panelList[i][j].value; 5785 const className = (panelList[i][j].value === undefined || panelList[i][j].value === null ) ? "" : "file-name--success"; 5786 const fileOpenDiv = "<div class='step-summary__item step-summary__file-attachment'><div class='step-summary__value file-name "+ className + "'>"; 5787 const fileCloseDiv = "</div></div>"; 5788 5789 if(Array.isArray(attachmentName) && attachmentName.length !== 0) { 5790 attachmentName.forEach((el, i) => { 5791 rowHTML = rowHTML + fileOpenDiv + attachmentName[i].name + fileCloseDiv; 5792 }); 5793 } else if(attachmentName === "--" || attachmentName.length === 0) { 5794 rowHTML = rowHTML + fileOpenDiv + "--" + fileCloseDiv; 5795 } else { 5796 rowHTML = rowHTML + fileOpenDiv + attachmentName.name + fileCloseDiv; 5797 } 5798 } 5799 break; 5800 5801 // Checkbox 5802 case "checkbox": 5803 if ( panelList[i][j].repeatablepaneltitlevisible !== undefined && panelList[i][j].repeatablepaneltitlevisible && !repeatablePanelValSet && panelList[i][j].repeatableparent !== undefined ) { 5804 repeatablePanelValSet = true; 5805 repeatablePanelLabel = panelList[i][j].repeatableparent; 5806 rowHTML = rowHTML + "<div class='step-summary__item label-input'><div class='step-summary__label repeated-panel-label'>"+repeatablePanelLabel +"</div></div>"; 5807 5808 } 5809 const labelCheckBox = "<div class='step-summary__label'>" + panelList[i][j].title + "</div>"; 5810 const emptyCheckBoxValue = "<div class='step-summary__value'>--</div>"; 5811 const checkBoxClass = (panelList[i][j].cmp.checked) ? "step-summary__checkBoxItem" : "step-summary__unCheckBoxItem" 5812 const checkboxOptions = panelList[i][j].cmp.enum; 5813 let valueCheckBox = (panelList[i][j].value === undefined || panelList[i][j].value === null ) ? labelCheckBox + emptyCheckBoxValue : panelList[i][j].value; 5814 5815 if(checkboxOptions.length && valueCheckBox !== labelCheckBox + emptyCheckBoxValue) { 5816 valueCheckBox = labelCheckBox + "<div class='step-summary__label " + checkBoxClass + "'>" + panelList[i][j].cmp.enumNames[checkboxOptions.indexOf(valueCheckBox)] + "</div>"; 5817 } 5818 5819 rowHTML = rowHTML + "<div class='step-summary__item step-summary__checkbox-list "+ panelList[i][j].type + "'>" + valueCheckBox + "</div>"; 5820 break; 5821 5822 // Checkbox Group 5823 case "checkbox-group": 5824 if ( panelList[i][j].repeatablepaneltitlevisible !== undefined && panelList[i][j].repeatablepaneltitlevisible && !repeatablePanelValSet && panelList[i][j].repeatableparent !== undefined ) { 5825 repeatablePanelValSet = true; 5826 repeatablePanelLabel = panelList[i][j].repeatableparent; 5827 rowHTML = rowHTML + "<div class='step-summary__item label-input'><div class='step-summary__label repeated-panel-label'>"+repeatablePanelLabel +"</div></div>"; 5828 5829 } 5830 const labelCheckboxGroup = "<div class='step-summary__label'>" + panelList[i][j].title + "</div>"; 5831 let checkboxGroupSelections = (panelList[i][j].value !== 'false' && panelList[i][j].value !== undefined && panelList[i][j].value !== null) ? panelList[i][j].value : []; 5832 // Obtain the original checkbox list from jsonModel 5833 const checkboxGroupOptions = panelList[i][j].cmp._jsonModel.enum; 5834 const checkboxDisplayNameOptions = panelList[i][j].cmp._jsonModel.enumNames; 5835 5836 // Construct list of selections 5837 let finalValue = ""; 5838 if(checkboxGroupSelections.length) { 5839 checkboxGroupSelections.forEach((el, i) => { 5840 finalValue = finalValue + "<li class='step-summary__checkBoxItem'>" + checkboxDisplayNameOptions[checkboxGroupOptions.indexOf(checkboxGroupSelections[i])] + "</li>"; 5841 }); 5842 5843 finalValue = "<ul>" + finalValue + "</ul>"; 5844 } else { 5845 finalValue = "--"; 5846 } 5847 5848 const valueCheckbox = "<div class='step-summary__value'>" + finalValue + "</div>"; 5849 rowHTML = rowHTML + "<div class='step-summary__item step-summary__checkbox-list'>" + labelCheckboxGroup + valueCheckbox + "</div>"; 5850 break; 5851 5852 // RadioButton 5853 case "radio-group": 5854 if ( panelList[i][j].repeatablepaneltitlevisible !== undefined && panelList[i][j].repeatablepaneltitlevisible && !repeatablePanelValSet && panelList[i][j].repeatableparent !== undefined ) { 5855 repeatablePanelValSet = true; 5856 repeatablePanelLabel = panelList[i][j].repeatableparent; 5857 rowHTML = rowHTML + "<div class='step-summary__item label-input'><div class='step-summary__label repeated-panel-label>"+repeatablePanelLabel +"</div></div>"; 5858 5859 } 5860 const labelRadiobutton = "<div class='step-summary__label'>" + panelList[i][j].title + "</div>"; 5861 const radioSelection = panelList[i][j].value; 5862 let finalRadioValue = (radioSelection !== null) ? radioSelection : "--"; 5863 const radioOptions = panelList[i][j].cmp._jsonModel.enum; 5864 5865 if(radioOptions.length && finalRadioValue !== "--") { 5866 finalRadioValue = panelList[i][j].cmp.enumNames[radioOptions.indexOf(radioSelection)]; 5867 } 5868 5869 let valueRadiobutton = "<div class='step-summary__value'><strong> " + finalRadioValue + "</strong></div>" 5870 rowHTML = rowHTML + "<div class='step-summary__item step-summary__radio'>" + labelRadiobutton + valueRadiobutton + "</div>"; 5871 break; 5872 } 5873 } 5874 rowHTML = rowHTML + "</div>"; 5875 } 5876 5877 // Append summary panels to review-submit container 5878 formsReviewSubmitContainer.innerHTML = window.DOMPurify ? window.DOMPurify.sanitize(rowHTML):rowHTML; 5879 } 5880 5881 // Check for form updates 5882 gb.on("elementValueChanged", function () { 5883 if(wizardLabelContainer.length > 0) { 5884 setTimeout(() => { 5885 updateSummary(); 5886 },200); 5887 } 5888 }); 5889 }) 5890})(); 5891(function() { 5892 "use strict"; 5893 const gb = window.guideBridge; 5894 const wizardLabelContainer = document.getElementsByClassName('cmp-adaptiveform-wizard__label-container'); 5895 const el = document.querySelector(".ethicsreviewformcontent"); 5896 if (!el) return;
5896// To execute the below code only if component is EthicsReviewFormContent 5897 gb.connect(async function () { 5898 function updateSummary() { 5899 5900 const panelCount = document.querySelectorAll('[role="tabpanel"]').length; 5901 const wizardComponentPath = "copapwp-adaptive-form-components/components/form/wizard/v1/wizard"; 5902 let panelArray = []; // define panel array 5903 let fieldArray = []; // define field array 5904 let labelCounterGlobal = 1; 5905 5906 gb.getFormModel().visit(function(cmp) { 5907 if(cmp.fieldType === "panel" && cmp.visible && cmp.label.value !== wizardLabelContainer[0].innerHTML 5908 && (cmp.index + 1) < panelCount && cmp.parent._jsonModel[":type"] === wizardComponentPath) { 5909 labelCounterGlobal = 1; 5910 if (fieldArray.length === 0) { 5911 // Don't add to final array if fieldArray is empty 5912 } else { 5913 // Add to final array if fieldArray is not empty 5914 panelArray.push(fieldArray); 5915 fieldArray.unshift({ 5916 "name": cmp.name, 5917 "title": cmp.label.value, 5918 "type": cmp.fieldType, 5919 "id": cmp.id, 5920 "cmp": cmp 5921 }); 5922 } 5923 5924 fieldArray = []; // Create an empty array whenever we encounter a panel 5925 5926 } else if ((cmp.fieldType === "panel" && cmp.parent.repeatable)||(!cmp.repeatable && (cmp.name === undefined || !cmp.visible || cmp.fieldType === "captcha" || cmp.label.value === undefined || cmp.label.value === "" || cmp.fieldType === "button"))) { 5927 // Don't include these form fields. 5928 } else { 5929 if(cmp.fieldType === "panel" && cmp.parent._jsonModel[":type"] !== wizardComponentPath && !cmp.repeatable && !cmp.parent.repeatable){ 5930 fieldArray.push({ 5931 "name":cmp.name, 5932 "title": cmp.label.value, 5933 "value":cmp.value, 5934 "type":"child-panel", 5935 "cmp": cmp 5936 }); 5937 } else if (cmp.fieldType === "panel" && cmp.repeatable){ 5938 labelCounterGlobal++; 5939 fieldArray.push({ 5940 "name":cmp.name, 5941 "title": cmp.label.value, 5942 "value":cmp.value, 5943 "type":"repeated-panel", 5944 "cmp": cmp, 5945 "repeatable":cmp.repeatable 5946 }); 5947 } else if(cmp.fieldType !== "panel" && cmp.parent.repeatable) { 5948 5949 // Push fields info to fieldArray 5950 let labelVisible = false; 5951 if (cmp.parent.label.visible === undefined && cmp.parent.label.value !== undefined) 5952 { 5953 labelVisible = true; 5954 }else{ 5955 labelVisible = cmp.parent.label.visible; 5956 } 5957 let labelTitle = cmp.parent.label.value; 5958 if (cmp.parent._jsonModel["appliedCssClassNames"] !== undefined && cmp.parent._jsonModel["appliedCssClassNames"] === "updateRootPanelLabel") { 5959 labelTitle = cmp.parent.label.value + " " + labelCounterGlobal; 5960 } 5961 fieldArray.push({ 5962 "name":cmp.name, 5963 "title": cmp.label.value, 5964 "value":cmp.value, 5965 "type":cmp.fieldType, 5966 "cmp": cmp, 5967 "repeatableparent":labelTitle, 5968 "repeatablepaneltitlevisible":labelVisible 5969 }); 5970 } 5971 5972 else { 5973 // Push fields info to fieldArray 5974 fieldArray.push({ 5975 "name":cmp.name, 5976 "title": cmp.label.value, 5977 "value":cmp.value, 5978 "type":cmp.fieldType, 5979 "cmp": cmp 5980 }); 5981 } 5982 } 5983 }); 5984 5985 populateSummaryContent(panelArray); //populates all the panel data entered by the user 5986 linkPanels(panelArray); //Links the panel id's to respective panels. onclick of edit icon for each accordion, redirects to corresponding panel 5987 expandFirstAccordion(); //By default the first accordion should be expanded 5988 } 5989 5990 function goToPanel(cmp, panelNumber, panelTitle){ 5991 const panelNumberText = document.getElementsByClassName("cmp-adaptiveform-wizard__guideActiveIndex"); 5992 const panelTitleText = document.getElementsByClassName("cmp-adaptiveform-wizard__singleActiveTitleDiv"); 5993 panelNumberText[0].innerHTML = panelNumber; 5994 panelTitleText[0].innerHTML = panelTitle; 5995 gb.getFormModel().setFocus(cmp); 5996 window.scrollTo(0, 0); 5997 } 5998 5999 function linkPanels(panelList) { 6000 const panelEditButtons = document.querySelectorAll('.step-summary__edit'); 6001 const submitButton = document.getElementById("form-wizard-submit-button"); 6002 panelEditButtons.forEach((el) => { 6003 el.addEventListener("click", (event) => { 6004 const panelId = event.currentTarget.getAttribute("data-panel-id"); 6005 for (let i = 0; i < panelList.length; i++) { 6006 for (let j = 0; j < panelList[i].length; j++) { 6007 if(panelList[i][j].id === panelId) { 6008 // Get panel with this ID and go to first child form field 6009 goToPanel(panelList[i][j + 1].cmp, (i + 1), panelList[i][j].title); 6010 if(submitButton !== null) { 6011 if(submitButton.getAttribute("data-cmp-visible") === "true") { 6012 submitButton.setAttribute("data-cmp-visible", "false") 6013 } 6014 } 6015 } 6016 } 6017 } 6018 }); 6019 }); 6020 } 6021 6022 function populateSummaryContent(panelList) { 6023 const formsReviewSubmitContainer = document.querySelector(".forms__review-submit"); // Static HTML node found on the page to be replaced with the dynamic container to be populated 6024 let rowHTML = ""; 6025 6026 let repeatablePanelLabel = ""; 6027 let repeatablePanelValSet = false;
6028 6029 // Iterate fieldArray array 6030 for (let i = 0; i < panelList.length; i++) { 6031 const skipGettingStartPanel = panelList[i].some( 6032 obj => obj.name === "gettingstarted" 6033 ); 6034 6035 if (skipGettingStartPanel) { 6036 continue; 6037 } 6038 rowHTML = rowHTML + "<div class='step-summary'>"; 6039 repeatablePanelValSet = false; 6040 repeatablePanelLabel = ""; 6041 for (let j = 0; j < panelList[i].length; j++) { 6042 // Depending on field type detected, create a field specific version of the row for the summary 6043 6044 switch (panelList[i][j].type) { 6045 // Panel details 6046 case "panel": 6047 rowHTML += "<div class='accordion-item'>"; 6048 rowHTML += "<div class='step-summary__title'>"; 6049 rowHTML += "<h2>" + panelList[i][j].title + "</h2>"; 6050 //rowHTML += "<div><img src='https://appsca.pwpca.pa.gov/ethicssfiadmin/images/tick-green.svg' alt='Completed' class='tick-mark-img'></div>"; 6051 rowHTML += "<div class='tick-mark'><i class='ri-checkbox-circle-fill'></i></div>"; 6052 rowHTML += "<div class='step-summary__button'>"; 6053 rowHTML += "<button type='button' class='step-summary__edit' data-panel-id='" + panelList[i][j].id + "' aria-label='Edit " + panelList[i][j].title + "'>"; 6054 rowHTML += "<span>Edit</span></button></div>"; 6055 rowHTML += "<button type='button' class='accordion-toggle' aria-expanded='false' aria-label='Toggle section'>+</button>"; 6056 rowHTML += "</div>"; // end step-summary__title 6057 rowHTML += "<div class='accordion-content'>"; 6058 break; 6059 // Repeated panel 6060 case "repeated-panel": 6061 repeatablePanelValSet = false; 6062 break; 6063 // Text Box 6064 case "text-input": 6065 if ( panelList[i][j].repeatablepaneltitlevisible !== undefined && panelList[i][j].repeatablepaneltitlevisible && !repeatablePanelValSet && panelList[i][j].repeatableparent !== undefined ) { 6066 repeatablePanelValSet = true; 6067 repeatablePanelLabel = panelList[i][j].repeatableparent; 6068 rowHTML = rowHTML + "<div class='step-summary__item label-input'><div class='step-summary__label repeated-panel-label'>"+repeatablePanelLabel +"</div></div>"; 6069 6070 } 6071 const labelText = "<div class='step-summary__label'>" + panelList[i][j].title + "</div>"; 6072 let valueTextEl = ""; 6073 if ( panelList[i][j].cmp.properties.mask ) { 6074 valueTextEl = (panelList[i][j].value === undefined || panelList[i][j].value === null ) ? "--" : panelList[i][j].value.replaceAll("<", "").replaceAll(">", "").replace(/./g, "*"); 6075 } else { 6076 valueTextEl = (panelList[i][j].value === undefined || panelList[i][j].value === null ) ? "--" : panelList[i][j].value.replaceAll("<", "").replaceAll(">", "").replaceAll("\n","<br/>"); 6077 } 6078 const valueText = "<div class='step-summary__value'>" + valueTextEl + "</div>"; 6079 rowHTML = rowHTML + "<div class='step-summary__item "+ panelList[i][j].type + "'>" + labelText + valueText + "</div>"; 6080 break; 6081 6082 //number input 6083 case "number-input": 6084 if ( panelList[i][j].repeatablepaneltitlevisible !== undefined && panelList[i][j].repeatablepaneltitlevisible && !repeatablePanelValSet && panelList[i][j].repeatableparent !== undefined ) { 6085 repeatablePanelValSet = true; 6086 repeatablePanelLabel = panelList[i][j].repeatableparent; 6087 rowHTML = rowHTML + "<div class='step-summary__item label-input'><div class='step-summary__label repeated-panel-label'>"+repeatablePanelLabel +"</div></div>"; 6088 6089 } 6090 const labelTextNum = "<div class='step-summary__label'>" + panelList[i][j].title + "</div>"; 6091 const valueTextElNum = (panelList[i][j].value === undefined || panelList[i][j].value === null ) ? "--" : panelList[i][j].value; 6092 const valueTextNum = "<div class='step-summary__value'>" + valueTextElNum + "</div>"; 6093 rowHTML = rowHTML + "<div class='step-summary__item "+ panelList[i][j].type + "'>" + labelTextNum + valueTextNum+ "</div>"; 6094 break; 6095 6096 // Text Area 6097 case "multiline-input": 6098 if ( panelList[i][j].repeatablepaneltitlevisible !== undefined && panelList[i][j].repeatablepaneltitlevisible && !repeatablePanelValSet && panelList[i][j].repeatableparent !== undefined ) { 6099 repeatablePanelValSet = true; 6100 repeatablePanelLabel = panelList[i][j].repeatableparent; 6101 rowHTML = rowHTML + "<div class='step-summary__item label-input'><div class='step-summary__label repeated-panel-label'>"+repeatablePanelLabel +"</div></div>"; 6102 6103 } 6104 const labelTextArea = "<div class='step-summary__label'>" + panelList[i][j].title + "</div>"; 6105 const valueTextAreaEl = (panelList[i][j].value === undefined || panelList[i][j].value === null ) ? "--" : panelList[i][j].value.replaceAll("<", "").replaceAll(">", "").replaceAll("\n","<br/>"); 6106 const valueTextArea = "<div class='step-summary__value'>" + valueTextAreaEl + "</div>"; 6107 rowHTML = rowHTML + "<div class='step-summary__item "+ panelList[i][j].type + "'>" + labelTextArea + valueTextArea + "</div>"; 6108 break; 6109 6110 // Email 6111 case "email": 6112 if ( panelList[i][j].repeatablepaneltitlevisible !== undefined && panelList[i][j].repeatablepaneltitlevisible && !repeatablePanelValSet && panelList[i][j].repeatableparent !== undefined ) { 6113 repeatablePanelValSet = true; 6114 repeatablePanelLabel = panelList[i][j].repeatableparent; 6115 rowHTML = rowHTML + "<div class='step-summary__item label-input'><div class='step-summary__label repeated-panel-label'>"+repeatablePanelLabel +"</div></div>"; 6116 6117 } 6118 const labelEmail = "<div class='step-summary__label'>" + panelList[i][j].title + "</div>"; 6119 const valueEmailEl = (panelList[i][j].value === undefined || panelList[i][j].value === null ) ? "--" : panelList[i][j].value; 6120 const valueEmail = "<div class='step-summary__value'>" + valueEmailEl + "</div>"; 6121 rowHTML = rowHTML + "<div class='step-summary__item "+ panelList[i][j].type + "'>" + labelEmail + valueEmail + "</div>"; 6122 break; 6123 6124 // Drop-Down 6125 case "drop-down": 6126 if ( panelList[i][j].repeatablepaneltitlevisible !== undefined && panelList[i][j].repeatablepaneltitlevisible && !repeatablePanelValSet && panelList[i][j].repeatableparent !== undefined ) { 6127 repeatablePanelValSet = true; 6128 repeatablePanelLabel = panelList[i][j].repeatableparent; 6129 rowHTML = rowHTML + "<div class='step-summary__item label-input'><div class='step-summary__label repeated-panel-label'>"+repeatablePanelLabel +"</div></div>"; 6130 6131 } 6132 const labelSelect = "<div class='step-summary__label'>" + panelList[i][j].title + "</div>"; 6133 const valueSelectEl = (panelList[i][j].value === undefined || panelList[i][j].value === null) ? "--" : panelList[i][j].value; 6134 let valueSelect = "<div class='step-summary__value'>--</div>"; 6135 6136 const dropdownGroupOptions = (panelList[i][j].value === undefined || panelList[i][j].value === null) ? "--" : panelList[i][j].cmp.enum; 6137 //For county & county entity, options in the list are dynamic. Using enum instead of enumnames 6138 if((panelList[i][j].name === 'county' || panelList[i][j].name === 'countyentity') && dropdownGroupOptions.length && valueSelectEl !== "--"){ 6139 valueSelect = "<div class='step-summary__value'>" + panelList[i][j].cmp.enum[dropdownGroupOptions.indexOf(valueSelectEl)] + "</div>"; 6140 } 6141 else if(dropdownGroupOptions.length && valueSelectEl !== "--") { 6142 valueSelect = "<div class='step-summary__value'>" + panelList[i][j].cmp.enumNames[dropdownGroupOptions.indexOf(valueSelectEl)] + "</div>"; 6143 } 6144 6145 rowHTML = rowHTML + "<div class='step-summary__item'>" + labelSelect + valueSelect + "</div>"; 6146 break; 6147 6148 // Datepicker
6149 case "date-input": 6150 if ( panelList[i][j].repeatablepaneltitlevisible !== undefined && panelList[i][j].repeatablepaneltitlevisible && !repeatablePanelValSet && panelList[i][j].repeatableparent !== undefined ) { 6151 repeatablePanelValSet = true; 6152 repeatablePanelLabel = panelList[i][j].repeatableparent; 6153 rowHTML = rowHTML + "<div class='step-summary__item label-input'><div class='step-summary__label repeated-panel-label'>"+repeatablePanelLabel +"</div></div>"; 6154 6155 } 6156 const labelDate = "<div class='step-summary__label'>" + panelList[i][j].title + "</div>"; 6157 const valueDateEl = (panelList[i][j].value === undefined || panelList[i][j].value === null ) ? "--" : panelList[i][j].value; 6158 const valueDate = "<div class='step-summary__value'>" + valueDateEl + "</div>"; 6159 rowHTML = rowHTML + "<div class='step-summary__item'>" + labelDate + valueDate + "</div>"; 6160 break; 6161 6162 // File Upload 6163 case "file-input": 6164 if ( panelList[i][j].repeatablepaneltitlevisible !== undefined && panelList[i][j].repeatablepaneltitlevisible && !repeatablePanelValSet && panelList[i][j].repeatableparent !== undefined ) { 6165 repeatablePanelValSet = true; 6166 repeatablePanelLabel = panelList[i][j].repeatableparent; 6167 rowHTML = rowHTML + "<div class='step-summary__item label-input'><div class='step-summary__label repeated-panel-label'>"+repeatablePanelLabel +"</div></div>"; 6168 6169 } 6170 if (panelList[i][j].cmp.properties["fd:viewType"] === "signature") { 6171 const labelText = "<div class='step-summary__label'>" + panelList[i][j].title + "</div>"; 6172 const valueSelectEl = "--"; 6173 let valueText = ""; 6174 if (panelList[i][j].value === undefined || panelList[i][j].value === null) { 6175 valueText = "<div class='step-summary__value'>" + valueSelectEl + " </div>"; 6176 } else { 6177 panelList[i][j].cmp.serialize().then((files) => { 6178 let signatureDataUrl; 6179 if (files && files.length > 0 && files[0]) { 6180 signatureDataUrl = files[0].data; 6181 document.querySelector("#signature_" + panelList[i][j].cmp.id).src = signatureDataUrl; 6182 } 6183 }); 6184 valueText = "<div class='step-summary__value'><img id='signature_" + panelList[i][j].cmp.id + "' alt='"+panelList[i][j].cmp._jsonModel["label"].value+"'></img> </div>"; 6185 } 6186 6187 rowHTML = rowHTML + "<div class='step-summary__item "+ panelList[i][j].type + "'>" + labelText + valueText +"</div>"; 6188 } else { 6189 const labelFile = "<div class='step-summary__label'>Attachments</div>"; 6190 rowHTML = rowHTML + "<div class='step-summary__item step-summary__file'>" + labelFile + "</div>"; 6191 const attachmentName = (panelList[i][j].value === undefined || panelList[i][j].value === null) ? "--" : panelList[i][j].value; 6192 const className = (panelList[i][j].value === undefined || panelList[i][j].value === null ) ? "" : "file-name--success"; 6193 const fileOpenDiv = "<div class='step-summary__item step-summary__file-attachment'><div class='step-summary__value file-name "+ className + "'>"; 6194 const fileCloseDiv = "</div></div>"; 6195 6196 if(Array.isArray(attachmentName) && attachmentName.length !== 0) { 6197 attachmentName.forEach((el, i) => { 6198 rowHTML = rowHTML + fileOpenDiv + attachmentName[i].name + fileCloseDiv; 6199 }); 6200 } else if(attachmentName === "--" || attachmentName.length === 0) { 6201 rowHTML = rowHTML + fileOpenDiv + "--" + fileCloseDiv; 6202 } else { 6203 rowHTML = rowHTML + fileOpenDiv + attachmentName.name + fileCloseDiv; 6204 } 6205 } 6206 break; 6207 6208 // Checkbox 6209 case "checkbox": 6210 if ( panelList[i][j].repeatablepaneltitlevisible !== undefined && panelList[i][j].repeatablepaneltitlevisible && !repeatablePanelValSet && panelList[i][j].repeatableparent !== undefined ) { 6211 repeatablePanelValSet = true; 6212 repeatablePanelLabel = panelList[i][j].repeatableparent; 6213 rowHTML = rowHTML + "<div class='step-summary__item label-input'><div class='step-summary__label repeated-panel-label'>"+repeatablePanelLabel +"</div></div>"; 6214 6215 } 6216 const labelCheckBox = "<div class='step-summary__label'>" + panelList[i][j].title + "</div>"; 6217 const emptyCheckBoxValue = "<div class='step-summary__value'>--</div>"; 6218 const checkBoxClass = (panelList[i][j].cmp.checked) ? "step-summary__checkBoxItem" : "step-summary__unCheckBoxItem" 6219 const checkboxOptions = panelList[i][j].cmp.enum; 6220 let valueCheckBox = (panelList[i][j].value === undefined || panelList[i][j].value === null ) ? labelCheckBox + emptyCheckBoxValue : panelList[i][j].value; 6221 6222 if(checkboxOptions.length && valueCheckBox !== labelCheckBox + emptyCheckBoxValue) { 6223 valueCheckBox = labelCheckBox + "<div class='step-summary__label " + checkBoxClass + "'>" + panelList[i][j].cmp.enumNames[checkboxOptions.indexOf(valueCheckBox)] + "</div>"; 6224 } 6225 6226 rowHTML = rowHTML + "<div class='step-summary__item step-summary__checkbox-list "+ panelList[i][j].type + "'>" + valueCheckBox + "</div>"; 6227 break; 6228 6229 // Checkbox Group 6230 case "checkbox-group": 6231 if ( panelList[i][j].repeatablepaneltitlevisible !== undefined && panelList[i][j].repeatablepaneltitlevisible && !repeatablePanelValSet && panelList[i][j].repeatableparent !== undefined ) { 6232 repeatablePanelValSet = true; 6233 repeatablePanelLabel = panelList[i][j].repeatableparent; 6234 rowHTML = rowHTML + "<div class='step-summary__item label-input'><div class='step-summary__label repeated-panel-label'>"+repeatablePanelLabel +"</div></div>"; 6235 6236 } 6237 const labelCheckboxGroup = "<div class='step-summary__label'>" + panelList[i][j].title + "</div>"; 6238 let checkboxGroupSelections = (panelList[i][j].value !== 'false' && panelList[i][j].value !== undefined && panelList[i][j].value !== null) ? panelList[i][j].value : []; 6239 // Obtain the original checkbox list from jsonModel 6240 const checkboxGroupOptions = panelList[i][j].cmp._jsonModel.enum; 6241 const checkboxDisplayNameOptions = panelList[i][j].cmp._jsonModel.enumNames; 6242 6243 // Construct list of selections 6244 let finalValue = ""; 6245 if(checkboxGroupSelections.length) { 6246 checkboxGroupSelections.forEach((el, i) => { 6247 finalValue = finalValue + "<li class='step-summary__checkBoxItem'>" + checkboxDisplayNameOptions[checkboxGroupOptions.indexOf(checkboxGroupSelections[i])] + "</li>"; 6248 }); 6249 6250 finalValue = "<ul>" + finalValue + "</ul>"; 6251 } else { 6252 finalValue = "--"; 6253 } 6254 6255 const valueCheckbox = "<div class='step-summary__value'>" + finalValue + "</div>"; 6256 rowHTML = rowHTML + "<div class='step-summary__item step-summary__checkbox-list'>" + labelCheckboxGroup + valueCheckbox + "</div>"; 6257 break; 6258 6259 // RadioButton 6260 case "radio-group": 6261 if ( panelList[i][j].repeatablepaneltitlevisible !== undefined && panelList[i][j].repeatablepaneltitlevisible && !repeatablePanelValSet && panelList[i][j].repeatableparent !== undefined ) { 6262 repeatablePanelValSet = true; 6263 repeatablePanelLabel = panelList[i][j].repeatableparent; 6264 rowHTML = rowHTML + "<div class='step-summary__item label-input'><div class='step-summary__label repeated-panel-label>"+repeatablePanelLabel +"</div></div>"; 6265 6266 } 6267 const labelRadiobutton = "<div class='step-summary__label'>" + panelList[i][j].title + "</div>"; 6268 const radioSelection = panelList[i][j].value; 6269 let finalRadioValue = (radioSelection !== null) ? radioSelection : "--"; 6270 const radioOptions = panelList[i][j].cmp._jsonModel.enum; 6271 6272 if(radioOptions.length && finalRadioValue !== "--") { 6273 finalRadioValue = panelList[i][j].cmp.enumNames[radioOptions.indexOf(radioSelection)]; 6274 } 6275 6276 let valueRadiobutton = "<div class='step-summary__value'><strong> " + finalRadioValue + "</strong></div>" 6277 rowHTML = rowHTML + "<div class='step-summary__item step-summary__radio'>" + labelRadiobutton + valueRadiobutton + "</div>"; 6278 break; 6279 } 6280 } 6281 rowHTML = rowHTML + "</div></div></div>"; 6282 } 6283 6284 // Append summary panels to review-submit container 6285 formsReviewSubmitContainer.innerHTML = window.DOMPurify ? window.DOMPurify.sanitize(rowHTML):rowHTML; 6286 } 6287 6288 function expandFirstAccordion() { 6289 const allStepSummaries = document.querySelectorAll(".step-summary"); 6290 if (allStepSummaries.length > 1) { 6291 const firstSummary = allStepSummaries[0]; 6292 const firstToggle = firstSummary.querySelector(".accordion-toggle"); 6293 if (firstToggle) { 6294 firstToggle.setAttribute("aria-expanded", "true"); 6295 firstToggle.textContent = "-"; 6296 firstSummary.querySelector(".accordion-content").classList.add("open"); 6297 firstSummary.querySelector(".step-summary__button").classList.add("visible"); 6298 firstSummary.querySelector(".tick-mark").style.display = "none"; 6299 firstSummary.setAttribute("data-opened-once", "true"); 6300 } 6301 } 6302 } 6303 6304 // Check for form updates 6305 gb.on("elementValueChanged", function () { 6306 if(wizardLabelContainer.length > 0) { 6307 setTimeout(() => { 6308 updateSummary(); 6309 },200); 6310 } 6311 }); 6312
6313 //To expand & collapse the accordions on click of + & - icons 6314 document.addEventListener("click", function (e) { 6315 //if (!e.target.classList.contains("accordion-toggle")) return; 6316 const btn = e.target.closest("button[aria-expanded]"); 6317 if (!btn) return; 6318 const stepSummary = btn.closest(".step-summary"); 6319 if (!stepSummary) return; 6320 6321 const allSummaries = document.querySelectorAll(".step-summary"); 6322 const isExpanded = btn.getAttribute("aria-expanded") === "true"; 6323 6324 // Close ALL accordions first 6325 allSummaries.forEach(summary => { 6326 const b = summary.querySelector("button[aria-expanded]"); 6327 const content = summary.querySelector(".accordion-content"); 6328 const btnContainer = summary.querySelector(".step-summary__button"); 6329 //const tickImg = summary.querySelector(".tick-mark-img"); 6330 const tickImg = summary.querySelector(".tick-mark"); 6331 const hasBeenOpened = summary.getAttribute("data-opened-once") === "true"; 6332 6333 b.setAttribute("aria-expanded", "false"); 6334 b.textContent = "+"; 6335 content.classList.remove("open"); 6336 btnContainer.classList.remove("visible"); 6337 6338 if (hasBeenOpened) { 6339 tickImg.style.display = "inline-block"; 6340 } 6341 }); 6342 6343 // Open clicked accordion if it was closed 6344 if (!isExpanded) { 6345 btn.setAttribute("aria-expanded", "true"); 6346 btn.textContent = "-"; 6347 6348 stepSummary.querySelector(".accordion-content").classList.add("open"); 6349 stepSummary.querySelector(".step-summary__button").classList.add("visible"); 6350 stepSummary.querySelector(".tick-mark").style.display = "none"; 6351 stepSummary.setAttribute("data-opened-once", "true"); 6352 } 6353 }); 6354 }) 6355})(); 6356/******************************************************************************* 6357 * Copyright 2022 Adobe 6358 * 6359 * Licensed under the Apache License, Version 2.0 (the "License"); 6360 * you may not use this file except in compliance with the License. 6361 * You may obtain a copy of the License at 6362 * 6363 * http://www.apache.org/licenses/LICENSE-2.0 6364 * 6365 * Unless required by applicable law or agreed to in writing, software 6366 * distributed under the License is distributed on an "AS IS" BASIS, 6367 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 6368 * See the License for the specific language governing permissions and 6369 * limitations under the License. 6370 ******************************************************************************/ 6371 6372(function () { 6373 6374 const keyCodes = { 6375 END: 35, 6376 HOME: 36, 6377 ARROW_LEFT: 37, 6378 ARROW_UP: 38, 6379 ARROW_RIGHT: 39, 6380 ARROW_DOWN: 40 6381 }; 6382 6383 class Wizard extends FormView.FormPanel { 6384 6385 _templateHTML = {}; 6386 #_active; 6387 6388 static NS = FormView.Constants.NS; 6389 static IS = "adaptiveFormWizard"; 6390 static bemBlock = "cmp-adaptiveform-wizard"; 6391 static #tabIdSuffix = "_wizard-item-nav"; 6392 static #wizardPanelIdSuffix = "__wizardpanel"; 6393 maxEnabledTab = 0; 6394 minEnabledTab = 0; 6395 static DATA_ATTRIBUTE_VISIBLE = 'data-cmp-visible'; 6396 6397 static selectors = { 6398 self: "[data-" + Wizard.NS + '-is="' + Wizard.IS + '"]', 6399 active: { 6400 tab: "cmp-adaptiveform-wizard__tab--active", 6401 wizardpanel: "cmp-adaptiveform-wizard__wizardpanel--active" 6402 }, 6403 label: `.${Wizard.bemBlock}__label`, 6404 description: `.${Wizard.bemBlock}__longdescription`, 6405 qm: `.${Wizard.bemBlock}__questionmark`, 6406 widget: `.${Wizard.bemBlock}__widget`, 6407 tooltipDiv: `.${Wizard.bemBlock}__shortdescription`, 6408 previousButton: `.${Wizard.bemBlock}__previousNav`, 6409 previousButtonHidden: "cmp-adaptiveform-wizard__previousNav__hidden", 6410 nextButton: `.${Wizard.bemBlock}__nextNav`, 6411 previousButtonV2: `.${Wizard.bemBlock}__nav--previous`, 6412 nextButtonV2: `.${Wizard.bemBlock}__nav--next`, 6413 nextButtonHidden: "cmp-adaptiveform-wizard__nextNav__hidden", 6414 olTabList: `.${Wizard.bemBlock}__tabList`, 6415 singleActiveTitleDiv: `${Wizard.bemBlock}__singleActiveTitleDiv`, 6416 guideActiveIndex: `${Wizard.bemBlock}__guideActiveIndex`, 6417 guideLastIndex: `${Wizard.bemBlock}
6417__guideLastIndex` 6418 }; 6419 6420 constructor(params) { 6421 super(params); 6422 const {element} = params; 6423 this.#cacheElements(element); 6424 this.#setActive(this.#getCachedTabs()) 6425 this.#_active = this.#getActiveIndex(this.#getCachedTabs()); 6426 this.#setSingleActiveIndexTitle(); 6427 this.#setActiveStepCount(); 6428 this.#setNavigationRange(); 6429 this.#hideUnhideNavButtons(this.#_active); 6430 this.#refreshActive(); 6431 6432 this.#bindEvents(); 6433 if (window.Granite && window.Granite.author && window.Granite.author.MessageChannel) { 6434 /* 6435 * Editor message handling: 6436 * - subscribe to "cmp.panelcontainer" message requests sent by the editor frame 6437 * - check that the message data panel container type is correct and that the id (path) matches this specific Tabs component 6438 * - if so, route the "navigate" operation to enact a navigation of the Tabs based on index data 6439 */ 6440 CQ.CoreComponents.MESSAGE_CHANNEL = CQ.CoreComponents.MESSAGE_CHANNEL || new window.Granite.author.MessageChannel("cqauthor", window); 6441 const _self = this; 6442 CQ.CoreComponents.MESSAGE_CHANNEL.subscribeRequestMessage("cmp.panelcontainer", function (message) { 6443 if (message.data && message.data.type === "cmp-adaptiveform-wizard" && message.data.id === _self._elements.self.dataset["cmpPanelcontainerId"]) { 6444 if (message.data.operation === "navigate") { 6445 _self.#navigate(message.data.index); 6446 } 6447 } 6448 }); 6449 } 6450 } 6451 6452 /** 6453 * Caches the Tabs elements as defined via the {@code data-tabs-hook="ELEMENT_NAME"} markup API 6454 * 6455 * @private 6456 * @param {HTMLElement} wrapper The Tabs wrapper element 6457 */ 6458 #cacheElements(wrapper) { 6459 this._elements = {}; 6460 this._elements.self = wrapper; 6461 const hooks = this._elements.self.querySelectorAll("[data-" + Wizard.NS + "-hook-" + Wizard.IS + "]"); 6462 6463 for (let i = 0; i < hooks.length; i++) { 6464 let hook = hooks[i]; 6465 if (hook.closest("[data-cmp-is=" + Wizard.IS + "]") === this._elements.self) { // only process own tab elements 6466 let key = hook.dataset[Wizard.NS + "Hook" + "Adaptiveformwizard"]; 6467 if (this._elements[key]) { 6468 if (!Array.isArray(this._elements[key])) { 6469 let tmp = this._elements[key]; 6470 this._elements[key] = [tmp]; 6471 } 6472 this._elements[key].push(hook); 6473 } else { 6474 this._elements[key] = [hook]; 6475 } 6476 } 6477 } 6478 } 6479 6480 getClass() { 6481 return Wizard.IS; 6482 } 6483 6484 setFocus(id) { 6485 super.setFocus(id); 6486 this.setActive(); 6487 const index = this.#getTabIndexById(id + '_wizard-item-nav'); 6488 this.#navigate(index); 6489 } 6490 6491 getWidget() { 6492 return this.element.querySelector(Wizard.selectors.widget); 6493 } 6494 6495 getDescription() { 6496 return this.element.querySelector(Wizard.selectors.description); 6497 } 6498 6499 getLabel() { 6500 return this.element.querySelector(Wizard.selectors.label); 6501 } 6502 6503 getErrorDiv() { 6504 return this.element.querySelector(Wizard.selectors.errorDiv); 6505 } 6506 6507 getTooltipDiv() { 6508 return this.element.querySelector(Wizard.selectors.tooltipDiv); 6509 } 6510 6511 getQuestionMarkDiv() { 6512 return this.element.querySelector(Wizard.selectors.qm); 6513 } 6514 6515 getPreviousButtonDiv() { 6516 return (this.element.querySelector(Wizard.selectors.previousButton) || this.element.querySelector(Wizard.selectors.previousButtonV2)); 6517 } 6518 6519 getNextButtonDiv() { 6520 return (this.element.querySelector(Wizard.selectors.nextButton) || this.element.querySelector(Wizard.selectors.nextButtonV2)); 6521 } 6522 6523 #getTabListElement() { 6524 return this.element.querySelector(Wizard.selectors.olTabList) 6525 } 6526 6527 6528 /** 6529 * Binds navigation buttons event handling 6530 * 6531 * @private 6532 */ 6533 #bindEvents() { 6534 const _self = this; 6535 this.getNextButtonDiv().addEventListener("click", function (event) { 6536 _self.#navigateToNextTab(); 6537 }) 6538 this.getPreviousButtonDiv().addEventListener("click", function (event) { 6539 _self.#navigateToPreviousTab(); 6540 }) 6541 6542 6543 } 6544 6545 /** 6546 * Returns the index of the active tab, if no tab is active returns 0 6547 * 6548 * @param {Array} tabs Tab elements 6549 * @returns {Number} Index of the active tab, 0 if none is active 6550 */ 6551 #getActiveIndex(tabs) { 6552 if (tabs) { 6553 for (let i = 0; i < tabs.length; i++) { 6554 if (tabs[i].classList.contains(Wizard.selectors.active.tab)) { 6555 return i; 6556 } 6557 } 6558 } 6559 return 0; 6560 } 6561 6562 #setActive(tabs) { 6563 if (tabs) { 6564 tabs[0].classList.add(Wizard.selectors.active.tab); 6565 } 6566 } 6567 6568 /** 6569 * Handles tab keydown events 6570 * 6571 * @private 6572 * @param {Object} event The keydown event 6573 */ 6574 #onKeyDown(event) { 6575 const index = this.#_active; 6576 6577 const lastIndex = this.#getCachedTabs().length - 1; 6578 6579 switch (event.keyCode) { 6580 case keyCodes.ARROW_LEFT: 6581 case keyCodes.ARROW_UP: 6582 event.preventDefault(); 6583 if (index > 0) { 6584 this.#navigateAndFocusTab(index - 1); 6585 } 6586 break; 6587 case keyCodes.ARROW_RIGHT: 6588 case keyCodes.ARROW_DOWN: 6589 event.preventDefault(); 6590 if (index < lastIndex) { 6591 this.#navigateAndFocusTab(index + 1); 6592 } 6593 break; 6594 case keyCodes.HOME: 6595 event.preventDefault(); 6596 this.#navigateAndFocusTab(0); 6597 break; 6598 case keyCodes.END: 6599 event.preventDefault(); 6600 this.#navigateAndFocusTab(lastIndex); 6601 break; 6602 default: 6603 return; 6604 } 6605 } 6606 6607 /** 6608 * Refreshes the tab markup based on the current {@code Tabs#_active} index 6609 * 6610 * @private 6611 */ 6612 #refreshActive() { 6613 const wizardPanels = this.#getCachedWizardPanels(); 6614 const tabs = this.#getCachedTabs(); 6615 if (wizardPanels) { 6616 for (let i = 0; i < wizardPanels.length; i++) { 6617 if (i === parseInt(this.#_active)) { 6618 wizardPanels[i].classList.add(Wizard.selectors.active.wizardpanel); 6619 wizardPanels[i].removeAttribute(FormView.Constants.ARIA_HIDDEN); 6620 tabs[i].classList.add(Wizard.selectors.active.tab); 6621 tabs[i].setAttribute(FormView.Constants.ARIA_SELECTED, true); 6622 tabs[i].setAttribute(FormView.Constants.TABINDEX, "0"); 6623 } else { 6624 wizardPanels[i].classList.remove(Wizard.selectors.active.wizardpanel); 6625 wizardPanels[i].setAttribute(FormView.Constants.ARIA_HIDDEN, true); 6626 tabs[i].classList.remove(Wizard.selectors.active.tab); 6627 tabs[i].setAttribute(FormView.Constants.ARIA_SELECTED, false); 6628 tabs[i].setAttribute(FormView.Constants.TABINDEX, "-1"); 6629 } 6630 } 6631 } 6632 this.#hideUnhideNavButtons(this.#_active); 6633 } 6634 6635 /** 6636 * Focuses the element and prevents scrolling the element into view 6637 * 6638 * @param {HTMLElement} element Element to focus 6639 */ 6640 focusWithoutScroll(element) { 6641 const x = window.scrollX || window.pageXOffset; 6642 const y = window.scrollY || window.pageYOffset; 6643 element.focus(); 6644 window.scrollTo(x, y); 6645 } 6646 6647 6648 #navigateToNextTab() { 6649 const activeIndex = this.#_active; 6650 const activeTabElement = this.#getCachedTabs()[activeIndex]; 6651 6652 const activeChildId = activeTabElement.id.substring(0, activeTabElement.id.lastIndexOf(Wizard.#tabIdSuffix)); 6653 const activeChildView = this.getChild(activeChildId); 6654 let activeChildModel; 6655 if(activeChildView) { 6656 activeChildModel = activeChildView.getModel(); 6657 } 6658 else { 6659 activeChildModel = this.getModel().items.find(child => child.id === activeChildId); 6660 } 6661 let validationErrorList; 6662 if (!this.#isAuthoring()) { 6663 validationErrorList = activeChildModel.validate(); 6664 } 6665 if (validationErrorList === undefined || validationErrorList.length === 0) { 6666 let tabs = this.#getCachedTabs(); 6667 let nextVisibleIndex = this.#findNextVisibleChildIndex(activeIndex); 6668 if (tabs && nextVisibleIndex >= 0) { 6669 this.#navigateAndFocusTab(nextVisibleIndex); 6670 this.#setSingleActiveIndexTitle(); 6671 this.#setActiveStepCount(); 6672 window.scrollTo(0, 0); 6673 } 6674 } else { 6675 const firstInvalidField = document.querySelectorAll('#' + validationErrorList[0].fieldName + ' input'); 6676 6677 if(firstInvalidField.length) { 6678 firstInvalidField[0].focus(); 6679 } 6680 6681 if(validationErrorList[0].fieldName.includes("textinput") && !firstInvalidField.length) { 6682 const invalidTextArea = document.querySelectorAll('#' + validationErrorList[0].fieldName + ' textarea'); 6683 invalidTextArea[0].focus(); 6684 } 6685 } 6686 this.#hideUnhideNavButtons(this.#_active); 6687 } 6688 6689 #isAuthoring() { 6690 return window.Granite && window.Granite.author; 6691 } 6692 6693 #navigateToPreviousTab() { 6694 const activeIndex = this.#_active; 6695 const tabs = this.#getCachedTabs(); 6696 const lastVisibleIndex = this.#findLastVisibleChildIndex(activeIndex); 6697 if (tabs && lastVisibleIndex >= 0) { 6698 this.#navigateAndFocusTab(lastVisibleIndex); 6699 this.#setSingleActiveIndexTitle(); 6700 this.#setActiveStepCount(); 6701 window.scrollTo(0, 0); 6702 } 6703 this.#hideUnhideNavButtons(this.#_active); 6704 } 6705 6706 /** 6707 * Hides or shows, next and previous navigation buttons 6708 * 6709 * @private 6710 * @param {Number} index The index of the tab to navigate to 6711 * @param {Number} total number of tabs 6712 */ 6713 #hideUnhideNavButtons(activeTabIndex) { 6714 const tabsLength = this.#getCachedTabs() ? this.#getCachedTabs().length : 0; 6715 6716 const nextVisible = this.#findNextVisibleChildIndex(activeTabIndex); 6717 const previousVisible = this.#findLastVisibleChildIndex(activeTabIndex); 6718 6719 if(tabsLength === 0 || this.maxEnabledTab <= this.minEnabledTab) { 6720 this.getPreviousButtonDiv().setAttribute(Wizard.DATA_ATTRIBUTE_VISIBLE,"false"); 6721 this.getNextButtonDiv().setAttribute(Wizard.DATA_ATTRIBUTE_VISIBLE,"false"); 6722 } 6723 6724 if(activeTabIndex <= this.minEnabledTab || previousVisible === -1) { 6725 this.getPreviousButtonDiv().setAttribute(Wizard.DATA_ATTRIBUTE_VISIBLE,"false"); 6726 } 6727 if(activeTabIndex === this.maxEnabledTab || nextVisible === -1) { 6728 this.getNextButtonDiv().setAttribute(Wizard.DATA_ATTRIBUTE_VISIBLE,"false"); 6729 } 6730 6731 if(tabsLength > 1 && activeTabIndex > this.minEnabledTab && previousVisible > -1) { 6732 this.getPreviousButtonDiv().setAttribute(Wizard.DATA_ATTRIBUTE_VISIBLE,"true"); 6733 } 6734 6735 if(activeTabIndex < this.maxEnabledTab && nextVisible > -1) { 6736 this.getNextButtonDiv().setAttribute(Wizard.DATA_ATTRIBUTE_VISIBLE,"true"); 6737 } 6738 } 6739 6740 #setNavigationRange() { 6741 const wizardPanels = this.#getCachedWizardPanels(); 6742 if(wizardPanels) { 6743 this.maxEnabledTab = wizardPanels.length-1; 6744 this.minEnabledTab = 0; 6745 for (let i = 0; i < wizardPanels.length; i++) { 6746 if(!this.#childComponentVisible(this.#getCachedWizardPanels()[i])) { 6747 this.minEnabledTab = i+1; 6748 } else { 6749 break; 6750 } 6751 } 6752 for (let i = wizardPanels.length - 1; i >= 0; i--) { 6753 if(!this.#childComponentVisible(this.#getCachedWizardPanels()[i])) { 6754 this.maxEnabledTab = i; 6755 } else { 6756 break; 6757 } 6758 } 6759 this.minEnabledTab = Math.max(0, this.minEnabledTab); 6760 this.maxEnabledTab = Math.min(this.#getCachedTabs().length-1, this.maxEnabledTab); 6761 } 6762 } 6763 6764 #childComponentVisible(wizardTab) { 6765 return wizardTab.children[0].getAttribute('data-cmp-visible') === 'true'; 6766 } 6767 6768 #findNextVisibleChildIndex(currentIndex) { 6769 const tabs = this.#getCachedTabs(); 6770 const tabsLength = tabs? tabs.length : 0; 6771 for (let i = currentIndex + 1; i < tabsLength; i++) { 6772 let isVisible = tabs[i].getAttribute(Wizard.DATA_ATTRIBUTE_VISIBLE); 6773 if (isVisible === null || isVisible === 'true') { 6774 return i; 6775 } 6776 } 6777 return -1; 6778 } 6779 6780 #findLastVisibleChildIndex(currentIndex) { 6781 const tabs = this.#getCachedTabs(); 6782 if(tabs) { 6783 for (let i = currentIndex - 1; i >= 0; i--) { 6784 let isVisible = tabs[i].getAttribute(Wizard.DATA_ATTRIBUTE_VISIBLE); 6785 if (isVisible === null || isVisible === 'true') { 6786 return i; 6787 } 6788 } 6789 } 6790 return -1; 6791 } 6792 6793 6794 /** 6795 * Navigates to the tab at the provided index 6796 * 6797 * @private 6798 * @param {Number} index The index of the tab to navigate to 6799 */ 6800 #navigate(index) { 6801 this.#_active = index; 6802 this.#refreshActive(); 6803 } 6804 6805 /** 6806 * Navigates to the item at the provided index and ensures the active tab gains focus 6807 * 6808 * @private 6809 * @param {Number} index The index of the item to navigate to 6810 */ 6811 #navigateAndFocusTab(index) { 6812 this.#navigate(index); 6813 this.focusWithoutScroll(this.#getCachedTabs()[index]); 6814 } 6815 6816 #syncWizardNavLabels() { 6817 const tabs = this.#getCachedTabs(); 6818 const wizardPanels = this.#getCachedWizardPanels(); 6819 if (tabs) { 6820 for (let i = 0; i < tabs.length; i++) { 6821 let id = wizardPanels[i].querySelectorAll("[data-cmp-is]")[0].id; 6822 tabs[i].id = id + Wizard.#tabIdSuffix; 6823 tabs[i].setAttribute("aria-controls", id + Wizard.#wizardPanelIdSuffix); 6824 } 6825 } 6826 } 6827 6828 #syncWizardPanels() { 6829 const wizardPanels = this.#getCachedWizardPanels(); 6830 if (wizardPanels) { 6831 for (let i = 0; i < wizardPanels.length; i++) { 6832 let id = wizardPanels[i].querySelectorAll("[data-cmp-is]")[0].id; 6833 wizardPan
6833els[i].id = id + Wizard.#wizardPanelIdSuffix; 6834 wizardPanels[i].setAttribute("aria-labelledby", id + Wizard.#tabIdSuffix); 6835 } 6836 } 6837 } 6838 6839 syncMarkupWithModel() { 6840 super.syncMarkupWithModel(); 6841 this.#syncWizardNavLabels(); 6842 this.#syncWizardPanels(); 6843 } 6844 6845 handleChildAddition(childView) { 6846 if (childView.getInstanceManager() != null && this._templateHTML[childView.getInstanceManager().getId()] != null) { 6847 let navigationTabToBeRepeated = this._templateHTML[childView.getInstanceManager().getId()]['navigationTab'] 6848 .cloneNode(true); 6849 navigationTabToBeRepeated.id = childView.id + Wizard.#tabIdSuffix; 6850 navigationTabToBeRepeated.setAttribute("aria-controls", childView.id + Wizard.#wizardPanelIdSuffix); 6851 let instanceIndex = childView.getModel().index; 6852 let instanceManagerId = childView.getInstanceManager().getId() 6853 if (instanceIndex === 0) { 6854 let closestNonRepeatableFieldId = this._templateHTML[instanceManagerId]['closestNonRepeatableFieldId']; 6855 let closestRepeatableFieldInstanceManagerIds = this._templateHTML[instanceManagerId]['closestRepeatableFieldInstanceManagerIds']; 6856 let indexToInsert = this.getIndexToInsert(closestNonRepeatableFieldId, closestRepeatableFieldInstanceManagerIds); 6857 if (indexToInsert === 0) { 6858 let tabListParentElement = this.#getTabListElement(); 6859 tabListParentElement.insertBefore(navigationTabToBeRepeated, tabListParentElement.firstChild); 6860 } else { 6861 let beforeElement = this.#getCachedTabs()[indexToInsert - 1]; 6862 beforeElement.after(navigationTabToBeRepeated); 6863 } 6864 } else { 6865 let beforeTabNavElementId = childView.getInstanceManager().children[instanceIndex - 1].element.id + Wizard.#tabIdSuffix 6866 let beforeElement = this.#getTabNavElementById(beforeTabNavElementId); 6867 beforeElement.after(navigationTabToBeRepeated); 6868 } 6869 this.#cacheElements(this._elements.self); 6870 let repeatedWizardPanel = this.#getWizardPanelElementById(childView.id + Wizard.#wizardPanelIdSuffix); 6871 repeatedWizardPanel.setAttribute("aria-labelledby", childView.id + Wizard.#tabIdSuffix); 6872 this.#refreshActive(); 6873 this.#getTabIndexById(); 6874 if (childView.getInstanceManager().getModel().minOccur != undefined && childView.getInstanceManager().children.length > childView.getInstanceManager().getModel().minOccur) { 6875 this.#navigateAndFocusTab(this.#getTabIndexById(navigationTabToBeRepeated.id)); 6876 } 6877 } 6878 } 6879 6880 handleChildRemoval(removedInstanceView) { 6881 let removedTabPanelId = removedInstanceView.element.id + Wizard.#wizardPanelIdSuffix; 6882 let removedTabNavId = removedTabPanelId.substring(0, removedTabPanelId.lastIndexOf("__")) + Wizard.#tabIdSuffix; 6883 let wizardPanelElement = this.#getWizardPanelElementById(removedTabPanelId); 6884 let tabNavElement = this.#getTabNavElementById(removedTabNavId); 6885 tabNavElement.remove(); 6886 wizardPanelElement.remove(); 6887 this.children.splice(this.children.indexOf(removedInstanceView), 1); 6888 this.#cacheElements(this._elements.self); 6889 this.#_active = this.#getActiveIndex(this.#getCachedTabs()); 6890 this.#refreshActive(); 6891 } 6892 6893 addChild(childView) { 6894 super.addChild(childView); 6895 this.#cacheTemplateHTML(childView); 6896 //when all children are available in view 6897 if (this.getCountOfAllChildrenInModel() === this.children.length) { 6898 this.cacheClosestFieldsInView(); 6899 this.handleHiddenChildrenVisibility(); 6900 } 6901 this.#setNavigationRange(); 6902 this.#hideUnhideNavButtons(this.#_active); 6903 } 6904 6905 getChildViewByIndex(index) { 6906 let wizardPanels = this.#getCachedWizardPanels(); 6907 let fieldId = wizardPanels[index].id.substring(0, wizardPanels[index].id.lastIndexOf("__")); 6908 return this.getChild(fieldId); 6909 } 6910 6911 /** 6912 * Adds unique HTML for added instance corresponding to requirements of different types of repeatableParent 6913 * @param instanceManager of the repeated component 6914 * @param addedModel of the repeated component 6915 * @param htmlElement of the repeated component 6916 */ 6917 addRepeatableMarkup(instanceManager, addedModel, htmlElement) { 6918 let elementToEnclose = this._templateHTML[instanceManager.getId()]['targetWizardPanel'].cloneNode(false); 6919 elementToEnclose.id = addedModel.id + Wizard.#wizardPanelIdSuffix; 6920 let result = this.#getBeforeViewElement(instanceManager, addedModel.index); 6921 let beforeViewElement = result.beforeViewElement; 6922 beforeViewElement.after(elementToEnclose); 6923 elementToEnclose.append(htmlElement.querySelector('#' + addedModel.id)); 6924 return elementToEnclose; 6925 } 6926 6927 #cacheTemplateHTML(childView) { 6928 if (childView.getInstanceManager() != null && (this._templateHTML == null || this._templateHTML[childView.getInstanceManager().getId()] == null)) {
6929 let tabId = childView.element.id + Wizard.#tabIdSuffix; 6930 let wizardPanelId = childView.element.id + Wizard.#wizardPanelIdSuffix; 6931 let instanceManagerId = childView.getInstanceManager().getId(); 6932 let navigationTabToBeRepeated = this.#getTabNavElementById(tabId); 6933 let wizardPanelToBeRepeated = this.#getWizardPanelElementById(wizardPanelId) 6934 this._templateHTML[instanceManagerId] = {}; 6935 this._templateHTML[instanceManagerId]['navigationTab'] = navigationTabToBeRepeated; 6936 this._templateHTML[instanceManagerId]['targetWizardPanel'] = wizardPanelToBeRepeated; 6937 } 6938 } 6939 6940 #getCachedTabs() { 6941 return this._elements["tab"]; 6942 } 6943 6944 #getCachedWizardPanels() { 6945 return this._elements["wizardpanel"] 6946 } 6947 6948 #getTabNavElementById(tabId) { 6949 let tabs = this.#getCachedTabs(); 6950 if (tabs) { 6951 for (let i = 0; i < tabs.length; i++) { 6952 if (tabs[i].id === tabId) { 6953 return tabs[i]; 6954 } 6955 } 6956 } 6957 } 6958 6959 #getWizardPanelElementById(wizardPanelId) { 6960 let wizardPanels = this.#getCachedWizardPanels(); 6961 if (wizardPanels) { 6962 for (let i = 0; i < wizardPanels.length; i++) { 6963 if (wizardPanels[i].id === wizardPanelId) { 6964 return wizardPanels[i]; 6965 } 6966 } 6967 } 6968 } 6969 6970 #getTabIndexById(tabId) { 6971 let tabs = this.#getCachedTabs(); 6972 if (tabs) { 6973 for (let i = 0; i < tabs.length; i++) { 6974 if (tabs[i].id === tabId) { 6975 return i; 6976 } 6977 } 6978 } 6979 return -1; 6980 } 6981 6982 #getBeforeViewElement(instanceManager, instanceIndex) { 6983 let result = {}; 6984 let instanceManagerId = instanceManager.getId(); 6985 if (instanceIndex === 0) { 6986 let closestNonRepeatableFieldId = this._templateHTML[instanceManagerId]['closestNonRepeatableFieldId']; 6987 let closestRepeatableFieldInstanceManagerIds = this._templateHTML[instanceManagerId]['closestRepeatableFieldInstanceManagerIds']; 6988 let indexToInsert = this.getIndexToInsert(closestNonRepeatableFieldId, closestRepeatableFieldInstanceManagerIds); 6989 let wizardPanels = this.#getCachedWizardPanels(); 6990 if (indexToInsert > 0) { 6991 result.beforeViewElement = this.#getWizardPanelElementById(wizardPanels[indexToInsert - 1].id); 6992 } else { 6993 result.beforeViewElement = this.getPreviousButtonDiv(); 6994 } 6995 } else { 6996 let previousInstanceElement = instanceManager.children[instanceIndex - 1].element; 6997 let previousInstanceWizardPanelIndex = this.#getTabIndexById(previousInstanceElement.id + Wizard.#tabIdSuffix); 6998 result.beforeViewElement = this.#getCachedWizardPanels()[previousInstanceWizardPanelIndex]; 6999 } 7000 return result; 7001 } 7002 7003 updateChildVisibility(visible, state) { 7004 this.updateVisibilityOfNavigationElement(this.#getTabNavElementById(state.id + Wizard.#tabIdSuffix), visible); 7005 let activeTabNavElement = this.#getCachedTabs()[this.#_active]; 7006 this.#setNavigationRange(); 7007 this.#hideUnhideNavButtons(this.#_active); 7008 if (!visible && activeTabNavElement.id === state.id + Wizard.#tabIdSuffix) { 7009 let child = this.findFirstVisibleChild(this.#getCachedTabs()); 7010 if (child) { 7011 this.#navigateAndFocusTab(this.#getTabIndexById(child.id)); 7012 } 7013 } 7014 } 7015 7016 #getSingleActiveIndexTitle(tabs) { 7017 if (tabs) { 7018 for (let i = 0; i < tabs.length; i++) { 7019 if (tabs[i].classList.contains(Wizard.selectors.active.tab)) { 7020 return tabs[i].textContent; 7021 } 7022 } 7023 } 7024 return 0; 7025 } 7026 7027 #setSingleActiveIndexTitle() { 7028 const singleTitleLabel = document.getElementsByClassName(Wizard.selectors.singleActiveTitleDiv)[0]; 7029 singleTitleLabel.textContent = this.#getSingleActiveIndexTitle(this.#getCachedTabs()); 7030 } 7031 7032 #getTabCount(tabs) { 7033 if (tabs) { 7034 return tabs.length; 7035 } 7036 return 0; 7037 } 7038 7039 #setActiveStepCount() { 7040 const firstStepLabel = document.getElementsByClassName(Wizard.selectors.guideActiveIndex)[0]; 7041 const lastStepLabel = document.getElementsByClassName(Wizard.selectors.guideLastIndex)[0]; 7042 7043 const currentStep = (this.#getActiveIndex)(this.#getCachedTabs()); 7044 const lastStep = this.#getTabCount(this.#getCachedTabs()); 7045 firstStepLabel.textContent = (currentStep + 1); 7046 lastStepLabel.textContent = lastStep; 7047 } 7048 } 7049 7050 FormView.Utils.setupField(({element, formContainer}) => { 7051 return new Wizard({element, formContainer}) 7052 }, Wizard.selectors.self); 7053 7054}()); 7055 7056// Check for buttons contained in the OOTB wizard as divs and add click functionality when hitting Enter 7057document.querySelectorAll('div[role="button"], .cmp-adaptiveform-fileinput__dragarea label, input[type="radio"], input[type="checkbox"]').forEach(el => { 7058 el.addEventListener('keydown', e => {
7059 const keyDown = e.key !== undefined ? e.key : e.keyCode; 7060 if ( (keyDown === 'Enter' || keyDown === 13) || (['Spacebar', ' '].indexOf(keyDown) >= 0 || keyDown === 32)) { 7061 e.preventDefault(); 7062 el.click(); 7063 } 7064 }); 7065}); 7066function preparePayload(obj) { 7067 if (Array.isArray(obj)) { 7068 return obj.map(item => preparePayload(item)); 7069 } else if (obj && typeof obj === "object") { 7070 const cleaned = {}; 7071 for (const key in obj) { 7072 if (!obj.hasOwnProperty(key)) continue; 7073 7074 const value = obj[key]; 7075 const lowerKey = key.toLowerCase(); 7076 if ( 7077 (lowerKey.includes("button") && typeof value !== "object") || 7078 lowerKey === "addposition" || 7079 lowerKey === "addrepotransportationbtn" || 7080 lowerKey === "addincome" || 7081 lowerKey === "submit1711053557041" 7082 ) { 7083 continue; 7084 } 7085 cleaned[key] = value === undefined ? "" : value; 7086 } 7087 return cleaned; 7088 } else { 7089 return obj === undefined ? "" : obj; 7090 } 7091} 7092 7093function saveAsDraft() { 7094 //Get Query Parameters 7095 const urlParams = new URLSearchParams(window.location.search); 7096 const formId = urlParams.get('id'); 7097 const amend = urlParams.get('amend'); 7098 const isNewFiling = urlParams.get('type') === 'new-filing'; 7099 7100 //Get dashboardformid field via GuideBridge API 7101 const dashboardFormIdField = guideBridge.resolveNode("$form.sofiForm.gettingstarted.dashboardformid"); 7102 7103 let draftId = null; 7104 7105 try { 7106 const formData = guideBridge.getFormModel().exportData(); 7107 const payload = preparePayload(formData); 7108 console.log("Payload to send:", JSON.stringify(payload, null, 2)); 7109 7110 // In case of Resume Filing draftID will be Form ID 7111 if (amend == "false") { 7112 draftId = formId; 7113 } 7114 // In case of Amend draftID will be from payload if dashboardformid is not empty 7115 if (amend == "true") { 7116 if(dashboardFormIdField.value!==null) { 7117 draftId = payload.dashboardformid; 7118 } else { 7119 draftId = formId; 7120 } 7121 } 7122 // In case of New Filing draftID will be from payload if dashboardformid is not empty 7123 if (isNewFiling) { 7124 if(dashboardFormIdField.value!==null) { 7125 draftId = payload.dashboardformid; 7126 } else { 7127 draftId = null; 7128 } 7129 } 7130 7131 const requestBody = { 7132 payload: payload, 7133 draftId: draftId 7134 }; 7135 7136 fetch("/content/copaservlets/jcr:content/saveasdraft.json", { 7137 method: "POST", 7138 headers: { "Content-Type": "application/json" }, 7139 body: JSON.stringify(requestBody) 7140 }) 7141 .then(res => res.json()) 7142 .then(result => { 7143 console.log("Draft save response:", result); 7144 7145 // Amend and New Filing: Save saveasdraft form Id in form's dashboardformid 7146 if (amend == "true" || isNewFiling) { 7147 dashboardFormIdField.value = result.id; 7148 } 7149 //Display saved as draft modal popup 7150 const savedAsDraftModal = document.getElementById('saveasdraftpopup'); 7151 if(savedAsDraftModal) { 7152 document.getElementById('saveasdraftpopup').showModal(); 7153 } 7154 7155 }) 7156 .catch(err => console.error("Error saving draft:", err)); 7157 } catch (e) { 7158 console.error("Error in saveAsDraft:", e); 7159 } 7160 }; 7161 window.addEventListener("load", () => { 7162 const storedId = sessionStorage.getItem("draftId"); 7163 if (storedId) { 7164 draftId = storedId; 7165 console.log("Restored draftId from storage:", draftId); 7166 } 7167 }); 7168 7169 function closeErrorModal(id){ 7170 const closeModal = document.getElementById(id); 7171 if(closeModal) { 7172 closeModal.close(); 7173 } 7174 } 7175const sofiFormFunctions = { 7176 setFormCountryDropDowns: (elem, countyList) => { 7177 elem.enum = countyList; 7178 }, 7179 changeCountyEntity: (elem, countyValue, counties) => { 7180 const elemString = elem.replace('countydetails.county', 'countydetails.countyentity'); 7181 const countyEntityElem = guideBridge.resolveNode(elemString); 7182 const countyEntities = counties.find((county) => county.value === countyValue); 7183 let countyEntitiesArray = []; 7184 countyEntityElem.enum = []; 7185 7186 if (countyEntities.counties.length) {
7187 countyEntities.counties.forEach((countyEntity) => { 7188 countyEntitiesArray.push(countyEntity.value); 7189 }); 7190 }; 7191 7192 countyEntityElem.enum = countyEntitiesArray; 7193 countyEntityElem.value = ''; 7194 countyEntityElem.valid = true; 7195 countyEntityElem.errorMessage = ''; 7196 }, 7197 setNewCountyPanel: (countiesArray) => { 7198 let countyFlatList = []; 7199 countiesArray.forEach((item) => { 7200 countyFlatList.push(item.value); 7201 }); 7202 setTimeout(() => { 7203 const positionspanels = guideBridge.resolveNode('$form.sofiForm.public_position.positionpanelcontainer'); 7204 positionspanels.items[positionspanels.items.length - 1].items.forEach((position, x) => { 7205 switch (position.name) { 7206 case 'countydetails': 7207 position.items.forEach((countydetails, y) => { 7208 switch (countydetails.name) { 7209 case 'county': 7210 sofiFormFunctions.setFormCountryDropDowns(countydetails, countyFlatList); 7211 break; 7212 default: 7213 break; 7214 } 7215 }); 7216 break; 7217 default: 7218 break; 7219 } 7220 }); 7221 }, 100); 7222 }, 7223 popluateSofiForm: (formData, isAmend, isNew, countyList) => { 7224 let countyFlatList = []; 7225 7226 // Defines expandable panel section names 7227 const panels = { 7228 positionspanels: '$form.sofiForm.public_position.positionpanelcontainer', 7229 occupationpanels: '$form.sofiForm.public_position.occupation', 7230 realestatespanels: '$form.sofiForm.realestateinfo.realestatescontainer.realestates', 7231 creditorspanels: '$form.sofiForm.realestateinfo.creditorscontainer.creditors', 7232 giftspanels: '$form.sofiForm.giftstransportation.giftpanelcontainer.gifts', 7233 transportationpanels: '$form.sofiForm.giftstransportation.transportationpanelcontainer.transportationlist', 7234 businessentitiespanels: '$form.sofiForm.additionaldisclosure.businessentitiescontainer.businessentities', 7235 financialinterestpanels: '$form.sofiForm.additionaldisclosure.financialinterestscontainer.financialinterests', 7236 businessinterestpanels: '$form.sofiForm.additionaldisclosure.businessinterestscontainer.businessinterests', 7237 incomepanels: '$form.sofiForm.panel5.incomedetailspanelcontainer1.income' 7238 }; 7239 7240 // Defines single use formfields (outside of panels) 7241 const formFields = { 7242 acknowledgement: guideBridge.resolveNode("$form.sofiForm.gettingstarted.acknowledgement"), 7243 filingselection: guideBridge.resolveNode("$form.sofiForm.gettingstarted.filingselection"), 7244 filingyear: guideBridge.resolveNode("$form.sofiForm.gettingstarted.filingyear"), 7245 firstname: guideBridge.resolveNode("$form.sofiForm.personalInformation.firstname"), 7246 middleinitial: guideBridge.resolveNode("$form.sofiForm.personalInformation.middleinitial"), 7247 lastname: guideBridge.resolveNode("$form.sofiForm.personalInformation.lastname"), 7248 suffix: guideBridge.resolveNode("$form.sofiForm.personalInformation.suffix"), 7249 addresstype: guideBridge.resolveNode("$form.sofiForm.personalInformation.addresstype"), 7250 address1: guideBridge.resolveNode("$form.sofiForm.personalInformation.address1"), 7251 address2: guideBridge.resolveNode("$form.sofiForm.personalInformation.address2"), 7252 city: guideBridge.resolveNode("$form.sofiForm.personalInformation.city"), 7253 state: guideBridge.resolveNode("$form.sofiForm.personalInformation.state"), 7254 zipcode: guideBridge.resolveNode("$form.sofiForm.personalInformation.zipcode"), 7255 telephone: guideBridge.resolveNode("$form.sofiForm.personalInformation.telephone"), 7256 realestateinterestselection: guideBridge.resolveNode("$form.sofiForm.realestateinfo.realestateinterestselection"), 7257 realestateinterestselectionamend: guideBridge.resolveNode("$form.sofiForm.realestateinfo.realestateamend"), 7258 creditorsselection: guideBridge.resolveNode("$form.sofiForm.realestateinfo.creditorsselection"), 7259 creditorsselectionamend: guideBridge.resolveNode("$form.sofiForm.realestateinfo.creditorsamend"), 7260 giftselection: guideBridge.resolveNode("$form.sofiForm.giftstransportation.giftselection"), 7261 giftselectionamend: guideBridge.resolveNode("$form.sofiForm.giftstransportation.giftsamend"), 7262 transportationselection: guideBridge.resolveNode("$form.sofiForm.giftstransportation.transportationselection"), 7263 transportationselectionamend: guideBridge.resolveNode("$form.sofiForm.giftstransportation.transportationamend"), 7264 affiliationselection: guideBridge.resolveNode("$form.sofiForm.additionaldisclosure.affiliationselection"), 7265 affiliationselectionamend: guideBridge.resolveNode("$form.sofiForm.additionaldisclosure.businessentityamend"), 7266 financialinterestselection: guideBridge.resolveNode("$form.sofiForm.additionaldisclosure.financialinterestselection"), 7267 financialinterestselectionamend: guideBridge.resolveNode("$form.sofiForm.additionaldisclosure.financialinterestsamend"), 7268 businessinterestselection: guideBridge.resolveNode("$form.sofiForm.additionaldisclosure.businessinterestselection"), 7269 businessinterestselectionamend: guideBridge.resolveNode("$form.sofiForm.additionaldisclosure.businessinterestsamend"), 7270 incomesourceselection: guideBridge.resolveNode("$form.sofiForm.panel5.incomesourceselection"), 7271 incomesourceselectionamend: guideBridge.resolveNode("$form.sofiForm.panel5.incomeamend"), 7272 submissionfullname: guideBridge.resolveNode("$form.sofiForm.panel6.submissionfullname"), 7273 submissionconfirmation: guideBridge.resolveNode("$form.sofiForm.panel6.submissionconfirmation"), 7274 submissiondate: guideBridge.resolveNode("$form.sofiForm.panel6.submissiondate") 7275 }; 7276 7277 // Defines Guidebridge panel nodes 7278 const positionspanels = guideBridge.resolveNode(panels.positionspanels); 7279 const occupationpanels = guideBridge.resolveNode(panels.occupationpanels); 7280 const realestatespanels = guideBridge.resolveNode(panels.realestatespanels); 7281 const creditorspanels = guideBridge.resolveNode(panels.creditorspanels); 7282 const giftspanels = guideBridge.resolveNode(panels.giftspanels); 7283 const transportationpanels = guideBridge.resolveNode(panels.transportationpanels); 7284 const businessentitiespanel = guideBridge.resolveNode(panels.businessentitiespanels); 7285 const financialinterestpanel = guideBridge.resolveNode(panels.financialinterestpanels); 7286 const businessinterestpanel = guideBridge.resolveNode(panels.businessinterestpanels); 7287 const incomepanel = guideBridge.resolveNode(panels.incomepanels); 7288 7289 // Defines "Add Panel" buttons 7290 const addPosBtn = document.querySelector('button[class-label="btn-add-position"]'); 7291 const addOccBtn = document.querySelector('button[class-label="btn-add-occupation"]'); 7292 const addRealEstateBtn = document.querySelector('button[class-label="btn-add-real-estate"]'); 7293 const addCreditorBtn = document.querySelector('button[class-label="btn-add-creditor"]'); 7294 const addGiftBtn = document.querySelector('button[class-label="btn-add-gift"]'); 7295 const addTransportationBtn = document.querySelector('button[class-label="btn-add-trans
7295portation"]'); 7296 const addBusEntityBtn = document.querySelector('button[class-label="btn-add-business-entity"]'); 7297 const addFinancialInterestBtn = document.querySelector('button[class-label="btn-add-financial-interest"]'); 7298 const addBusInterestBtn = document.querySelector('button[class-label="btn-add-business-interest"]'); 7299 const addIncomeBtn = document.querySelector('button[class-label="btn-add-income"]'); 7300 7301 countyList.forEach((item) => { 7302 countyFlatList.push(item.value); 7303 }); 7304 7305 countyList.push('Not Listed'); 7306 7307 // Truthiness check for checkboxes 7308 const isChecked = (formValue) => { 7309 if (typeof formValue === 'string' || formValue instanceof String) { 7310 return formValue.toLowerCase() === 'on' || formValue.toLowerCase() === 'yes'; 7311 } else { 7312 return false; 7313 } 7314 }; 7315 7316 // Prepare the expandable form field sections (panels) by clicking the add button to create 7317 // new sections to fill based on the returned form data. 7318 if (formData?.positionpanelcontainer.length > 1) { 7319 for (let i = 0; i < formData?.positionpanelcontainer.length - 1; i++) { 7320 addPosBtn.click(); 7321 } 7322 }; 7323 7324 if (formData?.occupation.length > 1) { 7325 for (let i = 0; i < formData?.occupation.length - 1; i++) { 7326 addOccBtn.click(); 7327 } 7328 }; 7329 7330 if (!isNew) { 7331 if (formData?.realestates.length > 1) { 7332 for (let i = 0; i < formData?.realestates.length - 1; i++) { 7333 addRealEstateBtn.click(); 7334 } 7335 }; 7336 }; 7337 7338 if (formData?.creditors.length > 1) { 7339 for (let i = 0; i < formData?.creditors.length - 1; i++) { 7340 addCreditorBtn.click(); 7341 } 7342 }; 7343 7344 if (!isNew) { 7345 if (formData?.gifts.length > 1) { 7346 for (let i = 0; i < formData?.gifts.length - 1; i++) { 7347 addGiftBtn.click(); 7348 } 7349 }; 7350 }; 7351 7352 if (!isNew) { 7353 if (formData?.transportationlist.length > 1) { 7354 for (let i = 0; i < formData?.transportationlist.length - 1; i++) { 7355 addTransportationBtn.click(); 7356 } 7357 }; 7358 }; 7359 7360 7361 if (formData?.businessentities.length > 1) { 7362 for (let i = 0; i < formData?.businessentities.length - 1; i++) { 7363 addBusEntityBtn.click(); 7364 } 7365 }; 7366 7367 if (formData?.financialinterests.length > 1) { 7368 for (let i = 0; i < formData?.financialinterests.length - 1; i++) { 7369 addFinancialInterestBtn.click(); 7370 } 7371 }; 7372 7373 if (!isNew) { 7374 if (formData?.businessinterests.length > 1) { 7375 for (let i = 0; i < formData?.businessinterests.length - 1; i++) { 7376 addBusInterestBtn.click(); 7377 } 7378 }; 7379 }; 7380 7381 if (formData?.income.length > 1) { 7382 for (let i = 0; i < formData?.income.length - 1; i++) { 7383 if(formData?.income[i].typeofincome) { 7384 addIncomeBtn.click(); 7385 } 7386 } 7387 }; 7388 7389 // Update Panel 1 fields 7390 if (!isNew) { 7391 formFields.acknowledgement.checked = isAmend ? false : isChecked(formData?.acknowledgement); 7392 formFields.filingselection.value = formData?.filingselection; 7393 formFields.filingyear.enum = [formData?.filingyear]; 7394 formFields.filingyear.enumNames = [formData?.filingyear]; 7395 formFields.filingyear.value = formData?.filingyear; 7396 } 7397 7398 if (!isNew && isAmend){ 7399 formFields.filingyear.visible = false; 7400 } 7401 7402 // If not amend mode, make first panel fields read only 7403 if (!isAmend && !isNew) { 7404 formFields.acknowledgement.readOnly = true; 7405 formFields.filingselection.readOnly = true; 7406 formFields.filingyear.readOnly = true; 7407 } 7408 7409 // Update Panel 2 fields 7410 formFields.firstname.value = formData?.firstname; 7411 formFields.middleinitial.value = formData?.middleinitial; 7412 formFields.lastname.value = formData?.lastname; 7413 formFields.suffix.value = formData?.suffix; 7414 formFields.addresstype.value = formData?.addresstype; 7415 formFields.address1.value = formData?.address1; 7416 formFields.address2.value = formData?.address2; 7417 formFields.city.value = formData?.city; 7418 formFields.state.value = formData?.state; 7419 formFields.zipcode.value = formData?.zipcode; 7420 formFields.telephone.value = formData?.telephone; 7421 7422 // Update Panel 3 fields 7423
7424 positionspanels.items.forEach((positionpanel, i) => { 7425 positionpanel.items.forEach((position, x) => { 7426 switch (position.name) { 7427 case 'status': 7428 position.value = formData?.positionpanelcontainer[i].status; 7429 break; 7430 case 'govtlevelselection': 7431 position.value = formData?.positionpanelcontainer[i].govtlevelselection; 7432 break; 7433 case 'statedetails': 7434 if (formData?.positionpanelcontainer[i].govtlevelselection === 'State') { 7435 // The setTimeout function here fixes a timing issue with the fields not immediately being 7436 // available on county/state selection. 7437 setTimeout(() => { 7438 position.items.forEach((statedetails, y) => { 7439 switch (statedetails.name) { 7440 case 'stateentity': 7441 statedetails.value = formData?.positionpanelcontainer[i]?.stateentity; 7442 break; 7443 case 'otherstateentity': 7444 statedetails.value = formData?.positionpanelcontainer[i]?.otherstateentity; 7445 break; 7446 case 'position': 7447 statedetails.value = formData?.positionpanelcontainer[i]?.position; 7448 break; 7449 case 'receivedincome': 7450 statedetails.checked = isChecked(formData?.positionpanelcontainer[i].receivedincome); 7451 break; 7452 case 'stateincomedetails': 7453 statedetails.items.forEach((stateincomedetail,index) =>{ 7454 switch(stateincomedetail.name) { 7455 case 'stateincomeaddress': 7456 stateincomedetail.value = formData?.positionpanelcontainer[i]?.stateincomeaddress; 7457 break; 7458 case 'stateincomeaddress2' : 7459 stateincomedetail.value = formData?.positionpanelcontainer[i]?.stateincomeaddress2; 7460 break; 7461 case 'stateincomecity' : 7462 stateincomedetail.value = formData?.positionpanelcontainer[i]?.stateincomecity; 7463 break; 7464 case 'stateincomestate' : 7465 stateincomedetail.value = formData?.positionpanelcontainer[i]?.stateincomestate; 7466 break; 7467 case 'stateincomezipcode': 7468 stateincomedetail.value = formData?.positionpanelcontainer[i]?.stateincomezipcode; 7469 break; 7470 } 7471 }) 7472 break; 7473 default: 7474 break; 7475 } 7476 }); 7477 }, 200); 7478 } 7479 break; 7480 case 'countydetails': 7481 if (formData?.positionpanelcontainer[i].govtlevelselection === 'County/Local') { 7482 setTimeout(() => { 7483 position.items.forEach((countydetails, y) => { 7484 switch (countydetails.name) { 7485 case 'position': 7486 countydetails.value = formData?.positionpanelcontainer[i]?.position; 7487 break; 7488 case 'otherposition': 7489 countydetails.value = formData?.positionpanelcontainer[i]?.otherposition; 7490 break; 7491 case 'county': 7492 sofiFormFunctions.setFormCountryDropDowns(countydetails, countyFlatList); 7493 countydetails.value = formData?.positionpanelcontainer[i]?.county; 7494 countydetails.valid = true; 7495 countydetails.errorMessage = ''; 7496 break; 7497 case 'countyentity': 7498 countydetails.value = formData?.positionpanelcontainer[i]?.countyentity; 7499 break; 7500 case 'othercountyentity': 7501 countydetails.value = formData?.positionpanelcontainer[i].othercountyentity; 7502 break; 7503 case 'countyreceivedincome': 7504 countydetails.checked = isChecked(formData?.positionpanelcontainer[i].countyreceivedincome); 7505 break; 7506 case 'countyincomedetails': 7507 countydetails.items.forEac
7507h((countyincomedetail,index) =>{ 7508 switch(countyincomedetail.name) { 7509 case 'countyincomeaddress': 7510 countyincomedetail.value = formData?.positionpanelcontainer[i].countyincomeaddress; 7511 break; 7512 case 'countyincomeaddress2': 7513 countyincomedetail.value = formData?.positionpanelcontainer[i].countyincomeaddress2; 7514 break; 7515 case 'countyincomecity': 7516 countyincomedetail.value = formData?.positionpanelcontainer[i].countyincomecity; 7517 break; 7518 case 'countyincomestate': 7519 countyincomedetail.value = formData?.positionpanelcontainer[i].countyincomestate; 7520 break; 7521 case 'countyincomezipcode': 7522 countyincomedetail.value = formData?.positionpanelcontainer[i].countyincomezipcode; 7523 break; 7524 } 7525 }); 7526 break; 7527 default: 7528 break; 7529 } 7530 }); 7531 }, 200); 7532 } 7533 break; 7534 default: 7535 break; 7536 } 7537 }); 7538 }); 7539 7540 7541 occupationpanels.items.forEach((occupation, i) => { 7542 occupation.items.forEach((occupationfield, x) => { 7543 occupationfield.value = formData?.occupation[i].occupations; 7544 }); 7545 }); 7546 7547 //Update Panel 4 fields 7548 if (!isAmend && !isNew) { 7549 formFields.realestateinterestselectionamend.value = formData?.realestateinterestselection || formData?.realestateamend; 7550 formFields.creditorsselectionamend.value = formData?.creditorsselection || formData?.creditorsamend; 7551 } 7552 if (isNew) { 7553 formFields.creditorsselection.value = formData?.creditorsselection || formData?.creditorsamend; 7554 } 7555 7556 7557 if (!isNew) { 7558 realestatespanels?.items?.forEach((realestates, i) => { 7559 realestates?.items.forEach((realestate, x) => { 7560 switch (realestate.name) { 7561 case 'realestatetype': 7562 realestate.value = formData?.realestates[i].realestatetype; 7563 break; 7564 case 'realestateaddress1': 7565 realestate.value = formData?.realestates[i].realestateaddress1; 7566 break; 7567 case 'realestateaddress2': 7568 realestate.value = formData?.realestates[i].realestateaddress2; 7569 break; 7570 case 'realestatecity': 7571 realestate.value = formData?.realestates[i].realestatecity; 7572 break; 7573 case 'realestatestate': 7574 realestate.value = formData?.realestates[i].realestatestate; 7575 break; 7576 case 'realestatezipcode': 7577 realestate.value = formData?.realestates[i].realestatezipcode; 7578 break; 7579 default: 7580 break; 7581 } 7582 }); 7583 }); 7584 } 7585 7586 creditorspanels?.items?.forEach((creditors, i) => {
7587 creditors?.items.forEach((creditor, x) => { 7588 switch (creditor.name) { 7589 case 'creditorname': 7590 creditor.value = formData?.creditors[i].creditorname; 7591 break; 7592 case 'creditoraddress1': 7593 creditor.value = formData?.creditors[i].creditoraddress1; 7594 break; 7595 case 'creditoraddress2': 7596 creditor.value = formData?.creditors[i].creditoraddress2; 7597 break; 7598 case 'creditorcity': 7599 creditor.value = formData?.creditors[i].creditorcity; 7600 break; 7601 case 'creditorstate': 7602 creditor.value = formData?.creditors[i].creditorstate; 7603 break; 7604 case 'creditorzipcode': 7605 creditor.value = formData?.creditors[i].creditorzipcode; 7606 break; 7607 case 'interestrate': 7608 creditor.value = formData?.creditors[i].interestrate; 7609 break; 7610 default: 7611 break; 7612 } 7613 }); 7614 }); 7615 7616 // Update Panel 5 fields 7617 if (!isAmend && !isNew) { 7618 formFields.giftselectionamend.value = formData?.giftselection || formData?.giftsamend; 7619 formFields.transportationselectionamend.value = formData?.transportationselection || formData?.transportationamend; 7620 } 7621 // Update Panel 5 fields 7622 if (!isNew) { 7623 giftspanels?.items?.forEach((gifts, i) => { 7624 gifts?.items.forEach((gift, x) => { 7625 switch (gift.name) { 7626 case 'giftname': 7627 gift.value = formData?.gifts[i].giftname; 7628 break; 7629 case 'giftaddress1': 7630 gift.value = formData?.gifts[i].giftaddress1; 7631 break; 7632 case 'giftaddress2': 7633 gift.value = formData?.gifts[i].giftaddress2; 7634 break; 7635 case 'giftcity': 7636 gift.value = formData?.gifts[i].giftcity; 7637 break; 7638 case 'giftstate': 7639 gift.value = formData?.gifts[i].giftstate; 7640 break; 7641 case 'giftzipcode': 7642 gift.value = formData?.gifts[i].giftzipcode; 7643 break; 7644 case 'giftvalue': 7645 gift.value = formData?.gifts[i].giftvalue; 7646 break; 7647 case 'giftdescription': 7648 gift.value = formData?.gifts[i].giftdescription; 7649 break; 7650 default: 7651 break; 7652 } 7653 }); 7654 }); 7655 7656 transportationpanels?.items?.forEach((transportations, i) => { 7657 transportations?.items.forEach((transportation, x) => { 7658 switch (transportation.name) { 7659 case 'transportationname': 7660 transportation.value = formData?.transportationlist[i].transportationname; 7661 break; 7662 case 'transportationaddress1': 7663 transportation.value = formData?.transportationlist[i].transportationaddress1; 7664 break; 7665 case 'transportationaddress2': 7666 transportation.value = formData?.transportationlist[i].transportationaddress2; 7667 break; 7668 case 'transportationcity': 7669 transportation.value = formData?.transportationlist[i].transportationcity; 7670 break; 7671 case 'transportationstate': 7672 transportation.value = formData?.transportationlist[i].transportationstate; 7673 break; 7674 case 'transportationzipcode': 7675 transportation.value = formData?.transportationlist[i].transportationzipcode; 7676 break; 7677 case 'amount': 7678 transportation.value = formData?.transportationlist[i].amount; 7679 break; 7680 default: 7681 break; 7682 } 7683 }); 7684 }); 7685 } 7686 7687 // Update Panel 6 fields 7688 if (!isAmend && !isNew) { 7689 formFields.affiliationselectionamend.value = formData?.affiliationselection || formData?.businessentityamend; 7690 formFields.financialinterestselectionamend.value = formData?.financialinterestselection || formData?.financialinterestsamend; 7691 formFields.businessinterestselectionamend.value = formData?.businessinterestselection || formData?.businessinterestsamend; 7692 } 7693 if (isNew) { 7694 setTimeout(() => { 7695 formFields.affiliationselection.value = formData?.affiliationselection || formData?.businessentityamend; 7696 },1000); 7697 } 7698 7699 setTimeout(() => { 7700 businessentitiespanel?.items?.forEach((businessentities, i) => {
7701 businessentities?.items.forEach((businessentity, x) => { 7702 switch (businessentity.name) { 7703 case 'businessentitiesbusinesstype': 7704 businessentity.value = formData?.businessentities[i].businessentitiesbusinesstype; 7705 break; 7706 case 'businessentityname': 7707 businessentity.value = formData?.businessentities[i].businessentityname; 7708 break; 7709 case 'businessentityaddress1': 7710 businessentity.value = formData?.businessentities[i].businessentityaddress1; 7711 break; 7712 case 'businessentityaddress2': 7713 businessentity.value = formData?.businessentities[i].businessentityaddress2; 7714 break; 7715 case 'businessentitycity': 7716 businessentity.value = formData?.businessentities[i].businessentitycity; 7717 break; 7718 case 'businessentitystate': 7719 businessentity.value = formData?.businessentities[i].businessentitystate; 7720 break; 7721 case 'businessentityzipcode': 7722 businessentity.value = formData?.businessentities[i].businessentityzipcode; 7723 break; 7724 case 'positionheld': 7725 businessentity.value = formData?.businessentities[i].positionheld; 7726 break; 7727 case 'declareincome': 7728 businessentity.checked = isChecked(formData?.businessentities[i].declareincome); 7729 break; 7730 default: 7731 break; 7732 } 7733 }); 7734 }); 7735 },1000); 7736 7737 if(!isNew) { 7738 financialinterestpanel?.items?.forEach((financialinterests, i) => { 7739 financialinterests?.items.forEach((financialinterest, x) => { 7740 switch (financialinterest.name) { 7741 case 'financialinterestsbusinesstype': 7742 financialinterest.value = formData?.financialinterests[i].financialinterestsbusinesstype; 7743 break; 7744 case 'financialinterestname': 7745 financialinterest.value = formData?.financialinterests[i].financialinterestname; 7746 break; 7747 case 'financialinterestaddress1': 7748 financialinterest.value = formData?.financialinterests[i].financialinterestaddress1; 7749 break; 7750 case 'financialinterestaddress2': 7751 financialinterest.value = formData?.financialinterests[i].financialinterestaddress2; 7752 break; 7753 case 'financialinterestcity': 7754 financialinterest.value = formData?.financialinterests[i].financialinterestcity; 7755 break; 7756 case 'financialintereststate': 7757 financialinterest.value = formData?.financialinterests[i].financialintereststate; 7758 break; 7759 case 'financialinterestzipcode': 7760 financialinterest.value = formData?.financialinterests[i].financialinterestzipcode; 7761 break; 7762 case 'interestheld': 7763 financialinterest.value = formData?.financialinterests[i].interestheld; 7764 break; 7765 default: 7766 break; 7767 } 7768 }); 7769 }); 7770 } 7771 7772 if (!isNew) { 7773 businessinterestpanel?.items?.forEach((businessinterests, i) => { 7774 businessinterests?.items.forEach((businessinterest, x) => { 7775 switch (businessinterest.name) { 7776 case 'businessinterestsbusinesstype': 7777 businessinterest.value = formData?.businessinterests[i].businessinterestsbusinesstype; 7778 break; 7779 case 'businessname': 7780 businessinterest.value = formData?.businessinterests[i].businessname; 7781 break; 7782 case 'businessaddress1': 7783 businessinterest.value = formData?.businessinterests[i].businessaddress1; 7784 break; 7785 case 'businessaddress2': 7786 businessinterest.value = formData?.businessinterests[i].businessaddress2; 7787 break; 7788 case 'businesscity': 7789 businessinterest.value = formData?.businessinterests[i].businesscity; 7790 break; 7791 case 'businessstate': 7792 businessinterest.value = formData?.businessinterests[i].businessstate; 7793 break; 7794 case 'businesszipcode': 7795 businessinterest.value = formData?.businessinterests[i].businesszipcode; 7796 break; 7797 case 'interesttransferred': 7798 businessinterest.value = formData?.businessinterests[i].interesttransferred; 7799 break; 7800 case 'relationtotransferee': 7801 businessinterest.value = formData?.businessinterests[i].relationtotransferee; 7802 break; 7803 case 'transfereename': 7804 businessinterest.value = formData?.businessinterests[i].transfereename; 7805 break; 7806 case 'transfereeadress1': 7807 businessinterest.value = formData?.businessinterests[i].transfereeadress1; 7808 break; 7809 case 'transfereeadress2': 7810 businessinterest.value = formData?.businessinterests[i].transfereeadress2; 7811 break; 7812 case 'transfereecity': 7813 businessinterest.value = formData?.businessinterests[i].transfereecity; 7814 break; 7815 case 'transfereestate': 7816 businessinterest.value = formData?.businessinterests[i].transfereestate; 7817 break; 7818 case 'transfereezipcode': 7819 businessinterest.value = formData?.businessinterests[i].transfereezipcode; 7820 break; 7821 case 'datetransferred': 7822 businessinterest.value = formData?.businessinterests[i].datetransferred; 7823 break; 7824 default: 7825 break; 7826 } 7827 }); 7828 }); 7829 } 7830 7831 7832 // Update Panel 7 fields 7833 if (!isAmend && !isNew) { 7834 setTimeout(() => { 7835 formFields.incomesourceselectionamend.value = formData?.incomesourceselection || formData?.incomeamend; 7836 },1000); 7837 } 7838 if (isNew) { 7839 setTimeout(() => { 7840 formFields.incomesourceselection.value = formData?.incomesourceselection || formData?.incomeamend; 7841 },1000); 7842 } 7843 7844 setTimeout(() => { 7845 incomepanel?.items?.forEach((incomes, i) => { 7846
7847 incomes?.items.forEach((income, x) => { 7848 switch (income.name) { 7849 case 'typeofincome': 7850 income.value = formData?.income[i].typeofincome; 7851 break; 7852 case 'incomename': 7853 income.value = formData?.income[i].incomename; 7854 break; 7855 case 'incomeaddress1': 7856 income.value = formData?.income[i].incomeaddress1; 7857 break; 7858 case 'incomeaddress2': 7859 income.value = formData?.income[i].incomeaddress2; 7860 break; 7861 case 'incomecity': 7862 income.value = formData?.income[i].incomecity; 7863 break; 7864 case 'statelist': 7865 income.value = formData?.income[i].statelist; 7866 break; 7867 case 'incomezipcode': 7868 income.value = formData?.income[i].incomezipcode; 7869 break; 7870 default: 7871 break; 7872 } 7873 }); 7874 }); 7875 },1000); 7876 // Update Panel 8 fields 7877 if (!isNew) { 7878 formFields.submissionconfirmation.checked = isChecked(formData?.submissionconfirmation); 7879 formFields.submissiondate.value = formData?.submissiondate; 7880 formFields.submissionfullname.value = formData?.submissionfullname; 7881 } 7882 } 7883}; 7884 7885function getQueryParam(param) { 7886 const urlParams = new URLSearchParams(window.location.search); 7887 return urlParams.get(param); 7888} 7889// Function to update hidden fields in SOFI Form 7890function updateHiddenFields(jsonResponse, dashboardFormId, userEmail) { 7891 const formId = getQueryParam("id"); 7892 const amend = getQueryParam("amend"); 7893 7894 //Get Form fields via GuideBridge API 7895 const formIdfield = guideBridge.resolveNode("$form.sofiForm.gettingstarted.previousFormId"); 7896 const dashboardFormIdField = guideBridge.resolveNode("$form.sofiForm.gettingstarted.dashboardformid"); 7897 const isAmend = guideBridge.resolveNode("$form.sofiForm.gettingstarted.isamended"); 7898 const version = guideBridge.resolveNode("$form.sofiForm.gettingstarted.version"); 7899 const filerEmail = guideBridge.resolveNode("$form.sofiForm.gettingstarted.fileremail"); 7900 const prefillJson = guideBridge.resolveNode("$form.sofiForm.gettingstarted.prefilljson"); 7901 //Increment version In case of Amend=true 7902 if (amend === true || amend === "true") { 7903 let currentVersion = 0; 7904 if (jsonResponse?.version !== undefined) { 7905 currentVersion = parseInt(jsonResponse.version, 10); 7906 } else if (version?.value !== undefined) { 7907 currentVersion = parseInt(version.value, 10); 7908 } 7909 const newVersion = currentVersion + 1; 7910 if (version) { 7911 version.value = newVersion; 7912 } 7913 } 7914 //Keep same version In case of Amend=false 7915 if (amend === false || amend === "false") { 7916 version.value = jsonResponse.version; 7917 } 7918 if (amend === false || amend === "false") { 7919 if (formIdfield) { 7920 formIdfield.value = jsonResponse.previousFormId; 7921 } 7922 if (dashboardFormIdField) { 7923 dashboardFormIdField.value = dashboardFormId; 7924 } 7925 } else { 7926 if (formIdfield && formId !== null) { 7927 formIdfield.value = formId; 7928 } 7929 } 7930 if (isAmend && amend !== null) { 7931 isAmend.value = amend; 7932 } 7933 //Handle null UserEmail 7934 if (filerEmail) { 7935 if (userEmail != null) { 7936 filerEmail.value = userEmail; 7937 } if (jsonResponse && jsonResponse.fileremail) { 7938 filerEmail.value = jsonResponse.fileremail; 7939 } 7940 } 7941 if (prefillJson) { 7942 prefillJson.value = JSON.stringify(jsonResponse); 7943 } 7944} 7945 7946function missingYearHandler(missingYears, isCurrentYearFiled) { 7947 console.log("Starting populateMissingYearDropdown"); 7948 7949 const missingYearDropdown = guideBridge.resolveNode("$form.sofiForm.gettingstarted.filingyear"); 7950 const filingSelection = guideBridge.resolveNode("$form.sofiForm.gettingstarted.filingselection"); 7951 7952 // Handle Current Year radio 7953 if (isCurrentYearFiled === true || isCurrentYearFiled === "true") { 7954 disableRadio("0"); // Current Year 7955 } 7956 7957 // Handle Missing Year radio 7958 if (!missingYears || missingYears.length === 0) { 7959 disableRadio("1"); // Missing Year 7960 } 7961 7962 // Helper to disable/unselect radio buttons by value 7963 function disableRadio(value) { 7964 // Get the radio group container 7965 let radioGroupContainer = null; 7966 if (filingSelection.containerId) { 7967 radioGroupContainer = document.getElementById(filingSelection.containerId); 7968 console.log("radioGroupContainer:",radioGroupContainer); 7969 } 7970 if (!radioGroupContainer) { 7971 // fallback: first div[role='radiogroup'] in form 7972 const allGroups = document.querySelectorAll("div[role='radiogroup']"); 7973 for (let c of allGroups) { 7974 const input = c.querySelector("input"); 7975 if (input) { 7976 radioGroupContainer = c; 7977 break; 7978 } 7979 } 7980 } 7981 if (!radioGroupContainer) { 7982 console.warn("Radio group container not found for disableRadio(value=" + value + ")"); 7983 return; 7984 } 7985 7986 const radio = radioGroupContainer.querySelector(`input[value='${value}']`); 7987 if (!radio) { 7988 console.warn("Radio input not found for value:", value); 7989 return; 7990 } 7991 7992 // Uncheck if selected 7993 if (radio.checked) { 7994 console.log("Radio with value", value, "was checked, unchecking"); 7995 radio.checked = false;
7996 } 7997 7998 // Disable it 7999 radio.disabled = true; 8000 console.log("Radio with value", value, "disabled successfully."); 8001 } 8002 8003 // Populate Missing Year dropdown 8004 if (missingYears && Array.isArray(missingYears) && missingYears.length > 0) { 8005 const yearsList = missingYears.map(year => year.toString()); 8006 missingYearDropdown.enum = yearsList; 8007 missingYearDropdown.enumNames = yearsList; 8008 missingYearDropdown.value = ""; // reset to placeholder 8009 console.log("Dropdown updated with missing years:", yearsList); 8010 } else { 8011 console.log("missingYears is empty or null, dropdown not populated"); 8012 } 8013 console.log("Finished populateMissingYearDropdown"); 8014 } 8015 8016window.addEventListener("pageshow", function () { 8017 const urlParams = new URLSearchParams(window.location.search); 8018 const formId = urlParams.get('id'); 8019 const amend = urlParams.get('amend') === 'true'; 8020 const isNewFiling = urlParams.get('type') === 'new-filing'; 8021 8022 window.guideBridge.connect(() => { 8023 const sofiFormInstance = guideBridge.resolveNode('$form.sofiForm'); 8024 if (sofiFormInstance) { 8025 //Start-Hide saveAsDraft button on Step 1 8026 var formActivepanel = parseInt(document.getElementsByClassName("cmp-adaptiveform-wizard__guideActiveIndex")?document.getElementsByClassName("cmp-adaptiveform-wizard__guideActiveIndex")[0].textContent : 0); 8027 if (formActivepanel == 1) { 8028 const saveAsDraftBtn =document.getElementById('form-wizard-save-button'); 8029 if(saveAsDraftBtn) { 8030 saveAsDraftBtn.style.display ='none'; 8031 } 8032 } 8033 //End-Hide saveAsDraft button on Step 1 8034 8035 const fetchUrl = "/content/copaservlets/jcr:content/prefillform.json"; 8036 const fetchCountyUrl = "/content/copaservlets/_jcr_content/countytagslist.json"; 8037 let requestBody ={}; 8038 let countyArray = []; 8039 let missingYears = []; 8040 8041 if (formId) { 8042 requestBody = {formId: formId}; 8043 } else { 8044 console.log("No formId or EmailId/Type found- Skipping Prefill"); 8045 } 8046 8047 fetch(fetchCountyUrl, { 8048 method: "GET" 8049 }) 8050 .then(response => response.json()) 8051 .then(data => { 8052 countyArray = data; 8053 let countyFlatList = []; 8054 const positionspanels = guideBridge.resolveNode('$form.sofiForm.public_position.positionpanelcontainer'); 8055 8056 countyArray.forEach((item) => { 8057 countyFlatList.push(item.value); 8058 }); 8059 8060 positionspanels.items.forEach((positionpanel, i) => { 8061 positionpanel.items.forEach((position, x) => { 8062 switch (position.name) { 8063 case 'countydetails': 8064 position.items.forEach((countydetails, y) => { 8065 switch (countydetails.name) { 8066 case 'county': 8067 sofiFormFunctions.setFormCountryDropDowns(countydetails, countyFlatList); 8068 break; 8069 default: 8070 break; 8071 } 8072 }); 8073 break; 8074 default: 8075 break; 8076 } 8077 }); 8078 }); 8079 }) 8080 .catch(err => console.error("Error fetching county data:", err)); 8081 8082 if (formId || isNewFiling) { 8083 fetch(fetchUrl, { 8084 method: "POST", 8085 headers: { "Content-Type": "application/json" }, 8086 body: JSON.stringify(requestBody) 8087 }) 8088 .then(response => response.json()) 8089 .then(data => { 8090 //Get values from response to fill hidden fields in form 8091 const dashboardFormId= data.id; 8092 const jsonText = data.jsonText;
8093 const userEmail = data.filerEmail; 8094 8095 // Get values for Missing year dropdown population 8096 const missingYears = data.missingYears || []; 8097 const isCurrentYearFiled = data.isCurrentYearFiled; 8098 8099 // Populate missing year dropdown 8100 if (isNewFiling) { 8101 missingYearHandler(missingYears, isCurrentYearFiled); 8102 } 8103 8104 const jsonResponse = JSON.parse(data.jsonText); 8105 sofiFormFunctions.popluateSofiForm(jsonResponse, amend, isNewFiling, countyArray); 8106 //check if userEmail is null 8107 if (userEmail !== null) { 8108 updateHiddenFields(jsonResponse, dashboardFormId, userEmail); 8109 } else { 8110 updateHiddenFields(jsonResponse, dashboardFormId); 8111 } 8112 }) 8113 .catch(err => console.error("Error fetching form data:", err)); 8114 } 8115 8116 guideBridge.on("elementValueChanged", (payload) => { 8117 if (payload.detail.fieldName === 'county') { 8118 sofiFormFunctions.changeCountyEntity(payload.detail.fieldQualifiedName, payload.detail.currentValue, countyArray); 8119 } 8120 }); 8121 8122 const addPosBtn = document.querySelector('button[class-label="btn-add-position"]'); 8123 addPosBtn.addEventListener('click', () => { 8124 sofiFormFunctions.setNewCountyPanel(countyArray); 8125 }); 8126 } 8127 }); 8128}); 8129function readPreviousPanelData() { 8130 var nextRunFlag = false; 8131 var panel = ''; 8132 var nextBtn = document.getElementById("form-wizard-next-button"); 8133 var backBtn = document.getElementById("form-wizard-back-button"); 8134 var businessEntities; 8135 var valueEntity; 8136 if(!nextBtn) return; 8137 nextBtn.addEventListener('click', function() { 8138 var activePanel = parseInt(document.getElementsByClassName("cmp-adaptiveform-wizard__guideActiveIndex")?document.getElementsByClassName("cmp-adaptiveform-wizard__guideActiveIndex")[0].textContent : 0); 8139 var activePanelList = document.getElementsByClassName("cmp-adaptiveform-wizard__tab"); 8140 if(!activePanelList || !activePanel) return; 8141 //Show SaveAsDraft Button on Steps except 1 8142 if (activePanel != 1) { 8143 const saveAsDraftBtn =document.getElementById('form-wizard-save-button'); 8144 if(saveAsDraftBtn) { 8145 saveAsDraftBtn.style.display ='block'; 8146 } 8147 } 8148 if(activePanel == 7 || activePanel == 4) nextRunFlag = true; 8149 else nextRunFlag = false; 8150 if(nextRunFlag) { 8151 if(activePanel == 4){ 8152 (function () { 8153 panel = guideBridge.resolveNode("$form.sofiForm.public_position.positionpanelcontainer"); 8154 if (!panel || !panel.items) { 8155 console.warn("Position panel not found."); 8156 return; 8157 } 8158 8159 valueEntity = []; 8160 panel.items.forEach(function (item, index) { 8161 // Check if item exists and has _data property 8162 if (!item || !item._data || !item._data.$_items) { 8163 //console.log("Panel " + index + " - Invalid item structure."); 8164 return; 8165 } 8166 8167 var fields = item._data.$_items; 8168 8169 // Check receivedincome field 8170 var receivedIncome = null; 8171 if (fields.receivedincome && fields.receivedincome.$_value !== undefined) { 8172 receivedIncome = fields.receivedincome.$_value; 8173 } 8174 8175 // Check govtLevel field 8176 var govtLevel = null; 8177 if (fields.govtlevelselection && fields.govtlevelselection.$_value !== undefined) { 8178 govtLevel = fields.govtlevelselection.$_value; 8179 } 8180
8181 // Check state entity fields 8182 var stateEntity = null; 8183 if (fields.stateentity && fields.stateentity.$_value !== undefined) { 8184 stateEntity = fields.stateentity.$_value; 8185 } 8186 8187 var otherStateEntity = null; 8188 if (fields.otherstateentity && fields.otherstateentity.$_value !== undefined) { 8189 otherStateEntity = fields.otherstateentity.$_value; 8190 } 8191 8192 // Check county entity fields 8193 var countyEntity = null; 8194 if (fields.countyentity && fields.countyentity.$_value !== undefined) { 8195 countyEntity = fields.countyentity.$_value; 8196 } 8197 8198 var otherCountyEntity = null; 8199 if (fields.othercountyentity && fields.othercountyentity.$_value !== undefined) { 8200 otherCountyEntity = fields.othercountyentity.$_value; 8201 } 8202 8203 var valueToAdd = null; 8204 8205 // Check conditions based on government level 8206 if (govtLevel === "State") { 8207 if (stateEntity && stateEntity !== "Not Listed") { 8208 valueToAdd = stateEntity; 8209 } else if (otherStateEntity) { 8210 valueToAdd = otherStateEntity; 8211 } 8212 } else if (govtLevel === "County/Local") { 8213 if (countyEntity && countyEntity !== "Not Listed") { 8214 valueToAdd = countyEntity; 8215 } else if (otherCountyEntity) { 8216 valueToAdd = otherCountyEntity; 8217 } 8218 } 8219 8220 if (receivedIncome === "Yes") { 8221 if (valueToAdd) { 8222 valueEntity.push(valueToAdd); 8223 } else { 8224 console.log("Panel " + index + " - receivedincome checked but no valid entity found."); 8225 } 8226 } else { 8227 //console.log("One valueToAdd is popped from the ARRAY --> " + valueToAdd); 8228 } 8229 }); 8230 })(); 8231 } else if(activePanel == 7) { 8232 (function () { 8233 panel = guideBridge.resolveNode("$form.sofiForm.additionaldisclosure.businessentitiescontainer.businessentities"); 8234 if (!panel || !panel.items) { 8235 console.warn("Business entities panel not found."); 8236 return; 8237 } 8238 businessEntities = []; 8239 panel.items.forEach(function (item, index) { 8240 // Check if item exists and has _data property 8241 if (!item || !item._data || !item._data.$_items) { 8242 //console.log("Panel " + index + " - Invalid item structure."); 8243 return; 8244 } 8245 8246 var fields = item._data.$_items; 8247 8248 // Check declareincome field 8249 var declareIncome = null; 8250 if (fields.declareincome && fields.declareincome.$_value !== undefined) { 8251 declareIncome = fields.declareincome.$_value; 8252 } 8253 8254 // Check business entity name field 8255 var businessEntityName = null; 8256 if (fields.businessentityname && fields.businessentityname.$_value !== undefined) { 8257 businessEntityName = fields.businessentityname.$_value; 8258 } 8259 8260 if (declareIncome === "Yes") { 8261 businessEntities.push(businessEntityName); 8262 console.log("Panel " + index + " - declareincome checked. Business: " + businessEntityName); 8263 } else { 8264 //console.log("One businessEntityName poped from ARRAY --> " + businessEntityName); 8265 } 8266 8267 }); 8268 })(); 8269 } 8270 } 8271 }); 8272 8273 if(!backBtn) return; 8274 //Back button event listener- to hide SaveAsDraft button on Step1 8275 backBtn.addEventListener('click', function() { 8276 var activePanel = parseInt(document.getElementsByClassName("cmp-adaptiveform-wizard__guideActiveIndex")?document.getElementsByClassName("cmp-adaptiveform-wizard__guideActiveIndex")[0].textContent : 0); 8277 if (activePanel == 1) { 8278 const saveAsDraftBtn =document.getElementById('form-wizard-save-button'); 8279 if(saveAsDraftBtn) { 8280 saveAsDraftBtn.style.display ='none'; 8281 } 8282 } 8283 }); 8284}; 8285 8286 document.addEventListener("DOMContentLoaded", function () { 8287 window.guideBridge.connect(function () { 8288 readPreviousPanelData(); 8289 }) 8290 }); 8291 8292/******************************************************************************* 8293 * Copyright 2025 Adobe 8294 * 8295 * Licensed under the Apache License, Version 2.0 (the "License");
8296 * you may not use this file except in compliance with the License. 8297 * You may obtain a copy of the License at 8298 * 8299 * http://www.apache.org/licenses/LICENSE-2.0 8300 * 8301 * Unless required by applicable law or agreed to in writing, software 8302 * distributed under the License is distributed on an "AS IS" BASIS, 8303 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 8304 * See the License for the specific language governing permissions and 8305 * limitations under the License. 8306 ******************************************************************************/ 8307 8308if(window.GeoLocationQuery === undefined) { 8309 window.GeoLocationQuery = class GeoLocationQuery { 8310 constructor() { 8311 this._active = false; 8312 } 8313 8314 init(success, failure) { 8315 this._successHandler = success; 8316 this._errorHandler = failure; 8317 this._active = true; 8318 return this; 8319 } 8320 8321 _handleSuccess(data) { 8322 if (this._successHandler) { 8323 this._successHandler(data); 8324 } 8325 } 8326 8327 _handleError(err) { 8328 if (this._errorHandler) { 8329 this._errorHandler(err); 8330 } 8331 } 8332 8333 query() { 8334 const onSuccess = (pos) => { 8335 if (this._active) { 8336 this._handleSuccess(pos); 8337 } 8338 this._active = false; 8339 }; 8340 8341 const onError = (err) => { 8342 if (this._active) { 8343 this._handleError(err); 8344 } 8345 this._active = false; 8346 }; 8347 8348 navigator.geolocation.getCurrentPosition(onSuccess, onError, { timeout: 10000 }); 8349 } 8350 8351 cancel() { 8352 this._active = false; 8353 } 8354 } 8355} 8356/******************************************************************************* 8357 * Copyright 2025 Adobe 8358 * 8359 * Licensed under the Apache License, Version 2.0 (the "License"); 8360 * you may not use this file except in compliance with the License. 8361 * You may obtain a copy of the License at 8362 * 8363 * http://www.apache.org/licenses/LICENSE-2.0 8364 * 8365 * Unless required by applicable law or agreed to in writing, software 8366 * distributed under the License is distributed on an "AS IS" BASIS, 8367 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 8368 * See the License for the specific language governing permissions and 8369 * limitations under the License. 8370 ******************************************************************************/ 8371 8372 8373(function() { 8374 "use strict"; 8375 /** 8376 * class definition for GeoLocationQueryRequest 8377 * encapsulated success and error handlers 8378 */ 8379 class Scribble extends FormView.FormFieldBase { 8380 _geoLocQuery=null; 8381 _signSubmitted=false; 8382 _enforceGeoLoc=!!navigator.userAgent.match(/iPad/i); 8383 existingSign = ''; 8384 existingCanvas = ''; 8385 lang = "en"; 8386 static NS = FormView.Constants.NS; 8387 static IS = "adaptiveFormScribble"; 8388 static bemBlock = 'cmp-adaptiveform-scribble'; 8389 static selectors = { 8390 self: `[data-${this.NS}-is="${this.IS}"]`, 8391 scribbleContainer: `.${Scribble.bemBlock}__container`, 8392 scribbleContainerPanel: `.${Scribble.bemBlock}__panel`, 8393 keyboardSignBox: `.${Scribble.bemBlock}__keyboard-sign-box`, 8394 scribbleControlPanel: `.${Scribble.bemBlock}__controlpanel`, 8395 geoCanvas: `.${Scribble.bemBlock}__geocanvas`, 8396 canvasSignedContainer: `.${Scribble.bemBlock}__canvas-signed-container`, 8397 canvas: `.${Scribble.bemBlock}__canvas`, 8398 label: `.${Scribble.bemBlock}__label`, 8399 description: `.${Scribble.bemBlock}__longdescription`, 8400 qm: `.${Scribble.bemBlock}__questionmark`, 8401 errorDiv: `.${Scribble.bemBlock}__errormessage`, 8402 tooltipDiv: `.${Scribble.bemBlock}__shortdescription`, 8403 scribbleCloseButton: `.${Scribble.bemBlock}__button-close`, 8404 brushControl: `.${Scribble.bemBlock}__control-brush`, 8405 scribbleGeoControl: `.${Scribble.bemBlock}__control-geo`, 8406 clearControl: `.${Scribble.bemBlock}__control-clear`, 8407 scribbleTextControl: `.${Scribble.bemBlock}__control-text`, 8408 scribbleMessage: `.${Scribble.bemBlock}__control-message`, 8409 clearSignButton: `.${Scribble.bemBlock}__button--primary`, 8410 cancelClearSignButton: `.${Scribble.bemBlock}__button--secondary`, 8411 clearSignContainer: `.${Scribble.bemBlock}__clearsign-container`, 8412 scribbleSubmitControl: `.${Scribble.bemBlock}__save-button`, 8413 scribbleBrushList: `.${Scribble.bemBlock}__brushlist`, 8414 signCanvases: `.${Scribble.bemBlock}__signcanvases`, 8415 saveCanvas: `.${Scribble.bemBlock}__save-button`, 8416 canvasSignedImage: `.${Scribble.bemBlock}__canvas-signed-image`, 8417 mainCanvas: `.${Scribble.bemBlock}__canvas__main` 8418 }; 8419 8420 constructor(params) { 8421 super(params); 8422 this.initializeScribble(); 8423 } 8424 8425 setModel(model) { 8426 super.setModel(model); 8427 this.lang = model.lang; 8428 } 8429 8430 initializeScribble() { 8431 this.getCanvasContainer().addEventListener('click', () => this.scribbleContainerClickHandler()); 8432 this.initScribbleModal(); 8433 } 8434 8435 getWidget() { 8436 return this.element.querySelector(Scribble.selectors.canvasSignedContainer); 8437 } 8438 8439 getLabel() { 8440 return this.element.querySelector(Scribble.selectors.label); 8441 } 8442 8443 getErrorDiv() { 8444 return this.element.querySelector(Scribble.selectors.errorDiv); 8445 } 8446 8447 getTooltipDiv() { 8448 return this.element.querySelector(Scribble.selectors.tooltipDiv); 8449 } 8450 8451 getQuestionMarkDiv() { 8452 return this.element.querySelector(Scribble.selectors.qm); 8453 } 8454 8455 getScribbleControlPanel() { 8456 return this.element.querySelector(Scribble.selectors.scribbleControlPanel); 8457 } 8458 8459 getScribbleContainer() { 8460 return this.element.querySelector(Scribble.selectors.scribbleContainer); 8461 } 8462 8463 getMessage() { 8464 return this.element.querySelector(Scribble.selectors.scribbleMessage); 8465 } 8466 8467 getClearSignContainer() { 8468 return this.element.querySelector(Scribble.selectors.clearSignContainer); 8469 } 8470 8471 getClearSignButton() { 8472 return this.element.querySelector(Scribble.selectors.clearSignButton); 8473 } 8474 8475 getCancelClearSignButton() { 8476 return this.element.querySelector(Scribble.selectors.cancelClearSignButton); 8477 } 8478 8479 getBrushList() { 8480 return this.element.querySelector(Scribble.selectors.scribbleBrushList); 8481 } 8482 8483 getBrush() { 8484 return this.element.querySelector(Scribble.selectors.brushControl); 8485 } 8486 8487 getClearControl() { 8488 return this.element.querySelector(Scribble.selectors.clearControl); 8489 } 8490 8491 getSaveControl() { 8492 return this.element.querySelector(Scribble.selectors.saveCanvas); 8493 } 8494 8495 getGeoLocationIcon() { 8496 return this.element.querySelector(Scribble.selectors.scribbleGeoControl); 8497 } 8498 8499 getTextSignControl() { 8500 return this.element.querySelector(Scribble.selectors.scribbleTextControl); 8501 } 8502 8503 getScribbleContainerPanel() { 8504 return this.element.querySelector(Scribble.selectors.scribbleContainerPanel); 8505 } 8506 8507 getKeyboardSignBox() { 8508 return this.element.querySelector(Scribble.selectors.keyboardSignBox); 8509 } 8510 8511 getGeoCanvas() { 8512 return this.element.querySelector(Scribble.selectors.geoCanvas); 8513 } 8514 8515 getCanvasContainer() { 8516 return this.element.querySelector(Scribble.selectors.canvasSignedContainer); 8517 } 8518 8519 getScribbleCloseButton() { 8520 return this.element.querySelector(Scribble.selectors.scribbleCloseButton); 8521 } 8522 8523 getCanvas() { 8524 return this.element.querySelector(Scribble.selectors.canvas); 8525 } 8526 8527 getMainCanvas() { 8528 return this.element.querySelector(Scribble.selectors.mainCanvas); 8529 } 8530 8531 getSignCanvasesContainer() { 8532 return this.element.querySelector(Scribble.selectors.signCanvases); 8533 } 8534 8535 getDescription() { 8536 return this.element.querySelector(Scribble.selectors.description); 8537 } 8538 8539 getSignedCanvasImage() { 8540 return this.element.querySelector(Scribble.selectors.canvasSignedImage); 8541 } 8542 8543 showMessage(msg){ 8544 if(this._msgTimeout) { clearTimeout(this._msgTimeout); this._msgTimeout=0; } 8545 const scribbleMessage = this.getMessage(); 8546 scribbleMessage.innerHTML = msg; 8547 scribbleMessage.style.display = 'block'; 8548 this._msgTimeout = window.setTimeout(function(){ 8549 scribbleMessage.innerHTML = ''; 8550 },15000); 8551 } 8552 8553 openClearSignModal() { 8554 const clearSignContainer = this.getClearSignContainer(); 8555 const clearSignButton = this.getClearSignButton(); 8556 const cancelClearSignButton = this.getCancelClearSignButton(); 8557 8558 clearSignContainer.style.display = 'inline-block'; 8559 // Set focus to the clear sign modal container for accessibility 8560 clearSignContainer.setAttribute('tabindex', '-1'); 8561 clearSignContainer.focus(); 8562 8563 const handleClearSign = () => { 8564 this.existingSign = ''; 8565 const mainCanvas = this.getMainCanvas(); 8566 const existingCanvas = this.existingCanvas; 8567 8568 if (mainCanvas && existingCanvas) { 8569 mainCanvas.parentNode.replaceChild(existingCanvas, mainCanvas); 8570 const ctx = existingCanvas.getContext('2d'); 8571 ctx.clearRect(0, 0, existingCanvas.width, existingCanvas.height); 8572 } 8573 8574 const geoCanvas = this.getGeoCanvas(); 8575 if (geoCanvas) { 8576 const geoCtx = geoCanvas.getContext('2d'); 8577 geoCtx.clearRect(0, 0, geoCanvas.width, geoCanvas.height); 8578 } 8579 8580 this.enableControls(['brushes', 'geolocation', 'clearSign', 'textSign', 'save']); 8581
8582 const signedImage = this.getSignedCanvasImage(); 8583 if (signedImage) { 8584 signedImage.removeAttribute('alt'); 8585 signedImage.removeAttribute('title'); 8586 signedImage.removeAttribute('src'); 8587 signedImage.removeAttribute('style'); 8588 this.element.querySelector('.cmp-adaptiveform-scribble__clear-sign')?.remove(); 8589 clearSignContainer.style.display = 'none'; 8590 this.getKeyboardSignBox().value = ''; 8591 } 8592 8593 this._signSubmitted = false; 8594 this.setModelValue(undefined); 8595 }; 8596 8597 clearSignButton.addEventListener('click', handleClearSign); 8598 8599 cancelClearSignButton.addEventListener('click', () => { 8600 clearSignContainer.style.display = 'none'; 8601 }); 8602 } 8603 8604 createCanvas() { 8605 const mainCanvas = document.createElement('canvas'); 8606 mainCanvas.classList.add('cmp-adaptiveform-scribble__canvasImage'); 8607 } 8608 8609 updateEmptyStatus () { 8610 super.updateEmptyStatus(); 8611 } 8612 8613 updateValue(value) { 8614 let that = this; 8615 this._model.serialize().then((files) => { 8616 if (files && files.length > 0 && files[0]) { 8617 let signatureDataUrl = files[0].data; 8618 signatureDataUrl = typeof signatureDataUrl === "undefined" ? null : signatureDataUrl; 8619 const signedImage = that.getSignedCanvasImage(); 8620 if (signedImage && signatureDataUrl) { 8621 signedImage.src = signatureDataUrl; 8622 signedImage.setAttribute('alt', FormView.LanguageUtils.getTranslatedString(this.lang, 'signature') || 'Signature'); 8623 signedImage.setAttribute('title', FormView.LanguageUtils.getTranslatedString(this.lang, 'signature') || 'Signature'); 8624 that.updateEmptyStatus(); 8625 } 8626 } 8627 }); 8628 } 8629 8630 isCanvasEmpty(canvas) { 8631 const ctx = canvas.getContext('2d'); 8632 const width = canvas.width; 8633 const height = canvas.height; 8634 8635 // Get pixel data from the canvas 8636 const imageData = ctx.getImageData(0, 0, width, height); 8637 8638 // Check if any pixel is not transparent (not [0, 0, 0, 0] = transparent) 8639 for (let i = 0; i < imageData.data.length; i += 4) { 8640 if (imageData.data[i + 3] > 0) { 8641 return false; // Found non-transparent pixel 8642 } 8643 } 8644 8645 return true; // No non-transparent pixels found 8646 } 8647 8648 submitSign() { 8649 if (!this.isCanvasEmpty(this.canvas)) { 8650 const mainCanvas = this.createMainCanvas(); 8651 const sigCnv = this.getCanvas(); // Get the sign canvas 8652 const geoCnv = this.getGeoCanvas(); // Get the geo canvas 8653 8654 this.drawCanvasesOnMainCanvas(mainCanvas, sigCnv, geoCnv); 8655 8656 this.existingCanvas = sigCnv; 8657 sigCnv.height = mainCanvas.height; 8658 sigCnv.parentNode.replaceChild(mainCanvas, sigCnv); 8659 8660 let submitData = mainCanvas.toDataURL("image/png"); 8661 submitData = submitData.replace("data:image/png;base64,", "data:image/png;name=fd_type_signature.png;base64,") 8662 this.existingSign = mainCanvas; 8663 8664 this.updateSignedImage(submitData); 8665 this.setModelValue(submitData); 8666 this.addClearSignButton(); 8667 8668 if (this._geoLocQuery) { 8669 this._geoLocQuery.cancel(); // Cancel the current geo loc request 8670 } 8671 8672 this.closeEditModal(); 8673 this._signSubmitted = true; 8674 } 8675 } 8676 8677 createMainCanvas() { 8678 const mainCanvas = document.createElement('canvas'); 8679 mainCanvas.classList.add('cmp-adaptiveform-scribble__canvas__main'); 8680 mainCanvas.ariaLabel = FormView.LanguageUtils.getTranslatedString(this.lang, "SignatureCanvas"); 8681 return mainCanvas; 8682 } 8683 8684 drawCanvasesOnMainCanvas(mainCanvas, sigCnv, geoCnv) { 8685 const ctx = mainCanvas.getContext('2d'); 8686 if (geoCnv && geoCnv.width > 0 && geoCnv.height > 0) { 8687 // Set the dimensions of the mainCanvas to accommodate both canvases vertically 8688 mainCanvas.width = Math.max(sigCnv.width, geoCnv.width); 8689 mainCanvas.height = sigCnv.height + geoCnv.height; 8690 // Draw the sign canvas on the main canvas 8691 ctx.drawImage(sigCnv, 0, 0); 8692 // Draw the geo canvas below the sign canvas 8693 ctx.drawImage(geoCnv, 0, sigCnv.height, geoCnv.width, geoCnv.height); 8694 } else { 8695 mainCanvas.width = sigCnv.width; 8696 mainCanvas.height = sigCnv.height; 8697 ctx.drawImage(sigCnv, 0, 0); 8698 } 8699 } 8700 8701 updateSignedImage(newData) {
8702 const img = this.getSignedCanvasImage(); 8703 img.src = newData; 8704 img.style.width = '100%'; 8705 img.style.height = '150px'; 8706 } 8707 8708 addClearSignButton() { 8709 const clearSignButton = document.createElement('div'); 8710 clearSignButton.setAttribute('role', 'button'); 8711 clearSignButton.setAttribute('tabindex', '0'); 8712 clearSignButton.setAttribute('aria-label', FormView.LanguageUtils.getTranslatedString(this.lang, 'clearSign') || 'Clear Signature'); 8713 clearSignButton.classList.add('cmp-adaptiveform-scribble__clear-sign'); 8714 8715 const mainCanvasImageContainer = this.getCanvasContainer(); 8716 mainCanvasImageContainer.appendChild(clearSignButton); 8717 8718 clearSignButton.addEventListener('click', (e) => { 8719 e.stopPropagation(); 8720 this.openClearSignModal(); 8721 }); 8722 // Keyboard accessibility: allow Enter/Space to trigger clear 8723 clearSignButton.addEventListener('keydown', (e) => { 8724 if (e.key === 'Enter' || e.key === ' ') { 8725 e.preventDefault(); 8726 this.openClearSignModal(); 8727 } 8728 }); 8729 } 8730 8731 geoQueryErrorHandler(err){ 8732 this.showMessage('errorFetchGeoLocation'); 8733 } 8734 8735 renderBrushList() { 8736 [2,3,4,5,6,7,8,9,10].forEach((brush) => { 8737 var divel = document.createElement('div'); 8738 var cnv = document.createElement('canvas'); 8739 var ctx = cnv.getContext('2d'); 8740 cnv.style.border='1px solid #AAAAAA'; 8741 cnv.width=100; 8742 cnv.height=20; 8743 cnv.style.backgroundColor = 'white'; 8744 cnv.ariaLabel = FormView.LanguageUtils.getTranslatedString(this.lang, "brushSize") + brush; 8745 ctx.lineWidth=brush; 8746 ctx.beginPath(); 8747 ctx.moveTo(10,cnv.height/2); 8748 ctx.lineTo(cnv.width-10,cnv.height/2); 8749 ctx.stroke(); 8750 divel.appendChild(cnv); 8751 divel.addEventListener('click', (e) => { 8752 e.stopPropagation(); 8753 this.context.lineWidth=brush; 8754 this.toggleBrushList(); 8755 }) 8756 this.getBrushList().append(divel); 8757 }); 8758 } 8759 8760 resizeCanvas(percentage) { 8761 const signCanvas = this.getCanvas(); 8762 const ctx = signCanvas.getContext('2d', { willReadFrequently: true }); 8763 const container = this.getCanvasContainer();
8764 this.getSignCanvasesContainer().style.width = `${percentage}%`; 8765 8766 // Ensure the canvas has valid dimensions 8767 if (signCanvas.width === 0 || signCanvas.height === 0) { 8768 return; 8769 } 8770 8771 // Save the content of the canvas if it has valid dimensions 8772 let imgData = null; 8773 if (signCanvas.width > 0 && signCanvas.height > 0) { 8774 imgData = ctx.getImageData(0, 0, signCanvas.width, signCanvas.height); 8775 } 8776 // Calculate the new width based on the percentage of the container's width 8777 const newWidth = container.offsetWidth * (percentage / 100); 8778 // Set the new width and height of the canvas 8779 signCanvas.width = newWidth; 8780 // Restore the content back to the resized canvas if it has valid content 8781 if (imgData) { 8782 ctx.putImageData(imgData, 0, 0); 8783 } 8784 } 8785 8786 geoQuerySuccessHandler(position) { 8787 if (position && position.coords) { 8788 this.showMessage(''); 8789 const { latitude, longitude } = position.coords; 8790 const latStr = `Latitude: ${latitude}`; 8791 const longStr = `Longitude: ${longitude}`; 8792 const dateObj = new Date(); 8793 const tZone = (dateObj.getTimezoneOffset() / 60) * -1; 8794 const timeStr = `${dateObj.getTime()}: ${(dateObj.getMonth() + 1)}/${dateObj.getDate()}/${dateObj.getFullYear()} ${dateObj.getHours()}:${dateObj.getMinutes()}:${dateObj.getSeconds()}${tZone > 0 ? ' +' : ' '}${tZone}`; 8795 this.updateGeoCanvas(latStr, longStr, timeStr); 8796 } 8797 } 8798 8799 updateGeoCanvas(latStr, longStr, timeStr) { 8800 const geoCanvas = this.getGeoCanvas(); 8801 geoCanvas.style.height = '50px'; 8802 geoCanvas.style.width = '200px'; 8803 geoCanvas.style.display = 'block'; 8804 8805 if (geoCanvas) { 8806 const ctx = geoCanvas.getContext('2d'); 8807 geoCanvas.width = geoCanvas.offsetWidth; 8808 geoCanvas.height = geoCanvas.offsetHeight; 8809 8810 ctx.font = 'bold 10px Arial'; // Font size and type 8811 ctx.fillStyle = 'black'; // Text color 8812 ctx.measureText("m").width * 1.5; 8813 let x = 0; 8814 let y = 15; 8815 8816 // Draw the text on the canvas 8817 ctx.fillText(latStr, x, y); 8818 ctx.fillText(longStr, x, y + 15); 8819 ctx.fillText(timeStr, x, y + 30); 8820 } 8821 } 8822 8823 handleGeoLocation() { 8824 if (navigator.geolocation) { 8825 this._geoLocQuery = new GeoLocationQuery(); 8826 this._geoLocQuery.init( 8827 this.geoQuerySuccessHandler.bind(this), 8828 this.geoQueryErrorHandler.bind(this) 8829 ); 8830 this._geoLocQuery.query(); 8831 var message = FormView.LanguageUtils.getTranslatedString(this.lang, 'geoLocationFetch'); 8832 this.showMessage(message); 8833 } 8834 } 8835 8836 geoQueryErrorHandler(err) { 8837 var message = FormView.LanguageUtils.getTranslatedString(this.lang, 'geoLocationError') 8838 this.showMessage(message); 8839 } 8840 8841 enableControls(controls) { 8842 controls.forEach(control => { 8843 const element = this.element.querySelector('[data-cmp-scribble-button="'+ control +'"]'); 8844 element?.classList.remove('disable_button'); 8845 element?.removeAttribute('disabled'); 8846 }); 8847 } 8848 8849 disableControl(controls) { 8850 controls.forEach(control => { 8851 const element = this.element.querySelector('[data-cmp-scribble-button="'+ control +'"]'); 8852 element?.classList.add('disable_button'); 8853 element?.setAttribute('disabled', 'true'); 8854 }); 8855 } 8856 8857 toggleBrushList(event) { 8858 var brushList = this.getBrushList(); 8859 if(getComputedStyle(brushList).display === 'none') { 8860 brushList.style.display = 'block'; 8861 } else { 8862 brushList.style.display = 'none'; 8863 } 8864 } 8865 8866 controlPanelClickHandler(event) { 8867 const scribbleButton = event.target.getAttribute('data-cmp-scribble-button'); 8868 switch(scribbleButton){ 8869 case 'save': 8870 this.submitSign(); 8871 break; 8872 case 'close': 8873 this.closeEditModal(); 8874 break; 8875 case 'clearSign': 8876 this.eraseSignature(); 8877 this.widget.value = ''; 8878 break; 8879 case 'textSign': 8880 this.enableSignatureTextBox(); 8881 break; 8882 case 'geolocation': 8883 this.handleGeoLocation(); 8884 break; 8885 case 'brushes': 8886 this.handleBrush(event); 8887 this.toggleBrushList(); 8888 break; 8889 } 8890 } 8891 8892 closeEditModal() { 8893 if(this.getCanvas()) this.getCanvas().style.display = 'block'; 8894 if(!this._signSubmitted) { 8895 this.eraseSignature() 8896 } 8897 this.hideScribbleModal(); 8898 } 8899 8900 handleBrush(evt){ 8901 this.getKeyboardSignBox().style.display = 'none'; 8902 if (this.canvas.style.display == "none") { 8903 this.canvas.style.display = "block"; 8904 this.context.clearRect(0, 0, this.canvas?.width, this.canvas?.height); 8905 this.eraseSignature(); 8906 this.initializeCanvas(); 8907 } 8908 } 8909 initScribbleModal() {
8910 const controlPanel = this.getScribbleControlPanel(); 8911 const toggleBrushListIcon = this.getBrush(); 8912 const brushList = this.getBrushList(); 8913 const keyboardSignBox = this.getKeyboardSignBox(); 8914 8915 this.renderBrushList(); 8916 8917 this.addEventListeners(controlPanel, 'click', this.controlPanelClickHandler.bind(this)); 8918 8919 keyboardSignBox.addEventListener('input', (event) => { 8920 if (event?.target?.value) { 8921 this.enableControls(['save', 'clearSign']); 8922 } else { 8923 this.disableControl(['save', 'clearSign']); 8924 } 8925 }); 8926 8927 keyboardSignBox.addEventListener('keyup', () => { 8928 this.updateKeyboardSignBoxFont(keyboardSignBox); 8929 }); 8930 8931 document.addEventListener('click', (event) => { 8932 if (!brushList.contains(event.target) && !toggleBrushListIcon.contains(event.target)) { 8933 brushList.style.display = 'none'; 8934 } 8935 }); 8936 } 8937 8938 addEventListeners(element, eventType, handler, checkDisabled = false) { 8939 if (element) { 8940 element.addEventListener(eventType, (event) => { 8941 if (!checkDisabled || element.getAttribute('disabled') !== 'true') { 8942 handler(event); 8943 } 8944 }); 8945 } 8946 } 8947 8948 updateKeyboardSignBoxFont(keyboardSignBox) { 8949 const fontFamily = "sans-serif, Georgia"; 8950 const fontStyle = "italic"; 8951 keyboardSignBox.style.font = `${fontStyle} 2rem ${fontFamily}`; 8952 const value = keyboardSignBox.value; 8953 const canvas = this.getCanvas(); 8954 const ctx = this.context; 8955 const maxFontSize = 10; // rem 8956 const minFontSize = 1; // rem 8957 // Set to max font size to measure 8958 ctx.clearRect(0, 0, canvas.width, canvas.height); 8959 // Find the largest font size that fits the text within the canvas width 8960 let fontSize = maxFontSize; 8961 ctx.font = `${fontStyle} ${fontSize}rem ${fontFamily}`; 8962 let textWidth = ctx.measureText(value).width; 8963 const canvasWidth = canvas.width; 8964 while (fontSize > minFontSize && textWidth > canvasWidth) { 8965 fontSize -= 0.5; 8966 ctx.font = `${fontStyle} ${fontSize}rem ${fontFamily}`; 8967 textWidth = ctx.measureText(value).width; 8968 } 8969 fontSize = Math.max(minFontSize, fontSize); 8970 ctx.font = `${fontStyle} ${fontSize}rem ${fontFamily}`; 8971 ctx.fillText(value, 0, canvas.height / 2); 8972 } 8973 8974 enableSignatureTextBox() { 8975 this.eraseSignature(); 8976 this.getKeyboardSignBox().style.display = "inline-block"; 8977 this.getCanvas().style.display = "none"; 8978 } 8979 8980 eraseSignature() { 8981 this.context?.clearRect(0, 0, this.canvas?.width, this.canvas?.height); 8982 const geoCnv = this.getGeoCanvas(); 8983 if(geoCnv) { 8984 const geoCanvasContext = geoCnv?.getContext('2d'); 8985 geoCanvasContext?.clearRect(0, 0, geoCnv.width, geoCnv.height); 8986 geoCnv.style.display = 'none'; 8987 } 8988 this.getKeyboardSignBox().value=''; 8989 this.disableControl(['clearSign','save']); 8990 } 8991 8992 resizeAndFixCanvas() { 8993 const dpr = window.devicePixelRatio || 1; 8994 let imgData = null; 8995 if (this.canvas.width > 0 && this.canvas.height > 0) { 8996 imgData = this.context.getImageData(0, 0, this.canvas.width, this.canvas.height); 8997 } 8998 this.canvas.width = this.canvas.offsetWidth * dpr; 8999 this.canvas.height = this.canvas.offsetHeight * dpr; 9000 if (imgData) { 9001 this.context.putImageData(imgData, 0, 0); 9002 } 9003 } 9004 9005 handleCanvasEvent(event) { 9006 switch (event.type) { 9007 case 'mousedown': 9008 case 'touchstart': 9009 this.startDrawing(event); 9010 break; 9011 case 'mousemove': 9012 case 'touchmove': 9013 this.draw(event); 9014 break; 9015 case 'mouseup': 9016 case 'mouseleave': 9017 case 'touchend': 9018 case 'touchcancel': 9019 this.stopDrawing(); 9020 break; 9021 } 9022 } 9023 9024 addCanvasEventListeners() { 9025 const events = ['mousedown', 'mousemove', 'mouseup', 'mouseleave', 'touchstart', 'touchmove', 'touchend', 'touchcancel'];
9026 events.forEach(event => { 9027 this.canvas.addEventListener(event, this.handleCanvasEvent.bind(this)); 9028 }); 9029 } 9030 9031 initializeCanvas() { 9032 if(this.existingSign) { 9033 this.getCanvasContainer().style.width = '100%'; 9034 this.getMainCanvas().style.border = '1px solid black'; 9035 this.getKeyboardSignBox().style.display = 'none'; 9036 this.disableControl(['brushes','geolocation','clearSign','textSign','save']); 9037 } else { 9038 this.canvas = this.getCanvas(); 9039 this.canvas.style.display = 'block'; 9040 this.context = this.canvas.getContext('2d', { willReadFrequently: true }); 9041 this.resizeCanvas(100); 9042 this.resizeAndFixCanvas(); 9043 if (this.canvas) { 9044 this.canvas.style.border = '1px dashed #AAAAAA'; 9045 this.getKeyboardSignBox().style.display = 'none'; 9046 this.addCanvasEventListeners(); 9047 this.isDrawing = false; 9048 } 9049 } 9050 // Add event listener for window resize to make the canvas responsive 9051 window.addEventListener('resize', this.resizeAndFixCanvas.bind(this)); 9052 // } 9053 } 9054 9055 showScribbleModal() { 9056 if(window.getComputedStyle(this.getScribbleContainer()).display !== 'block') { 9057 this.disableControl(['clearSign','save']); 9058 } 9059 const container = this.getScribbleContainer(); 9060 container.style.display = 'block'; 9061 // Set focus to the modal container for accessibility 9062 container.setAttribute('tabindex', '-1'); 9063 container.focus(); 9064 } 9065 9066 hideScribbleModal() {
9067 this.getScribbleContainer().style.display = 'none'; 9068 } 9069 9070 scribbleContainerClickHandler() { 9071 this.showScribbleModal(); 9072 this.initializeCanvas(); 9073 } 9074 9075 startDrawing(event) { 9076 // Ensure the context is initialized 9077 if (!this.context) { 9078 return; 9079 } 9080 9081 // Normalize event coordinates for touch events 9082 const { offsetX, offsetY } = this.getEventCoordinates(event); 9083 9084 this.isDrawing = true; 9085 this.context.beginPath(); 9086 this.context.moveTo(offsetX, offsetY); 9087 } 9088 9089 getMousePos(event) { 9090 const rect = this.canvas.getBoundingClientRect(); 9091 const offsetX = event.clientX - rect.left; 9092 const offsetY = event.clientY - rect.top; 9093 return { offsetX, offsetY }; 9094 } 9095 9096 getEventCoordinates(event) { 9097 const rect = this.canvas.getBoundingClientRect(); 9098 const dpr = window.devicePixelRatio || 1; 9099 if (event.touches && event.touches.length > 0) { 9100 const touch = event.touches[0]; 9101 return { 9102 offsetX: (touch.clientX - rect.left) * dpr, 9103 offsetY: (touch.clientY - rect.top) * dpr 9104 }; 9105 } else { 9106 return { 9107 offsetX: (event.clientX - rect.left) * dpr, 9108 offsetY: (event.clientY - rect.top) * dpr 9109 }; 9110 } 9111 } 9112 9113 draw(event) { 9114 if (!this.isDrawing) return; 9115 const { offsetX, offsetY } = this.getEventCoordinates(event); 9116 this.context.lineTo(offsetX, offsetY); 9117 this.context.stroke(); 9118 this.enableControls(['clearSign','save']); 9119 } 9120 9121 stopDrawing() { 9122 if (this.isDrawing) { 9123 this.context.closePath(); 9124 this.isDrawing = false; 9125 } 9126 } 9127 } 9128 9129 FormView.Utils.setupField(({element, formContainer}) => { 9130 return new Scribble({element, formContainer}) 9131 }, Scribble.selectors.self); 9132})(); 9133 9134/******************************************************************************* 9135 * Copyright 2022 Adobe 9136 * 9137 * Licensed under the Apache License, Version 2.0 (the "License"); 9138 * you may not use this file except in compliance with the License. 9139 * You may obtain a copy of the License at 9140 * 9141 * http://www.apache.org/licenses/LICENSE-2.0 9142 * 9143 * Unless required by applicable law or agreed to in writing, software 9144 * distributed under the License is distributed on an "AS IS" BASIS, 9145 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9146 * See the License for the specific language governing permissions and 9147 * limitations under the License. 9148 ******************************************************************************/ 9149(function() { 9150 9151 "use strict"; 9152 class RadioButton extends FormView.FormOptionFieldBase { 9153 9154 static NS = FormView.Constants.NS; 9155 /** 9156 * Each FormField has a data attribute class that is prefixed along with the global namespace to 9157 * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be 9158 * data-{NS}-{IS}-x="" 9159 * @type {string} 9160 */ 9161 static IS = "adaptiveFormRadioButton"; 9162 static bemBlock = 'cmp-adaptiveform-radiobutton'; 9163 static selectors = { 9164 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 9165 widgets: `.${RadioButton.bemBlock}__widget`, 9166 widget: `.${RadioButton.bemBlock}__option__widget`, 9167 label: `.${RadioButton.bemBlock}__label`, 9168 description: `.${RadioButton.bemBlock}__longdescription`, 9169 qm: `.${RadioButton.bemBlock}__questionmark`, 9170 errorDiv: `.${RadioButton.bemBlock}__errormessage`, 9171 tooltipDiv: `.${RadioButton.bemBlock}__shortdescription`, 9172 option: `.${RadioButton.bemBlock}__option`, 9173 optionLabel: `.${RadioButton.bemBlock}__option-label` 9174 }; 9175 9176 constructor(params) { 9177 super(params); 9178 this.qm = this.element.querySelector(RadioButton.selectors.qm); 9179 } 9180 9181 getWidgets() { 9182 return this.element.querySelector(RadioButton.selectors.widgets); 9183 } 9184 9185 getWidget() { 9186 return this.element.querySelectorAll(RadioButton.selectors.widget); 9187 } 9188 9189 getDescription() { 9190 return this.element.querySelector(RadioButton.selectors.description); 9191 } 9192 9193 getLabel() { 9194 return this.element.querySelector(RadioButton.selectors.label); 9195 } 9196 9197 getQuestionMarkDiv() { 9198 return this.element.querySelector(RadioButton.selectors.qm); 9199 } 9200 9201 getTooltipDiv() { 9202 return this.element.querySelector(RadioButton.selectors.tooltipDiv); 9203 } 9204 9205 getErrorDiv() { 9206 return this.element.querySelector(RadioButton.selectors.errorDiv); 9207 } 9208 9209 getOptions() { 9210 return this.element.querySelectorAll(RadioButton.selectors.option); 9211 } 9212 9213 #addWidgetListeners(optionWidget) { 9214 optionWidget.addEventListener('change', (e) => { 9215 this.setModelValue(e.target.value); 9216 }); 9217 optionWidget.addEventListener('focus', (e) => { 9218 this.setActive(); 9219 }); 9220 optionWidget.addEventListener('blur', (e) => { 9221 this.setInactive(); 9222 }); 9223 } 9224 9225 setModel(model) { 9226 super.setModel(model); 9227 this.widget.forEach(optionWidget => { 9228 this.#addWidgetListeners(optionWidget); 9229 }); 9230 } 9231 9232 updateEnabled(enabled, state) { 9233 this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_ENABLED, enabled); 9234 let widgets = this.widget;
9235 widgets.forEach(widget => { 9236 if (enabled === false) { 9237 if(state.readOnly === false){ 9238 widget.setAttribute(FormView.Constants.HTML_ATTRS.DISABLED, "disabled"); 9239 } 9240 } else if (state.readOnly === false) { 9241 widget.removeAttribute(FormView.Constants.HTML_ATTRS.DISABLED); 9242 } 9243 }); 9244 } 9245 9246 updateReadOnly(readonly) { 9247 let widgets = this.widget; 9248 this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_READONLY, readonly); 9249 widgets.forEach(widget => { 9250 if (readonly === true) { 9251 widget.setAttribute(FormView.Constants.HTML_ATTRS.DISABLED, "disabled"); 9252 } else { 9253 widget.removeAttribute(FormView.Constants.HTML_ATTRS.DISABLED); 9254 } 9255 }); 9256 } 9257 9258 updateValidity(validity) { 9259 if(validity.valid === undefined) { 9260 this.element.removeAttribute(FormView.Constants.DATA_ATTRIBUTE_VALID); 9261 this.widget.forEach(widget => widget.removeAttribute(FormView.Constants.ARIA_INVALID)); 9262 } else { 9263 this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_VALID, validity.valid); 9264 this.widget.forEach(widget => widget.setAttribute(FormView.Constants.ARIA_INVALID, !validity.valid)); 9265 } 9266 } 9267 9268 updateValue(modelValue) { 9269 this.widget.forEach(widget => { 9270 if (modelValue != null && widget.value != null && (modelValue.toString() == widget.value.toString())) { 9271 widget.checked = true; 9272 widget.setAttribute(FormView.Constants.HTML_ATTRS.CHECKED, FormView.Constants.HTML_ATTRS.CHECKED); 9273 } else { 9274 widget.checked = false; 9275 widget.removeAttribute(FormView.Constants.HTML_ATTRS.CHECKED); 9276 } 9277 }, this) 9278 super.updateEmptyStatus(); 9279 } 9280 9281 #createRadioOption(value, itemLabel) { 9282 const optionTemplate = ` 9283 <div class="${RadioButton.selectors.option.slice(1)}"> 9284 <label class="${RadioButton.selectors.optionLabel.slice(1)}"> 9285 <input type="radio" name="${this._model.name}" class="${RadioButton.selectors.widget.slice(1)}" value="${value}" tabindex="0"> 9286 <span>${itemLabel}</span> 9287 </label> 9288 </div>`; 9289 9290 const container = document.createElement('div'); // Create a container element to hold the template 9291 container.innerHTML = optionTemplate; 9292 let addedOptionWidget = container.querySelector(RadioButton.selectors.widget); 9293 if(this._model.readOnly === true || this._model.enabled === false) { 9294 addedOptionWidget.setAttribute("disabled", true); 9295 if(this._model.readOnly === true) { 9296 addedOptionWidget.setAttribute("aria-readonly", true); 9297 } 9298 } 9299 this.#addWidgetListeners(addedOptionWidget); 9300 return container.firstElementChild; // Return the first child, which is the created option 9301 } 9302 9303 updateEnum(newEnums) { 9304 super.updateEnumForRadioButtonAndCheckbox(newEnums, this.#createRadioOption); 9305 // refresh the widget references, to dynamically added options 9306 this.widget = this.getWidget(); 9307 } 9308 9309 updateEnumNames(newEnumNames) { 9310 super.updateEnumNamesForRadioButtonAndCheckbox(newEnumNames, this.#createRadioOption); 9311 // refresh the widget references, to dynamically added options 9312 this.widget = this.getWidget(); 9313 } 9314 9315 updateRequired(required, state) { 9316 if (this.widget) { 9317 this.element.toggleAttribute("required", required); 9318 this.element.setAttribute("data-cmp-required", required); 9319 } 9320 } 9321 9322 syncMarkupWithModel() { 9323 super.syncMarkupWithModel(); 9324 this.#syncWidgetName(); 9325 } 9326 9327 #syncWidgetName() { 9328 const name = this.getModel()?.name; 9329 this.widget.forEach(widget => { 9330 widget.setAttribute("name", `${this.id}_${name}`); 9331 }); 9332 } 9333 } 9334 9335 FormView.Utils.setupField(({element, formContainer}) => { 9336 return new RadioButton({element, formContainer}); 9337 }, RadioButton.selectors.self); 9338 9339})(); 9340 9341/******************************************************************************* 9342 * Copyright 2025 Adobe 9343 * 9344 * Licensed under the Apache License, Version 2.0 (the "License");
9345 * you may not use this file except in compliance with the License. 9346 * You may obtain a copy of the License at 9347 * 9348 * http://www.apache.org/licenses/LICENSE-2.0 9349 * 9350 * Unless required by applicable law or agreed to in writing, software 9351 * distributed under the License is distributed on an "AS IS" BASIS, 9352 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9353 * See the License for the specific language governing permissions and 9354 * limitations under the License. 9355 ******************************************************************************/ 9356 9357/** 9358 * This class is responsible for interacting with the file input widget. It implements the file preview, 9359 * file list, handling invalid file size, file name, file mime type functionality 9360 */ 9361 9362if (typeof window.FileInputWidget === 'undefined') { 9363 window.FileInputWidget = class extends FormView.FormFileInputWidget { 9364 9365 constructor(params) { 9366 super(params); 9367 this.invalidFeature = { 9368 ...this.invalidFeature, 9369 "SIZE_ZERO": 4 9370 } 9371 } 9372 9373 attachEventHandlers(widget, dragArea, model) { 9374 super.attachEventHandlers(widget, dragArea, model) 9375 const customBtn = dragArea?.querySelector(".cmp-adaptiveform-fileinput__widgetlabel") 9376 customBtn?.addEventListener("click", () => { 9377 widget.click(); 9378 }); 9379 customBtn?.addEventListener('keydown', function(event) { 9380 // Check if the Enter key is pressed 9381 if (event.key === 'Enter' || event.keyCode === 13) { 9382 // Trigger the click event of the file input 9383 widget.click(); 9384 } 9385 }); 9386 } 9387 // CoPA Customization - File attachment reset issue fix- E-002160553 9388 setValue(value) { 9389 let isValueSame = false; 9390 if (value != null) { 9391 // change to array since we store array internally 9392 value = Array.isArray(value) ? value : [value]; 9393 } 9394 // check if current values and new values are same 9395 if (this.fileArr != null && value != null) { 9396 isValueSame = JSON.stringify(FormView.FileAttachmentUtils.extractFileInfo(this.fileArr)) === JSON.stringify(value); 9397 } 9398 // if new values, update the DOM 9399 if (!isValueSame) { 9400 let oldUrls = {}; 9401 // Cache the url before deletion 9402 this.fileList.querySelectorAll(".cmp-adaptiveform-fileinput__filename").forEach(function (elem) { 9403 let url = elem.dataset.key; 9404 if (typeof url !== "undefined") { 9405 let fileName = url.substring(url.lastIndexOf("/") + 1); 9406 oldUrls[fileName] = url; 9407 } 9408 }); 9409 // empty the file list 9410 while (this.fileList.lastElementChild) { 9411 this.fileList.removeChild(this.fileList.lastElementChild); 9412 } 9413 // set the new value 9414 if (value != null) { 9415 let self = this; 9416 // Update the value array with the file 9417 this.values = value.map(function (file, index) { 9418 // Check if file Name is a path, if yes get the last part after "/" 9419 let isFileObject= window.File ? file.data instanceof window.File : false, 9420 fileName = typeof file === "string" ? file : file.name, 9421 fileUrl = typeof file === "string" ? file : (isFileObject ? "" : file.data), 9422 fileSize = file.size, 9423 fileUploadUrl = fileUrl; 9424 if (oldUrls[fileName]) { 9425 fileUploadUrl = oldUrls[fileName]; 9426 } 9427 self.showFileList(fileName, fileSize, null, fileUploadUrl); 9428 return fileName; 9429 }); 9430 this.fileArr = [...value]; 9431 } else { 9432 this.values = []; 9433 this.fileArr = []; 9434 this.widget.value = ''; 9435 } 9436 } 9437 } 9438 9439 9440 fileItem(fileName, fileSize, comment, fileUrl) { 9441 let self = this; 9442 let id = `${Date.now() + '_' + Math.floor(Math.random() * 10000)}_file_size` 9443 let fileItem = document.createElement('li'); 9444 fileItem.setAttribute("class", "cmp-adaptiveform-fileinput__fileitem"); 9445 let fileNameDom = document.createElement('a'); 9446 let fileSizeDom = document.createElement('span'); 9447 9448 fileSizeDom.setAttribute('class', "cmp-adaptiveform-fileinput__filesize"); 9449 fileSizeDom.setAttribute('id', id); 9450 fileSizeDom.textContent = this.formatBytes(fileSize); 9451 9452 fileNameDom.setAttribute('tabindex', '0'); 9453 fileNameDom.setAttribute('class', "cmp-adaptiveform-fileinput__filename"); 9454 fileNameDom.setAttribute('aria-describedby', id); 9455 // CoPA Customization - Added aria-label for accessibility fix 9456 fileNameDom.setAttribute('aria-label', fileName); 9457 fileNameDom.textContent = fileName; 9458 // CoPA Customization - Added role for accessibility fix 9459 fileNameDom.setAttribute('role', 'document'); 9460 fileNameDom.addEventListener('keypress', function(e) { 9461 if (e.keyCode === 13 || e.charCode === 32) { 9462 e.target.click(); 9463 } 9464 }); 9465 fileNameDom.addEventListener('click', function(e) { 9466 self.handleFilePreview(e); 9467 }); 9468 fileItem.appendChild(fileNameDom); 9469 if(fileUrl != null){ 9470 fileNameDom.dataset.key = fileUrl; 9471 } 9472 let fileEndContainer = document.createElement('span'); 9473 let fileClose = document.createElement('button'); 9474 fileEndContainer.setAttribute('class', "cmp-adaptiveform-fileinput__fileendcontainer"); 9475 fileClose.setAttribute('tabindex', '0'); 9476 fileClose.setAttribute('class', "cmp-adaptiveform-fileinput__filedelete"); 9477 fileClose.setAttribute('aria-label', FormView.LanguageUtils.getTranslatedString(this.lang, "FileCloseAccessText") + f
9477ileName); 9478 fileClose.textContent = "x"; 9479 fileClose.addEventListener('keypress', function(e) { 9480 if (e.keyCode === 13 || e.charCode === 32) { 9481 e.target.click(); 9482 } 9483 }); 9484 fileClose.addEventListener('click', function(e) { 9485 self.handleClick(e); 9486 }); 9487 fileEndContainer.appendChild(fileSizeDom); 9488 fileEndContainer.appendChild(fileClose); 9489 fileItem.appendChild(fileEndContainer); 9490 return fileItem; 9491 } 9492 validateFile(file, invalidFilesByType) { 9493 let currFileName = file.name.split("\\").pop(); 9494 let size = file.size / 1024 / 1024; 9495 if (file.size === 0) { 9496 invalidFilesByType.SIZE_ZERO.push(currFileName); 9497 return false; 9498 } else if (size > parseFloat(this.options.maxFileSize)) { 9499 invalidFilesByType.SIZE.push(currFileName); 9500 return false; 9501 } else if (!FileInputWidget.isValid(currFileName)) { 9502 invalidFilesByType.NAME.push(currFileName); 9503 return false; 9504 } else { 9505 let isMatch = false; 9506 let extension = currFileName.split('.').pop(); 9507 let mimeType = (file.type) ? file.type : this.extensionToMimeTypeMap[extension]; 9508 if (mimeType && mimeType.trim().length > 0) { 9509 isMatch = this.regexMimeTypeList.some(rx => rx.test(mimeType)); 9510 } 9511 if (!isMatch) { 9512 invalidFilesByType.MIMETYPE.push(currFileName); 9513 return false; 9514 } 9515 } 9516 return true; 9517 } 9518 handleChange(filesUploaded) { 9519 if (!this.isFileUpdate) { 9520 let self = this, 9521 files = filesUploaded; 9522 // Object of arrays to collect invalid file names by type 9523 let invalidFilesByType = { SIZE: [], SIZE_ZERO: [], NAME: [], MIMETYPE: [] }; 9524 if (typeof files !== "undefined") { 9525 let invalidFilesIndexes = []; 9526 Array.from(files).forEach(function (file, fileIndex) { 9527 if (self.validateFile(file, invalidFilesByType)) { 9528 if (self.isMultiSelect()) { 9529 self.values.push(file.name.split("\\").pop()); 9530 self.fileArr.push(file); 9531 } else { 9532 self.values = [file.name.split("\\").pop()]; 9533 self.fileArr = [file]; 9534 } 9535 } else { 9536 invalidFilesIndexes.push(fileIndex); 9537 } 9538 }, this); 9539 if (invalidFilesIndexes.length > 0 && this.widget !== null) { 9540 this.deleteFilesFromInputDom(invalidFilesIndexes); 9541 } 9542 } 9543 // set the new model value. 9544 this.model.value = this.fileArr; 9545 // Collate all error messages 9546 let errorMessages = []; 9547 if (invalidFilesByType.SIZE_ZERO.length > 0) { 9548 errorMessages.push(this.showInvalidMessage(invalidFilesByType.SIZE_ZERO.join(', '), this.invalidFeature.SIZE_ZERO)); 9549 } 9550 if (invalidFilesByType.SIZE.length > 0) { 9551 errorMessages.push(this.showInvalidMessage(invalidFilesByType.SIZE.join(', '), this.invalidFeature.SIZE)); 9552 } 9553 if (invalidFilesByType.NAME.length > 0) { 9554 errorMessages.push(this.showInvalidMessage(invalidFilesByType.NAME.join(', '), this.invalidFeature.NAME)); 9555 } 9556 if (invalidFilesByType.MIMETYPE.length > 0) { 9557 errorMessages.push(this.showInvalidMessage(invalidFilesByType.MIMETYPE.join(', '), this.invalidFeature.MIMETYPE)); 9558 } 9559 if (errorMessages.length > 0) { 9560 alert(errorMessages.join('\n')); 9561 } 9562 } 9563 this.widget.value = null; 9564 } 9565 showInvalidMessage(fileNames, invalidFeature) { 9566 let that = this; 9567 let IS_IPAD = navigator.userAgent.match(/iPad/i) !== null, 9568 IS_IPHONE = (navigator.userAgent.match(/iPhone/i) !== null); 9569 if (IS_IPAD || IS_IPHONE) { 9570 setTimeout(function () {
9571 return that.invalidMessage(fileNames, invalidFeature); 9572 }, 0); 9573 } else { 9574 return this.invalidMessage(fileNames, invalidFeature); 9575 } 9576 } 9577 invalidMessage(fileNames, invalidFeature) { 9578 const customMessages = this.options.constraintMessages || {}; 9579 const messages = { 9580 [this.invalidFeature.SIZE]: customMessages.maxFileSize || FormView.LanguageUtils.getTranslatedString(this.lang, "FileSizeGreater", [fileNames, this.options.maxFileSize]), 9581 [this.invalidFeature.NAME]: customMessages.invalidFileName || FormView.LanguageUtils.getTranslatedString(this.lang, "FileNameInvalid", [fileNames]), 9582 [this.invalidFeature.MIMETYPE]: customMessages.invalidMimeType || FormView.LanguageUtils.getTranslatedString(this.lang, "FileMimeTypeInvalid", [fileNames]), 9583 [this.invalidFeature.SIZE_ZERO]: customMessages.zeroFileSize || FormView.LanguageUtils.getTranslatedString(this.lang, "FileSizeZero", [fileNames]) 9584 }; 9585 return messages[invalidFeature]; 9586 } 9587 9588 handleClick (event){ 9589 let elem = event.target, 9590 text = elem.parentElement.previousSibling.textContent, 9591 index = this.getIndexOfText(text, elem.parentElement), 9592 url = elem.parentElement.previousSibling.dataset.key, 9593 objectUrl = elem.parentElement.previousSibling.dataset.objectUrl; 9594 if (index !== -1) { 9595 this.values.splice(index, 1); 9596 this.fileArr.splice(index, 1); 9597 // set the model with the new value 9598 this.model.value = this.fileArr; 9599 // value and fileArr contains items of both URL and file types, hence while removing from DOM 9600 // get the correct index as per this.#widget.files 9601 let domIndex = Array.from(this.widget.files).findIndex(function(file) { 9602 return file.name === text; 9603 }); 9604 this.deleteFilesFromInputDom([domIndex]); 9605 if (url != null) { 9606 // remove the data so that others don't use this url 9607 delete elem.parentElement.previousSibling.dataset.key; 9608 } 9609 if(objectUrl) { 9610 // revoke the object URL to avoid memory leaks in browser 9611 // since file is anyways getting deleted, remove the object URL's too 9612 window.URL.revokeObjectURL(objectUrl); 9613 } 9614 } 9615 // Remove the dom from view 9616 //All bound events and jQuery data associated with the element are also removed 9617 elem.parentElement.parentElement.remove(); 9618 // Set the focus on file upload button after click of close 9619 this.widget.focus(); 9620 9621 } 9622 } 9623} 9624/******************************************************************************* 9625 * Copyright 2025 Adobe 9626 * 9627 * Licensed under the Apache License, Version 2.0 (the "License"); 9628 * you may not use this file except in compliance with the License. 9629 * You may obtain a copy of the License at 9630 * 9631 * http://www.apache.org/licenses/LICENSE-2.0 9632 * 9633 * Unless required by applicable law or agreed to in writing, software 9634 * distributed under the License is distributed on an "AS IS" BASIS, 9635 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9636 * See the License for the specific language governing permissions and 9637 * limitations under the License. 9638 ******************************************************************************/ 9639(function() { 9640 9641 "use strict"; 9642 class FileInputV4 extends FormView.FormFileInput { 9643 9644 static NS = FormView.Constants.NS; 9645 /** 9646 * Each FormField has a data attribute class that is prefixed along with the global namespace to 9647 * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be 9648 * data-{NS}-{IS}-x="" 9649 * @type {string} 9650 */ 9651 static IS = "adaptiveFormFileInput"; 9652 static bemBlock = 'cmp-adaptiveform-fileinput' 9653 static selectors = { 9654 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 9655 widget: `.${FileInputV4.bemBlock}__widget`, 9656 label: `.${FileInputV4.bemBlock}__label`, 9657 description: `.${FileInputV4.bemBlock}__longdescription`, 9658 qm: `.${FileInputV4.bemBlock}__questionmark`, 9659 errorDiv: `.${FileInputV4.bemBlock}__errormessage`, 9660 tooltipDiv: `.${FileInputV4.bemBlock}__shortdescription`, 9661 fileListDiv : `.${FileInputV4.bemBlock}__filelist`, 9662 attachButtonLabel : `.${FileInputV4.bemBlock}__widgetlabel`, 9663 dragArea: `.${FileInputV4.bemBlock}__dragarea` 9664 }; 9665 9666 constructor(params) { 9667 super(params); 9668 } 9669 widgetFields = { 9670 widget: this.getWidget(), 9671 fileListDiv: this.getFileListDiv(), 9672 model: () => this._model, 9673 dragArea: this.getDragArea() 9674 }; 9675 9676 getWidget() { 9677 return this.element.querySelector(FileInputV4.selectors.widget); 9678 } 9679 9680 getDragArea() { 9681 return this.element.querySelector(FileInputV4.selectors.dragArea); 9682 } 9683 9684 getDescription() { 9685 return this.element.querySelector(FileInputV4.selectors.description); 9686 } 9687 9688 getLabel() { 9689 return this.element.querySelector(FileInputV4.selectors.label); 9690 } 9691 9692 getErrorDiv() { 9693 return this.element.querySelector(FileInputV4.selectors.errorDiv); 9694 } 9695 9696 getTooltipDiv() { 9697 return this.element.querySelector(FileInputV4.selectors.tooltipDiv); 9698 } 9699 9700 getQuestionMarkDiv() { 9701 return this.element.querySelector(FileInputV4.selectors.qm); 9702 } 9703 9704 getFileListDiv() { 9705 return this.element.querySelector(FileInputV4.selectors.fileListDiv); 9706 } 9707 9708 getAttachButtonLabel() { 9709 return this.element.querySelector(FileInputV4.selectors.attachButtonLabel); 9710 } 9711 9712 updateEnabled(enabled, state) { 9713 if (this.widget) { 9714 this.element.setAttribute(FormView.Constants.DATA_ATTRIBUTE_ENABLED, enabled); 9715 const isDisabled = !enabled || state.readOnly; 9716 if (isDisabled) { 9717 this.widget.setAttribute("disabled", "disabled"); 9718 } else { 9719 this.widget.removeAttribute("disabled"); 9720 } 9721 } 9722 } 9723
9724 updateValue(value) { 9725 if (this.widgetObject == null) { 9726 this.widgetObject = new FileInputWidget(this.widgetFields); 9727 } 9728 this.widgetObject.setValue(value); 9729 super.updateEmptyStatus(); 9730 } 9731 9732 setModel(model) { 9733 super.setModel(model); 9734 if (this.widgetObject == null) { 9735 this.widgetObject = new FileInputWidget(this.widgetFields); 9736 } 9737 this.getAttachButtonLabel().addEventListener('focus', () => { 9738 this.setActive(); 9739 }) 9740 this.getAttachButtonLabel().addEventListener('blur', () => { 9741 this.setInactive(); 9742 }) 9743 } 9744 9745 syncWidget() { 9746 let widgetElement = this.getWidget ? this.getWidget() : null; 9747 if (widgetElement) { 9748 widgetElement.id = this.getId() + "__widget"; 9749 const closestElement = widgetElement?.previousElementSibling; 9750 if (closestElement && closestElement.tagName.toLowerCase() === 'label') { 9751 closestElement.setAttribute('for', this.getId() + "__widget"); 9752 } else { 9753 this.getAttachButtonLabel().removeAttribute('for'); 9754 } 9755 } 9756 } 9757 } 9758 9759 FormView.Utils.setupField(({element, formContainer}) => { 9760 return new FileInputV4({element, formContainer}) 9761 }, FileInputV4.selectors.self); 9762 9763})(); 9764 9765/******************************************************************************* 9766 * Copyright 2024 Adobe 9767 * 9768 * Licensed under the Apache License, Version 2.0 (the "License"); 9769 * you may not use this file except in compliance with the License. 9770 * You may obtain a copy of the License at 9771 * 9772 * http://www.apache.org/licenses/LICENSE-2.0 9773 * 9774 * Unless required by applicable law or agreed to in writing, software 9775 * distributed under the License is distributed on an "AS IS" BASIS, 9776 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9777 * See the License for the specific language governing permissions and 9778 * limitations under the License. 9779 ******************************************************************************/ 9780(function() { 9781 9782 "use strict"; 9783 class HCaptcha extends FormView.FormFieldBase { 9784 9785 static NS = FormView.Constants.NS; 9786 static IS = "adaptiveFormHCaptcha"; 9787 static bemBlock = 'cmp-adaptiveform-hcaptcha'; 9788 static selectors = { 9789 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 9790 widget: `.${HCaptcha.bemBlock}__widget`, 9791 label: `.${HCaptcha.bemBlock}__label`, 9792 errorDiv: `.${HCaptcha.bemBlock}__errormessage` 9793 }; 9794 9795 constructor(params) { 9796 super(params); 9797 } 9798 9799 getWidget() { 9800 return this.element.querySelector(HCaptcha.selectors.widget); 9801 } 9802 9803 getDescription() { 9804 return null; 9805 } 9806 9807 getLabel() { 9808 return this.element.querySelector(HCaptcha.selectors.label); 9809 } 9810 9811 getTooltipDiv() { 9812 return null; 9813 } 9814 9815 getErrorDiv() { 9816 return this.element.querySelector(HCaptcha.selectors.errorDiv); 9817 } 9818 9819 getQuestionMarkDiv() { 9820 return null; 9821 } 9822 9823 initializeWidget() { 9824 this.widgetObject = new HCaptchaWidget(this, this._model, this.getWidget()); 9825 this.getWidget().addEventListener('blur', (e) => { 9826 if(this.element) { 9827 this.setInactive(); 9828 } 9829 }); 9830 9831 } 9832 9833 setModel(model) { 9834 super.setModel(model); 9835 if (this.widgetObject == null) { 9836 this.initializeWidget(); 9837 } else { 9838 if (this.widget.value !== '') { 9839 this._model.value = this.widget.value; 9840 } 9841 } 9842 } 9843 } 9844 9845 FormView.Utils.setupField(({element, formContainer}) => { 9846 return new HCaptcha({element, formContainer}) 9847 }, HCaptcha.selectors.self); 9848 9849})(); 9850 9851/******************************************************************************* 9852 * Copyright 2024 Adobe 9853 * 9854 * Licensed under the Apache License, Version 2.0 (the "License");
9855 * you may not use this file except in compliance with the License. 9856 * You may obtain a copy of the License at 9857 * 9858 * http://www.apache.org/licenses/LICENSE-2.0 9859 * 9860 * Unless required by applicable law or agreed to in writing, software 9861 * distributed under the License is distributed on an "AS IS" BASIS, 9862 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9863 * See the License for the specific language governing permissions and 9864 * limitations under the License. 9865 ******************************************************************************/ 9866 9867/** 9868 * This class is responsible for interacting with the hCaptcha widget. It displays hCaptcha challenge. 9869 */ 9870 9871if (typeof window.HCaptchaWidget === 'undefined') { 9872 window.HCaptchaWidget = class { 9873 #widget = null 9874 #model = null // passed by reference 9875 #options = null 9876 #lang = 'en' 9877 static FD_CAPTCHA = "fd:captcha"; 9878 9879 constructor(view, model, widget) { 9880 // initialize the widget and model 9881 this.#widget = widget; 9882 this.#model = model; 9883 this.#widget = document.createElement("div"); 9884 this.#widget.classList.add("cmp-adaptiveform-hcaptcha__widget"); 9885 this.#lang = view.formContainer.getModel().lang; 9886 9887 //Always inserting it in body 9888 document.body.appendChild(this.#widget); 9889 this.#options = Object.assign({}, this.#model._jsonModel); 9890 9891 this.#renderHCaptcha(widget); 9892 } 9893 9894 #renderHCaptcha(element) { 9895 9896 const self = this; 9897 const hCaptchaConfigData = this.#options; 9898 element.innerHTML = '<div class="h-captcha"></div>'; 9899 const hcontainer = document.getElementsByClassName("h-captcha")[0]; 9900 let widgetId; 9901 const url = hCaptchaConfigData.properties[HCaptchaWidget.FD_CAPTCHA].config.uri; 9902 9903 const successCallback = function(response) { 9904 self.setCaptchaModel(response); 9905 }; 9906 9907 const expiredCallback = function() { 9908 hcaptcha.reset(widgetId); 9909 self.setCaptchaModel(""); 9910 }; 9911 9912 const onloadCallbackInternal = function() { 9913 widgetId = hcaptcha.render( 9914 hcontainer, 9915 hparameters 9916 ); 9917 return widgetId; 9918 }; 9919 9920 const hparameters = { 9921 'sitekey': hCaptchaConfigData.properties[HCaptchaWidget.FD_CAPTCHA].config.siteKey, 9922 'size': hCaptchaConfigData.properties[HCaptchaWidget.FD_CAPTCHA].config.size, 9923 'theme': hCaptchaConfigData.properties[HCaptchaWidget.FD_CAPTCHA].config.theme || 'light', 9924 'callback': successCallback, 9925 'expired-callback': expiredCallback 9926 }; 9927 9928 window.onloadHCaptchaCallback = onloadCallbackInternal; 9929 9930 const runtimeLocale = this.#lang; 9931 9932 const scr = document.createElement('script'); 9933 scr.src = url + "?onload=onloadHCaptchaCallback&render=explicit&hl=" + runtimeLocale; 9934 scr.async = true; 9935 element.appendChild(scr); 9936 } 9937 9938 setCaptchaModel = function(response) { 9939 this.#model.dispatch(new FormView.Actions.UIChange({'value': response})); 9940 } 9941 } 9942} 9943 9944/******************************************************************************* 9945 * Copyright 2024 Adobe 9946 * 9947 * Licensed under the Apache License, Version 2.0 (the "License"); 9948 * you may not use this file except in compliance with the License. 9949 * You may obtain a copy of the License at 9950 * 9951 * http://www.apache.org/licenses/LICENSE-2.0 9952 * 9953 * Unless required by applicable law or agreed to in writing, software 9954 * distributed under the License is distributed on an "AS IS" BASIS, 9955 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9956 * See the License for the specific language governing permissions and 9957 * limitations under the License. 9958 ******************************************************************************/ 9959 9960(function () { 9961 9962 "use strict"; 9963 class Review extends FormView.FormFieldBase { 9964 9965 static NS = FormView.Constants.NS; 9966 /** 9967 * Each FormField has a data attribute class that is prefixed along with the global namespace to 9968 * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be 9969 * data-{NS}-{IS}-x="" 9970 * @type {string} 9971 */ 9972 static IS = "adaptiveFormReview"; 9973 static bemBlock = 'cmp-adaptiveform-review'; 9974 static templateAttribute = 'data-cmp-review'; 9975 static DATA_ATTRIBUTE_VISIBLE = 'data-cmp-visible'; 9976 static FIELD_TYPE = FormView.Constants.FIELD_TYPE; 9977 static HIDE_FIELD_FROM_REVIEW = [Review.FIELD_TYPE.BUTTON, Review.FIELD_TYPE.PLAIN_TEXT, Review.FIELD_TYPE.CAPTCHA, Review.FIELD_TYPE.IMAGE]; 9978 static panelModifier = '__panel--repeatable'; 9979 static fieldModifier = '__field--'; 9980 static selectors = { 9981 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 9982 container: `.${Review.bemBlock}__container`, 9983 templates: "template[data-cmp-review-fieldType]", 9984 label: '[' + Review.templateAttribute + '-label]', 9985 value: '[' + Review.templateAttribute + '-value]', 9986 editButton:'[' + Review.templateAttribute + '-editButton]', 9987 fieldId: Review.templateAttribute + '-fieldId', 9988 fieldType: Review.templateAttribute + '-fieldType', 9989 panelContent:'[' + Review.templateAttribute + '-content]', 9990 labelContainer: `.${Review.bemBlock}__label-container`, 9991 intersection: Review.templateAttribute + "-intersection=" 9992 }; 9993 static intersectionOptions = { 9994 root: null, 9995 rootMargin: "0px", 9996 threshold: Review.buildThresholdList(), 9997 }; 9998 static buildThresholdList() { 9999 let thresholds = []; 10000 let numSteps = 20; 10001 for (let i = 1.0; i <= numSteps; i++) { 10002 thresholds.push(i / numSteps); 10003 } 10004 thresholds.push(0); 10005 return thresholds; 10006 } 10007 10008 static sanitizedValue(value, options) { 10009 if(options){ 10010 return window.DOMPurify ? window.DOMPurify.sanitize(value, options) : value; 10011 } 10012 return window.DOMPurify ? window.DOMPurify.sanitize(value) : value; 10013 } 10014 10015 static hasChild(element) { 10016 return element && element.children && element.children.length; 10017 } 10018 10019 static addClassModifier(element, item) { 10020 if(item.fieldType !== Review.FIELD_TYPE.PANEL){ 10021 element.querySelector('div').classList.add(Review.bemBlock + Review.fieldModifier + item.fieldType); 10022 } 10023 if(item.repeatable){ 10024 element.querySelector('div').classList.add(Review.bemBlock + Review.panelModifier); 10025 } 10026 if(item.name){ 10027 element.querySelector('div').classList.add(item.name); 10028 } 10029 } 10030 10031 static renderLabel(element, item) { 10032 const label = element.querySelector(Review.selectors.label); 10033 label.innerHTML = item.fieldType === Review.FIELD_TYPE.PLAIN_TEXT ? Review.sanitizedValue(item.value) : Review.sanitizedValue(item?.label?.value, {ALLOWED_TAGS: [] }); 10034 if (item.required) { 10035 label.setAttribute('data-cmp-required', item.required); 10036 } 10037 } 10038 10039 static renderValue(element, item) { 10040 const value = element.querySelector(Review.selectors.value); 10041 if (value) { 10042 const plainText = Review.getValue(item, item.value) || ''; 10043 value.innerHTML = Review.sanitizedValue(plainText); 10044 } 10045 } 10046 10047 static addAccessibilityAttributes(element, item) { 10048 const container = element.querySelector('div'); 10049 const label = element.querySelector(Review.selectors.label); 10050 const value = element.querySelector(Review.selectors.value); 10051 const editButton = element.querySelector(Review.selectors.editButton); 10052 const id = `${item.id}-review-label`; 10053 if(label){ 10054 label.setAttribute('id', id); 10055 container.setAttribute('role', 'region'); 10056 container.setAttribute('aria-labelledby', id); 10057 } 10058 if(value){ 10059 value.setAttribute('aria-labelledby', id); 10060 } 10061 } 10062 10063 static isRepeatable(item) { 10064 return item.fieldType === Review.FIELD_TYPE.PANEL && item.type === 'array' 10065 } 10066 10067 /* return value of the field, if value is array then return comma separated string and 10068 if value is file then return file name 10069 */ 10070 static getValue(item, value) { 10071 if (value === undefined || value === null) return ''; 10072 if (item.fieldType === Review.FIELD_TYPE.FILE_INPUT) { 10073 return Array.isArray(value) ? value.filter(file => file && file.name).map(file => file.name).join(', ') : (value.name || ''); 10074 } 10075 if (Array.isArray(item.enumNames)) { 10076 const values = Array.isArray(value) ? value : [value]; 10077 return values.reduce((names, val) => { 10078 const index = item.enum.indexOf(val); 10079 if (index >= 0) { 10080 names.push(item.enumNames[index]); 10081 } 10082 return names; 10083 }, []).join(', '); 10084 } 10085 if (Array.isArray(value)) { 10086 return value.join(', '); 10087 } 10088 return value; 10089 } 10090 10091 constructor(params) { 10092 super(params); 10093 this.#attachIntersectionObserver(); 10094 this.#attachClickEventOnEdit(); 10095 this.#setFieldTemplateMapping(); 10096 } 10097 getContainer() { 10098 return this.element.querySelector(Review.selectors.container); 10099 } 10100 getTemplates() { 10101 return this.element.querySelectorAll(Review.selectors.templates); 10102 } 10103 getIntersectionElement() { 10104 return this.element.querySelector("[" + Review.selectors.intersection + this.id + "]"); 10105 } 10106 getWidget() { return null } 10107 getDescription() { return null; } 10108 getLabel() { return null; } 10109 getErrorDiv() { return null; } 10110 getTooltipDiv() { return null; } 10111 getQuestionMarkDiv() { return null; } 10112 setModel(model) { 10113 super.setModel(model); 10114 } 10115 10116 // attach intersection observer to the review container for lazy loading 10117 #attachIntersectionObserver() { 10118 let observer = new IntersectionObserver(this.#intersectionObserverHandler.bind(this), Review.intersectionOptions); 10119 const ele = this.getIntersectionElement(); 10120 if(ele){ 10121 observer.observe(ele); 10122 } 10123 } 10124 10125 // attach click event on edit button to set focus on the field 10126 #attachClickEventOnEdit() { 10127 this.getContainer().addEventListener('click', this.#clickHandler.bind(this)) 10128 } 10129 10130 // create template mapping based on field type and use it to render review fields 10131 #setFieldTemplateMapping() { 10132 const templates = this.getTemplates(); 10133 let mappings = {};
10134 templates.forEach(template => { 10135 const type = template.getAttribute(Review.selectors.fieldType); 10136 mappings[type || 'default'] = template; 10137 }); 10138 this.templateMappings = mappings; 10139 } 10140 10141 // click handler to set focus on the field when use click on edit button 10142 #clickHandler(event) { 10143 if (event?.target?.nodeName === 'BUTTON') { 10144 const id = event.target.getAttribute(Review.selectors.fieldId); 10145 const form = this.formContainer.getModel();; 10146 const field = this.formContainer.getField(id); 10147 if (form && field) { 10148 form.setFocus(field._model); 10149 } 10150 } 10151 } 10152 10153 // if review container is in view port then render review fields 10154 #intersectionObserverHandler(entries) { 10155 entries.forEach(entry => { 10156 if (entry.isIntersecting && this._model) { 10157 const panels = this.#getPanels(); 10158 const reviewContainer = this.getContainer(); 10159 const children = this.#renderReviewFields(panels); 10160 reviewContainer.innerHTML = ''; 10161 reviewContainer.appendChild(children); 10162 } 10163 }) 10164 } 10165 10166 // iterate over all the panels or linked panels and render child of each panel 10167 #renderReviewFields(items) { 10168 if (!items) return; 10169 const currentFragment = document.createDocumentFragment(); 10170 items.filter(item => item.visible !== false && item.fieldType && item[':type']).forEach(item => { 10171 if (Review.isRepeatable(item)) { 10172 const repeatableItems = this.getModel().form.getElement(item.id).getState(); 10173 const repeatablePanel = this.#renderReviewFields(repeatableItems.items); 10174 if (Review.hasChild(repeatablePanel)) { 10175 currentFragment.appendChild(repeatablePanel); 10176 } 10177 } else { 10178 let template = this.templateMappings[item.fieldType] || this.templateMappings['default']; 10179 const cloneNode = template.content.cloneNode(true); 10180 Review.addClassModifier(cloneNode, item); 10181 Review.renderLabel(cloneNode, item); 10182 this.#renderEditButton(cloneNode, item); 10183 if (item.fieldType === Review.FIELD_TYPE.PANEL) { 10184 const fields = this.#renderReviewFields(item.items); 10185 if (Review.hasChild(fields)) { 10186 const labelContainer = cloneNode.querySelector(Review.selectors.labelContainer); 10187 if(item?.label?.visible === false && labelContainer){ 10188 labelContainer.remove(); 10189 } 10190 Review.addAccessibilityAttributes(cloneNode, item); 10191 const contentElement = cloneNode.querySelector(Review.selectors.panelContent); 10192 if(contentElement){ 10193 contentElement.appendChild(fields); 10194 } 10195 currentFragment.appendChild(cloneNode); 10196 } 10197 } else if (!Review.HIDE_FIELD_FROM_REVIEW.includes(item.fieldType) && !item[':type'].endsWith('review')) { 10198 Review.renderValue(cloneNode, item); 10199 Review.addAccessibilityAttributes(cloneNode, item); 10200 currentFragment.appendChild(cloneNode); 10201 } 10202 } 10203 }); 10204 return currentFragment; 10205 } 10206 10207 #getPanels() { 10208 const linkedPanels = this.getModel().properties["fd:linkedPanels"] || []; 10209 if (linkedPanels.length) { 10210 return this.#getLinkedPanels([...linkedPanels]); 10211 } 10212 return this.#getAllPanels(); 10213 } 10214 10215 // return all top lavel panels if author has not linked any panel 10216 #getAllPanels() { 10217 let state = this.getModel().form.getState(); 10218 while (state?.items?.length === 1) { 10219 state = state.items[0]; 10220 } 10221 return state.items || []; 10222 } 10223 10224 // return linked panels if author has linked any panel 10225 #getLinkedPanels(linkedPanels) { 10226 let queue = [], result = []; 10227 let state = this.getModel().form.getState(); 10228 queue.push(state); 10229 while (queue.length && linkedPanels.length) { 10230 const items = Array.isArray(queue[0]) ? queue[0] : [queue[0]]; 10231 items.forEach(item => { 10232 const index = linkedPanels.indexOf(item.name); 10233 if (index > -1) { 10234 result.push(item); 10235 linkedPanels.splice(index, 1); 10236 } 10237 if (item.items) { 10238 queue.push(item.items); 10239 } 10240 }) 10241 queue.shift(); 10242 } 10243 return result; 10244 } 10245 10246 // render edit button of the field 10247 #renderEditButton(cloneNode, item) { 10248 const editButton = cloneNode.querySelector(Review.selectors.editButton); 10249 if (editButton) { 10250 editButton.setAttribute(Review.selectors.fieldId, item.id); 10251 const currentItemLabel = item?.label?.value; 10252 editButton.setAttribute('aria-label', Granite.I18n.get('Edit') + (currentItemLabel ? " " + currentItemLabel : "")); 10253 if (item.enabled === false) { 10254 editButton.setAttribute('disabled', true); 10255 } 10256 editButton.setAttribute(Review.DATA_ATTRIBUTE_VISIBLE, this.#isVisibleEditButton(item.fieldType)); 10257 } 10258 } 10259 #isVisibleEditButton(fieldType) { 10260 let editModeAction = this.getModel().properties?.['fd:editModeAction']; 10261 if (editModeAction === 'both' || 10262 (editModeAction === Review.FIELD_TYPE.PANEL && fieldType === Review.FIELD_TYPE.PANEL) || 10263 (editModeAction === 'field' && fieldType !== Review.FIELD_TYPE.PANEL)) { 10264 return true; 10265 } 10266 return false;
10267 } 10268 } 10269 10270 FormView.Utils.setupField(({ element, formContainer }) => { 10271 return new Review({ element, formContainer }) 10272 }, Review.selectors.self); 10273 10274})(); 10275 10276/******************************************************************************* 10277 * Copyright 2024 Adobe 10278 * 10279 * Licensed under the Apache License, Version 2.0 (the "License"); 10280 * you may not use this file except in compliance with the License. 10281 * You may obtain a copy of the License at 10282 * 10283 * http://www.apache.org/licenses/LICENSE-2.0 10284 * 10285 * Unless required by applicable law or agreed to in writing, software 10286 * distributed under the License is distributed on an "AS IS" BASIS, 10287 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10288 * See the License for the specific language governing permissions and 10289 * limitations under the License. 10290 ******************************************************************************/ 10291(function() { 10292 10293 "use strict"; 10294 class Turnstile extends FormView.FormFieldBase { 10295 10296 static NS = FormView.Constants.NS; 10297 static IS = "adaptiveFormTurnstile"; 10298 static bemBlock = 'cmp-adaptiveform-turnstile'; 10299 static selectors = { 10300 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 10301 widget: `.${Turnstile.bemBlock}__widget`, 10302 label: `.${Turnstile.bemBlock}__label`, 10303 errorDiv: `.${Turnstile.bemBlock}__errormessage` 10304 }; 10305 10306 constructor(params) { 10307 super(params); 10308 } 10309 10310 getWidget() { 10311 return this.element.querySelector(Turnstile.selectors.widget); 10312 } 10313 10314 getDescription() { 10315 return null; 10316 } 10317 10318 getLabel() { 10319 return this.element.querySelector(Turnstile.selectors.label); 10320 } 10321 10322 getTooltipDiv() { 10323 return null; 10324 } 10325 10326 getErrorDiv() { 10327 return this.element.querySelector(Turnstile.selectors.errorDiv); 10328 } 10329 10330 getQuestionMarkDiv() { 10331 return null; 10332 } 10333 10334 initializeWidget() { 10335 this.widgetObject = new TurnstileWidget(this, this._model, this.getWidget()); 10336 this.getWidget().addEventListener('blur', (e) => { 10337 if(this.element) { 10338 this.setInactive(); 10339 } 10340 }); 10341 10342 } 10343 10344 setModel(model) { 10345 super.setModel(model); 10346 if (this.widgetObject == null) { 10347 this.initializeWidget(); 10348 } else { 10349 if (this.widget.value !== '') { 10350 this._model.dispatch(new FormView.Actions.UIChange({'value': this.widget.value})); 10351 } 10352 } 10353 } 10354 } 10355 10356 FormView.Utils.setupField(({element, formContainer}) => { 10357 return new Turnstile({element, formContainer}) 10358 }, Turnstile.selectors.self); 10359 10360})(); 10361 10362/******************************************************************************* 10363 * Copyright 2024 Adobe 10364 * 10365 * Licensed under the Apache License, Version 2.0 (the "License"); 10366 * you may not use this file except in compliance with the License. 10367 * You may obtain a copy of the License at 10368 * 10369 * http://www.apache.org/licenses/LICENSE-2.0 10370 * 10371 * Unless required by applicable law or agreed to in writing, software 10372 * distributed under the License is distributed on an "AS IS" BASIS, 10373 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10374 * See the License for the specific language governing permissions and 10375 * limitations under the License. 10376 ******************************************************************************/ 10377 10378/** 10379 * This class is responsible for interacting with the turnstile widget. It displays turnstile challenge. 10380 */ 10381 10382if (typeof window.TurnstileWidget === 'undefined') { 10383 window.TurnstileWidget = class { 10384 #widget = null 10385 #model = null // passed by reference 10386 #options = null 10387 #lang = 'en' 10388 static FD_CAPTCHA = "fd:captcha"; 10389 10390 constructor(view, model, widget) { 10391 // initialize the widget and model 10392 this.#widget = widget; 10393 this.#model = model; 10394 this.#widget = document.createElement("div"); 10395 this.#widget.classList.add("cmp-adaptiveform-turnstile__widget"); 10396 this.#lang = view.formContainer.getModel().lang; 10397 10398 //Always inserting it in body 10399 document.body.appendChild(this.#widget); 10400 this.#options = Object.assign({}, this.#model._jsonModel); 10401 10402 this.#renderTurnstile(widget); 10403 } 10404 10405 #renderTurnstile(turnstileContainer) { 10406 10407 const self = this; 10408 const turnstileConfigData = this.#options; 10409 let widgetId; 10410 const url = turnstileConfigData.properties[TurnstileWidget.FD_CAPTCHA].config.uri; 10411 10412 const successCallback = function(response) { 10413 self.setCaptchaModel(response); 10414 }; 10415 10416 const expiredCallback = function() { 10417 turnstile.reset(widgetId); 10418 self.setCaptchaModel(""); 10419 }; 10420 10421 const onloadCallbackInternal = function() { 10422 widgetId = turnstile.render( 10423 turnstileContainer, 10424 turnstileParameters 10425 ); 10426 return widgetId; 10427 }; 10428 10429 const turnstileParameters = { 10430 'sitekey': this.#model.captchaSiteKey, 10431 'size': turnstileConfigData.properties[TurnstileWidget.FD_CAPTCHA].config.size, 10432 'theme': turnstileConfigData.properties[TurnstileWidget.FD_CAPTCHA].config.theme || 'light', 10433 'callback': successCallback, 10434 'expired-callback': expiredCallback, 10435 'language': this.#lang 10436 }; 10437 10438 window.onloadTurnstileCallback = onloadCallbackInternal; 10439 const scr = document.createElement('script'); 10440 const queryParams = (this.#model.captchaDisplayMode === 'invisible') 10441 ? "?render=explicit" 10442 : "?onload=onloadTurnstileCallback&render=explicit"; 10443 scr.src = url + queryParams; 10444 scr.async = true; 10445 turnstileContainer.appendChild(scr); 10446 } 10447 10448 setCaptchaModel(response) { 10449 this.#model.dispatch(new FormView.Actions.UIChange({'value': response})); 10450 } 10451 } 10452} 10453 10454/******************************************************************************* 10455 * Copyright 2025 Adobe 10456 * 10457 * Licensed under the Apache License, Version 2.0 (the "License");
10458 * you may not use this file except in compliance with the License. 10459 * You may obtain a copy of the License at 10460 * 10461 * http://www.apache.org/licenses/LICENSE-2.0 10462 * 10463 * Unless required by applicable law or agreed to in writing, software 10464 * distributed under the License is distributed on an "AS IS" BASIS, 10465 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10466 * See the License for the specific language governing permissions and 10467 * limitations under the License. 10468 ******************************************************************************/ 10469(function() { 10470 10471 "use strict"; 10472 class Datetime extends FormView.FormFieldBase { 10473 10474 static NS = FormView.Constants.NS; 10475 /** 10476 * Each FormField has a data attribute class that is prefixed along with the global namespace to 10477 * distinguish between them. If a component wants to put a data-attribute X, the attribute in HTML would be 10478 * data-{NS}-{IS}-x="" 10479 * @type {string} 10480 */ 10481 static IS = "adaptiveFormDatetime"; 10482 static bemBlock = 'cmp-adaptiveform-datetime' 10483 static selectors = { 10484 self: "[data-" + this.NS + '-is="' + this.IS + '"]', 10485 widget: `.${Datetime.bemBlock}__widget`, 10486 label: `.${Datetime.bemBlock}__label`, 10487 description: `.${Datetime.bemBlock}__longdescription`, 10488 qm: `.${Datetime.bemBlock}__questionmark`, 10489 errorDiv: `.${Datetime.bemBlock}__errormessage`, 10490 tooltipDiv: `.${Datetime.bemBlock}__shortdescription`, 10491 eyeIcon: `.${Datetime.bemBlock}__eyeicon` 10492 }; 10493 10494 constructor(params) { 10495 super(params); 10496 } 10497 10498 getWidget() { 10499 return this.element.querySelector(Datetime.selectors.widget); 10500 } 10501 10502 getDescription() { 10503 return this.element.querySelector(Datetime.selectors.description); 10504 } 10505 10506 getLabel() { 10507 return this.element.querySelector(Datetime.selectors.label); 10508 } 10509 10510 getErrorDiv() { 10511 return this.element.querySelector(Datetime.selectors.errorDiv); 10512 } 10513 10514 getTooltipDiv() { 10515 return this.element.querySelector(Datetime.selectors.tooltipDiv); 10516 } 10517 10518 getQuestionMarkDiv() { 10519 return this.element.querySelector(Datetime.selectors.qm); 10520 } 10521 10522 setModel(model) { 10523 super.setModel(model); 10524 if (this.widget.value !== '') { 10525 this._model.value = this.widget.value; 10526 } 10527 this.widget.addEventListener('blur', (e) => { 10528 this._model.value = e.target.value; 10529 this.setInactive(); 10530 }); 10531 this.widget.addEventListener('focus', (e) => { 10532 this.setActive(); 10533 }); 10534 } 10535 10536 } 10537 10538 FormView.Utils.setupField(({element, formContainer}) => { 10539 return new Datetime({element, formContainer}) 10540 }, Datetime.selectors.self); 10541 10542})();
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.