powerpagestoolkit 3.0.3215 → 3.0.4041
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +36 -37
- package/dist/src/ancillary/DOMNodeReference.d.ts +14 -31
- package/dist/src/ancillary/EventManager.d.ts +9 -9
- package/dist/src/ancillary/InfoElement.d.ts +25 -0
- package/dist/src/ancillary/LoadingSpinner.d.ts +16 -0
- package/dist/src/ancillary/Radio.d.ts +4 -1
- package/dist/src/ancillary/ValueManager.d.ts +2 -1
- package/dist/src/core/PowerPagesElement.d.ts +24 -3
- package/dist/src/core/getPowerPagesElement.d.ts +2 -36
- package/dist/src/globals.d.ts +27 -23
- package/dist/src/index.d.ts +2 -1
- package/dist/src/index.js +2 -2
- package/dist/src/index.js.map +4 -4
- package/dist/src/utils/InputMask.d.ts +11 -0
- package/dist/src/utils/MoneyMask.d.ts +36 -0
- package/dist/src/utils/PhoneNumberMask.d.ts +25 -0
- package/package.json +6 -3
- package/dist/src/utils/createInfoElement.d.ts +0 -8
package/dist/src/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/* @ts-self-types="./index.d.ts" */
|
|
2
|
-
function E(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,n,s){validateLoginSession(i,n,s,e.resolve)}).fail(e.reject)}).fail(function(){e.rejectWith(this,arguments)}),e.promise()}var H=class{static createRecord(e,t){return new Promise((i,n)=>{E({type:"POST",url:`/_api/${e}`,data:JSON.stringify(t),contentType:"application/json",success:function(s,o,a){i(a.getResponseHeader("entityid"))},error:s=>{n(s)}})})}static getRecord(e,t,i){return new Promise((n,s)=>{let o=`/_api/${e}(${t})${i?`?$${i}`:""}`;E({type:"GET",url:o,success:n,error:s})})}static getMultiple(e,t){return new Promise((i,n)=>{let s=`/_api/${e}${t?`?${t}`:""}`;E({type:"GET",url:s,success:function(o){i(o.value)},error:n})})}static updateRecord(e,t,i){return new Promise((n,s)=>{let o=`/_api/${e}(${t})`;E({type:"PATCH",url:o,data:JSON.stringify(i),success:n,error:s})})}},N=H;var v=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]),!0}catch{return!1}}registerEvent(e,t){return this.events.has(e)?(console.error("Event registration has already been defined for: ",e),!1):(this.listeners.set(e,new Set),this.events.set(e,t),!0)}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),!0}else return console.error("No event registration found for: ",e),!1}emit(e,...t){if(this.events.has(e)){let i=this.events.get(e),n=this.listeners.get(e);if(!n)return;for(let s of n)i.call(s,...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:n}=t;e.observe(i,n),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()}};var M=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}};function P(r,e){if(typeof r!="string")throw new Error(`argument "titleString" must be of type "string". Received: "${typeof r}"`);if(e&&typeof e!="object")throw new Error(`argument "iconStyle" must be of type "object". Received: "${typeof e}"`);let t=document.createElement("span");t.classList.add("info-icon");let i=document.createElement("i");i.classList.add("fa","fa-solid","fa-info-circle"),i.setAttribute("aria-label","Info"),i.style.cursor="pointer";let n=document.createElement("div");n.innerHTML=r,n.classList.add("flyout-content"),t.appendChild(i),t.appendChild(n),e&&Object.assign(i.style,e);let s=()=>{n.style.display="block";let o=n.getBoundingClientRect(),a=window.innerWidth;if(o.right>a){let c=o.right-a;n.style.left=`calc(50% - ${c}px)`}if(o.left<0){let c=Math.abs(o.left);n.style.left=`calc(50% + ${c}px)`}};return t.addEventListener("mouseenter",()=>{s()}),t.addEventListener("mouseleave",o=>{let a=o.relatedTarget;t.contains(a)||(n.style.display="none")}),i.addEventListener("touchstart",o=>{o.preventDefault(),n.style.display=n.style.display==="block"?"none":"block",n.style.display==="block"&&s()}),document.body.addEventListener("click",o=>{t.contains(o.target)||(n.style.display="none")}),n.style.display="none",t}function b(r,e=document,t=!1,i){return new Promise((n,s)=>{if(t){let o,a=[],c=new Set;if(i<1)return n(Array.from(e.querySelectorAll(r)));let m=new MutationObserver(()=>{Array.from(e.querySelectorAll(r)).forEach(O=>{c.has(O)||(c.add(O),a.push(O))}),clearTimeout(o),o=setTimeout(()=>{a.length>0?(m.disconnect(),n(a)):s(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)});m.observe(e,{childList:!0,subtree:!0,attributes:!1})}else{let o=new MutationObserver(()=>{let m=e.querySelector(r);m&&(clearTimeout(a),o.disconnect(),n(m))}),a=setTimeout(()=>{o.disconnect(),s(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),c=e.querySelector(r);if(c)return clearTimeout(a),n(c);o.observe(e,{subtree:!0,attributes:!0,childList:!0})}})}var p=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)}},V=class extends p{constructor(e,t){super(e,`There was an error initializing a DOMNodeReference for target: ${e.target}, :: ${t}`)}},S=class extends p{constructor(e){super(e,`The targeted DOM element was not found: ${e.target}`)}},x=class extends p{constructor(e){super(e,"Page_Validators could not be found")}},k=class extends p{constructor(e){super(e,`Error applying business rule to target: ${e.target}`)}},A=class extends p{constructor(e){super(e,"Self-referential dependency found. A DOMNodeReference cannot depend on itself")}},_=class extends p{constructor(e){super(e,`No label could be found for the target: ${e.target}`)}},C=class extends p{constructor(e,t,i,n,s){let o=n.join(" or ");super(e,`${t} expects ${i} to be of type ${o}. Received: ${s===null?"null":typeof s}`)}},B={NodeNotFoundError:S,InitializationError:V,Page_ValidatorsNotFoundError:x,BusinessRuleError:k,SelfReferenceError:A,LabelNotFoundError:_,IncorrectParameterError:C},d=B;var u=Symbol("init"),f=Symbol("destroy");var T={CHECKBOX:"click",RADIO:"click",SELECT:"change",TEXT:"keyup",DEFAULT:"input"};var h=class r{static instances=[];target;logicalName;root;timeoutMs;isLoaded;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[u](){if(this.target instanceof HTMLElement?this.element=this.target:this.element=await b(this.target,this.root,!1,this.timeoutMs),!this.element)throw new d.NodeNotFoundError(this);this.eventManager=new v,this.visibilityManager=new M(this.element)}_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.element,e,this.updateValue.bind(this)),this._isDateInput()&&this._dateSync(this.element)}_determineEventType(){return this.element instanceof HTMLSelectElement?"change":this.element instanceof HTMLTextAreaElement?"keyup":this.element instanceof HTMLInputElement?T[this.element.type.toUpperCase()]||T.DEFAULT:T.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 b("[data-date-format]",t,!1,1500);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))}}[f](){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 d.IncorrectParameterError(this,"on","eventHandler",["function"],typeof t);let i=t;return this.eventManager.registerDOMEventListener(this.element,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(n=>n.id),i=r.instances.filter(n=>t.includes(n.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 d.LabelNotFoundError(this);return e}addLabelTooltip(e,t){return this.getLabel()?.append(P(e,t||void 0)),this}addTooltip(e,t){return this.append(P(e,t||void 0)),this}setInnerHTML(e){return this.element.innerHTML=e,this}remove(){return this.element.remove(),this}setStyle(e){if(e===null||typeof e!="object")throw new d.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{if(e.setVisibility){let s=e.setVisibility.call(this);this.toggleVisibility(s)}if(e.setRequirements){let{isRequired:n,isValid:s}=e.setRequirements();if(typeof Page_Validators>"u")throw new d.Page_ValidatorsNotFoundError(this);let o=()=>!0;n&&s?o=()=>{let a=n.call(this),c=this.visibilityManager.getVisibility();return!a||c&&s.call(this,a)}:s?o=()=>this.visibilityManager.getVisibility()&&s.call(this):n&&(o=()=>this.visibilityManager.getVisibility()&&n.call(this)),this._createValidator(o)}if(e.setValue){let{condition:n,value:s}=e.setValue();s instanceof Function&&(s=s()),n.call(this)&&this.setValue.call(this,s)}e.setDisabled&&(e.setDisabled.call(this)?this.disable():this.enable());let i=this._returnBusinessRuleHandler(e);return i(),t.length&&this._configureDependencyTracking(i,t),this}catch(i){throw i instanceof Error?i:new d.BusinessRuleError(this)}}_returnBusinessRuleHandler(e){return()=>{let t=!1;if(e.setVisibility){let i=e.setVisibility;t=t||!i.call(this),this.toggleVisibility(i.call(this))}if(e.setRequirements&&e.setRequirements().isRequired){let{isRequired:i}=e.setRequirements();this.setRequiredLevel(i.call(this))}if(e.setValue){let{condition:i,value:n}=e.setValue();i.call(this)&&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 s=this.getLabel();if(!s)throw new d.LabelNotFoundError(this);return s=s.innerHTML,s.length>50&&(s=s.substring(0,50)+"..."),s})(),i=`${this.element.id}Validator`,n=document.createElement("span");if(n.style.display="none",n.id=i,Object.assign(n,{controltovalidate:this.element.id,errormessage:`<a href='#${this.element.id}_label'>${t} is a required field</a>`,evaluationfunction:e}),Page_Validators==null)throw new d.Page_ValidatorsNotFoundError(this);Page_Validators.push(n)}_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 d.SelfReferenceError(this);i.eventManager.registerDependent(this,e.bind(this))})}setRequiredLevel(e){return e instanceof Function?(e()?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 l=class extends h{radioType=null;constructor(e,t,i=document.body,n,s){super(t,i,n),this.radioParent=e,this.radioType=s}async[u](){try{await super[u](),this.valueManager=new g(this),this._valueSync(),this._bindMethods();let e=new MutationObserver(t=>{for(let i of t)if(Array.from(i.removedNodes).includes(this.element)){this[f](),e.disconnect();break}});e.observe(document.body,{childList:!0,subtree:!0}),h.instances.push(this),this.isLoaded=!0}catch(e){let t=e instanceof Error?e.message:String(e);throw new d.InitializationError(this,t)}}[f](){super[f](),this.radioParent=void 0}};var g=class{value;checked=!1;element;noRadio;yesRadio;radioParent;isRadio=!1;constructor(e){e instanceof y?(this.noRadio=e.noRadio,this.yesRadio=e.yesRadio,this.radioParent=void 0):e instanceof l&&(this.isRadio=!0,this.noRadio=void 0,this.yesRadio=void 0,this.radioParent=e.radioParent),this.element=e.element}setValue(e){let t=this._validateValue(e);this.yesRadio instanceof l&&this.noRadio instanceof l?(this.yesRadio.element.checked=!!e,this.noRadio.element.checked=!e,this.value=e,this.element.checked=!!e,this.element.value=e):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(),this.yesRadio instanceof l&&this.noRadio instanceof l&&(this.yesRadio.updateValue(),this.noRadio.updateValue());let t=await this.getElementValue();this.value=t.value,t.checked!==void 0&&(this.checked=t.checked)}getElementValue(){return new Promise(e=>{let t=this.element,i=this.element;this.yesRadio instanceof l&&this.noRadio instanceof l&&e({value:this.yesRadio.checked,checked:this.yesRadio.checked});let n={value:null};switch(t.type){case"checkbox":case"radio":e({value:t.checked,checked:t.checked});break;case"select-multiple":e({value:Array.from(i.selectedOptions).map(s=>s.value)});break;case"select-one":e({value:i.value});break;case"number":e({value:t.value!==""?Number(t.value):null});break;default:{let s=t.value;this.element.classList.contains("decimal")&&(s=parseFloat(t.value.replace(/[$,]/g,"").trim())),n={value:s}}}n={...n,value:this._validateValue(n.value)},e(n)})}_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 y=class r extends h{constructor(e,t=document.body,i){super(e,t,i)}async[u](){try{await super[u](),this.element.id&&this.element.querySelectorAll(`#${this.element.id} > input[type="radio"]`).length>0&&await this._attachRadioButtons(),this.valueManager=new g(this),this._valueSync(),this._bindMethods();let e=new MutationObserver(t=>{for(let i of t)if(Array.from(i.removedNodes).includes(this.element)){typeof this[f]=="function"&&this[f](),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 d.InitializationError(this,t)}}async _attachRadioButtons(){if(!this.element){console.error("'this.element' not found: cannot attach radio buttons for ",this.target);return}this.yesRadio=new l(this,'input[type="radio"][value="1"]',this.element,0,"truthy"),this.noRadio=new l(this,'input[type="radio"][value="0"]',this.element,0,"falsy"),await this.yesRadio[u](),await this.noRadio[u]()}clearValue(){this.yesRadio instanceof l&&this.noRadio instanceof l&&(this.yesRadio.clearValue(),this.noRadio.clearValue()),super.clearValue()}uncheckRadios(){return this.yesRadio instanceof h&&this.noRadio instanceof h?(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}[f](){super[f](),this.yesRadio?.[f](),this.noRadio?.[f](),this.yesRadio=void 0,this.noRadio=void 0}};var w=class extends Array{hideAll(){return this.forEach(e=>e.hide()),this}showAll(){return this.forEach(e=>e.show()),this}};function R(r){let e=new w(...r);return new Proxy(e,{get(t,i,n){if(i in t)return Reflect.get(t,i,n);if(typeof i=="string")return t.find(s=>s.target.toString().replace(/[#\[\]]/g,"")===i||s.logicalName===i)}})}async function L(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}'`);j(e);let{multiple:t=!1,root:i=document.body,timeoutMs:n=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 b(r,i,!0,n),c=await Promise.all(a.map(async m=>{let D=new y(m,i,n);return await D[u](),new Proxy(D,F())}));return R(c)}let o=new y(r,i,n);return await o[u](),new Proxy(o,F())}catch(t){throw t instanceof Error?t:new Error("Failed to get DOM Node by target: "+r)}}function j(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 n=e();if(typeof n!="boolean")throw new TypeError(`'multiple' function must return a boolean. Received type: '${typeof n}'`)}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 F(){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 q(r){try{let e=await N.getRecord("systemforms",r),{formxml:t}=e,n=new DOMParser().parseFromString(t,"application/xml"),s=I(n.getElementsByTagName("control")),o=I(n.getElementsByTagName("section")),a=I(n.getElementsByTagName("tab")),c=await Promise.all([...s,...o,...a]);return R(c.filter(m=>m!==null))}catch(e){throw e instanceof Error?(console.error(e.message),e):(console.error(e),new Error(String(e)))}}function I(r){return Array.from(r).map(e=>{let t=z(e.tagName),i=e.getAttribute(t);if(!i)return null;let n=G(e.tagName,i);return n?L(n).catch(s=>(console.warn(`Failed to create a reference to the form field: ${i}`,s),null)):null}).filter(Boolean)}function z(r){return r==="control"?"id":r==="tab"||r==="section"?"name":"id"}function G(r,e){return r==="control"?`#${e}`:r==="tab"||r==="section"?`[data-name="${e}"]`:null}export{N as API,q as bindForm,L as get,b as waitFor};
|
|
2
|
+
function L(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 S=class{static createRecord(e,t){return new Promise((i,s)=>{L({type:"POST",url:`/_api/${e}`,data:JSON.stringify(t),contentType:"application/json",success:function(n,o,l){i(l.getResponseHeader("entityid"))},error:n=>{s(n)}})})}static getRecord(e,t,i){return new Promise((s,n)=>{let o=`/_api/${e}(${t})${i?`?$${i}`:""}`;L({type:"GET",url:o,success:s,error:n})})}static getMultiple(e,t){return new Promise((i,s)=>{let n=`/_api/${e}${t?`?${t}`:""}`;L({type:"GET",url:n,success:function(o){i(o.value)},error:s})})}static updateRecord(e,t,i){return new Promise((s,n)=>{let o=`/_api/${e}(${t})`;L({type:"PATCH",url:o,data:JSON.stringify(i),success:s,error:n})})}},H=S;var g=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 O={CHECKBOX:"click",RADIO:"click",SELECT:"change",TEXT:"keyup",DEFAULT:"input"};var h=Symbol("init"),p=Symbol("destroy");var b=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(),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;return`${Math.min(e-40,600)}px`}positionFlyout(){this.flyoutContent.style.display="block";let e=this.icon.getBoundingClientRect(),t=this.flyoutContent.getBoundingClientRect(),i=self.innerHeight,n=e.bottom-5;n+t.height>i&&(n=e.top-t.height),this.flyoutContent.style.top=`${n}px`}updateFlyoutWidth(){this.flyoutContent.style.minWidth=this.getDesiredWidth()}handleClick(e){this.contains(e.target)||(this.flyoutContent.style.display="none")}handleResize(e){this.flyoutContent.style.minWidth=this.getDesiredWidth()}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())}};customElements.define("pptk-info-element",b);function v(r,e=document,t=!1,i){return new Promise((s,n)=>{if(t){let o,l=[],a=new Set;if(i<1)return s(Array.from(e.querySelectorAll(r)));let c=new MutationObserver(()=>{Array.from(e.querySelectorAll(r)).forEach(C=>{a.has(C)||(a.add(C),l.push(C))}),clearTimeout(o),o=setTimeout(()=>{l.length>0?(c.disconnect(),s(l)):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(l),o.disconnect(),s(c))}),l=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),a=e.querySelector(r);if(a)return clearTimeout(l),s(a);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}`)}},J={NodeNotFoundError:I,InitializationError:k,Page_ValidatorsNotFoundError:F,BusinessRuleError:A,SelfReferenceError:_,LabelNotFoundError:B,IncorrectParameterError:q},u=J;import j from"DOMPurify";var f=class r{static instances=[];target;logicalName;root;timeoutMs;isLoaded;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 v(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.element,e,this.updateValue.bind(this)),this._isDateInput()&&this._dateSync(this.element)}_determineEventType(){return this.element instanceof HTMLSelectElement?"change":this.element instanceof HTMLTextAreaElement?"keyup":this.element instanceof HTMLInputElement?O[this.element.type.toUpperCase()]||O.DEFAULT:O.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 v("[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.element,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=j.sanitize(e);return this.getLabel()?.append(new b(i,t||void 0)),this}addTooltip(e,t){let i=j.sanitize(e);return this.append(new b(i,t||void 0)),this}set innerHTML(e){let t=j.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):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}),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()?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 E=class{constructor(){}onFocus(){setTimeout(()=>this.input.select(),0)}onBlur(){this.formatInput()}setValue(e){this.input.value=String(e)}};var R=class extends E{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 a=this.options.countryCode.length;e.length>a?(i=e.substring(0,a),t=e.substring(a)):(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 a=0;a<n.length&&o<t.length;a++)n[a]==="x"&&(n=n.substring(0,a)+t[o++]+n.substring(a+1));n=n.replace(/x/g,"");let l=n.split("").findIndex((a,c)=>!/\d/.test(a)&&n.substring(c).indexOf("x")===-1&&n.substring(c).replace(/[\s\-()]/g,"").length===0);return l!==-1&&(n=n.substring(0,l)),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 M=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()}};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](),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 M}initValueManager(){this.valueManager=new w(this),this._valueSync()}initVisibilityManager(){this.visibilityManager=new g(this.element)}[p](){super[p](),this.radioParent=void 0,this.radioType=void 0}};var w=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);this.yesRadio instanceof d&&this.noRadio instanceof d?(this.yesRadio.element.checked=!!e,this.noRadio.element.checked=!e,this.value=e,this.element.checked=!!e,this.element.value=e):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()}}getElementValue(){return new Promise(e=>{let t=this.element,i=this.element;this.yesRadio instanceof d&&this.noRadio instanceof d&&e({value:this.yesRadio.checked,checked:this.yesRadio.checked});let s={value:null};switch(t.type){case"checkbox":case"radio":e({value:t.checked,checked:t.checked});break;case"select-multiple":e({value:Array.from(i.selectedOptions).map(n=>n.value)});break;case"select-one":e({value:i.value});break;case"number":e({value:t.value!==""?Number(t.value):null});break;default:{let n=t.value;this.element.classList.contains("decimal")&&(n=parseFloat(t.value.replace(/[$,]/g,"").trim())),s={value:n}}}s={...s,value:this._validateValue(s.value)},e(s)})}_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.defaultValue="",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 E{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 l;n===""||n==="-"?l=0:l=parseFloat(n.replace(this.options.decimalSeparator,".")),isNaN(l)&&(l=0);let a=this.formatNumber(l);this.input.value=a;let c=t+(a.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,l]=n.split("."),a=o.replace(this.thousandsRegex,this.options.thousandsSeparator);return(i?"-":"")+this.options.prefix+a+(this.options.decimalPlaces>0?this.options.decimalSeparator+l:"")}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 l=Number(this.buffer||"0"),a=this.formatNumber(l);this.input.value=a;let c=this.mapRawIndexToFormattedPosition(o,a);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(),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 w(this),this._valueSync()}initVisibilityManager(){this.visibilityManager=new g(this.element)}initEventManager(){this.eventManager=new M}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 D(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 x(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}'`);U(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 l=await v(r,i,!0,s),a=await Promise.all(l.map(async c=>{let V=new y(c,i,s);return await V[h](),new Proxy(V,W())}));return D(a)}let o=new y(r,i,s);return await o[h](),new Proxy(o,W())}catch(t){throw t instanceof Error?t:new Error("Failed to get DOM Node by target: "+r)}}function U(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 W(){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 G(r){try{let e=await H.getRecord("systemforms",r),{formxml:t}=e,s=new DOMParser().parseFromString(t,"application/xml"),n=z(s.getElementsByTagName("control")),o=z(s.getElementsByTagName("section")),l=z(s.getElementsByTagName("tab")),a=await Promise.all([...n,...o,...l]);return D(a.filter(c=>c!==null))}catch(e){throw e instanceof Error?(console.error(e.message),e):(console.error(e),new Error(String(e)))}}function z(r){return Array.from(r).map(e=>{let t=K(e.tagName),i=e.getAttribute(t);if(!i)return null;let s=X(e.tagName,i);return s?x(s).catch(n=>(console.warn(`Failed to create a reference to the form field: ${i}`,n),null)):null}).filter(Boolean)}function K(r){return r==="control"?"id":r==="tab"||r==="section"?"name":"id"}function X(r,e){return r==="control"?`#${e}`:r==="tab"||r==="section"?`[data-name="${e}"]`:null}var N=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")}};customElements.define("pptk-loading-spinner",N);export{H as API,N as LoadingSpinner,G as bindForm,x as get,v as waitFor};
|
|
3
3
|
/*! For license information please see index.js.LEGAL.txt */
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
if (typeof document !== 'undefined') {
|
|
8
8
|
const style = document.createElement('style');
|
|
9
|
-
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.
|
|
9
|
+
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";
|
|
10
10
|
document.head.appendChild(style);
|
|
11
11
|
}
|
|
12
12
|
|