powerpagestoolkit 3.0.4062 → 3.0.5001

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.
@@ -74,7 +74,7 @@ export default abstract class DOMNodeReference {
74
74
  * or a natural boolean to determine the visibility of this
75
75
  * @returns - Instance of this [provides option to method chain]
76
76
  */
77
- toggleVisibility(shouldShow: ((this: DOMNodeReference) => boolean) | boolean): DOMNodeReference;
77
+ toggleVisibility(shouldShow: EvaluationFunction | boolean): DOMNodeReference;
78
78
  /**
79
79
  * Sets the value of the HTML element.
80
80
  * @param value - The value to set for the HTML element.
@@ -179,7 +179,7 @@ export default abstract class DOMNodeReference {
179
179
  * If true, the "required-field" class is added to the label; if false, it is removed.
180
180
  * @returns Instance of this [provides option to method chain]
181
181
  */
182
- setRequiredLevel(isRequired: ((this: DOMNodeReference) => boolean) | boolean): DOMNodeReference;
182
+ setRequiredLevel(isRequired: EvaluationFunction | boolean): DOMNodeReference;
183
183
  /**
184
184
  * Executes a callback function once the element is fully loaded.
185
185
  * If the element is already loaded, the callback is called immediately.
@@ -24,13 +24,17 @@ declare abstract class API {
24
24
  * @returns a Promise resolving the successful results of the GET request, or rejecting the failed results of the GET request
25
25
  */
26
26
  static getRecord<T>(tableSetName: string, recordID: string, ODataQueryString?: string): Promise<T>;
27
+ /**
28
+ * More flexible method for building completely custom queries
29
+ */
30
+ static request(options: JQuery.AjaxSettings): Promise<Response | Error>;
27
31
  /**
28
32
  *
29
33
  * @param tableSetName The dataverse set name of the table being queried
30
34
  * @param queryParameters *OPTIONAL* the OData query parameters for refining search results: *format = $filter=filters&$select=columns*
31
35
  * @returns a Promise resolving the successful results of the GET request, or rejecting the failed results of the GET request
32
36
  */
33
- static getMultiple(tableSetName: string, queryParameters?: string): Promise<Array<object>>;
37
+ static getMultiple<T = object>(tableSetName: string, queryParameters?: string): Promise<Array<T>>;
34
38
  /**
35
39
  *
36
40
  * @param tableSetName The dataverse set name for the table that you are updating a record in
@@ -1,83 +1,86 @@
1
- /// <reference path="../core/PowerPagesElement.ts"/>
1
+ import type DOMNodeReference from "../ancillary/DOMNodeReference.d.ts";
2
+ import type PowerPagesElement from "../core/PowerPagesElement.d.ts";
3
+
4
+ declare global {
5
+ type EventCallback = () => any;
6
+
7
+ interface CreationOptions {
8
+ /**
9
+ * Should this call return an array of instantiated references, or just a single?
10
+ * Defaults to false, returning a single instance.
11
+ */
12
+ multiple?: (() => boolean) | boolean;
13
+
14
+ /**
15
+ * Optionally specify the element within which to search for the element targeted by 'target'.
16
+ * Defaults to 'document.body'.
17
+ */
18
+ root?: HTMLElement;
19
+
20
+ /**
21
+ * Optionally specify the amount of time that should be waited to find the targeted element before throwing an error.
22
+ * Useful for async DOM loading. Relies on MutationObserver.
23
+ * WARNING: Implementing multiple references with timeout can result in infinite loading.
24
+ */
25
+ timeoutMs?: number;
26
+ }
27
+
28
+ interface SystemForm extends Object {
29
+ "@odata.context": string;
30
+ "@odata.etag": string;
31
+ "overwritetime@OData.Community.Display.V1.FormattedValue": string;
32
+ overwritetime: Date;
33
+ "isdesktopenabled@OData.Community.Display.V1.FormattedValue": string;
34
+ isdesktopenabled: boolean;
35
+ "publishedon@OData.Community.Display.V1.FormattedValue": Date;
36
+ publishedon: Date;
37
+ "_organizationid_value@OData.Community.Display.V1.FormattedValue": string;
38
+ "_organizationid_value@Microsoft.Dynamics.CRM.associatednavigationproperty": string;
39
+ "_organizationid_value@Microsoft.Dynamics.CRM.lookuplogicalname": string;
40
+ _organizationid_value: string;
41
+ formxml: string;
42
+ introducedversion: string;
43
+ "isairmerged@OData.Community.Display.V1.FormattedValue": string;
44
+ isairmerged: boolean;
45
+ "istabletenabled@OData.Community.Display.V1.FormattedValue": string;
46
+ istabletenabled: boolean;
47
+ solutionid: string;
48
+ formidunique: string;
49
+ "ismanaged@OData.Community.Display.V1.FormattedValue": string;
50
+ ismanaged: boolean;
51
+ "isdefault@OData.Community.Display.V1.FormattedValue": string;
52
+ isdefault: boolean;
53
+ "objecttypecode@OData.Community.Display.V1.FormattedValue": string;
54
+ objecttypecode: string;
55
+ "type@OData.Community.Display.V1.FormattedValue": string;
56
+ type: number;
57
+ "componentstate@OData.Community.Display.V1.FormattedValue": string;
58
+ componentstate: number;
59
+ "formpresentation@OData.Community.Display.V1.FormattedValue": string;
60
+ formpresentation: number;
61
+ "formactivationstate@OData.Community.Display.V1.FormattedValue": string;
62
+ formactivationstate: number;
63
+ name: string;
64
+ "versionnumber@OData.Community.Display.V1.FormattedValue": string;
65
+ versionnumber: number;
66
+ formjson: string;
67
+ description: string;
68
+ formid: string;
69
+ }
70
+
71
+ interface Form extends Partial<SystemForm> {
72
+ formxml: string;
73
+ }
74
+
75
+ type EvaluationFunction<T = any[]> = (
76
+ this: DOMNodeReference,
77
+ ...args: T[]
78
+ ) => boolean;
79
+
80
+ type EvaluationResults<T extends EvaluationFunction> = ReturnType<T>;
81
+
82
+ type IsRequired = EvaluationResults<EvaluationFunction>;
2
83
 
