powerpagestoolkit 3.0.2 → 3.0.311
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 +26 -43
- package/dist/src/{core → ancillary}/DOMNodeReference.d.ts +20 -42
- package/dist/src/ancillary/EventManager.d.ts +25 -0
- package/dist/src/ancillary/Radio.d.ts +8 -0
- package/dist/src/ancillary/ValueManager.d.ts +27 -0
- package/dist/src/ancillary/VisibilityManager.d.ts +11 -0
- package/dist/src/constants/EventTypes.d.ts +2 -2
- package/dist/src/core/PowerPagesElement.d.ts +32 -0
- package/dist/src/core/PowerPagesElementArray.d.ts +12 -0
- package/dist/src/core/bindForm.d.ts +7 -7
- package/dist/src/core/{createDOMNodeReferences.d.ts → getPowerPagesElement.d.ts} +16 -16
- package/dist/src/errors/errors.d.ts +32 -9
- package/dist/src/globals.d.ts +14 -11
- package/dist/src/index.d.ts +2 -2
- package/dist/src/index.js +2 -2
- package/dist/src/index.js.map +4 -4
- package/dist/src/utils/enhanceArray.d.ts +4 -4
- package/package.json +1 -1
- package/dist/src/core/DOMNodeReferenceArray.d.ts +0 -12
- package/dist/src/managers/ReferenceManager.d.ts +0 -6
package/dist/src/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import API from "./core/API.d.ts";
|
|
2
|
-
import
|
|
2
|
+
import get from "./core/getPowerPagesElement.d.ts";
|
|
3
3
|
import waitFor from "./core/waitFor.d.ts";
|
|
4
4
|
import bindForm from "./core/bindForm.d.ts";
|
|
5
|
-
export { API, bindForm,
|
|
5
|
+
export { API, bindForm, get, waitFor };
|
package/dist/src/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/* @ts-self-types="./index.d.ts" */
|
|
2
|
-
function f(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(n,i,o){validateLoginSession(n,i,o,e.resolve)}).fail(e.reject)}).fail(function(){e.rejectWith(this,arguments)}),e.promise()}var L=class{static createRecord(e,t){return new Promise((n,i)=>{f({type:"POST",url:`/_api/${e}`,data:JSON.stringify(t),contentType:"application/json",success:function(o,s,a){n(a.getResponseHeader("entityid"))},error:o=>{i(o)}})})}static getRecord(e,t,n){return new Promise((i,o)=>{let s=`/_api/${e}(${t})${n?`?$${n}`:""}`;f({type:"GET",url:s,success:i,error:o})})}static getMultiple(e,t){return new Promise((n,i)=>{let o=`/_api/${e}${t?`?${t}`:""}`;f({type:"GET",url:o,success:function(s){n(s.value)},error:i})})}static updateRecord(e,t,n){return new Promise((i,o)=>{let s=`/_api/${e}(${t})`;f({type:"PATCH",url:s,data:JSON.stringify(n),success:i,error:o})})}},D=L;function d(r,e=document,t=!1,n){return new Promise((i,o)=>{if(t){let s,a=[],l=new Set;if(n<1)return i(Array.from(e.querySelectorAll(r)));let c=new MutationObserver(()=>{Array.from(e.querySelectorAll(r)).forEach(w=>{l.has(w)||(l.add(w),a.push(w))}),clearTimeout(s),s=setTimeout(()=>{a.length>0?(c.disconnect(),i(a)):o(new Error(`No elements found with target: "${r}" within ${n/1e3} seconds. If the element you are expecting has not loaded yet, consider raising your timeout.`))},n)});c.observe(e,{childList:!0,subtree:!0,attributes:!1})}else{let s=new MutationObserver(()=>{let c=e.querySelector(r);c&&(clearTimeout(a),s.disconnect(),i(c))}),a=setTimeout(()=>{s.disconnect(),o(new Error(`Element not found by target: "${r}" within ${n/1e3} second. If the element you are expecting has not loaded yet, consider raising your timeout.`))},n),l=e.querySelector(r);if(l)return clearTimeout(a),i(l);s.observe(e,{subtree:!0,attributes:!0,childList:!0})}})}function E(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 n=document.createElement("i");n.classList.add("fa","fa-solid","fa-info-circle"),n.setAttribute("aria-label","Info"),n.style.cursor="pointer";let i=document.createElement("div");i.innerHTML=r,i.classList.add("flyout-content"),t.appendChild(n),t.appendChild(i),e&&Object.assign(n.style,e);let o=()=>{i.style.display="block";let s=i.getBoundingClientRect(),a=window.innerWidth;if(s.right>a){let l=s.right-a;i.style.left=`calc(50% - ${l}px)`}if(s.left<0){let l=Math.abs(s.left);i.style.left=`calc(50% + ${l}px)`}};return t.addEventListener("mouseenter",()=>{o()}),t.addEventListener("mouseleave",s=>{let a=s.relatedTarget;t.contains(a)||(i.style.display="none")}),n.addEventListener("touchstart",s=>{s.preventDefault(),i.style.display=i.style.display==="block"?"none":"block",i.style.display==="block"&&o()}),document.body.addEventListener("click",s=>{t.contains(s.target)||(i.style.display="none")}),i.style.display="none",t}var m=Symbol("init"),p=Symbol("destroy");var M={CHECKBOX:"click",RADIO:"click",SELECT:"change",TEXT:"keyup",DEFAULT:"input"};var R=class extends Error{constructor(e,t){super(`There was an error initializing a DOMNodeReference for target: ${e.target}, :: ${t}`),this.name="DOMNodeInitializationError"}},T=class extends Error{constructor(e){super(`The targeted DOM element was not found: ${e.target}`)}};var y=class extends Error{constructor(e,t){super(`Validation configuration error for ${e.target}: ${t}`),this.name="ValidationConfigError"}};var h=class r{static instances=[];target;logicalName;root;_timeoutMs;_isLoaded;_defaultDisplay;_observers=[];_boundListeners=[];_dependents=new Map;_isRadio=!1;_radioType=null;value;constructor(e,t=document.body,n){this.target=e,this.logicalName=this._extractLogicalName(e),this.root=t,this._timeoutMs=n,this._isLoaded=!1,this._defaultDisplay="",this.value=null,this._bindMethods()}_extractLogicalName(e){if(typeof e!="string")return"";let t=e.match(/\[([^\]]+)\]/);if(!t)return e.replace(/[#\[\]]/g,"");let n=t[1];return(n.match(/["']([^"']+)["']/)?.[1]||n).replace(/[#\[\]]/g,"")}async[m](){try{if(this.target instanceof HTMLElement?this.element=this.target:this.element=await d(this.target,this.root,!1,this._timeoutMs),!this.element)throw new T(this);this.element.id&&this.element.querySelectorAll(`#${this.element.id} > input[type="radio"]`).length>0&&await this._attachRadioButtons(),this._valueSync(),this._attachVisibilityController(),this._defaultDisplay=this._visibilityController.style.display;let e=new MutationObserver(t=>{for(let n of t)if(Array.from(n.removedNodes).includes(this.element)){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 R(this,t)}}_valueSync(){if(!this._isValidFormElement(this.element))return;this.updateValue();let e=this._determineEventType();this._registerEventListener(this.element,e,this.updateValue),this._isDateInput()&&this._dateSync(this.element)}_determineEventType(){return this.element instanceof HTMLSelectElement?"change":this.element instanceof HTMLTextAreaElement?"keyup":this.element instanceof HTMLInputElement?M[this.element.type.toUpperCase()]||M.DEFAULT:M.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}_registerEventListener(e,t,n){e.addEventListener(t,n),this._boundListeners.push({element:e,handler:n,event:t})}async _dateSync(e){let t=e.parentElement;if(!t)throw new Error("Date input must have a parent element");let n=await d("[data-date-format]",t,!1,1500);this._registerEventListener(n,"select",this.updateValue)}_getElementValue(){return new Promise(e=>{let t=this.element,n=this.element;this.yesRadio instanceof r&&this.noRadio instanceof r&&e({value:this.yesRadio.checked,checked:this.yesRadio.checked});let i={value:null};switch(t.type){case"checkbox":case"radio":e({value:t.checked,checked:t.checked});break;case"select-multiple":e({value:Array.from(n.selectedOptions).map(o=>o.value)});break;case"select-one":e({value:n.value});break;case"number":e({value:t.value!==""?Number(t.value):null});break;default:{let o=t.value;this.element.classList.contains("decimal")&&(o=parseFloat(t.value.replace(/[$,]/g,"").trim())),i={value:o}}}i={...i,value:this._validateValue(i.value)},e(i)})}_attachVisibilityController(){if(this._visibilityController=this.element,this.element.tagName==="TABLE"){let t=this.element.closest("fieldset");t&&(this._visibilityController=t);return}if(["SPAN","INPUT","TEXTAREA","SELECT","TABLE"].includes(this.element.tagName)){let t=this.element.closest("td");t&&(this._visibilityController=t)}}async _attachRadioButtons(){if(!this.element){console.error("'this.element' not found: cannot attach radio buttons for ",this.target);return}this.yesRadio=await u('input[type="radio"][value="1"]',{root:this.element}),this.yesRadio._isRadio=!0,this.yesRadio._radioType="truthy",this.yesRadio.radioParent=this,this.noRadio=await u('input[type="radio"][value="0"]',{root:this.element}),this.noRadio._isRadio=!0,this.noRadio._radioType="falsy",this.noRadio.radioParent=this}_bindMethods(){let e=Object.getPrototypeOf(this);for(let t of Object.getOwnPropertyNames(e)){let n=this[t];t!=="constructor"&&typeof n=="function"&&(this[t]=n.bind(this))}}[p](){this._boundListeners?.forEach(e=>{e.element?.removeEventListener(e.event,e.handler)}),this._boundListeners=[],this._observers?.forEach(e=>{e.disconnect()}),this._observers=[],this.yesRadio?.[p](),this.noRadio?.[p](),this.yesRadio=null,this.noRadio=null,this._isLoaded=!1,this.value=null,this._dependents.clear(),this.radioParent=null}async updateValue(e){if(e&&!e.isTrusted)return;e&&e.stopPropagation(),this.yesRadio instanceof r&&this.noRadio instanceof r&&(this.yesRadio.updateValue(),this.noRadio.updateValue());let t=await this._getElementValue();this.value=t.value,t.checked!==void 0&&(this.checked=t.checked),this._triggerDependentsHandlers()}_triggerDependentsHandlers(){for(let[e,t]of this._dependents){if(e._dependents)for(let[n,i]of e._dependents)i();t()}}_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)}on(e,t){if(typeof t!="function")throw new Error(`Argument "eventHandler" must be a Function. Received: ${typeof t}`);return this._registerEventListener(this.element,e,t.bind(this)),this}hide(){return this._visibilityController.style.display="none",this}show(){return this._visibilityController.style.display=this._defaultDisplay,this}toggleVisibility(e){return e instanceof Function?e.call(this)?this.show():this.hide():e?this.show():this.hide(),this}setValue(e){e instanceof Function&&(e=e());let t=this._validateValue(e);return this.yesRadio instanceof r&&this.noRadio instanceof r?(this.yesRadio.element.checked=!!e,this.noRadio.element.checked=!e,this.value=e,this.checked=e,this.element.checked=!!e,this.element.value=e):this._isRadio||this.element.type==="radio"?(this.checked=e,this.element.checked=e,this.radioParent?.updateValue()):this.element.value=t,this.value=t,console.log("finished setting value for ",this.target,{target:this}),this}disable(){try{this.element.disabled=!0}catch(e){let t=e instanceof Error?e.message:String(e);throw new Error(`There was an error trying to disable the target: ${this.target}: "${t}"`)}return this}async 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,this._getChildren()&&this._callAgainstChildInputs(t=>t.clearValue()));return this.yesRadio instanceof r&&this.noRadio instanceof r&&(await this.yesRadio.clearValue(),await this.noRadio.clearValue()),this}catch(e){let t=`Failed to clear values for element with target "${this.target}": ${e instanceof Error?e.message:String(e)}`;throw new Error(t)}}_getChildren(){let t=Array.from(this.element.querySelectorAll("input, select, textarea")).map(i=>i.id);return r.instances.filter(i=>t.includes(i.element.id))??null}async _callAgainstChildInputs(e){let t=this._getChildren();if(t&&t.length>0){let n=t.map(async i=>{await e(i)});await Promise.all(n);return}else return}enable(){try{this.element.disabled=!1}catch{throw new Error(`There was an error trying to disable the target: ${this.target}`)}return 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(){return document.querySelector(`#${this.element.id}_label`)||null}addLabelTooltip(e,t){return this.getLabel()?.append(E(e,t||void 0)),this}addTooltip(e,t){return this.append(E(e,t||void 0)),this}setInnerHTML(e){return this.element.innerHTML=e,this}remove(){return this.element.remove(),this}setStyle(e){if(Object.prototype.toString.call(e)!=="[object Object]")throw new Error(`powerpagestoolkit: 'DOMNodeReference.setStyle' required options to be in the form of an object. Argument passed was of type: ${typeof e}`);for(let t in e){let n=t;this.element.style[n]=e[n]}return this}uncheckRadios(){return this.yesRadio instanceof r&&this.noRadio instanceof r?(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}applyBusinessRule(e,t){try{if(e.setVisibility){let o=e.setVisibility.call(this);this.toggleVisibility(o)}if(e.setRequirements){let{isRequired:i,isValid:o}=e.setRequirements();if(typeof Page_Validators>"u")throw new y(this,"Page_Validators not found");let s=()=>!0;i&&o?s=()=>{let a=i.call(this),l=this._getVisibility();return!a||l&&o.call(this,a)}:o?s=()=>this._getVisibility()&&o.call(this):i&&(s=()=>this._getVisibility()&&i.call(this)),this._createValidator(s)}if(e.setValue){let{condition:i,value:o}=e.setValue();o instanceof Function&&(o=o()),i.call(this)&&this.setValue.call(this,o)}e.setDisabled&&(e.setDisabled.call(this)?this.disable():this.enable());let n=this._returnAggregateHandler(e);return n(),t.length&&this._configureDependencyTracking(n,t),this}catch(n){throw n instanceof Error?n:new y(this,`Failed to apply business rule: ${n}`)}}_returnAggregateHandler(e){return()=>{let t=!1;if(e.setVisibility){let n=e.setVisibility;t=t||!n.call(this),this.toggleVisibility(n.call(this))}if(e.setRequirements&&e.setRequirements().isRequired){let{isRequired:n}=e.setRequirements();this.setRequiredLevel(n.call(this))}if(e.setValue){let{condition:n,value:i}=e.setValue();n.call(this)&&this.setValue.call(this,i)}e.setDisabled&&(e.setDisabled.call(this)?this.disable():this.enable()),t&&!e.setValue&&this.clearValue()}}_createValidator(e){let t=(()=>{let o=this.getLabel();if(!o)throw new Error(`There was an error accessing the label for this element: ${this.target}`);return o=o.innerHTML,o.length>50&&(o=o.substring(0,50)+"..."),o})(),n=`${this.element.id}Validator`,i=document.createElement("span");i.style.display="none",i.id=n,Object.assign(i,{controltovalidate:this.element.id,errormessage:`<a href='#${this.element.id}_label'>${t} is a required field</a>`,evaluationfunction:e}),Page_Validators.push(i)}_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(n=>{if(!n||!(n instanceof r))throw new TypeError("Each dependency must be a valid DOMNodeReference instance");if(n.logicalName===this.logicalName)throw new Error(`powerpagestoolkit: Self-referential dependency detected; a node cannot depend on itself: Source: ${this.element.id}`);n._dependents.set(this,e.bind(this))})}_getVisibility(){return window.getComputedStyle(this._visibilityController).display!=="none"&&window.getComputedStyle(this._visibilityController).visibility!=="hidden"&&this._visibilityController.getBoundingClientRect().height>0&&this._visibilityController.getBoundingClientRect().width>0}_receiveNotification(){this.updateValue()}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(()=>{document.querySelector(this.target)&&(t.disconnect(),this._isLoaded=!0,e(this))});t.observe(document.body,{subtree:!0,childList:!0}),this._observers.push(t)}};var g=class extends Array{hideAll(){return this.forEach(e=>e.hide()),this}showAll(){return this.forEach(e=>e.show()),this}};function b(r){let e=new g(...r);return new Proxy(e,{get(t,n,i){if(n in t)return Reflect.get(t,n,i);if(typeof n=="string")return t.find(o=>o.target.toString().replace(/[#\[\]]/g,"")===n||o.logicalName===n)}})}async function u(r,e={multiple:!1,root:document.body,timeoutMs:0}){try{if(typeof e!="object")throw new Error(`'options' must be of type 'object'. Received type: '${typeof e}'`);H(e);let{multiple:t=!1,root:n=document.body,timeoutMs:i=0}=e;if(typeof t=="function"?t():t){if(typeof r!="string")throw new Error(`'target' must be of type 'string' if 'multiple' is set to 'true'. Received type: '${typeof r}'`);let a=await d(r,n,!0,i),l=await Promise.all(a.map(async c=>{let v=new h(c,n,i);return await v[m](),new Proxy(v,O())}));return b(l)}let s=new h(r,n,i);return await s[m](),new Proxy(s,O())}catch(t){throw new Error(t)}}function H(r){let{multiple:e=!1,root:t=document.body,timeoutMs:n=0}=r;if(typeof e!="boolean"&&typeof e!="function")throw new Error(`'multiple' must be of type 'boolean' or 'function'. Received type: '${typeof e}'`);if(typeof e=="function"){let i=e();if(typeof i!="boolean")throw new Error(`'multiple' function must return a boolean. Received type: '${typeof i}'`)}if(!(t instanceof HTMLElement))throw new Error(`'root' must be of type 'HTMLElement'. Received type: '${typeof t}'`);if(typeof n!="number")throw new Error(`'timeout' must be of type 'number'. Received type: '${typeof n}'`)}function O(){return{get:(r,e)=>{if(e.toString().startsWith("_"))return;let t=r[e];return typeof t=="function"&&e!=="onceLoaded"?(...n)=>(r.onceLoaded(()=>t.apply(r,n)),r):t}}}async function _(r){try{let e=await D.getRecord("systemforms",r),{formxml:t}=e,i=new DOMParser().parseFromString(t,"application/xml"),o=N(i.getElementsByTagName("control")),s=N(i.getElementsByTagName("section")),a=N(i.getElementsByTagName("tab")),l=await Promise.all([...o,...s,...a]);return b(l.filter(c=>c!==null))}catch(e){throw e instanceof Error?(console.error(e.message),e):(console.error(e),new Error(String(e)))}}function N(r){return Array.from(r).map(e=>{let t=A(e.tagName),n=e.getAttribute(t);if(!n)return null;let i=V(e.tagName,n);return i?u(i).catch(o=>(console.warn(`Failed to create a reference to the form field: ${n}`,o),null)):null}).filter(Boolean)}function A(r){return r==="control"?"id":r==="tab"||r==="section"?"name":"id"}function V(r,e){return r==="control"?`#${e}`:r==="tab"||r==="section"?`[data-name="${e}"]`:null}export{D as API,_ as bindForm,u as createRef,d as waitFor};
|
|
2
|
+
function M(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)=>{M({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}`:""}`;M({type:"GET",url:o,success:n,error:s})})}static getMultiple(e,t){return new Promise((i,n)=>{let s=`/_api/${e}${t?`?${t}`:""}`;M({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})`;M({type:"PATCH",url:o,data:JSON.stringify(i),success:n,error:s})})}},N=H;function T(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 l=o.right-a;n.style.left=`calc(50% - ${l}px)`}if(o.left<0){let l=Math.abs(o.left);n.style.left=`calc(50% + ${l}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 f(r,e=document,t=!1,i){return new Promise((n,s)=>{if(t){let o,a=[],l=new Set;if(i<1)return n(Array.from(e.querySelectorAll(r)));let m=new MutationObserver(()=>{Array.from(e.querySelectorAll(r)).forEach(D=>{l.has(D)||(l.add(D),a.push(D))}),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),l=e.querySelector(r);if(l)return clearTimeout(a),n(l);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},c=B;var P={CHECKBOX:"click",RADIO:"click",SELECT:"change",TEXT:"keyup",DEFAULT:"input"};var y=Symbol("init"),u=Symbol("destroy");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}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}_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?P[this.element.type.toUpperCase()]||P.DEFAULT:P.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 f("[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))}}[u](){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 c.IncorrectParameterError(this,"on","eventHandler",["function"],typeof t);return this.eventManager.registerDOMEventListener(this.element,e,t.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 c.LabelNotFoundError(this);return e}addLabelTooltip(e,t){return this.getLabel()?.append(T(e,t||void 0)),this}addTooltip(e,t){return this.append(T(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 c.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 c.Page_ValidatorsNotFoundError(this);let o=()=>!0;n&&s?o=()=>{let a=n.call(this),l=this.visibilityManager.getVisibility();return!a||l&&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 c.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 c.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 c.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 c.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 g=class{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 b=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 d=class extends h{radioType=null;constructor(e,t,i=document.body,n,s){super(t,i,n),this.radioParent=e,this.radioType=s}async[y](){try{if(this.target instanceof HTMLElement?this.element=this.target:this.element=await f(this.target,this.root,!1,this.timeoutMs),!this.element)throw new c.NodeNotFoundError(this);this.eventManager=new b,this.visibilityManager=new g(this.element),this.valueManager=new E({element:this.element,isRadio:!0,radioParent:this.radioParent}),this._valueSync(),this._bindMethods();let e=new MutationObserver(t=>{for(let i of t)if(Array.from(i.removedNodes).includes(this.element)){this[u](),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 c.InitializationError(this,t)}}[u](){super[u](),this.radioParent=void 0,this.eventManager.destroy(),this.eventManager=null,this.visibilityManager.destroy(),this.visibilityManager=null,this.valueManager.destroy(),this.valueManager=null}};var E=class{value;checked=!1;element;noRadio;yesRadio;isRadio=!1;constructor(e){this.element=e.element,this.noRadio=e.noRadio,this.yesRadio=e.yesRadio,this.isRadio=e.isRadio}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.radioParent?.updateValue()):this.element.value=t,this.value=t}async updateValue(e){e&&e.stopPropagation(),this.yesRadio instanceof d&&this.noRadio instanceof d&&(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 d&&this.noRadio instanceof d&&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 v=class r extends h{constructor(e,t=document.body,i){super(e,t,i)}async[y](){try{if(this.target instanceof HTMLElement?this.element=this.target:this.element=await f(this.target,this.root,!1,this.timeoutMs),!this.element)throw new c.NodeNotFoundError(this);this.element.id&&this.element.querySelectorAll(`#${this.element.id} > input[type="radio"]`).length>0&&await this._attachRadioButtons(),this.eventManager=new b,this.visibilityManager=new g(this.element),this.valueManager=new E({element:this.element,isRadio:!1,noRadio:this.noRadio,yesRadio:this.yesRadio}),this._valueSync(),this._bindMethods();let e=new MutationObserver(t=>{for(let i of t)if(Array.from(i.removedNodes).includes(this.element)){typeof this[u]=="function"&&this[u](),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 c.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 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[y](),await this.noRadio[y]()}clearValue(){this.yesRadio instanceof d&&this.noRadio instanceof d&&(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}[u](){super[u](),this.yesRadio?.[u](),this.noRadio?.[u](),this.yesRadio=void 0,this.noRadio=void 0,this.eventManager.destroy(),this.eventManager=null,this.visibilityManager.destroy(),this.visibilityManager=null,this.valueManager.destroy(),this.valueManager=null}};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 f(r,i,!0,n),l=await Promise.all(a.map(async m=>{let O=new v(m,i,n);return await O[y](),new Proxy(O,F())}));return R(l)}let o=new v(r,i,n);return await o[y](),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")),l=await Promise.all([...s,...o,...a]);return R(l.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=J(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 J(r,e){return r==="control"?`#${e}`:r==="tab"||r==="section"?`[data-name="${e}"]`:null}export{N as API,q as bindForm,L as get,f 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}\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.info-icon .flyout-content {\r\n max-width: calc(100vw - 20px); /* 20px margin on both sides */\r\n display: none; /* Initially hidden */\r\n position: absolute;\r\n left: 50%; /* Center horizontally */\r\n transform: translateX(-50%); /* Adjust positioning */\r\n color: #000;\r\n background-color: #f9f9f9;\r\n padding: 10px;\r\n border: 1px solid #ddd;\r\n z-index: 1;\r\n min-width: 200px; /* Minimum width for better readability */\r\n box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);\r\n border-radius: 4px; /* Rounded corners */\r\n}\r\n\r\n@media (max-width: 600px) {\r\n .info-icon .flyout-content {\r\n max-width: 95vw;\r\n padding: 12px;\r\n font-size: 0.9em;\r\n display: block;\r\n right: auto;\r\n }\r\n}\r\n\r\n.required-field::after {\r\n content: \" *\" !important;\r\n color: #f00 !important;\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.info-icon .flyout-content {\r\n max-width: calc(100vw - 20px); /* 20px margin on both sides */\r\n display: none; /* Initially hidden */\r\n position: absolute;\r\n left: 50%; /* Center horizontally */\r\n transform: translateX(-50%); /* Adjust positioning */\r\n color: #000;\r\n background-color: #f9f9f9;\r\n padding: 10px;\r\n border: 1px solid #ddd;\r\n z-index: 1;\r\n min-width: 200px; /* Minimum width for better readability */\r\n box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);\r\n border-radius: 4px; /* Rounded corners */\r\n}\r\n\r\n@media (max-width: 600px) {\r\n .info-icon .flyout-content {\r\n max-width: 95vw;\r\n padding: 12px;\r\n font-size: 0.9em;\r\n display: block;\r\n right: auto;\r\n }\r\n}\r\n\r\n.required-field::after {\r\n content: \" *\" !important;\r\n color: #f00 !important;\r\n}\r\n";
|
|
10
10
|
document.head.appendChild(style);
|
|
11
11
|
}
|
|
12
12
|
|