powerpagestoolkit
Version:
Reference, manipulate, and engage with Power Pages sites through the nodes in the DOM; use a variety of custom methods that allow customizing your power pages site quicker and easier.
12 lines (9 loc) • 35.9 kB
JavaScript
/* @ts-self-types="./index.d.ts" */
function g(r){let e=$.Deferred();return shell.getTokenDeferred().done(function(t){r.headers?r.headers.__RequestVerificationToken=t:$.extend(r,{headers:{__RequestVerificationToken:t}}),$.ajax(r).done(function(i,s,n){validateLoginSession(i,s,n,e.resolve)}).fail(e.reject)}).fail(function(){e.rejectWith(this,arguments)}),e.promise()}var V=class{static createRecord(e,t){return new Promise((i,s)=>{g({type:"POST",url:`/_api/${e}`,data:JSON.stringify(t),contentType:"application/json",success:function(n,o,a){i(a.getResponseHeader("entityid"))},error:n=>{s(n)}})})}static getRecord(e,t,i){let s="";return i&&(s=i.startsWith("?")?i.slice(1,i.length):"?"+i),new Promise((n,o)=>{let a=`/_api/${e}(${t})${s}`;g({type:"GET",url:a,success:n,error:o})})}static request(e,t){return new Promise((i,s)=>{let n=`/_api/${e}`;g({url:n,success:i,error:s,...t})})}static getMultiple(e,t){let i="";return t&&(i=t.startsWith("?")?t.slice(1,t.length):"?"+t),new Promise((s,n)=>{let o=`/_api/${e}${i}`;g({type:"GET",url:o,success:function(a){s(a.value)},error:n})})}static updateRecord(e,t,i){return new Promise((s,n)=>{let o=`/_api/${e}(${t})`;g({type:"PATCH",url:o,data:JSON.stringify(i),success:s,error:n})})}},H=V;var b=class{defaultVisibility;set defaultDisplay(e){this.defaultVisibility=e}constructor(e){if(this.visibilityController=e,e.tagName==="TABLE"){let i=e.closest("fieldset");i&&(this.visibilityController=i)}if(["SPAN","INPUT","TEXTAREA","SELECT","TABLE"].includes(e.tagName)){let i=e.closest("td");i&&(this.visibilityController=i)}this.defaultVisibility=this.visibilityController.style.display}hide(){this.visibilityController.style.display="none"}show(){this.visibilityController.style.display=this.defaultVisibility}toggleVisibility(e){e?this.show():this.hide()}getVisibility(){return window.getComputedStyle(this.visibilityController).display!=="none"&&window.getComputedStyle(this.visibilityController).visibility!=="hidden"&&this.visibilityController.getBoundingClientRect().height>0&&this.visibilityController.getBoundingClientRect().width>0}destroy(){this.visibilityController=null,this.defaultVisibility=null}};var x={CHECKBOX:"click",RADIO:"click",SELECT:"change",TEXT:"keyup",DEFAULT:"input"};var h=Symbol("init"),p=Symbol("destroy");var v=class extends HTMLElement{flyoutContent;icon;observers=[];constructor(e,t){if(super(),typeof e!="string")throw new Error(`argument "titleString" must be of type "string". Received: "${typeof e}"`);if(t&&typeof t!="object")throw new Error(`argument "iconStyle" must be of type "object". Received: "${typeof t}"`);this.classList.add("info-icon"),this.icon=document.createElement("i"),this.icon.classList.add("fa","fa-solid","fa-info-circle"),this.icon.setAttribute("aria-label","Info"),this.icon.style.cursor="pointer",this.flyoutContent=document.createElement("div"),this.flyoutContent.innerHTML=e,this.flyoutContent.classList.add("flyout-content"),this.appendChild(this.icon),this.appendChild(this.flyoutContent),t&&Object.assign(this.icon.style,t),this.handleClick=this.handleClick.bind(this),this.handleResize=this.handleResize.bind(this),this.handleTouchStart=this.handleTouchStart.bind(this),this.handleMouseEnter=this.handleMouseEnter.bind(this),this.handleMouseLeave=this.handleMouseLeave.bind(this),this.handleScroll=this.handleScroll.bind(this),this.flyoutContent.style.minWidth=this.getDesiredWidth().min,this.flyoutContent.style.display="none",this.attachEventListeners(),this.setupObservers()}attachEventListeners(){document.body.addEventListener("click",this.handleClick),self.addEventListener("resize",this.handleResize),this.icon.addEventListener("touchstart",this.handleTouchStart),this.addEventListener("mouseenter",this.handleMouseEnter),this.addEventListener("mouseleave",this.handleMouseLeave),self.addEventListener("scroll",this.handleScroll)}setupObservers(){let e=new MutationObserver(i=>{for(let s of i)for(let n of Array.from(s.removedNodes))if(n===this){this.destroy();return}});e.observe(document,{childList:!0,subtree:!0,attributes:!1});let t=new MutationObserver(()=>this.updateFlyoutWidth);t.observe(document,{childList:!0,subtree:!0,attributes:!1}),this.observers.push(e,t)}getDesiredWidth(){let e=self.innerWidth,t=Math.min(e-40,200);return{min:`${Math.min(e-40,600)}px`,max:`${t}px`}}positionFlyout(){this.flyoutContent.style.display="block";let e=this.icon.getBoundingClientRect(),t=this.flyoutContent.getBoundingClientRect(),i=self.innerWidth,s=self.innerHeight,o=e.bottom-5;if(o+t.height>s&&(o=e.top-t.height),this.flyoutContent.style.top=`${o}px`,i<=500)this.flyoutContent.style.left="50%",this.flyoutContent.style.transform="translateX(-50%)";else{let a=e.left;this.flyoutContent.style.left=`${a}px`,this.flyoutContent.style.transform="none"}}updateFlyoutWidth(){this.flyoutContent.style.minWidth=this.getDesiredWidth().min,this.flyoutContent.style.minWidth=this.getDesiredWidth().max}handleClick(e){this.contains(e.target)||(this.flyoutContent.style.display="none")}handleResize(e){this.flyoutContent.style.minWidth=this.getDesiredWidth().min,this.flyoutContent.style.minWidth=this.getDesiredWidth().max}handleTouchStart(){this.flyoutContent.style.display=this.flyoutContent.style.display==="block"?"none":"block",this.flyoutContent.style.display==="block"&&this.positionFlyout()}handleMouseEnter(e){this.positionFlyout()}handleMouseLeave(e){let t=e.relatedTarget;this.contains(t)||(this.flyoutContent.style.display="none")}handleScroll(){let e=this.flyoutContent.style.display;e!=="none"&&(this.positionFlyout(),this.flyoutContent.style.display=e)}destroy(){document.body.removeEventListener("click",this.handleClick),self.removeEventListener("resize",this.handleResize),this.icon.removeEventListener("touchstart",this.handleTouchStart),this.removeEventListener("mouseenter",this.handleMouseEnter),this.removeEventListener("mouseleave",this.handleMouseLeave),self.removeEventListener("scroll",this.handleScroll),this.observers.forEach(e=>e.disconnect())}},X=`info-icon-${crypto.randomUUID()}`;customElements.define(X,v);function E(r,e=document,t=!1,i){return new Promise((s,n)=>{if(t){let o,a=[],l=new Set;if(i<1)return s(Array.from(e.querySelectorAll(r)));let c=new MutationObserver(()=>{Array.from(e.querySelectorAll(r)).forEach(S=>{l.has(S)||(l.add(S),a.push(S))}),clearTimeout(o),o=setTimeout(()=>{a.length>0?(c.disconnect(),s(a)):n(new Error(`No elements found with target: "${r}" within ${i/1e3} seconds. If the element you are expecting has not loaded yet, consider raising your timeout.`))},i)});c.observe(e,{childList:!0,subtree:!0,attributes:!1})}else{let o=new MutationObserver(()=>{let c=e.querySelector(r);c&&(clearTimeout(a),o.disconnect(),s(c))}),a=setTimeout(()=>{o.disconnect(),n(new Error(`Element not found by target: "${r}" within ${i/1e3} second. If the element you are expecting has not loaded yet, consider raising your timeout.`))},i),l=e.querySelector(r);if(l)return clearTimeout(a),s(l);o.observe(e,{subtree:!0,attributes:!0,childList:!0})}})}var m=class extends Error{node;constructor(e,t){super(t),this.node=e,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},k=class extends m{constructor(e,t){super(e,`There was an error initializing a DOMNodeReference for target: ${e.target}, :: ${t}`)}},I=class extends m{constructor(e){super(e,`The targeted DOM element was not found: ${e.target}`)}},F=class extends m{constructor(e){super(e,"Page_Validators could not be found")}},A=class extends m{constructor(e){super(e,`Error applying business rule to target: ${e.target}`)}},_=class extends m{constructor(e){super(e,"Self-referential dependency found. A DOMNodeReference cannot depend on itself")}},B=class extends m{constructor(e){super(e,`No label could be found for the target: ${e.target}`)}},q=class extends m{constructor(e,t,i,s,n){let o=s.join(" or ");super(e,`${t} expects ${i} to be of type ${o}. Received: ${n===null?"null":typeof n}`)}},G={NodeNotFoundError:I,InitializationError:k,Page_ValidatorsNotFoundError:F,BusinessRuleError:A,SelfReferenceError:_,LabelNotFoundError:B,IncorrectParameterError:q},u=G;import W from"DOMPurify";var f=class r{static instances=[];target;logicalName;root;timeoutMs;isLoaded;changeEmitter;get value(){return this.valueManager.value}set value(e){this.valueManager.setValue(e)}get checked(){return this.valueManager.checked}set defaultDisplay(e){this.visibilityManager.defaultDisplay=e}visibilityManager;valueManager;eventManager;constructor(e,t=document.body,i){this.target=e,this.logicalName=this._extractLogicalName(e),this.root=t,this.timeoutMs=i,this.isLoaded=!1}async[h](){if(this.target instanceof HTMLElement?this.element=this.target:this.element=await E(this.target,this.root,!1,this.timeoutMs),!this.element)throw new u.NodeNotFoundError(this)}_extractLogicalName(e){if(typeof e!="string")return"";let t=e.match(/\[([^\]]+)\]/);if(!t)return e.replace(/[#\[\]]/g,"");let i=t[1];return(i.match(/["']([^"']+)["']/)?.[1]||i).replace(/[#\[\]]/g,"")}_valueSync(){if(!this._isValidFormElement(this.element))return;this.updateValue();let e=this._determineEventType();this.eventManager.registerDOMEventListener(this.changeEmitter,e,this.updateValue.bind(this)),this._isDateInput()&&this._dateSync(this.element)}containsMultiSelectClass(){return Array.from(this.element.parentElement.querySelectorAll("*")).some(e=>Array.from(e.classList).some(t=>t.toLowerCase().includes("multiselect")))}_initChangeEmitter(){let e=this.element.parentElement;if(e){let t=Array.from(e.children).find(i=>i.id?.toLowerCase().startsWith("pcfcontrol"));this.changeEmitter=t??this.element}else this.changeEmitter=this.element}_determineEventType(){return this.containsMultiSelectClass()||this.element instanceof HTMLSelectElement?"change":this.element instanceof HTMLTextAreaElement?"keyup":this.element instanceof HTMLInputElement?x[this.element.type.toUpperCase()]||x.DEFAULT:x.DEFAULT}_isDateInput(){return this.element instanceof HTMLInputElement&&this.element.dataset.type==="date"}_isValidFormElement(e){return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSpanElement||e instanceof HTMLButtonElement||e instanceof HTMLFieldSetElement}async _dateSync(e){let t=e.parentElement;if(!t)throw new DOMException("Date input must have a parent element");let i=await E("[data-date-format]",t,!1,1500);this.valueManager.element=i,this.eventManager.registerDOMEventListener(i,"select",this.updateValue.bind(this))}_bindMethods(){let e=Object.getPrototypeOf(this);for(let t of Object.getOwnPropertyNames(e)){let i=this[t];t!=="constructor"&&typeof i=="function"&&(this[t]=i.bind(this))}}[p](){this.isLoaded=!1,this.value=null,this.eventManager.destroy(),this.eventManager=null,this.visibilityManager.destroy(),this.visibilityManager=null,this.valueManager.destroy(),this.valueManager=null}async updateValue(e){e&&!e.isTrusted||(await this.valueManager.updateValue(e),this.triggerDependentsHandlers())}triggerDependentsHandlers(){this.eventManager.dispatchDependencyHandlers()}on(e,t){if(typeof t!="function")throw new u.IncorrectParameterError(this,"on","eventHandler",["function"],typeof t);let i=t;return this.eventManager.registerDOMEventListener(this.changeEmitter,e,i.bind(this)),this}hide(){return this.visibilityManager.hide(),this}show(){return this.visibilityManager.show(),this}toggleVisibility(e){let t=e instanceof Function?e.call(this):e;return this.visibilityManager.toggleVisibility(t),this}setValue(e){return e instanceof Function&&(e=e()),this.valueManager.setValue(e),this}disable(){return this.element.disabled=!0,this}clearValue(){this.valueManager.clearValue(),this._getChildren()&&this.callAgainstChildrenInputs(e=>e.clearValue())}_getChildren(){let t=Array.from(this.element.querySelectorAll("input, select, textarea")).map(s=>s.id),i=r.instances.filter(s=>t.includes(s.element.id));return i.length>0?i:null}callAgainstChildrenInputs(e){let t=this._getChildren();if(!t){console.error("No child inputs found for target: ",this);return}for(let i of t)e(i)}enable(){return this.element.disabled=!1,this}prepend(...e){return this.element.prepend(...e),this}append(...e){return this.element.append(...e),this}before(...e){return this.element.before(...e),this}after(...e){return this.element.after(...e),this}getLabel(){let e=document.querySelector(`#${this.element.id}_label`)||null;if(!e)throw new u.LabelNotFoundError(this);return e}addLabelTooltip(e,t){let i=W.sanitize(e);return this.getLabel()?.append(new v(i,t||void 0)),this}addTooltip(e,t){let i=W.sanitize(e);return this.append(new v(i,t||void 0)),this}set innerHTML(e){let t=W.sanitize(e);this.element.innerHTML=t}remove(){return this.element.remove(),this}setStyle(e){if(e===null||typeof e!="object")throw new u.IncorrectParameterError(this,"setStyle","options",["Partial<CSSStyleDeclaration>"],typeof e);return Object.entries(e).forEach(([t,i])=>{i!==void 0&&(this.element.style[t]=i)}),this}applyBusinessRule(e,t){try{e.setRequirements&&this._setupRequirementsValidator(e.setRequirements());let i=this._createBusinessRuleHandler(e);return i(),t.length&&this._configureDependencyTracking(i,t),this}catch(i){throw i instanceof Error?i:new u.BusinessRuleError(this)}}_setupRequirementsValidator(e){let{isRequired:t,isValid:i}=e;if(typeof Page_Validators>"u")throw new u.Page_ValidatorsNotFoundError(this);let s=()=>!0;t&&i?s=()=>{let n=t.call(this),o=this.visibilityManager.getVisibility();return!n||o&&i.call(this,n)}:i?s=()=>this.visibilityManager.getVisibility()&&i.call(this,!1):t&&(s=()=>this.visibilityManager.getVisibility()&&t.call(this)),this._createValidator(s)}_createBusinessRuleHandler(e){return()=>{let t=!1;if(e.setVisibility){let s=e.setVisibility.call(this);t=!s,this.toggleVisibility(s)}if(e.setRequirements&&e.setRequirements().isRequired){let{isRequired:i}=e.setRequirements();this.setRequiredLevel(i.call(this))}if(e.setValue){let{condition:i,value:s}=e.setValue();if(i.call(this)){let n=s instanceof Function?s():s;this.setValue.call(this,n)}}e.setDisabled&&(e.setDisabled.call(this)?this.disable():this.enable()),t&&!e.setValue&&this.clearValue(),this.triggerDependentsHandlers()}}_createValidator(e){let t=(()=>{let n=this.getLabel();if(!n)throw new u.LabelNotFoundError(this);return n=n.innerHTML,n.length>50&&(n=n.substring(0,50)+"..."),n})(),i=`${this.element.id}Validator`,s=document.createElement("span");if(s.style.display="none",s.id=i,Object.assign(s,{controltovalidate:this.element.id,errormessage:`<a href='#${this.element.id}_label'>${t} is a required field</a>`,evaluationfunction:e.bind(this)}),Page_Validators==null)throw new u.Page_ValidatorsNotFoundError(this);Page_Validators.push(s)}_configureDependencyTracking(e,t){if(t.length<1){console.error(`powerpagestoolkit: No dependencies specified for ${this.element.id}. Include all required nodes in the dependency array for proper tracking.`);return}t.forEach(i=>{if(!i||!(i instanceof r))throw new TypeError("Each dependency must be a valid DOMNodeReference instance");if(i.logicalName===this.logicalName)throw new u.SelfReferenceError(this);i.eventManager.registerDependent(this,e.bind(this))})}setRequiredLevel(e){return e instanceof Function?(e.call(this)?this.getLabel()?.classList.add("required-field"):this.getLabel()?.classList.remove("required-field"),this):(e?this.getLabel()?.classList.add("required-field"):this.getLabel()?.classList.remove("required-field"),this)}onceLoaded(e){if(this.isLoaded){e(this);return}if(this.target instanceof HTMLElement){e(this);return}let t=new MutationObserver(function(){document.querySelector(this.target)&&(t.disconnect(),this.isLoaded=!0,e(this))}.bind(this));this.eventManager.registerObserver(t,{nodeToObserve:document.body,options:{subtree:!0,childList:!0}})}};var M=class{constructor(){}onFocus(){setTimeout(()=>this.input.select(),0)}onBlur(){this.formatInput()}setValue(e){this.input.value=String(e)}};var R=class extends M{input;options;constructor(e,t={}){super(),this.input=e,this.options={format:t.format||"(xxx) xxx-xxxx",countryCode:t.countryCode||"",countryCodeFormat:t.countryCodeFormat||"+"},this.onFocus=this.onFocus.bind(this),this.formatInput=this.formatInput.bind(this),this.onBlur=this.onBlur.bind(this),this.setupEventListeners(),setTimeout(()=>{this.formatInput()},0)}setupEventListeners(){this.input.addEventListener("focus",this.onFocus),this.input.addEventListener("input",this.formatInput),this.input.addEventListener("blur",this.onBlur)}formatInput(){let e=this.input.value,t=this.input.selectionStart||0,i=e.length,s=e.replace(/\D/g,""),n=this.formatPhoneNumber(s);this.input.value=n;let o=Math.min(t+(n.length-i),n.length);this.input.setSelectionRange(o,o)}formatPhoneNumber(e){if(!e)return"";let t=e,i="";if(this.options.countryCode){let l=this.options.countryCode.length;e.length>l?(i=e.substring(0,l),t=e.substring(l)):(i=e,t="")}let s="";if(i)switch(this.options.countryCodeFormat){case"+":s=`+${i} `;break;case"()":s=`(${i}) `;break;case"00":s=`00${i} `;break;default:s=`+${i} `}let n=this.options.format,o=0;for(let l=0;l<n.length&&o<t.length;l++)n[l]==="x"&&(n=n.substring(0,l)+t[o++]+n.substring(l+1));n=n.replace(/x/g,"");let a=n.split("").findIndex((l,c)=>!/\d/.test(l)&&n.substring(c).indexOf("x")===-1&&n.substring(c).replace(/[\s\-()]/g,"").length===0);return a!==-1&&(n=n.substring(0,a)),s+n}onFocus(){setTimeout(()=>this.input.select(),0)}onBlur(){this.formatInput();let e=this.getDigits(),t=this.options.countryCode?7+this.options.countryCode.length:7;e.length<t}getDigits(){return this.input.value.replace(/\D/g,"")}getCountryCode(){if(!this.options.countryCode)return"";let e=this.getDigits(),t=this.options.countryCode.length;return e.length>=t?e.substring(0,t):e}getPhoneDigits(){if(!this.options.countryCode)return this.getDigits();let e=this.getDigits(),t=this.options.countryCode.length;return e.length>t?e.substring(t):""}setValue(e){let t=e.replace(/\D/g,"");this.input.value=this.formatPhoneNumber(t)}isValid(){let e=this.getPhoneDigits(),t=this.getCountryCode();return(!this.options.countryCode||t.length===this.options.countryCode.length)&&e.length>=10}destroy(){this.input.removeEventListener("focus",this.onFocus),this.input.removeEventListener("input",this.formatInput),this.input.removeEventListener("blur",this.onBlur)}};var w=class{events=new Map;listeners=new Map;dependencyHandlers=new Set;observers=[];boundListeners=[];constructor(){}dispatchDependencyHandlers(){for(let[e,t]of this.dependencyHandlers)t.call(e)}registerDependent(e,t){try{return this.dependencyHandlers.add([e,t]),"success"}catch{return new Error(`Failed register dependant: ${e.target}`)}}registerEvent(e,t){return this.events.has(e)?(console.error("Event registration has already been defined for: ",e),new Error(`Event registration has already been defined for: ${e}`)):(this.listeners.set(e,new Set),this.events.set(e,t),"success")}registerListener(e,t){if(this.events.has(e)){let i=this.listeners.get(e)??new Set;return i.add(t),this.listeners.set(e,i),"success"}else return console.error("No event registration found for: ",e),new Error(`No event registration found for: ${e}`)}emit(e,...t){if(this.events.has(e)){let i=this.events.get(e),s=this.listeners.get(e);if(!s)return;for(let n of s)i.call(n,...t)}else console.error("Event not found in EventRegistry: ",e)}stopListening(e){for(let[t,i]of this.listeners)i.has(e)&&i.delete(e)}registerObserver(e,t){let{nodeToObserve:i,options:s}=t;e.observe(i,s),this.observers.push(e)}registerDOMEventListener(e,t,i){e.addEventListener(t,i),this.boundListeners.push({element:e,handler:i,event:t})}destroy(){this.boundListeners?.forEach(e=>{e.element?.removeEventListener(e.event,e.handler)}),this.boundListeners=[],this.observers?.forEach(e=>{e.disconnect()}),this.observers=[],this.events.clear(),this.dependencyHandlers.clear(),this.listeners.clear()}};function z(r){if(r==null||r.length<1)return null;let e=JSON.parse(r),t=[];return e.forEach(i=>{i.Value&&t.push(i.Value)}),t.join(",")}var d=class extends f{radioType;constructor(e,t,i=document.body,s,n){super(t,i,s),this.radioParent=e,this.radioType=n}async[h](){try{await super[h](),super._initChangeEmitter(),this.initEventManager(),this.initVisibilityManager(),this.initValueManager(),this._bindMethods();let e=new MutationObserver(t=>{for(let i of t)if(Array.from(i.removedNodes).includes(this.element)){this[p](),e.disconnect();break}});e.observe(document.body,{childList:!0,subtree:!0}),f.instances.push(this),this.isLoaded=!0}catch(e){let t=e instanceof Error?e.message:String(e);throw new u.InitializationError(this,t)}}initEventManager(){this.eventManager=new w}initValueManager(){this.valueManager=new L(this),this._valueSync()}initVisibilityManager(){this.visibilityManager=new b(this.element)}[p](){super[p](),this.radioParent=void 0,this.radioType=void 0}};var L=class{value;checked=!1;element;noRadio;yesRadio;radioParent;isRadio=!1;radioType;constructor(e){e instanceof y?(this.noRadio=e.noRadio,this.yesRadio=e.yesRadio,this.radioParent=void 0):e instanceof d&&(this.isRadio=!0,this.noRadio=void 0,this.yesRadio=void 0,this.radioParent=e.radioParent,this.radioType=e.radioType),this.element=e.element}setValue(e){let t=this._validateValue(e);if(this.yesRadio instanceof d&&this.noRadio instanceof d)if(typeof e=="string"){let i=e.toLowerCase();["true","yes","truthy"].includes(i)?(this.yesRadio.element.checked=!0,this.noRadio.element.checked=!1,this.value=!0):["false","no","falsy"].includes(i)&&(this.yesRadio.element.checked=!1,this.noRadio.element.checked=!0,this.value=!1)}else typeof e=="boolean"&&(this.yesRadio.element.checked=!!e,this.noRadio.element.checked=!e,this.value=e);else this.isRadio||this.element.type==="radio"?(this.element.checked=e,this.checked=e,this.value=e,this.radioParent?.updateValue()):(this.element.value=t,this.value=t)}async updateValue(e){e&&e.stopPropagation();let t=await this.getElementValue();if(this.value=t.value,t.checked!==void 0&&(this.checked=t.checked),this.radioParent instanceof y&&e&&e.type!=="manual-radio-sync"){switch(this.radioType){case"falsy":this.radioParent.yesRadio.setValue(!t),await this.radioParent.yesRadio.updateValue(new Event("manual-radio-sync"));break;case"truthy":this.radioParent.noRadio.setValue(!t),await this.radioParent.noRadio.updateValue(new Event("manual-radio-sync"));break}this.radioParent.updateValue()}}containsMultiSelectClass(){return Array.from(this.element.parentElement.querySelectorAll("*")).some(e=>Array.from(e.classList).some(t=>t.toLowerCase().includes("multiselect")))}delay(e){return new Promise(t=>setTimeout(t,e))}async getElementValue(){let e=this.element,t=this.element;if(this.yesRadio instanceof d&&this.noRadio instanceof d)return{value:this.yesRadio.checked,checked:this.yesRadio.checked};if(this.containsMultiSelectClass())return await this.delay(500),{value:z(e.value)};let i={value:null};switch(e.type){case"checkbox":case"radio":return{value:e.checked,checked:e.checked};case"select-multiple":return{value:Array.from(t.selectedOptions).map(s=>s.value)};case"select-one":return{value:t.value};case"number":return{value:e.value!==""?Number(e.value):null};default:{let s=e.value;this.element.classList.contains("decimal")&&(s=parseFloat(e.value.replace(/[$,]/g,"").trim())),i={value:s}}}return i={...i,value:this._validateValue(i.value)},i}_validateValue(e){return typeof e=="boolean"||e==="true"||e==="false"?e===!0||e==="true":this.element instanceof HTMLSelectElement||this.element.type==="text"&&!this.element.classList.contains("decimal")||e===null||e===""||isNaN(Number(e))?e:Number(e)}clearValue(){try{let e=this.element;if(e instanceof HTMLInputElement)switch(e.type.toLowerCase()){case"checkbox":case"radio":e.checked=!1,this.checked=!1,this.value=!1;break;case"number":e.value="",this.value=null;break;default:e.value="",this.value=null;break}else e instanceof HTMLSelectElement?e.multiple?(Array.from(e.options).forEach(t=>t.selected=!1),this.value=null):(e.selectedIndex=-1,this.value=null):e instanceof HTMLTextAreaElement?(e.value="",this.value=null):this.value=null}catch(e){let t=`Failed to clear values for element with target "${this}": ${e instanceof Error?e.message:String(e)}`;throw new Error(t)}}destroy(){this.value=null,this.checked=!1,this.element=null,this.noRadio=void 0,this.yesRadio=void 0,this.isRadio=!1}};var P=class extends M{input;options;buffer="";charAtSelection="";charBeforeSelection="";lengthOf0FormattedValue;digitRegex=/\d/;nonDigitRegex=/\D/g;thousandsRegex=/\B(?=(\d{3})+(?!\d))/g;separatorRegex;constructor(e,t={}){super(),this.input=e,this.options={prefix:t.prefix||"$",decimalPlaces:t.decimalPlaces??2,thousandsSeparator:t.thousandsSeparator||",",decimalSeparator:t.decimalSeparator||".",allowNegative:t.allowNegative??!0};let i=this.escapeRegExp(this.options.thousandsSeparator),s=this.escapeRegExp(this.options.decimalSeparator);this.separatorRegex=new RegExp(`[${i}${s}]`),this.onFocus=this.onFocus.bind(this),this.onInput=this.onInput.bind(this),this.onSelectionChange=this.onSelectionChange.bind(this),this.onBlur=this.onBlur.bind(this),this.lengthOf0FormattedValue=`0${this.options.decimalPlaces>0?this.options.decimalSeparator+"0".repeat(this.options.decimalPlaces):""}`.length,this.setupEventListeners(),this.input.value&&(this.buffer=this.input.value.replace(this.nonDigitRegex,"")),this.formatAndDisplay()}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}formatAndDisplay(){let e=Number(this.buffer||"0");this.input.value=this.formatNumber(e)}setupEventListeners(){this.input.addEventListener("focus",this.onFocus),this.input.addEventListener("input",this.onInput),this.input.addEventListener("selectionchange",this.onSelectionChange),this.input.addEventListener("blur",this.onBlur)}formatInput(){let e=this.input.value,t=this.input.selectionStart||0,i=e.length,s=new RegExp(`[^0-9${this.options.decimalSeparator}${this.options.allowNegative?"-":""}]`,"g"),n=e.replace(s,""),o=n.split(this.options.decimalSeparator);o.length>2&&(n=o[0]+this.options.decimalSeparator+o.slice(1).join("")),this.options.allowNegative&&n.indexOf("-")>0&&(n=n.replace(/-/g,""),n.charAt(0)!=="-"&&(n="-"+n));let a;n===""||n==="-"?a=0:a=parseFloat(n.replace(this.options.decimalSeparator,".")),isNaN(a)&&(a=0);let l=this.formatNumber(a);this.input.value=l;let c=t+(l.length-i);this.input.setSelectionRange(c,c)}formatNumber(e){let t=e/10**this.options.decimalPlaces,i=t<0,n=Math.abs(t).toFixed(this.options.decimalPlaces),[o,a]=n.split("."),l=o.replace(this.thousandsRegex,this.options.thousandsSeparator);return(i?"-":"")+this.options.prefix+l+(this.options.decimalPlaces>0?this.options.decimalSeparator+a:"")}onSelectionChange(e){let t=this.input.selectionStart;this.charAtSelection=this.input.value[t],this.charBeforeSelection=this.input.value[t-1]}onInput(e){let t=e,i=this.input.value,s=this.input.selectionStart??0,n=i.slice(0,s).replace(this.nonDigitRegex,"").length,o=n;switch(t.inputType){case"insertText":this.buffer=this.buffer.slice(0,n-1)+(t.data||"").replace(this.nonDigitRegex,"")+this.buffer.slice(n-1),o=n;break;case"deleteContentBackward":n>=0?this.separatorRegex.test(this.charBeforeSelection)?(this.buffer=this.buffer.slice(0,n-1)+this.buffer.slice(n),o=n-1):(this.buffer=this.buffer.slice(0,n)+this.buffer.slice(n+1),o=n):i===""&&(this.buffer="");break;case"deleteContentForward":n<this.buffer.length&&(this.buffer=this.buffer.slice(0,n)+this.buffer.slice(n+1));break;case"deleteWordBackward":case"deleteWordForward":this.buffer="",o=this.lengthOf0FormattedValue;break;default:this.buffer=i.replace(this.nonDigitRegex,""),o=this.buffer.length}let a=Number(this.buffer||"0"),l=this.formatNumber(a);this.input.value=l;let c=this.mapRawIndexToFormattedPosition(o,l);this.input.setSelectionRange(c,c)}mapRawIndexToFormattedPosition(e,t){let i=0;for(let s=0;s<t.length;s++)if(this.digitRegex.test(t[s])&&i++,i===e)return s+1;return t.length}onFocus(){setTimeout(()=>this.input.select(),0)}onBlur(){let e=Number(this.buffer||"0");if(this.input.value=this.formatNumber(e),e===0){this.buffer="";let t="0".repeat(this.options.decimalPlaces);this.input.value=`${this.options.prefix}0${this.options.decimalPlaces>0?this.options.decimalSeparator+t:""}`}}getNumericalValue(){return Number(this.buffer||"0")/10**this.options.decimalPlaces}setValue(e){let t=Math.round(Math.abs(e)*10**this.options.decimalPlaces);this.buffer=t.toString(),this.input.value=this.formatNumber(t)}destroy(){this.input.removeEventListener("focus",this.onFocus),this.input.removeEventListener("input",this.onInput),this.input.removeEventListener("selectionchange",this.onSelectionChange),this.input.removeEventListener("blur",this.onBlur)}};var y=class r extends f{isMasked=!1;yesRadio;noRadio;constructor(e,t=document.body,i){super(e,t,i)}async[h](){try{await super[h](),this.element.id&&this.element.querySelectorAll(`#${this.element.id} > input[type="radio"]`).length>0&&await this._attachRadioButtons(),super._initChangeEmitter(),this.initEventManager(),this.initVisibilityManager(),this.initValueManager(),this._bindMethods();let e=new MutationObserver(t=>{for(let i of t)if(Array.from(i.removedNodes).includes(this.element)){typeof this[p]=="function"&&this[p](),e.disconnect();break}});e.observe(document.body,{childList:!0,subtree:!0}),r.instances.push(this),this.isLoaded=!0}catch(e){let t=e instanceof Error?e.message:String(e);throw new u.InitializationError(this,t)}}initValueManager(){this.valueManager=new L(this),this._valueSync()}initVisibilityManager(){this.visibilityManager=new b(this.element)}initEventManager(){this.eventManager=new w}async _attachRadioButtons(){if(!this.element){console.error("'this.element' not found: cannot attach radio buttons for ",this.target);return}this.yesRadio=new d(this,'input[type="radio"][value="1"]',this.element,0,"truthy"),this.noRadio=new d(this,'input[type="radio"][value="0"]',this.element,0,"falsy"),await this.yesRadio[h](),await this.noRadio[h]()}clearValue(){this.yesRadio instanceof d&&this.noRadio instanceof d&&(this.yesRadio.clearValue(),this.noRadio.clearValue()),super.clearValue()}uncheckRadios(){return this.yesRadio instanceof f&&this.noRadio instanceof f?(this.yesRadio.element.checked=!1,this.noRadio.element.checked=!1):console.error("[SYNACT] Attempted to uncheck radios for an element that has no radios"),this}inputMask(e,t){if(this.isMasked)throw new Error(`You cannot apply multiple input masks to the same element. @${this.target}`);let i;switch(e){case"money":i=new P(this.element,t);break;case"phone":i=new R(this.element,t);break;default:throw new Error(`No type provided for 'inputMask()' at: ${this.target}`)}return this.valueManager.element=i.input,this.isMasked=!0,this}[p](){super[p](),this.yesRadio?.[p](),this.noRadio?.[p](),this.yesRadio=void 0,this.noRadio=void 0}};var T=class extends Array{hideAll(){return this.forEach(e=>e.hide()),this}showAll(){return this.forEach(e=>e.show()),this}};function C(r){let e=new T(...r);return new Proxy(e,{get(t,i,s){if(i in t)return Reflect.get(t,i,s);if(typeof i=="string")return t.find(n=>n.target.toString().replace(/[#\[\]]/g,"")===i||n.logicalName===i)}})}async function N(r,e={multiple:!1,root:document.body,timeoutMs:0}){try{if(typeof e!="object")throw new TypeError(`'options' must be of type 'object'. Received type: '${typeof e}'`);K(e);let{multiple:t=!1,root:i=document.body,timeoutMs:s=0}=e;if(typeof t=="function"?t():t){if(typeof r!="string")throw new TypeError(`'target' must be of type 'string' if 'multiple' is set to 'true'. Received type: '${typeof r}'`);let a=await E(r,i,!0,s),l=await Promise.all(a.map(async c=>{let O=new y(c,i,s);return await O[h](),new Proxy(O,J())}));return C(l)}let o=new y(r,i,s);return await o[h](),new Proxy(o,J())}catch(t){throw t instanceof Error?t:new Error("Failed to get DOM Node by target: "+r)}}function K(r){let{multiple:e=!1,root:t=document.body,timeoutMs:i=0}=r;if(typeof e!="boolean"&&typeof e!="function")throw new TypeError(`'multiple' must be of type 'boolean' or 'function'. Received type: '${typeof e}'`);if(typeof e=="function"){let s=e();if(typeof s!="boolean")throw new TypeError(`'multiple' function must return a boolean. Received type: '${typeof s}'`)}if(!(t instanceof HTMLElement))throw new TypeError(`'root' must be of type 'HTMLElement'. Received type: '${typeof t}'`);if(typeof i!="number")throw new TypeError(`'timeout' must be of type 'number'. Received type: '${typeof i}'`)}function J(){return{get:(r,e)=>{if(e.toString().startsWith("_"))return;let t=r[e];return typeof t=="function"&&e!=="onceLoaded"?(...i)=>(r.onceLoaded(()=>t.apply(r,i)),r):t}}}async function U(r){try{let e=await H.getRecord("systemforms",r);if(e instanceof Error)throw new Error(`Could not get the form with ID: ${r}`);let{formxml:t}=e,s=new DOMParser().parseFromString(t,"application/xml"),n=j(s.getElementsByTagName("control")),o=j(s.getElementsByTagName("section")),a=j(s.getElementsByTagName("tab")),l=await Promise.all([...n,...o,...a]);return C(l.filter(c=>c!==null))}catch(e){throw e instanceof Error?(console.error(e.message),e):(console.error(e),new Error(String(e)))}}function j(r){return Array.from(r).map(e=>{let t=Q(e.tagName),i=e.getAttribute(t);if(!i)return null;let s=Y(e.tagName,i);return s?N(s).catch(n=>(console.warn(`Failed to create a reference to the form field: ${i}`,n),null)):null}).filter(Boolean)}function Q(r){return r==="control"?"id":r==="tab"||r==="section"?"name":"id"}function Y(r,e){return r==="control"?`#${e}`:r==="tab"||r==="section"?`[data-name="${e}"]`:null}var D=class extends HTMLElement{element;constructor(){if(!document)throw new Error("Cannot instantiate 'LoadingSpinner': No DOM Found");super(),this.id="loader",this.classList.add("loader-overlay","hidden"),this.element=document.createElement("div"),this.element.classList.add("spinner-border","text-light"),this.element.role="status",this.appendChild(this.element);let e=document.createElement("span");e.classList.add("visually-hidden"),e.textContent="Loading...",this.element.appendChild(e),document.body.appendChild(this)}hide(){this.classList.add("hidden")}show(){this.classList.remove("hidden")}},Z=`loading-${crypto.randomUUID()}`;customElements.define(Z,D);export{H as API,D as LoadingSpinner,U as bindForm,N as get,E as waitFor};
/*! For license information please see index.js.LEGAL.txt */
//# sourceMappingURL=index.js.map
if (typeof document !== 'undefined') {
const style = document.createElement('style');
style.textContent = ".info-icon {\r\n position: relative;\r\n display: inline-block;\r\n margin: 3px;\r\n}\r\n\r\n.info-icon .fa-info-circle {\r\n cursor: pointer; /* Ensures the icon is recognized as interactive */\r\n}\r\n\r\n.flyout-content {\r\n max-width: 600px; /* Reasonable default max width */\r\n width: calc(\r\n 100vw - 40px\r\n ); /* Responsive width with 20px padding on each side */\r\n display: none; /* Initially hidden */\r\n position: fixed;\r\n left: 50%; /* Center horizontally */\r\n transform: translateX(-50%); /* Center adjustment */\r\n margin-top: 8px; /* Small gap from the icon */\r\n color: #000;\r\n background-color: #f9f9f9;\r\n padding: 10px;\r\n border: 1px solid #ddd;\r\n z-index: 1000; /* Ensure it appears above other content */\r\n box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);\r\n border-radius: 8px; /* Rounded corners */\r\n}\r\n\r\n@media (max-width: 600px) {\r\n .flyout-content {\r\n padding: 12px;\r\n font-size: 0.9em;\r\n }\r\n}\r\n\r\n\r\n.required-field::after {\r\n content: \" *\" !important;\r\n color: #f00 !important;\r\n}\r\n\r\n.loader-overlay {\r\n position: fixed;\r\n top: 0;\r\n left: 0;\r\n width: 100%;\r\n height: 100%;\r\n background-color: rgba(0, 0, 0, 0.5); /* Faded background */\r\n z-index: 9999; /* Ensure it's on top */\r\n display: flex;\r\n justify-content: center;\r\n align-items: center;\r\n}\r\n\r\n.loader-overlay.hidden {\r\n display: none;\r\n}\r\n";
document.head.appendChild(style);
}