3
- declare type EventCallback = () => any;
4
-
5
- declare interface CreationOptions {
6
- /**
7
- * Should this call return an array of instantiated references, or just a single?
8
- * Defaults to false, returning a single instance.
9
- */
10
- multiple?: (() => boolean) | boolean;
11
-
12
- /**
13
- * Optionally specify the element within which to search for the element targeted by 'target'.
14
- * Defaults to 'document.body'.
15
- */
16
- root?: HTMLElement;
17
-
18
- /**
19
- * Optionally specify the amount of time that should be waited to find the targeted element before throwing an error.
20
- * Useful for async DOM loading. Relies on MutationObserver.
21
- * WARNING: Implementing multiple references with timeout can result in infinite loading.
22
- */
23
- timeoutMs?: number;
24
- }
25
-
26
- declare interface SystemForm extends Object {
27
- "@odata.context": string;
28
- "@odata.etag": string;
29
- "overwritetime@OData.Community.Display.V1.FormattedValue": string;
30
- overwritetime: Date;
31
- "isdesktopenabled@OData.Community.Display.V1.FormattedValue": string;
32
- isdesktopenabled: boolean;
33
- "publishedon@OData.Community.Display.V1.FormattedValue": Date;
34
- publishedon: Date;
35
- "_organizationid_value@OData.Community.Display.V1.FormattedValue": string;
36
- "_organizationid_value@Microsoft.Dynamics.CRM.associatednavigationproperty": string;
37
- "_organizationid_value@Microsoft.Dynamics.CRM.lookuplogicalname": string;
38
- _organizationid_value: string;
39
- formxml: string;
40
- introducedversion: string;
41
- "isairmerged@OData.Community.Display.V1.FormattedValue": string;
42
- isairmerged: boolean;
43
- "istabletenabled@OData.Community.Display.V1.FormattedValue": string;
44
- istabletenabled: boolean;
45
- solutionid: string;
46
- formidunique: string;
47
- "ismanaged@OData.Community.Display.V1.FormattedValue": string;
48
- ismanaged: boolean;
49
- "isdefault@OData.Community.Display.V1.FormattedValue": string;
50
- isdefault: boolean;
51
- "objecttypecode@OData.Community.Display.V1.FormattedValue": string;
52
- objecttypecode: string;
53
- "type@OData.Community.Display.V1.FormattedValue": string;
54
- type: number;
55
- "componentstate@OData.Community.Display.V1.FormattedValue": string;
56
- componentstate: number;
57
- "formpresentation@OData.Community.Display.V1.FormattedValue": string;
58
- formpresentation: number;
59
- "formactivationstate@OData.Community.Display.V1.FormattedValue": string;
60
- formactivationstate: number;
61
- name: string;
62
- "versionnumber@OData.Community.Display.V1.FormattedValue": string;
63
- versionnumber: number;
64
- formjson: string;
65
- description: string;
66
- formid: string;
67
- }
68
-
69
- declare interface Form extends Partial<SystemForm> {
70
- formxml: string;
71
- }
72
-
73
- declare interface BusinessRule {
74
- /**
75
- * @param condition A function that returns a boolean to determine
76
- * the visibility of the target element. If `condition()` returns true, the element is shown;
77
- * otherwise, it is hidden.
78
-
79
- */
80
- setVisibility?: (this: DOMNodeReference) => boolean;
81
84
  /**
82
85
  * Configuration function for determining the required level, and field validity of the given fields
83
86
  * @param isRequired - Function determining if field is required
@@ -86,89 +89,101 @@ declare interface BusinessRule {
86
89
  * @param isValid.this - Reference to this PowerPagesElement
87
90
  * @param isValid.isRequiredResult - Only available if 'isRequired' is also returned from the configuration function
88
91
  */
89
- setRequirements?: () => {
90
- isRequired?: (this: DOMNodeReference) => boolean;
91
- isValid?: (this: DOMNodeReference, isRequired: boolean) => boolean;
92
- };
92
+ interface FieldValidationRules {
93
+ isRequired?: EvaluationFunction;
94
+ isValid?: EvaluationFunction<IsRequired>;
95
+ }
93
96
 
94
- /**
95
- * @param condition A function to determine if the value provided should be applied to this field
96
- * @param value The value to set for the HTML element.
97
- * for parents of boolean radios, pass true or false as value, or
98
- * an expression returning a boolean
99
- */
100
- setValue?: () => {
101
- condition: (this: DOMNodeReference) => boolean;
102
- value: (() => any) | any;
103
- };
104
- /**
105
- * @param condition A function to determine if this field
106
- * should be enabled in a form, or disabled. True || 1 = disabled. False || 0 = enabled
97
+ interface BusinessRule {
98
+ /**
99
+ * @param condition A function that returns a boolean to determine
100
+ * the visibility of the target element. If `condition()` returns true, the element is shown;
101
+ * otherwise, it is hidden.
102
+
107
103
  */
108
- setDisabled?: (this: DOMNodeReference) => boolean;
109
- }
110
-
111
- // This helper checks that an array type has at least one element.
112
- // If T is empty, it “fails” by evaluating to a string literal.
113
- type NonEmptyArray<T extends unknown[]> = T extends []
114
- ? "Error: Dependency array must have at least one element"
115
- : T;
116
-
117
- // Now, define DependencyArray so that it is essentially [T, ...T[]]
118
- // but if someone passes an empty array (i.e. []), the type becomes a custom error.
119
- declare type DependencyArray<T> = NonEmptyArray<[T, ...T[]]>;
120
-
121
- declare type DependencyHandler = () => void;
122
-
123
- declare interface BusinessRuleHandler extends DependencyHandler {}
124
-
125
- declare type Dependents = Map<PowerPagesElement, DependencyHandler>;
126
-
127
- declare type ValueElement =
128
- | HTMLInputElement
129
- | HTMLSelectElement
130
- | HTMLTextAreaElement
131
- | HTMLOptionElement;
132
-
133
- declare const Page_Validators: any[];
134
-
135
- declare interface ElementValue {
136
- value: any;
137
- checked?: boolean;
138
- }
139
-
140
- declare type RadioType = "truthy" | "falsy";
141
-
142
- declare interface BoundEventListener {
143
- element: Element;
144
- event: keyof HTMLElementEventMap;
145
- handler: (e: Event) => unknown;
146
- }
147
-
148
- declare type FormElement =
149
- | HTMLInputElement
150
- | HTMLSelectElement
151
- | HTMLTextAreaElement
152
- | HTMLSpanElement
153
- | HTMLButtonElement
154
- | HTMLFieldSetElement;
155
-
156
- declare type PhoneNumberFormats =
157
- | "xxx-xxx-xxxx"
158
- | "(xxx) xxx-xxxx"
159
- | "xxx xxx-xxxx"
160
- | "xxx.xxx.xxxx";
161
-
162
- declare type CountryCodeFormats = "+" | "()";
163
-
164
- declare type CurrencySymbol = "$" | "€" | "£" | "¥" | "¢";
165
-
166
- declare interface InputMaskOptions {
167
- format?: PhoneNumberFormats;
168
- countryCode?: CountryCodeFormats;
169
- prefix?: CurrencySymbol; // Currency symbol (e.g., "$")
170
- decimalPlaces?: number; // Number of decimal places (default: 2)
171
- thousandsSeparator?: string; // Character for separating thousands (e.g., ",")
172
- decimalSeparator?: string; // Character for decimal point (e.g., ".")
173
- allowNegative?: boolean; // Whether to allow negative values
104
+ setVisibility?: EvaluationFunction;
105
+
106
+ setRequirements?: () => FieldValidationRules;
107
+
108
+ /**
109
+ * @param condition A function to determine if the value provided should be applied to this field
110
+ * @param value The value to set for the HTML element.
111
+ * for parents of boolean radios, pass true or false as value, or
112
+ * an expression returning a boolean
113
+ */
114
+ setValue?: () => {
115
+ condition: EvaluationFunction;
116
+ value: (() => any) | any;
117
+ };
118
+ /**
119
+ * @param condition A function to determine if this field
120
+ * should be enabled in a form, or disabled. True || 1 = disabled. False || 0 = enabled
121
+ */
122
+ setDisabled?: EvaluationFunction;
123
+ }
124
+
125
+ // This helper checks that an array type has at least one element.
126
+ // If T is empty, it “fails” by evaluating to a string literal.
127
+ type NonEmptyArray<T extends unknown[]> = T extends []
128
+ ? "Error: Dependency array must have at least one element"
129
+ : T;
130
+
131
+ // Now, define DependencyArray so that it is essentially [T, ...T[]]
132
+ // but if someone passes an empty array (i.e. []), the type becomes a custom error.
133
+ type DependencyArray<T> = NonEmptyArray<[T, ...T[]]>;
134
+
135
+ type DependencyHandler = () => void;
136
+
137
+ interface BusinessRuleHandler extends DependencyHandler {}
138
+
139
+ type Dependents = Map<PowerPagesElement, DependencyHandler>;
140
+
141
+ type ValueElement =
142
+ | HTMLInputElement
143
+ | HTMLSelectElement
144
+ | HTMLTextAreaElement
145
+ | HTMLOptionElement;
146
+
147
+ const Page_Validators: any[];
148
+
149
+ interface ElementValue {
150
+ value: any;
151
+ checked?: boolean;
152
+ }
153
+
154
+ type RadioType = "truthy" | "falsy";
155
+
156
+ interface BoundEventListener {
157
+ element: Element;
158
+ event: keyof HTMLElementEventMap;
159
+ handler: (e: Event) => unknown;
160
+ }
161
+
162
+ type FormElement =
163
+ | HTMLInputElement
164
+ | HTMLSelectElement
165
+ | HTMLTextAreaElement
166
+ | HTMLSpanElement
167
+ | HTMLButtonElement
168
+ | HTMLFieldSetElement;
169
+
170
+ type PhoneNumberFormats =
171
+ | "xxx-xxx-xxxx"
172
+ | "(xxx) xxx-xxxx"
173
+ | "xxx xxx-xxxx"
174
+ | "xxx.xxx.xxxx";
175
+
176
+ type CountryCodeFormats = "+" | "()";
177
+
178
+ type CurrencySymbol = "$" | "€" | "£" | "¥" | "¢";
179
+
180
+ interface InputMaskOptions {
181
+ format?: PhoneNumberFormats;
182
+ countryCode?: CountryCodeFormats;
183
+ prefix?: CurrencySymbol; // Currency symbol (e.g., "$")
184
+ decimalPlaces?: number; // Number of decimal places (default: 2)
185
+ thousandsSeparator?: string; // Character for separating thousands (e.g., ",")
186
+ decimalSeparator?: string; // Character for decimal point (e.g., ".")
187
+ allowNegative?: boolean; // Whether to allow negative values
188
+ }
174
189
  }
package/dist/src/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /* @ts-self-types="./index.d.ts" */
2
- function R(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)=>{R({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}`:""}`;R({type:"GET",url:o,success:s,error:n})})}static getMultiple(e,t){return new Promise((i,s)=>{let n=`/_api/${e}${t?`?${t}`:""}`;R({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})`;R({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())}},G=`info-icon-${crypto.randomUUID()}`;customElements.define(G,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(V=>{a.has(V)||(a.add(V),l.push(V))}),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,!1):t&&(s=()=>this.visibilityManager.getVisibility()&&t.call(this)),this._createValidator(s)}_createBusinessRuleHandler(e){return()=>{let t=!1;if(e.setVisibility){let s=e.setVisibility.call(this);t=!s,this.toggleVisibility(s)}if(e.setRequirements&&e.setRequirements().isRequired){let{isRequired:i}=e.setRequirements();this.setRequiredLevel(i.call(this))}if(e.setValue){let{condition:i,value:s}=e.setValue();if(i.call(this)){let n=s instanceof Function?s():s;this.setValue.call(this,n)}}e.setDisabled&&(e.setDisabled.call(this)?this.disable():this.enable()),t&&!e.setValue&&this.clearValue(),this.triggerDependentsHandlers()}}_createValidator(e){let t=(()=>{let n=this.getLabel();if(!n)throw new u.LabelNotFoundError(this);return n=n.innerHTML,n.length>50&&(n=n.substring(0,50)+"..."),n})(),i=`${this.element.id}Validator`,s=document.createElement("span");if(s.style.display="none",s.id=i,Object.assign(s,{controltovalidate:this.element.id,errormessage:`<a href='#${this.element.id}_label'>${t} is a required field</a>`,evaluationfunction:e.bind(this)}),Page_Validators==null)throw new u.Page_ValidatorsNotFoundError(this);Page_Validators.push(s)}_configureDependencyTracking(e,t){if(t.length<1){console.error(`powerpagestoolkit: No dependencies specified for ${this.element.id}. Include all required nodes in the dependency array for proper tracking.`);return}t.forEach(i=>{if(!i||!(i instanceof r))throw new TypeError("Each dependency must be a valid DOMNodeReference instance");if(i.logicalName===this.logicalName)throw new u.SelfReferenceError(this);i.eventManager.registerDependent(this,e.bind(this))})}setRequiredLevel(e){return e instanceof Function?(e.call(this)?this.getLabel()?.classList.add("required-field"):this.getLabel()?.classList.remove("required-field"),this):(e?this.getLabel()?.classList.add("required-field"):this.getLabel()?.classList.remove("required-field"),this)}onceLoaded(e){if(this.isLoaded){e(this);return}if(this.target instanceof HTMLElement){e(this);return}let t=new MutationObserver(function(){document.querySelector(this.target)&&(t.disconnect(),this.isLoaded=!0,e(this))}.bind(this));this.eventManager.registerObserver(t,{nodeToObserve:document.body,options:{subtree:!0,childList:!0}})}};var E=class{constructor(){}onFocus(){setTimeout(()=>this.input.select(),0)}onBlur(){this.formatInput()}setValue(e){this.input.value=String(e)}};var L=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 L(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}'`);K(e);let{multiple:t=!1,root:i=document.body,timeoutMs:s=0}=e;if(typeof t=="function"?t():t){if(typeof r!="string")throw new TypeError(`'target' must be of type 'string' if 'multiple' is set to 'true'. Received type: '${typeof r}'`);let l=await v(r,i,!0,s),a=await Promise.all(l.map(async c=>{let C=new y(c,i,s);return await C[h](),new Proxy(C,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 K(r){let{multiple:e=!1,root:t=document.body,timeoutMs:i=0}=r;if(typeof e!="boolean"&&typeof e!="function")throw new TypeError(`'multiple' must be of type 'boolean' or 'function'. Received type: '${typeof e}'`);if(typeof e=="function"){let s=e();if(typeof s!="boolean")throw new TypeError(`'multiple' function must return a boolean. Received type: '${typeof s}'`)}if(!(t instanceof HTMLElement))throw new TypeError(`'root' must be of type 'HTMLElement'. Received type: '${typeof t}'`);if(typeof i!="number")throw new TypeError(`'timeout' must be of type 'number'. Received type: '${typeof i}'`)}function 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 U(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=X(e.tagName),i=e.getAttribute(t);if(!i)return null;let s=Y(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 X(r){return r==="control"?"id":r==="tab"||r==="section"?"name":"id"}function Y(r,e){return r==="control"?`#${e}`:r==="tab"||r==="section"?`[data-name="${e}"]`:null}var 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")}},Z=`loading-${crypto.randomUUID()}`;customElements.define(Z,N);export{H as API,N as LoadingSpinner,U as bindForm,x as get,v as waitFor};
2
+ function g(r){let e=$.Deferred();return shell.getTokenDeferred().done(function(t){r.headers?r.headers.__RequestVerificationToken=t:$.extend(r,{headers:{__RequestVerificationToken:t}}),$.ajax(r).done(function(i,s,n){validateLoginSession(i,s,n,e.resolve)}).fail(e.reject)}).fail(function(){e.rejectWith(this,arguments)}),e.promise()}var S=class{static createRecord(e,t){return new Promise((i,s)=>{g({type:"POST",url:`/_api/${e}`,data:JSON.stringify(t),contentType:"application/json",success:function(n,o,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}`:""}`;g({type:"GET",url:o,success:s,error:n})})}static request(e){return new Promise((t,i)=>{let s=`/_api/${query}`;g({url:s,...e})})}static getMultiple(e,t){return new Promise((i,s)=>{let n=`/_api/${e}${t?`?${t}`:""}`;g({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})`;g({type:"PATCH",url:o,data:JSON.stringify(i),success:s,error:n})})}},H=S;var b=class{defaultVisibility;set defaultDisplay(e){this.defaultVisibility=e}constructor(e){if(this.visibilityController=e,e.tagName==="TABLE"){let i=e.closest("fieldset");i&&(this.visibilityController=i)}if(["SPAN","INPUT","TEXTAREA","SELECT","TABLE"].includes(e.tagName)){let i=e.closest("td");i&&(this.visibilityController=i)}this.defaultVisibility=this.visibilityController.style.display}hide(){this.visibilityController.style.display="none"}show(){this.visibilityController.style.display=this.defaultVisibility}toggleVisibility(e){e?this.show():this.hide()}getVisibility(){return window.getComputedStyle(this.visibilityController).display!=="none"&&window.getComputedStyle(this.visibilityController).visibility!=="hidden"&&this.visibilityController.getBoundingClientRect().height>0&&this.visibilityController.getBoundingClientRect().width>0}destroy(){this.visibilityController=null,this.defaultVisibility=null}};var N={CHECKBOX:"click",RADIO:"click",SELECT:"change",TEXT:"keyup",DEFAULT:"input"};var h=Symbol("init"),p=Symbol("destroy");var v=class extends HTMLElement{flyoutContent;icon;observers=[];constructor(e,t){if(super(),typeof e!="string")throw new Error(`argument "titleString" must be of type "string". Received: "${typeof e}"`);if(t&&typeof t!="object")throw new Error(`argument "iconStyle" must be of type "object". Received: "${typeof t}"`);this.classList.add("info-icon"),this.icon=document.createElement("i"),this.icon.classList.add("fa","fa-solid","fa-info-circle"),this.icon.setAttribute("aria-label","Info"),this.icon.style.cursor="pointer",this.flyoutContent=document.createElement("div"),this.flyoutContent.innerHTML=e,this.flyoutContent.classList.add("flyout-content"),this.appendChild(this.icon),this.appendChild(this.flyoutContent),t&&Object.assign(this.icon.style,t),this.handleClick=this.handleClick.bind(this),this.handleResize=this.handleResize.bind(this),this.handleTouchStart=this.handleTouchStart.bind(this),this.handleMouseEnter=this.handleMouseEnter.bind(this),this.handleMouseLeave=this.handleMouseLeave.bind(this),this.handleScroll=this.handleScroll.bind(this),this.flyoutContent.style.minWidth=this.getDesiredWidth(),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())}},U=`info-icon-${crypto.randomUUID()}`;customElements.define(U,v);function E(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(V=>{a.has(V)||(a.add(V),l.push(V))}),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}`)}},G={NodeNotFoundError:I,InitializationError:k,Page_ValidatorsNotFoundError:F,BusinessRuleError:A,SelfReferenceError:_,LabelNotFoundError:B,IncorrectParameterError:q},u=G;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 E(this.target,this.root,!1,this.timeoutMs),!this.element)throw new u.NodeNotFoundError(this)}_extractLogicalName(e){if(typeof e!="string")return"";let t=e.match(/\[([^\]]+)\]/);if(!t)return e.replace(/[#\[\]]/g,"");let i=t[1];return(i.match(/["']([^"']+)["']/)?.[1]||i).replace(/[#\[\]]/g,"")}_valueSync(){if(!this._isValidFormElement(this.element))return;this.updateValue();let e=this._determineEventType();this.eventManager.registerDOMEventListener(this.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?N[this.element.type.toUpperCase()]||N.DEFAULT:N.DEFAULT}_isDateInput(){return this.element instanceof HTMLInputElement&&this.element.dataset.type==="date"}_isValidFormElement(e){return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSpanElement||e instanceof HTMLButtonElement||e instanceof HTMLFieldSetElement}async _dateSync(e){let t=e.parentElement;if(!t)throw new DOMException("Date input must have a parent element");let i=await E("[data-date-format]",t,!1,1500);this.valueManager.element=i,this.eventManager.registerDOMEventListener(i,"select",this.updateValue.bind(this))}_bindMethods(){let e=Object.getPrototypeOf(this);for(let t of Object.getOwnPropertyNames(e)){let i=this[t];t!=="constructor"&&typeof i=="function"&&(this[t]=i.bind(this))}}[p](){this.isLoaded=!1,this.value=null,this.eventManager.destroy(),this.eventManager=null,this.visibilityManager.destroy(),this.visibilityManager=null,this.valueManager.destroy(),this.valueManager=null}async updateValue(e){e&&!e.isTrusted||(await this.valueManager.updateValue(e),this.triggerDependentsHandlers())}triggerDependentsHandlers(){this.eventManager.dispatchDependencyHandlers()}on(e,t){if(typeof t!="function")throw new u.IncorrectParameterError(this,"on","eventHandler",["function"],typeof t);let i=t;return this.eventManager.registerDOMEventListener(this.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 v(i,t||void 0)),this}addTooltip(e,t){let i=j.sanitize(e);return this.append(new v(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,!1):t&&(s=()=>this.visibilityManager.getVisibility()&&t.call(this)),this._createValidator(s)}_createBusinessRuleHandler(e){return()=>{let t=!1;if(e.setVisibility){let s=e.setVisibility.call(this);t=!s,this.toggleVisibility(s)}if(e.setRequirements&&e.setRequirements().isRequired){let{isRequired:i}=e.setRequirements();this.setRequiredLevel(i.call(this))}if(e.setValue){let{condition:i,value:s}=e.setValue();if(i.call(this)){let n=s instanceof Function?s():s;this.setValue.call(this,n)}}e.setDisabled&&(e.setDisabled.call(this)?this.disable():this.enable()),t&&!e.setValue&&this.clearValue(),this.triggerDependentsHandlers()}}_createValidator(e){let t=(()=>{let n=this.getLabel();if(!n)throw new u.LabelNotFoundError(this);return n=n.innerHTML,n.length>50&&(n=n.substring(0,50)+"..."),n})(),i=`${this.element.id}Validator`,s=document.createElement("span");if(s.style.display="none",s.id=i,Object.assign(s,{controltovalidate:this.element.id,errormessage:`<a href='#${this.element.id}_label'>${t} is a required field</a>`,evaluationfunction:e.bind(this)}),Page_Validators==null)throw new u.Page_ValidatorsNotFoundError(this);Page_Validators.push(s)}_configureDependencyTracking(e,t){if(t.length<1){console.error(`powerpagestoolkit: No dependencies specified for ${this.element.id}. Include all required nodes in the dependency array for proper tracking.`);return}t.forEach(i=>{if(!i||!(i instanceof r))throw new TypeError("Each dependency must be a valid DOMNodeReference instance");if(i.logicalName===this.logicalName)throw new u.SelfReferenceError(this);i.eventManager.registerDependent(this,e.bind(this))})}setRequiredLevel(e){return e instanceof Function?(e.call(this)?this.getLabel()?.classList.add("required-field"):this.getLabel()?.classList.remove("required-field"),this):(e?this.getLabel()?.classList.add("required-field"):this.getLabel()?.classList.remove("required-field"),this)}onceLoaded(e){if(this.isLoaded){e(this);return}if(this.target instanceof HTMLElement){e(this);return}let t=new MutationObserver(function(){document.querySelector(this.target)&&(t.disconnect(),this.isLoaded=!0,e(this))}.bind(this));this.eventManager.registerObserver(t,{nodeToObserve:document.body,options:{subtree:!0,childList:!0}})}};var M=class{constructor(){}onFocus(){setTimeout(()=>this.input.select(),0)}onBlur(){this.formatInput()}setValue(e){this.input.value=String(e)}};var R=class extends M{input;options;constructor(e,t={}){super(),this.input=e,this.options={format:t.format||"(xxx) xxx-xxxx",countryCode:t.countryCode||"",countryCodeFormat:t.countryCodeFormat||"+"},this.onFocus=this.onFocus.bind(this),this.formatInput=this.formatInput.bind(this),this.onBlur=this.onBlur.bind(this),this.setupEventListeners(),setTimeout(()=>{this.formatInput()},0)}setupEventListeners(){this.input.addEventListener("focus",this.onFocus),this.input.addEventListener("input",this.formatInput),this.input.addEventListener("blur",this.onBlur)}formatInput(){let e=this.input.value,t=this.input.selectionStart||0,i=e.length,s=e.replace(/\D/g,""),n=this.formatPhoneNumber(s);this.input.value=n;let o=Math.min(t+(n.length-i),n.length);this.input.setSelectionRange(o,o)}formatPhoneNumber(e){if(!e)return"";let t=e,i="";if(this.options.countryCode){let 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 w=class{events=new Map;listeners=new Map;dependencyHandlers=new Set;observers=[];boundListeners=[];constructor(){}dispatchDependencyHandlers(){for(let[e,t]of this.dependencyHandlers)t.call(e)}registerDependent(e,t){try{return this.dependencyHandlers.add([e,t]),"success"}catch{return new Error(`Failed register dependant: ${e.target}`)}}registerEvent(e,t){return this.events.has(e)?(console.error("Event registration has already been defined for: ",e),new Error(`Event registration has already been defined for: ${e}`)):(this.listeners.set(e,new Set),this.events.set(e,t),"success")}registerListener(e,t){if(this.events.has(e)){let i=this.listeners.get(e)??new Set;return i.add(t),this.listeners.set(e,i),"success"}else return console.error("No event registration found for: ",e),new Error(`No event registration found for: ${e}`)}emit(e,...t){if(this.events.has(e)){let i=this.events.get(e),s=this.listeners.get(e);if(!s)return;for(let n of s)i.call(n,...t)}else console.error("Event not found in EventRegistry: ",e)}stopListening(e){for(let[t,i]of this.listeners)i.has(e)&&i.delete(e)}registerObserver(e,t){let{nodeToObserve:i,options:s}=t;e.observe(i,s),this.observers.push(e)}registerDOMEventListener(e,t,i){e.addEventListener(t,i),this.boundListeners.push({element:e,handler:i,event:t})}destroy(){this.boundListeners?.forEach(e=>{e.element?.removeEventListener(e.event,e.handler)}),this.boundListeners=[],this.observers?.forEach(e=>{e.disconnect()}),this.observers=[],this.events.clear(),this.dependencyHandlers.clear(),this.listeners.clear()}};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 w}initValueManager(){this.valueManager=new L(this),this._valueSync()}initVisibilityManager(){this.visibilityManager=new b(this.element)}[p](){super[p](),this.radioParent=void 0,this.radioType=void 0}};var L=class{value;checked=!1;element;noRadio;yesRadio;radioParent;isRadio=!1;radioType;constructor(e){e instanceof y?(this.noRadio=e.noRadio,this.yesRadio=e.yesRadio,this.radioParent=void 0):e instanceof d&&(this.isRadio=!0,this.noRadio=void 0,this.yesRadio=void 0,this.radioParent=e.radioParent,this.radioType=e.radioType),this.element=e.element}setValue(e){let t=this._validateValue(e);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 M{input;options;buffer="";charAtSelection="";charBeforeSelection="";lengthOf0FormattedValue;digitRegex=/\d/;nonDigitRegex=/\D/g;thousandsRegex=/\B(?=(\d{3})+(?!\d))/g;separatorRegex;constructor(e,t={}){super(),this.input=e,this.options={prefix:t.prefix||"$",decimalPlaces:t.decimalPlaces??2,thousandsSeparator:t.thousandsSeparator||",",decimalSeparator:t.decimalSeparator||".",allowNegative:t.allowNegative??!0};let i=this.escapeRegExp(this.options.thousandsSeparator),s=this.escapeRegExp(this.options.decimalSeparator);this.separatorRegex=new RegExp(`[${i}${s}]`),this.onFocus=this.onFocus.bind(this),this.onInput=this.onInput.bind(this),this.onSelectionChange=this.onSelectionChange.bind(this),this.onBlur=this.onBlur.bind(this),this.lengthOf0FormattedValue=`0${this.options.decimalPlaces>0?this.options.decimalSeparator+"0".repeat(this.options.decimalPlaces):""}`.length,this.setupEventListeners(),this.input.value&&(this.buffer=this.input.value.replace(this.nonDigitRegex,"")),this.formatAndDisplay()}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}formatAndDisplay(){let e=Number(this.buffer||"0");this.input.value=this.formatNumber(e)}setupEventListeners(){this.input.addEventListener("focus",this.onFocus),this.input.addEventListener("input",this.onInput),this.input.addEventListener("selectionchange",this.onSelectionChange),this.input.addEventListener("blur",this.onBlur)}formatInput(){let e=this.input.value,t=this.input.selectionStart||0,i=e.length,s=new RegExp(`[^0-9${this.options.decimalSeparator}${this.options.allowNegative?"-":""}]`,"g"),n=e.replace(s,""),o=n.split(this.options.decimalSeparator);o.length>2&&(n=o[0]+this.options.decimalSeparator+o.slice(1).join("")),this.options.allowNegative&&n.indexOf("-")>0&&(n=n.replace(/-/g,""),n.charAt(0)!=="-"&&(n="-"+n));let 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 L(this),this._valueSync()}initVisibilityManager(){this.visibilityManager=new b(this.element)}initEventManager(){this.eventManager=new w}async _attachRadioButtons(){if(!this.element){console.error("'this.element' not found: cannot attach radio buttons for ",this.target);return}this.yesRadio=new d(this,'input[type="radio"][value="1"]',this.element,0,"truthy"),this.noRadio=new d(this,'input[type="radio"][value="0"]',this.element,0,"falsy"),await this.yesRadio[h](),await this.noRadio[h]()}clearValue(){this.yesRadio instanceof d&&this.noRadio instanceof d&&(this.yesRadio.clearValue(),this.noRadio.clearValue()),super.clearValue()}uncheckRadios(){return this.yesRadio instanceof f&&this.noRadio instanceof f?(this.yesRadio.element.checked=!1,this.noRadio.element.checked=!1):console.error("[SYNACT] Attempted to uncheck radios for an element that has no radios"),this}inputMask(e,t){if(this.isMasked)throw new Error(`You cannot apply multiple input masks to the same element. @${this.target}`);let i;switch(e){case"money":i=new P(this.element,t);break;case"phone":i=new R(this.element,t);break;default:throw new Error(`No type provided for 'inputMask()' at: ${this.target}`)}return this.valueManager.element=i.input,this.isMasked=!0,this}[p](){super[p](),this.yesRadio?.[p](),this.noRadio?.[p](),this.yesRadio=void 0,this.noRadio=void 0}};var T=class extends Array{hideAll(){return this.forEach(e=>e.hide()),this}showAll(){return this.forEach(e=>e.show()),this}};function 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 O(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}'`);X(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 E(r,i,!0,s),a=await Promise.all(l.map(async c=>{let C=new y(c,i,s);return await C[h](),new Proxy(C,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 X(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 J(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=Q(e.tagName,i);return s?O(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 Q(r,e){return r==="control"?`#${e}`:r==="tab"||r==="section"?`[data-name="${e}"]`:null}var x=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")}},Y=`loading-${crypto.randomUUID()}`;customElements.define(Y,x);export{H as API,x as LoadingSpinner,J as bindForm,O as get,E as waitFor};
3
3
  /*! For license information please see index.js.LEGAL.txt */
4
4
  //# sourceMappingURL=index.js.map
5
5