@claspo/renderer 17.0.2 → 17.0.4

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.
Files changed (32) hide show
  1. package/README.md +52 -0
  2. package/RouterEvent.d.ts +3 -4
  3. package/RouterEvent.js +1 -1
  4. package/action/InAppActionFactory.d.ts +1 -3
  5. package/action/SysActionTypes.d.ts +12 -12
  6. package/action/SysActionTypes.js +1 -1
  7. package/action/actions/BaseRequestAction.js +1 -1
  8. package/action/actions/CloseWidgetAction.d.ts +2 -1
  9. package/action/actions/DispatchEventAction.d.ts +2 -1
  10. package/action/actions/GoToNextViewAction.d.ts +2 -1
  11. package/action/actions/GoToPreviousViewAction.d.ts +2 -1
  12. package/action/actions/GoToViewAction.d.ts +2 -1
  13. package/action/actions/InAppOpenLinkAction.d.ts +2 -1
  14. package/action/actions/OpenLinkAction.d.ts +2 -1
  15. package/action/actions/OpenLinkAction.js +1 -1
  16. package/action/actions/RequestAction.d.ts +2 -1
  17. package/action/actions/ShowWidgetAction.d.ts +2 -1
  18. package/action/actions/SubscribeContactAction.d.ts +2 -1
  19. package/common/SysEventTypes.d.ts +6 -6
  20. package/common/SysEventTypes.js +1 -1
  21. package/document-model/ModulesComponentExtractor.js +1 -1
  22. package/handler/ClickHandler.js +1 -1
  23. package/package.json +10 -5
  24. package/renderer/style/ClDocumentResizeListener.js +1 -1
  25. package/renderer/style/DefaultMediaQueryListener.js +1 -1
  26. package/renderer/style/MobileDeviceOrientationListener.js +1 -1
  27. package/sdk/WcElement.js +1 -1
  28. package/sdk/accessor/StyleAttributeAccessor.js +1 -1
  29. package/sdk/source/sources/DataLayerSource.js +1 -1
  30. package/sdk/source/sources/JSApiVariablesSource.js +1 -1
  31. package/sdk/source/sources/UrlQueryParamsSource.js +1 -1
  32. package/sdk/validators/required.d.ts +6 -3
package/README.md ADDED
@@ -0,0 +1,52 @@
1
+ # @claspo/renderer
2
+
3
+ Core Web Components rendering engine for Claspo widgets.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @claspo/renderer
9
+ ```
10
+
11
+ **Requirements:** Node.js >= 18.16.0
12
+
13
+ ## Package Overview
14
+
15
+ This package provides:
16
+ - **Web Component Base Classes**: WcElement, WcControlledElement
17
+ - **Action System**: Handler execution, URL validation
18
+ - **Form Management**: FormControl, FormGroup, validation
19
+ - **Services**: EventEmitter, Context, Config, Tracking
20
+ - **View Routing**: Multi-view widget navigation
21
+
22
+ ## Architecture
23
+
24
+ ```
25
+ ┌─────────────────────────────────────────────────────────────┐
26
+ │ @claspo/renderer │
27
+ ├─────────────────────────────────────────────────────────────┤
28
+ │ ┌─────────────────────────────────────────────────────┐ │
29
+ │ │ Entry Modules │ │
30
+ │ │ StaticEntryModule | UpdatingEntryModule │ │
31
+ │ └─────────────────────────────────────────────────────┘ │
32
+ │ │ │
33
+ │ ┌─────────────┬──────────┴──────────┬─────────────────┐ │
34
+ │ │ Actions │ View Router │ Form System │ │
35
+ │ │ System │ │ │ │
36
+ │ └─────────────┴─────────────────────┴─────────────────┘ │
37
+ │ │ │
38
+ │ ┌─────────────────────────────────────────────────────┐ │
39
+ │ │ SDK (Base Classes) │ │
40
+ │ │ WcElement | WcControlledElement │ │
41
+ │ └─────────────────────────────────────────────────────┘ │
42
+ │ │ │
43
+ │ ┌─────────────────────────────────────────────────────┐ │
44
+ │ │ Services │ │
45
+ │ │ EventEmitter | Context | Config | Tracking | Form │ │
46
+ │ └─────────────────────────────────────────────────────┘ │
47
+ └─────────────────────────────────────────────────────────────┘
48
+ ```
49
+
50
+ ## Links
51
+
52
+ - [Documentation](https://docs.claspo.io/docs/claspoeditor)
package/RouterEvent.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- declare const SysRouterEvent: {
2
- readonly NAVIGATION_END: "NAVIGATION_END";
3
- };
4
- export type SysRouterEventT = typeof SysRouterEvent[keyof typeof SysRouterEvent];
1
+ declare enum SysRouterEvent {
2
+ NAVIGATION_END = "NAVIGATION_END"
3
+ }
5
4
  export default SysRouterEvent;
package/RouterEvent.js CHANGED
@@ -1 +1 @@
1
- const SysRouterEvent={NAVIGATION_END:"NAVIGATION_END"};export default SysRouterEvent;
1
+ var SysRouterEvent;!function(t){t.NAVIGATION_END="NAVIGATION_END"}(SysRouterEvent||(SysRouterEvent={}));export default SysRouterEvent;
@@ -1,9 +1,7 @@
1
1
  export default class InAppActionFactory {
2
2
  eventEmitter: any;
3
3
  constructor(eventEmitter: any);
4
- executeAction(actionType: any, { params }?: {
5
- params: any;
6
- }): {
4
+ executeAction(actionType: any, { params }?: {}): {
7
5
  execute: (state: any, e: any) => Promise<boolean>;
8
6
  };
9
7
  get(action: any): {
@@ -1,13 +1,13 @@
1
- declare const SysActionTypes: {
2
- SUBSCRIBE_CONTACT: string;
3
- REQUEST: string;
4
- DISPATCH_EVENT: string;
5
- GO_TO_VIEW: string;
6
- GO_TO_PREVIOUS_VIEW: string;
7
- GO_TO_NEXT_VIEW: string;
8
- SHOW_WIDGET: string;
9
- OPEN_LINK: string;
10
- CLOSE_WIDGET: string;
11
- CLICK: string;
12
- };
1
+ declare enum SysActionTypes {
2
+ SUBSCRIBE_CONTACT = "SUBSCRIBE_CONTACT",
3
+ REQUEST = "REQUEST",
4
+ DISPATCH_EVENT = "DISPATCH_EVENT",
5
+ GO_TO_VIEW = "GO_TO_VIEW",
6
+ GO_TO_PREVIOUS_VIEW = "GO_TO_PREVIOUS_VIEW",
7
+ GO_TO_NEXT_VIEW = "GO_TO_NEXT_VIEW",
8
+ SHOW_WIDGET = "SHOW_WIDGET",
9
+ OPEN_LINK = "OPEN_LINK",
10
+ CLOSE_WIDGET = "CLOSE_WIDGET",
11
+ CLICK = "CLICK"
12
+ }
13
13
  export default SysActionTypes;
@@ -1 +1 @@
1
- const SysActionTypes={SUBSCRIBE_CONTACT:"SUBSCRIBE_CONTACT",REQUEST:"REQUEST",DISPATCH_EVENT:"DISPATCH_EVENT",GO_TO_VIEW:"GO_TO_VIEW",GO_TO_PREVIOUS_VIEW:"GO_TO_PREVIOUS_VIEW",GO_TO_NEXT_VIEW:"GO_TO_NEXT_VIEW",SHOW_WIDGET:"SHOW_WIDGET",OPEN_LINK:"OPEN_LINK",CLOSE_WIDGET:"CLOSE_WIDGET",CLICK:"CLICK"};export default SysActionTypes;
1
+ var SysActionTypes;!function(E){E.SUBSCRIBE_CONTACT="SUBSCRIBE_CONTACT",E.REQUEST="REQUEST",E.DISPATCH_EVENT="DISPATCH_EVENT",E.GO_TO_VIEW="GO_TO_VIEW",E.GO_TO_PREVIOUS_VIEW="GO_TO_PREVIOUS_VIEW",E.GO_TO_NEXT_VIEW="GO_TO_NEXT_VIEW",E.SHOW_WIDGET="SHOW_WIDGET",E.OPEN_LINK="OPEN_LINK",E.CLOSE_WIDGET="CLOSE_WIDGET",E.CLICK="CLICK"}(SysActionTypes||(SysActionTypes={}));export default SysActionTypes;
@@ -1 +1 @@
1
- import SysActionTypes from"../SysActionTypes";import SysEventTypes from"../../common/SysEventTypes";import HttpStatus from"@claspo/common/network/HttpStatus";import ActionCategory from"./ActionCategory";import systemResultStateNames from"../../document-model/systemResultStateNames";import DocumentUtils from"@claspo/common/document/DocumentUtils";import getComponentCountOnView from"../../sdk/getComponentCountOnView";import UTMParamsExtractor from"../UTMParamsExtractor";function componentModelHasSubmitAction(t){var e,s;try{return!!(null===(s=null===(e=t.props)||void 0===e?void 0:e.handlers)||void 0===s?void 0:s.find(t=>{var e;return null===(e=null==t?void 0:t.actions)||void 0===e?void 0:e.find(t=>[SysActionTypes.REQUEST,SysActionTypes.SUBSCRIBE_CONTACT].includes(t.type))}))}catch(t){return!1}}function viewHasControls(t){if(!t)return!1;let e=0;return DocumentUtils.iterateDepthFirst(t,t=>{(["INPUT","MULTIPLE_INPUT","PRIZE_BASED_GAMING"].includes(t.type)||componentModelHasSubmitAction(t))&&e++}),e>0}function isSystemView(t){return t&&systemResultStateNames.includes(t.label)}export const RequestStatus={SUCCESS:"SUCCESS",ALREADY_SUBSCRIBED:"ALREADY_SUBSCRIBED",ERROR:"ERROR",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS"};export default class BaseRequestAction{constructor(t,e,s,i,n,o,r,a,c){this.skipHttpRequest=!0,this.id=s.id,this.params=s.params,this.form=e,this.eventEmitter=t,this.httpClient=i,this.configService=n,this.formEventsListener=null,this.tracking=o,this.stateService=r,this.context=a,this.getServices=c,this.category=ActionCategory.SUBMIT}getTrackingMessageBeforeSentData(){return""}getTrackingMessageByStatus(t){return""}execute(t,e,s,i){if(this.formEventsListener&&this.formEventsListener.off(),!this.form.submitQueuedAfterPending||!0===t){if(!this.form.preventSubmit)return new Promise(n=>{if(!this.form.isPending()){this.form.submitQueuedAfterPending=!1;const o=!0===t?e:n;return this.submit(o,s,i)}this.form.submitQueuedAfterPending=!0,setTimeout(()=>this.execute(!0,n,s,i),500)});this.form.submitQueuedAfterPending=!1}}submit(t,e,s){const i=this.getServices().viewRouter.getCurrentViewIndex(),n=this.getServices().documentModel.getViews().slice(i+1).filter(t=>!systemResultStateNames.includes(t.label)).length>0,o=Object.assign(Object.assign({},this.params),s);if(this.form.markAsTouched(),this.stateService.getState().emitActionOnSubmit&&this.eventEmitter.emit(this.stateService.getState().emitActionOnSubmit.eventName),this.stateService.getState().interceptSubmitActions&&!e)return;if(!this.form.isValid()&&!o.skipValidation)return this.eventEmitter.emit("INVALID_CONTACT_DATA_SUBMIT_ATTEMPT"),void t(!1);const r=this.stateService,a=r.getState().conditionalRedirectViewId,c=o.conditionalRedirectViewId||a;a&&(o.conditionalRedirectViewId=a,r.setState({conditionalRedirectViewId:null}));let u=this.getServices().documentModel.getViews()[i+1];const m=this.getServices().documentModel.getViews()[i];if(c&&getComponentCountOnView(m,"SysNetPromoterScoreComponent")+getComponentCountOnView(m,"SysFeedbackComponent")===1&&(u=this.getServices().documentModel.getViews().find(t=>t.id===o.conditionalRedirectViewId),viewHasControls(u)||isSystemView(u)))return this.goToView(u.path[0],o),void t(!0);const S=this.form.getControlsMap(),d=this.context.getKVMap();if(n&&(viewHasControls(u)||!Object.keys(S).length&&!Object.keys(d).length))return this.goToView(i+1,o),void t(!0);if(!Object.keys(S).length&&!Object.keys(d).length)return void t(!0);const l=UTMParamsExtractor.extractUtmParams(this.context),g=this.constructRequestPayload({contextValue:d,formValue:S,utmParams:l});this.eventEmitter.emit("CONTACT_DATA_SUBMIT",g);this.getTrackingMessageBeforeSentData()&&this.tracking.send("FormFinish_[Name]"),this.configService.getConfig("isBot")?t():this.sendRequest(g).then(t=>t.json().then(e=>t.status===HttpStatus.TOO_MANY_REQUESTS?{state:RequestStatus.TOO_MANY_REQUESTS}:{contactId:e.contactId,state:e&&e.next&&e.next.type}),()=>({state:RequestStatus.ERROR})).then(e=>{const s=this.getTrackingMessageByStatus(e.state);switch(e.state){case RequestStatus.SUCCESS:s&&this.tracking.send(s),this.goToView(n&&u?u.path[0]:this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_SUCCESS"===t.label||"DOCUMENT_VIEW_TYPE_SUCCESSFUL_REQUEST"===t.label||"REQUEST_FORM_VIEW_TYPE_SUCCESS"===t.label));break;case RequestStatus.ALREADY_SUBSCRIBED:s&&this.tracking.send(s),this.goToView(c&&u?u.path[0]:this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_SUBSCRIBED"===t.label));break;case RequestStatus.ERROR:s&&this.tracking.send(s),this.goToView(c&&u?u.path[0]:this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_ERROR"===t.label));break;case RequestStatus.TOO_MANY_REQUESTS:s&&this.tracking.send(s),this.goToView(c&&u?u.path[0]:this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_ERROR"===t.label)),this.eventEmitter.emit(SysEventTypes.TOO_MANY_REQUESTS)}e.contactId&&"0"!==e.contactId&&this.eventEmitter.emit("CONTACT_ID_WAS_RECEIVED",e.contactId),t(e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED)}).catch(()=>{this.goToView(this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_ERROR"===t.label)),t(!1)})}constructDataToSent({contextValue:t,formValue:e,utmParams:s}){const i=Object.assign({},t);return i.tracking=s,Object.keys(e).forEach(t=>{if(t.startsWith("clConsentId")){if(t.endsWith("_label"))return;const s={value:e[t]};e[`${t}_label`]&&(s.text=e[`${t}_label`]),i.consents?i.consents[t]=s:i.consents={[t]:s}}else i[t]=e[t]}),i}constructRequestPayload({contextValue:t,formValue:e,utmParams:s}){let i={data:this.constructDataToSent({contextValue:t,formValue:e,utmParams:s}),referrer:window.location.href,triggeredBy:this.configService.getConfig("triggeredBy")};return this.configService.getConfig("widgetDebugMode")&&(i.ignoreTracking=!0),i}constructRequestHeaders(){const t={},e=this.configService.getConfig("clCustomerId");return e&&Object.assign(t,{"cl-customer-id":e}),t}goToView(t,e){this.eventEmitter.emit(SysActionTypes.GO_TO_VIEW,t,e)}sendRequest(t){return this.skipHttpRequest?Promise.resolve({status:200,json:()=>Promise.resolve({next:{type:RequestStatus.SUCCESS}})}):this.httpClient.execute(this.configService.getConfig("subscribeContactUrl"),"POST",t,this.constructRequestHeaders())}}
1
+ import SysActionTypes from"../SysActionTypes";import SysEventTypes from"../../common/SysEventTypes";import{HttpStatus}from"@claspo/common/network/HttpStatus";import ActionCategory from"./ActionCategory";import systemResultStateNames from"../../document-model/systemResultStateNames";import DocumentUtils from"@claspo/common/document/DocumentUtils";import getComponentCountOnView from"../../sdk/getComponentCountOnView";import UTMParamsExtractor from"../UTMParamsExtractor";function componentModelHasSubmitAction(t){var e,s;try{return!!(null===(s=null===(e=t.props)||void 0===e?void 0:e.handlers)||void 0===s?void 0:s.find(t=>{var e;return null===(e=null==t?void 0:t.actions)||void 0===e?void 0:e.find(t=>[SysActionTypes.REQUEST,SysActionTypes.SUBSCRIBE_CONTACT].includes(t.type))}))}catch(t){return!1}}function viewHasControls(t){if(!t)return!1;let e=0;return DocumentUtils.iterateDepthFirst(t,t=>{(["INPUT","MULTIPLE_INPUT","PRIZE_BASED_GAMING"].includes(t.type)||componentModelHasSubmitAction(t))&&e++}),e>0}function isSystemView(t){return t&&systemResultStateNames.includes(t.label)}export const RequestStatus={SUCCESS:"SUCCESS",ALREADY_SUBSCRIBED:"ALREADY_SUBSCRIBED",ERROR:"ERROR",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS"};export default class BaseRequestAction{constructor(t,e,s,i,n,o,r,a,c){this.skipHttpRequest=!0,this.id=s.id,this.params=s.params,this.form=e,this.eventEmitter=t,this.httpClient=i,this.configService=n,this.formEventsListener=null,this.tracking=o,this.stateService=r,this.context=a,this.getServices=c,this.category=ActionCategory.SUBMIT}getTrackingMessageBeforeSentData(){return""}getTrackingMessageByStatus(t){return""}execute(t,e,s,i){if(this.formEventsListener&&this.formEventsListener.off(),!this.form.submitQueuedAfterPending||!0===t){if(!this.form.preventSubmit)return new Promise(n=>{if(!this.form.isPending()){this.form.submitQueuedAfterPending=!1;const o=!0===t?e:n;return this.submit(o,s,i)}this.form.submitQueuedAfterPending=!0,setTimeout(()=>this.execute(!0,n,s,i),500)});this.form.submitQueuedAfterPending=!1}}submit(t,e,s){const i=this.getServices().viewRouter.getCurrentViewIndex(),n=this.getServices().documentModel.getViews().slice(i+1).filter(t=>!systemResultStateNames.includes(t.label)).length>0,o=Object.assign(Object.assign({},this.params),s);if(this.form.markAsTouched(),this.stateService.getState().emitActionOnSubmit&&this.eventEmitter.emit(this.stateService.getState().emitActionOnSubmit.eventName),this.stateService.getState().interceptSubmitActions&&!e)return;if(!this.form.isValid()&&!o.skipValidation)return this.eventEmitter.emit("INVALID_CONTACT_DATA_SUBMIT_ATTEMPT"),void t(!1);const r=this.stateService,a=r.getState().conditionalRedirectViewId,c=o.conditionalRedirectViewId||a;a&&(o.conditionalRedirectViewId=a,r.setState({conditionalRedirectViewId:null}));let u=this.getServices().documentModel.getViews()[i+1];const m=this.getServices().documentModel.getViews()[i];if(c&&getComponentCountOnView(m,"SysNetPromoterScoreComponent")+getComponentCountOnView(m,"SysFeedbackComponent")===1&&(u=this.getServices().documentModel.getViews().find(t=>t.id===o.conditionalRedirectViewId),viewHasControls(u)||isSystemView(u)))return this.goToView(u.path[0],o),void t(!0);const S=this.form.getControlsMap(),d=this.context.getKVMap();if(n&&(viewHasControls(u)||!Object.keys(S).length&&!Object.keys(d).length))return this.goToView(i+1,o),void t(!0);if(!Object.keys(S).length&&!Object.keys(d).length)return void t(!0);const l=UTMParamsExtractor.extractUtmParams(this.context),g=this.constructRequestPayload({contextValue:d,formValue:S,utmParams:l});this.eventEmitter.emit("CONTACT_DATA_SUBMIT",g);this.getTrackingMessageBeforeSentData()&&this.tracking.send("FormFinish_[Name]"),this.configService.getConfig("isBot")?t():this.sendRequest(g).then(t=>t.json().then(e=>t.status===HttpStatus.TOO_MANY_REQUESTS?{state:RequestStatus.TOO_MANY_REQUESTS}:{contactId:e.contactId,state:e&&e.next&&e.next.type}),()=>({state:RequestStatus.ERROR})).then(e=>{const s=this.getTrackingMessageByStatus(e.state);switch(e.state){case RequestStatus.SUCCESS:s&&this.tracking.send(s),this.goToView(n&&u?u.path[0]:this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_SUCCESS"===t.label||"DOCUMENT_VIEW_TYPE_SUCCESSFUL_REQUEST"===t.label||"REQUEST_FORM_VIEW_TYPE_SUCCESS"===t.label));break;case RequestStatus.ALREADY_SUBSCRIBED:s&&this.tracking.send(s),this.goToView(c&&u?u.path[0]:this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_SUBSCRIBED"===t.label));break;case RequestStatus.ERROR:s&&this.tracking.send(s),this.goToView(c&&u?u.path[0]:this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_ERROR"===t.label));break;case RequestStatus.TOO_MANY_REQUESTS:s&&this.tracking.send(s),this.goToView(c&&u?u.path[0]:this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_ERROR"===t.label)),this.eventEmitter.emit(SysEventTypes.TOO_MANY_REQUESTS)}e.contactId&&"0"!==e.contactId&&this.eventEmitter.emit("CONTACT_ID_WAS_RECEIVED",e.contactId),t(e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED)}).catch(()=>{this.goToView(this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_ERROR"===t.label)),t(!1)})}constructDataToSent({contextValue:t,formValue:e,utmParams:s}){const i=Object.assign({},t);return i.tracking=s,Object.keys(e).forEach(t=>{if(t.startsWith("clConsentId")){if(t.endsWith("_label"))return;const s={value:e[t]};e[`${t}_label`]&&(s.text=e[`${t}_label`]),i.consents?i.consents[t]=s:i.consents={[t]:s}}else i[t]=e[t]}),i}constructRequestPayload({contextValue:t,formValue:e,utmParams:s}){let i={data:this.constructDataToSent({contextValue:t,formValue:e,utmParams:s}),referrer:window.location.href,triggeredBy:this.configService.getConfig("triggeredBy")};return this.configService.getConfig("widgetDebugMode")&&(i.ignoreTracking=!0),i}constructRequestHeaders(){const t={},e=this.configService.getConfig("clCustomerId");return e&&Object.assign(t,{"cl-customer-id":e}),t}goToView(t,e){this.eventEmitter.emit(SysActionTypes.GO_TO_VIEW,t,e)}sendRequest(t){return this.skipHttpRequest?Promise.resolve({status:200,json:()=>Promise.resolve({next:{type:RequestStatus.SUCCESS}})}):this.httpClient.execute(this.configService.getConfig("subscribeContactUrl"),"POST",t,this.constructRequestHeaders())}}
@@ -1,9 +1,10 @@
1
+ import SysActionTypes from "../SysActionTypes";
1
2
  export default class CloseWidgetAction {
2
3
  params: any;
3
4
  eventEmitter: any;
4
5
  configService: any;
5
6
  tracking: any;
6
- type: string;
7
+ type: SysActionTypes;
7
8
  constructor(eventEmitter: any, actionConfig: any, configService: any, tracking: any);
8
9
  execute(): Promise<unknown>;
9
10
  }
@@ -1,7 +1,8 @@
1
+ import SysActionTypes from "../SysActionTypes";
1
2
  export default class DispatchEventAction {
2
3
  eventEmitter: any;
3
4
  config: any;
4
- type: string;
5
+ type: SysActionTypes;
5
6
  constructor(eventEmitter: any, config: any);
6
7
  execute(payload: any): Promise<boolean>;
7
8
  }
@@ -1,9 +1,10 @@
1
+ import SysActionTypes from "../SysActionTypes";
1
2
  export default class GoToNextViewAction {
2
3
  eventEmitter: any;
3
4
  form: any;
4
5
  config: any;
5
6
  tracking: any;
6
- type: string;
7
+ type: SysActionTypes;
7
8
  constructor(eventEmitter: any, form: any, config: any, tracking: any);
8
9
  execute(): Promise<boolean>;
9
10
  }
@@ -1,8 +1,9 @@
1
+ import SysActionTypes from "../SysActionTypes";
1
2
  export default class GoToPreviousViewAction {
2
3
  eventEmitter: any;
3
4
  config: any;
4
5
  tracking: any;
5
- type: string;
6
+ type: SysActionTypes;
6
7
  constructor(eventEmitter: any, config: any, tracking: any);
7
8
  execute(): Promise<boolean>;
8
9
  }
@@ -1,3 +1,4 @@
1
+ import SysActionTypes from "../SysActionTypes";
1
2
  export default class GoToViewAction {
2
3
  eventEmitter: any;
3
4
  config: any;
@@ -5,7 +6,7 @@ export default class GoToViewAction {
5
6
  viewRouter: any;
6
7
  documentModel: any;
7
8
  tracking: any;
8
- type: string;
9
+ type: SysActionTypes;
9
10
  constructor(eventEmitter: any, actionConfig: any, configService: any, form: any, viewRouter: any, documentModel: any, tracking: any);
10
11
  execute(): Promise<boolean>;
11
12
  }
@@ -1,7 +1,8 @@
1
+ import SysActionTypes from "../SysActionTypes";
1
2
  export default class InAppOpenLinkAction {
2
3
  params: any;
3
4
  eventEmitter: any;
4
- type: string;
5
+ type: SysActionTypes;
5
6
  constructor(eventEmitter: any, action: any);
6
7
  execute(state: any, event: any): Promise<boolean>;
7
8
  constructCustomData(customData: any): any;
@@ -1,8 +1,9 @@
1
+ import SysActionTypes from "../SysActionTypes";
1
2
  export default class OpenLinkAction {
2
3
  params: any;
3
4
  configService: any;
4
5
  tracking: any;
5
- type: string;
6
+ type: SysActionTypes;
6
7
  constructor(actionConfig: any, configService: any, tracking: any);
7
8
  execute(state: any, event: any): Promise<boolean>;
8
9
  static appendQueryParamsToLink(link: any, queryParams: any): string;
@@ -1 +1 @@
1
- import SysActionTypes from"../SysActionTypes";import sanitizeUrl from"@claspo/common/url/sanitizeUrl";export default class OpenLinkAction{constructor(t,a,e){this.type=SysActionTypes.OPEN_LINK,this.params=t.params,this.configService=a,this.tracking=e}execute(t,a){a.stopPropagation(),this.tracking.send("FormClick_[Name]"),this.tracking.trackTargetAction(this.params.countAsTargetAction),this.tracking.trackClick({params:this.params.trackClickParams,countAsTargetAction:this.params.countAsTargetAction});let e=this.params.link;const n=this.configService.getConfig("utmTag");if(this.params.tagsEnabled&&(null==n?void 0:n.enabled)){const t=OpenLinkAction.getDynamicUtmParamsMap(this.configService),a=OpenLinkAction.getUtmTags(n,t);e=OpenLinkAction.appendQueryParamsToLink(this.params.link,a)}return window.open(sanitizeUrl(e),this.params.target),Promise.resolve(!0)}static appendQueryParamsToLink(t,a){const e=new URL(t);return Object.keys(a).forEach(t=>{e.searchParams.has(t)||e.searchParams.append(t,a[t])}),e.href}static getUtmTags(t,a){const e={},n=new Map([["utmSource","utm_source"],["utmMedium","utm_medium"],["utmCampaign","utm_campaign"],["utmContent","utm_content"],["utmTerm","utm_term"]]);return["utmSource","utmMedium","utmCampaign","utmContent","utmTerm"].filter(a=>void 0!==(null==t?void 0:t[a])).forEach(i=>{const o=n.get(i),s=a.has(t[i])?a.get(t[i]):encodeURIComponent(t[i]);e[o]=s}),(null==t?void 0:t.customTagsEnabled)&&Object.keys((null==t?void 0:t.utmCustomTags)||{}).filter(a=>{var e;return void 0!==(null===(e=null==t?void 0:t.utmCustomTags)||void 0===e?void 0:e[a])}).forEach(n=>{e[n]=a.has(t.utmCustomTags[n])?a.get(t.utmCustomTags[n]):encodeURIComponent(t.utmCustomTags[n])}),e}static getDynamicUtmParamsMap(t){const a=a=>OpenLinkAction.normalizeUtmParam(t.getConfig(a));return new Map([["$widgetId",a("widgetId")],["$widgetName",encodeURIComponent(a("widgetName"))],["$widgetType",a("layoutType")],["$widgetLang",a("browserLanguage")],["$contactId",encodeURIComponent(a("clContactId"))]])}static normalizeUtmParam(t){return null==t?"":String(t)}}
1
+ import SysActionTypes from"../SysActionTypes";import sanitizeUrl from"@claspo/common/url/sanitizeUrl";export default class OpenLinkAction{constructor(t,a,e){this.type=SysActionTypes.OPEN_LINK,this.params=t.params,this.configService=a,this.tracking=e}execute(t,a){a.stopPropagation(),this.tracking.send("FormClick_[Name]"),this.tracking.trackTargetAction(this.params.countAsTargetAction),this.tracking.trackClick({params:this.params.trackClickParams,countAsTargetAction:this.params.countAsTargetAction});let e=this.params.link;const n=this.configService.getConfig("utmTag");if(this.params.tagsEnabled&&(null==n?void 0:n.enabled)){const t=OpenLinkAction.getDynamicUtmParamsMap(this.configService),a=OpenLinkAction.getUtmTags(n,t);e=OpenLinkAction.appendQueryParamsToLink(this.params.link,a)}return window.open(sanitizeUrl(e),this.params.target),Promise.resolve(!0)}static appendQueryParamsToLink(t,a){const e=new URL(t);return Object.keys(a).forEach(t=>{e.searchParams.has(t)||e.searchParams.append(t,a[t])}),e.href}static getUtmTags(t,a){const e={},n=new Map([["utmSource","utm_source"],["utmMedium","utm_medium"],["utmCampaign","utm_campaign"],["utmContent","utm_content"],["utmTerm","utm_term"]]);return["utmSource","utmMedium","utmCampaign","utmContent","utmTerm"].filter(a=>void 0!==(null==t?void 0:t[a])).forEach(i=>{const o=n.get(i),s=a.has(t[i])?a.get(t[i]):encodeURIComponent(t[i]);e[o]=s}),(null==t?void 0:t.customTagsEnabled)&&Object.keys((null==t?void 0:t.utmCustomTags)||{}).filter(a=>{var e;return void 0!==(null===(e=null==t?void 0:t.utmCustomTags)||void 0===e?void 0:e[a])}).forEach(n=>{e[n]=a.has(t.utmCustomTags[n])?a.get(t.utmCustomTags[n]):encodeURIComponent(t.utmCustomTags[n])}),e}static getDynamicUtmParamsMap(t){const a=a=>OpenLinkAction.normalizeUtmParam(t.getConfig(a));return new Map([["$widgetId",a("formVariantId")],["$widgetName",encodeURIComponent(a("widgetName"))],["$widgetType",a("layoutType")],["$widgetLang",a("browserLanguage")],["$contactId",encodeURIComponent(a("clContactId"))]])}static normalizeUtmParam(t){return null==t?"":String(t)}}
@@ -1,6 +1,7 @@
1
+ import SysActionTypes from '../SysActionTypes';
1
2
  import BaseRequestAction from "./BaseRequestAction";
2
3
  export default class RequestAction extends BaseRequestAction {
3
- type: string;
4
+ type: SysActionTypes;
4
5
  getTrackingMessageBeforeSentData(): string;
5
6
  getTrackingMessageByStatus(status: any): string;
6
7
  }
@@ -1,8 +1,9 @@
1
+ import SysActionTypes from "../SysActionTypes";
1
2
  export default class ShowWidgetAction {
2
3
  params: any;
3
4
  eventEmitter: any;
4
5
  tracking: any;
5
- type: string;
6
+ type: SysActionTypes;
6
7
  constructor(eventEmitter: any, action: any, tracking: any);
7
8
  execute(): Promise<boolean>;
8
9
  }
@@ -1,7 +1,8 @@
1
+ import SysActionTypes from '../SysActionTypes';
1
2
  import BaseRequestAction from "./BaseRequestAction";
2
3
  export default class SubscribeContactAction extends BaseRequestAction {
3
4
  formEventsListener: any;
4
- type: string;
5
+ type: SysActionTypes;
5
6
  formDataValidation(formValue: any): boolean;
6
7
  getTrackingMessageBeforeSentData(): string;
7
8
  getTrackingMessageByStatus(status: any): string;
@@ -1,7 +1,7 @@
1
- declare const SysEventTypes: {
2
- TOO_MANY_REQUESTS: string;
3
- COMPONENT_RESOURCES_LOADED: string;
4
- FAILED_TO_LOAD_COMPONENT_RESOURCE: string;
5
- EXECUTE_ACTION_BY_PREDICATE: string;
6
- };
1
+ declare enum SysEventTypes {
2
+ TOO_MANY_REQUESTS = "TOO_MANY_REQUESTS",
3
+ COMPONENT_RESOURCES_LOADED = "COMPONENT_RESOURCES_LOADED",
4
+ FAILED_TO_LOAD_COMPONENT_RESOURCE = "FAILED_TO_LOAD_COMPONENT_RESOURCE",
5
+ EXECUTE_ACTION_BY_PREDICATE = "EXECUTE_ACTION_BY_PREDICATE"
6
+ }
7
7
  export default SysEventTypes;
@@ -1 +1 @@
1
- const SysEventTypes={TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS",COMPONENT_RESOURCES_LOADED:"COMPONENT_RESOURCES_LOADED",FAILED_TO_LOAD_COMPONENT_RESOURCE:"FAILED_TO_LOAD_COMPONENT_RESOURCE",EXECUTE_ACTION_BY_PREDICATE:"EXECUTE_ACTION_BY_PREDICATE"};export default SysEventTypes;
1
+ var SysEventTypes;!function(E){E.TOO_MANY_REQUESTS="TOO_MANY_REQUESTS",E.COMPONENT_RESOURCES_LOADED="COMPONENT_RESOURCES_LOADED",E.FAILED_TO_LOAD_COMPONENT_RESOURCE="FAILED_TO_LOAD_COMPONENT_RESOURCE",E.EXECUTE_ACTION_BY_PREDICATE="EXECUTE_ACTION_BY_PREDICATE"}(SysEventTypes||(SysEventTypes={}));export default SysEventTypes;
@@ -1 +1 @@
1
- import ViewEntryType from"./ViewEntryType";export default class ModulesComponentExtractor{static extract(e){const t=e.views.map(e=>{const t=e.children.map(e=>e.type===ViewEntryType.MODULE?Object.assign(Object.assign({},e),ModulesComponentExtractor.moduleToContainerParams):e);return Object.assign(Object.assign({},e),{children:t})});return Object.assign(Object.assign({},e),{views:t})}static sort(e,t){return e.index>t.index?1:-1}static reIndex(e,t){return Object.assign(Object.assign({},e),{index:t+e.index})}}ModulesComponentExtractor.moduleToContainerParams={name:"SysContainerComponent",version:"1.0.0"};
1
+ import ViewEntryType from"./ViewEntryType";class ModulesComponentExtractor{static extract(e){const t=e.views.map(e=>{const t=e.children.map(e=>e.type===ViewEntryType.MODULE?Object.assign(Object.assign({},e),ModulesComponentExtractor.moduleToContainerParams):e);return Object.assign(Object.assign({},e),{children:t})});return Object.assign(Object.assign({},e),{views:t})}static sort(e,t){return e.index>t.index?1:-1}static reIndex(e,t){return Object.assign(Object.assign({},e),{index:t+e.index})}}ModulesComponentExtractor.moduleToContainerParams={name:"SysContainerComponent",version:"1.0.0"};export default ModulesComponentExtractor;
@@ -1 +1 @@
1
- var __asyncValues=this&&this.__asyncValues||function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,s=t[Symbol.asyncIterator];return s?s.call(t):(t="function"==typeof __values?__values(t):t[Symbol.iterator](),e={},r("next"),r("throw"),r("return"),e[Symbol.asyncIterator]=function(){return this},e);function r(s){e[s]=t[s]&&function(e){return new Promise(function(r,n){(function(t,e,s,r){Promise.resolve(r).then(function(e){t({value:e,done:s})},e)})(r,n,(e=t[s](e)).done,e.value)})}}};import{applySysAttrPrefix}from"../renderer/RenderConstants";import ViewEntryType from"../document-model/ViewEntryType";import SysActionTypes from"../action/SysActionTypes";export class ClickHandler{static sortActions(t){const e={[SysActionTypes.CLOSE_WIDGET]:-1,[SysActionTypes.OPEN_LINK]:-2,[SysActionTypes.SHOW_WIDGET]:1,[SysActionTypes.SUBSCRIBE_CONTACT]:2,[SysActionTypes.REQUEST]:3},s=t=>void 0!==e[t.type]?e[t.type]:0;return[...t].sort((t,e)=>s(t)>s(e)?-1:s(t)<s(e)?1:0)}constructor(t,e){this.config=t,this.actions=ClickHandler.sortActions(e),this.listener=null,this.targetElements=[],this.eventsQueue=[],this.state=null,this.postponed=!1}activate(t,e,s){this.state=t;const r=s(),n=r.getAttribute(applySysAttrPrefix("id"));this.listener=t=>{const e=t.composedPath().filter(t=>t instanceof HTMLElement&&t.getAttribute(applySysAttrPrefix("type")));let s=0;for(;e[s]&&e[s].getAttribute(applySysAttrPrefix("id"))!==n;){let t=e[s].getAttribute(applySysAttrPrefix("type"));if(ClickHandler.IGNORING_VIEW_ENTRY_TYPES.includes(t))return;s++}this.eventsQueue.push({event:t}),this.postponed||this.execute()},this.targetElements=this.config.relativeSelector?Array.from((r.shadowRoot||r).querySelectorAll(this.config.relativeSelector)):[r],this.targetElements.forEach(t=>{t.addEventListener("click",this.listener)})}async execute(){var t,e,s,r;try{for(var n,i=!0,o=__asyncValues(this.eventsQueue);!(t=(n=await o.next()).done);){r=n.value,i=!1;try{const{event:t}=r;for(const e of this.actions){if(!await e.execute(this.state.getState(),t))break}}finally{i=!0}}}catch(t){e={error:t}}finally{try{i||t||!(s=o.return)||await s.call(o)}finally{if(e)throw e.error}}this.eventsQueue=[]}postpone(){this.postponed=!0}release(){this.postponed=!1,this.execute()}destroy(){this.listener&&this.targetElements.length&&(this.targetElements.forEach(t=>{t.removeEventListener("click",this.listener)}),this.targetElements=[])}}ClickHandler.IGNORING_VIEW_ENTRY_TYPES=[ViewEntryType.BUTTON,ViewEntryType.CONSENT,ViewEntryType.INPUT];
1
+ var __asyncValues=this&&this.__asyncValues||function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,s=t[Symbol.asyncIterator];return s?s.call(t):(t="function"==typeof __values?__values(t):t[Symbol.iterator](),e={},r("next"),r("throw"),r("return"),e[Symbol.asyncIterator]=function(){return this},e);function r(s){e[s]=t[s]&&function(e){return new Promise(function(r,n){(function(t,e,s,r){Promise.resolve(r).then(function(e){t({value:e,done:s})},e)})(r,n,(e=t[s](e)).done,e.value)})}}};import{applySysAttrPrefix}from"../renderer/RenderConstants";import ViewEntryType from"../document-model/ViewEntryType";import SysActionTypes from"../action/SysActionTypes";export class ClickHandler{static sortActions(t){const e={[SysActionTypes.CLOSE_WIDGET]:-1,[SysActionTypes.OPEN_LINK]:-2,[SysActionTypes.SHOW_WIDGET]:1,[SysActionTypes.SUBSCRIBE_CONTACT]:2,[SysActionTypes.REQUEST]:3},s=t=>void 0!==e[t.type]?e[t.type]:0;return[...t].sort((t,e)=>s(t)>s(e)?-1:s(t)<s(e)?1:0)}constructor(t,e){this.config=t,this.actions=ClickHandler.sortActions(e),this.listener=null,this.targetElements=[],this.eventsQueue=[],this.state=null,this.postponed=!1}activate(t,e,s){this.state=t;const r=s(),n=r.getAttribute(applySysAttrPrefix("id"));this.listener=t=>{const e=t.composedPath().filter(t=>t instanceof HTMLElement&&t.getAttribute(applySysAttrPrefix("type")));let s=0;for(;e[s]&&e[s].getAttribute(applySysAttrPrefix("id"))!==n;){let t=e[s].getAttribute(applySysAttrPrefix("type"));if(ClickHandler.IGNORING_VIEW_ENTRY_TYPES.includes(t))return;s++}this.eventsQueue.push({event:t}),this.postponed||this.execute()},this.targetElements=this.config.relativeSelector?Array.from((r.shadowRoot||r).querySelectorAll(this.config.relativeSelector)):[r],this.targetElements.forEach(t=>{t.addEventListener("click",this.listener)})}async execute(){var t,e,s,r;try{for(var n,i=!0,o=__asyncValues(this.eventsQueue);!(t=(n=await o.next()).done);i=!0){r=n.value,i=!1;const{event:t}=r;for(const e of this.actions){if(!await e.execute(this.state.getState(),t))break}}}catch(t){e={error:t}}finally{try{i||t||!(s=o.return)||await s.call(o)}finally{if(e)throw e.error}}this.eventsQueue=[]}postpone(){this.postponed=!0}release(){this.postponed=!1,this.execute()}destroy(){this.listener&&this.targetElements.length&&(this.targetElements.forEach(t=>{t.removeEventListener("click",this.listener)}),this.targetElements=[])}}ClickHandler.IGNORING_VIEW_ENTRY_TYPES=[ViewEntryType.BUTTON,ViewEntryType.CONSENT,ViewEntryType.INPUT];
package/package.json CHANGED
@@ -1,19 +1,20 @@
1
1
  {
2
2
  "name": "@claspo/renderer",
3
- "version": "17.0.2",
3
+ "version": "17.0.4",
4
4
  "scripts": {
5
5
  "dev": " tsc --project tsconfig.json --watch",
6
6
  "build": "rm -rf out && tsc --project tsconfig.json && npm run minify",
7
+ "build:docs": "rm -rf ./docs && typedoc --options typedoc.md.json && npx concat-md --decrease-title-levels docs > docs/index.md && find docs -name '*.md' ! -name 'index.md' -delete",
7
8
  "minify": "find out -name '*.js' ! -name '*.d.js' -exec terser {} --compress --mangle --output {} \\;",
8
9
  "test": "jest --no-cache --coverage",
9
10
  "lint": "eslint src",
10
- "package": "npm i && npm run lint && npm run test && npm run build && cp package.json out && cd out && npm publish --access=public && cd .."
11
+ "package": "npm i && npm run lint && npm run test && npm run build && cp package.json README.md out && cd out && npm publish --access=public && cd .."
11
12
  },
12
13
  "engines": {
13
14
  "node": ">=18.16.0"
14
15
  },
15
16
  "dependencies": {
16
- "@claspo/common": "6.0.5",
17
+ "@claspo/common": "6.0.6",
17
18
  "@testing-library/dom": "^10.4.0"
18
19
  },
19
20
  "devDependencies": {
@@ -22,18 +23,22 @@
22
23
  "@types/jest": "^27.5.1",
23
24
  "@typescript-eslint/parser": "^8.53.0",
24
25
  "babel-loader": "^9.1.3",
26
+ "concat-md": "^0.5.1",
25
27
  "eslint": "^9.15.0",
28
+ "glob": "^8.0.3",
26
29
  "jest": "^28.1.0",
27
30
  "jest-environment-jsdom": "^28.1.0",
28
31
  "terser": "^5.37.0",
29
32
  "ts-jest": "^28.0.3",
30
33
  "ts-loader": "^9.5.0",
31
34
  "ts-node": "^10.8.0",
32
- "typescript": "^4.9.5",
35
+ "typedoc": "^0.28.0",
36
+ "typedoc-plugin-markdown": "^4.4.1",
37
+ "typescript": "^5.8.2",
33
38
  "webpack": "^5.89.0",
34
39
  "webpack-cli": "^5.1.4"
35
40
  },
36
41
  "author": "alex-chernysh",
37
42
  "license": "",
38
- "homepage": "https://claspo.io/"
43
+ "homepage": "https://docs.claspo.io/docs/claspoeditor"
39
44
  }
@@ -1 +1 @@
1
- import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{DocumentModelUpdateType}from"../../document-model/DocumentModelService";export default class ClDocumentResizeListener extends DefaultEventEmitter{constructor(e,t){super(),this.documentModel=e,this.containerElement=t,this.mobileBreakpointWidth=this.documentModel.getShared().mobileBreakpointWidth,this._isMobile=this._calculateMobileFlag(),this.documentModel.on(DocumentModelUpdateType.ENVIRONMENT_UPDATE,e=>{this._isMobile=e.isMobileEnv,this.emit(ClDocumentResizeListener.changeEventName,this._isMobile)})}isMobile(){return this._isMobile}destroy(){super.destroy()}_calculateMobileFlag(){return this._getElementsWidthPx(this.containerElement)<=this.mobileBreakpointWidth}_getElementsWidthPx(e){return parseInt(getComputedStyle(e).width)}}ClDocumentResizeListener.changeEventName="CHANGE";
1
+ import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{DocumentModelUpdateType}from"../../document-model/DocumentModelService";class ClDocumentResizeListener extends DefaultEventEmitter{constructor(e,t){super(),this.documentModel=e,this.containerElement=t,this.mobileBreakpointWidth=this.documentModel.getShared().mobileBreakpointWidth,this._isMobile=this._calculateMobileFlag(),this.documentModel.on(DocumentModelUpdateType.ENVIRONMENT_UPDATE,e=>{this._isMobile=e.isMobileEnv,this.emit(ClDocumentResizeListener.changeEventName,this._isMobile)})}isMobile(){return this._isMobile}destroy(){super.destroy()}_calculateMobileFlag(){return this._getElementsWidthPx(this.containerElement)<=this.mobileBreakpointWidth}_getElementsWidthPx(e){return parseInt(getComputedStyle(e).width)}}ClDocumentResizeListener.changeEventName="CHANGE";export default ClDocumentResizeListener;
@@ -1 +1 @@
1
- import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{DocumentModelUpdateType}from"../../document-model/DocumentModelService";export default class DefaultMediaQueryListener extends DefaultEventEmitter{constructor(e,i){super(),this.config=i,this.handleMobileBreakpoint(e.getShared().mobileBreakpointWidth),e.on(DocumentModelUpdateType.ENVIRONMENT_UPDATE,({isMobileEnv:e})=>{this._isMobile=e,this.emit(DefaultMediaQueryListener.changeEventName,this._isMobile)})}handleMobileBreakpoint(e){this.mobileBreakpointWidth=e;const i=Number.isInteger(this.mobileBreakpointWidth)?`${this.mobileBreakpointWidth}px`:this.mobileBreakpointWidth;this.mediaQueryList=window.matchMedia(`(max-width: ${i})`),this.mediaQueryList.addListener(this.listener.bind(this)),this._isMobile=this.mediaQueryList.matches,this.emit(DefaultMediaQueryListener.changeEventName,this._isMobile)}isMobile(){return this.config.forceMobileEnv||this._isMobile}listener(e){this._isMobile=e.matches,this.emit(DefaultMediaQueryListener.changeEventName,this._isMobile)}destroy(){super.destroy(),this.mediaQueryList.removeListener(this.listener.bind(this))}}DefaultMediaQueryListener.changeEventName="CHANGE";
1
+ import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{DocumentModelUpdateType}from"../../document-model/DocumentModelService";class DefaultMediaQueryListener extends DefaultEventEmitter{constructor(e,i){super(),this.config=i,this.handleMobileBreakpoint(e.getShared().mobileBreakpointWidth),e.on(DocumentModelUpdateType.ENVIRONMENT_UPDATE,({isMobileEnv:e})=>{this._isMobile=e,this.emit(DefaultMediaQueryListener.changeEventName,this._isMobile)})}handleMobileBreakpoint(e){this.mobileBreakpointWidth=e;const i=Number.isInteger(this.mobileBreakpointWidth)?`${this.mobileBreakpointWidth}px`:this.mobileBreakpointWidth;this.mediaQueryList=window.matchMedia(`(max-width: ${i})`),this.mediaQueryList.addListener(this.listener.bind(this)),this._isMobile=this.mediaQueryList.matches,this.emit(DefaultMediaQueryListener.changeEventName,this._isMobile)}isMobile(){return this.config.forceMobileEnv||this._isMobile}listener(e){this._isMobile=e.matches,this.emit(DefaultMediaQueryListener.changeEventName,this._isMobile)}destroy(){super.destroy(),this.mediaQueryList.removeListener(this.listener.bind(this))}}DefaultMediaQueryListener.changeEventName="CHANGE";export default DefaultMediaQueryListener;
@@ -1 +1 @@
1
- import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{detectOrientation}from"@claspo/common/utils/orientationUtils";import{isIOS}from"@claspo/common/utils/deviceUtils";import{DocumentModelUpdateType}from"../../document-model/DocumentModelService";export default class MobileDeviceOrientationListener extends DefaultEventEmitter{constructor(e,t){var n;super(),this.documentModel=e,this._orientation=null!==(n=t.config.defaultOrientation)&&void 0!==n?n:detectOrientation(),this.documentModel.on(DocumentModelUpdateType.ENVIRONMENT_UPDATE,e=>{e.orientation&&(this._orientation=e.orientation,this.emit(MobileDeviceOrientationListener.changeEventName,this._orientation))}),this.handleOrientationChangeBound=this.handleOrientationChange.bind(this),this.addOrientationChangeListener()}isPortrait(){return"PORTRAIT"===this._orientation}handleOrientationChange(e){var t,n;this._orientation=null!==(n=null===(t=null==e?void 0:e.detail)||void 0===t?void 0:t.orientation)&&void 0!==n?n:detectOrientation(),this.emit(MobileDeviceOrientationListener.changeEventName,this._orientation)}addOrientationChangeListener(){!isIOS()&&window.screen.orientation?window.screen.orientation.addEventListener("change",this.handleOrientationChangeBound):"orientation"in window&&window.addEventListener("orientationchange",this.handleOrientationChangeBound)}removeOrientationChangeListener(){!isIOS()&&window.screen.orientation?window.screen.orientation.removeEventListener("change",this.handleOrientationChangeBound):"orientation"in window&&window.removeEventListener("orientationchange",this.handleOrientationChangeBound)}destroy(){super.destroy(),this.removeOrientationChangeListener()}}MobileDeviceOrientationListener.changeEventName="CHANGE";
1
+ import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{detectOrientation}from"@claspo/common/utils/orientationUtils";import{isIOS}from"@claspo/common/utils/deviceUtils";import{DocumentModelUpdateType}from"../../document-model/DocumentModelService";class MobileDeviceOrientationListener extends DefaultEventEmitter{constructor(e,t){var n;super(),this.documentModel=e,this._orientation=null!==(n=t.config.defaultOrientation)&&void 0!==n?n:detectOrientation(),this.documentModel.on(DocumentModelUpdateType.ENVIRONMENT_UPDATE,e=>{e.orientation&&(this._orientation=e.orientation,this.emit(MobileDeviceOrientationListener.changeEventName,this._orientation))}),this.handleOrientationChangeBound=this.handleOrientationChange.bind(this),this.addOrientationChangeListener()}isPortrait(){return"PORTRAIT"===this._orientation}handleOrientationChange(e){var t,n;this._orientation=null!==(n=null===(t=null==e?void 0:e.detail)||void 0===t?void 0:t.orientation)&&void 0!==n?n:detectOrientation(),this.emit(MobileDeviceOrientationListener.changeEventName,this._orientation)}addOrientationChangeListener(){!isIOS()&&window.screen.orientation?window.screen.orientation.addEventListener("change",this.handleOrientationChangeBound):"orientation"in window&&window.addEventListener("orientationchange",this.handleOrientationChangeBound)}removeOrientationChangeListener(){!isIOS()&&window.screen.orientation?window.screen.orientation.removeEventListener("change",this.handleOrientationChangeBound):"orientation"in window&&window.removeEventListener("orientationchange",this.handleOrientationChangeBound)}destroy(){super.destroy(),this.removeOrientationChangeListener()}}MobileDeviceOrientationListener.changeEventName="CHANGE";export default MobileDeviceOrientationListener;
package/sdk/WcElement.js CHANGED
@@ -1 +1 @@
1
- import HandlerFactory from"../handler/HandlerFactory";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import addEventListenerToElement from"@claspo/common/utils/addEventListener";import DefaultState from"../common/DefaultState";import{DocumentModelUpdateType}from"../document-model/DocumentModelService";import DefaultMediaQueryListener from"../renderer/style/DefaultMediaQueryListener";import{applySysAttrPrefix,applySysClassPrefix,RenderConstants}from"../renderer/RenderConstants";import StyleAttributeAccessor from"./accessor/StyleAttributeAccessor";import CommonStylesService from"../renderer/style/CommonStylesService";import ColorSchemaListener from"../renderer/style/ColorSchemaListener";import HttpClient from"@claspo/common/network/HttpClient";import omitKeys from"@claspo/common/object/omitKeys";import{CaseTransformer}from"@claspo/common/utils/CaseTransformer";import ComponentResourceManager from"../resource-management/ComponentResourceManager";import createObservers from"../wc-renderer/observers/createObservers";import observerType from"../wc-renderer/observers/observerType";import createSubscriptions from"../wc-renderer/subscriptions/createSubscriptions";import recursiveFindParentNodeByAttribute from"@claspo/common/element/recursiveFindParentNodeByAttribute";import{getTranslationsMap,getWidgetLanguages}from"./TranslationUtils";import ActionCategory from"../action/actions/ActionCategory";import SysActionTypes from"../action/SysActionTypes";import mergeAdaptiveStylesWithEnvIndependentStyles from"../document-model/MergeAdaptiveStylesWithEnvIndependentStyles";import{applySharedClasses,getAdaptiveStylesForPlatform}from"./ModelStyleUtils";import insertHtmlIntoElement from"@claspo/common/dom/insertHtmlIntoElement";import{PayloadEvent}from"./PayloadEvent";import{RenderMode}from"@claspo/common/RenderMode";export default class WcElement extends HTMLElement{constructor(){var e,t;super(),this.construct=()=>{let e;const t=this.getAttribute(applySysAttrPrefix("id")),s=this.getWidgetContainerNode();if(!s)throw new Error("Widget container not found in construct");const o=s.closest(`[${applySysAttrPrefix("widget-id")}]`);let r;o&&(r=o.getAttribute(applySysAttrPrefix("widget-id")));let i=new PayloadEvent("cl-props-request",{nodeName:this.nodeName,path:this.getAttribute(applySysAttrPrefix("path")),id:t,widgetId:r},{bubbles:!0,composed:!0});this.dispatchEvent(i),e=i.detail.props,Object.assign(this,e),this.observers=createObservers(observerType.PROPS,observerType.SHARED,observerType.ENVIRONMENT),this.subscriptions=createSubscriptions(),this.state=new DefaultState({}),this.componentEventEmitter=new DefaultEventEmitter,this.componentResourceManager=new ComponentResourceManager(this.model.id,this.services.eventEmitter,this.isStaticRenderMode()),this.mergeTagsProcessor=this.services.mergeTagsProcessorFactory.create(),this._actionFactory=this.services.actionFactory,this._handlerFactory=new HandlerFactory(this._actionFactory,this.services.actionRegister),this.prevProps=this.model.props,this.prevEnvironment=this.getEnvironment(),this.documentModel.on(`${DocumentModelUpdateType.COMPONENT_PROPS_UPDATE}_${this.model.id}`,e=>{this.model.props=e,this.observers.get(observerType.PROPS).forEach(t=>t(this.prevProps,e)),this.prevProps=e;const t=this.getHostElement(),s=applySysAttrPrefix("floating");e.floating&&!t.getAttribute(s)?t.setAttribute(s,"true"):!e.floating&&t.getAttribute(s)&&t.removeAttribute(s)}),this.documentModel.on(`${DocumentModelUpdateType.COMPONENT_UPDATE}_${this.model.id}`,e=>{Object.assign(this.model,e)}),this.documentModel.on(DocumentModelUpdateType.SHARED_UPDATE_ALL,()=>{this.applyAutoAdaptiveStyles(this.prevProps.adaptiveStyles,this.prevProps.styles),this.observers.get(observerType.SHARED).forEach(e=>e(this.getShared()))}),this.model.props.backgroundDynamicInlineSVGElements&&(this.colorSchemaListener=new ColorSchemaListener(this.documentModel,this.getHostElement(),()=>this.getShared(),()=>this.model.props,()=>this.getEnvironment(),HttpClient),this.colorSchemaListener.apply(this.getEnvironment()).then(()=>{this.subscriptions.push(this.colorSchemaListener.on())})),this.prevProps.adaptiveStyles&&this.subscriptions.push(this.resizeListener.on(DefaultMediaQueryListener.changeEventName,()=>{this.applyAutoAdaptiveStyles(this.prevProps.adaptiveStyles,this.prevProps.styles);const e=this.getEnvironment();this.observers.get(observerType.ENVIRONMENT).forEach(t=>t(this.prevEnvironment,e)),this.prevEnvironment=e}))},this.attachHandlers=()=>{this.getHandlers().map(e=>this._handlerFactory.get(e)).map(e=>()=>e.activate(this.state,this.componentEventEmitter,this.getHostElement.bind(this))).forEach(e=>e())},this.postponeHandlers=()=>{var e;null===(e=this.handlers)||void 0===e||e.forEach(e=>e.postpone())},this.releaseHandlers=()=>{var e;null===(e=this.handlers)||void 0===e||e.forEach(e=>e.release())},this.getProps=()=>{var e;return null===(e=this.getModel())||void 0===e?void 0:e.props},this.getShared=()=>this.documentModel.getShared(),this.getEnvironment=()=>this.resizeListener.isMobile()?"mobile":"desktop",this.isStaticRenderMode=()=>this.services.config.getConfig("renderMode")===RenderMode.STATIC,this.isUpdatingRenderMode=()=>this.services.config.getConfig("renderMode")===RenderMode.UPDATING,this.getRootElement=()=>this.shadowRoot?this.shadowRoot:this,this.getHostElement=()=>this,this.observeProps=e=>{this.observers.get(observerType.PROPS).push(e),e(null,this.prevProps)},this.observeShared=e=>{this.observers.get(observerType.SHARED).push(e),e(this.getShared())},this.observeEnvironment=e=>{this.observers.get(observerType.ENVIRONMENT).push(e),e(null,this.getEnvironment())},this.getElements=()=>[this.getHostElement(),...Array.from(this.getRootElement().querySelectorAll(`[${applySysAttrPrefix("element")}]`)).filter(e=>!e.hasAttribute(applySysAttrPrefix("component")))],this.getElement=(e,t)=>this.getElements().find(s=>t?s.getAttribute(applySysAttrPrefix("element"))===e&&s.id===t:s.getAttribute(applySysAttrPrefix("element"))===e),this.applyAutoAdaptiveStyles=(e,t)=>{if(!e&&!t)return;const s=this.getElements();if(!s.length)return;const o=mergeAdaptiveStylesWithEnvIndependentStyles(e,t),r=applySysAttrPrefix("type"),i="element-styles";let n=this.getRootElement().querySelector(`style[${r}="${i}"]`);n||(n=document.createElement("style"),n.setAttribute(r,i),this.getRootElement().appendChild(n)),insertHtmlIntoElement({element:n,html:""}),s.forEach(e=>{let t=e.getAttribute(applySysAttrPrefix("element"));const s=this.getEnvironment();let r=getAdaptiveStylesForPlatform(o,s,t);if(r){if(this.resizeListener.isMobile()){const e=getAdaptiveStylesForPlatform(o,"desktop",t);e&&(r=Object.assign(Object.assign({},r),{styleAttributes:Object.assign(Object.assign({},e.styleAttributes),r.styleAttributes)}))}this.applyStylesToElement(e,this.applySharedClassesToElementModel(r),n)}}),this._addLinkColor(n,this.getShared())},this.registerComponentResourceManagement=()=>{this.viewResourceManager.registerComponent(this.model.id,this.componentResourceManager)},this.applyStyles=(e,t={})=>{if(!e||!e.style)return!1;for(const[s,o]of Object.entries(t))e.style[s]=o;return!0},this.applyStylesToElement=(e,t,s)=>{var o,r;const i=[];if("host"===(t=WcElement._resolveTogglableStylesForElementModel(t)).element){CommonStylesService.applyHostStyles(this.model.type,e,null,this.layoutType);!!("desktop"===this.getEnvironment()&&(null===(o=this.model.props.backgroundDynamicInlineSVGElements)||void 0===o?void 0:o.desktop)||"mobile"===this.getEnvironment()&&(null===(r=this.model.props.backgroundDynamicInlineSVGElements)||void 0===r?void 0:r.mobile))&&(this.colorSchemaListener.apply(this.getEnvironment()),i.push("background"))}let n=t.styleAttributes.background,l=n&&n.match(/url\("([^"]*)"\)/);if(this.manifest.waitForResourcesLoad&&l){this.componentResourceManager.getPending().increment();const e=new Image;e.src=l[1],addEventListenerToElement(e,"load",()=>{this.componentResourceManager.getPending().decrement()}),addEventListenerToElement(e,"error",()=>{this.componentResourceManager.onResourceLoadFailure(e.src),this.isUpdatingRenderMode&&this.componentResourceManager.getPending().decrement()})}const a=Object.assign(Object.assign({},t),{styleAttributes:omitKeys(t.styleAttributes,i)});if(StyleAttributeAccessor.set(e,a),this._setClassAttributes(e,t),s){if(t.hoverStyleAttributes){let o=Object.assign({},t.hoverStyleAttributes);if("FILL_UP"===t.hoverAnimationType){e.style.boxShadow="inset 0px 0px 0px 0px rgb(0, 0, 0, 0)",e.style.overflow="hidden";const s=e.tagName.toLowerCase(),r=`flip-up-animation-${t.element}`;let i=this.getRootElement().querySelector(`#${r}`);i||(i=document.createElement("style"),i.id=r,e.appendChild(i)),insertHtmlIntoElement({element:i,html:`\n ${s}::before {\n content: '';\n background: ${o.background};\n position: absolute;\n left: 0;\n top: ${e.getBoundingClientRect().height}px;\n height: ${e.getBoundingClientRect().height}px;\n width: 100%;\n z-index: -10;\n }\n ${s}:hover::before {\n top: 0;\n transition: 0.3s;\n }\n `}),o=Object.assign(Object.assign({},t.hoverStyleAttributes),{background:"transparent",position:"relative"})}o.borderTopWidth&&"0px"!==o.borderTopWidth||delete o.borderTopColor;o.borderBottomWidth&&"0px"!==o.borderBottomWidth||delete o.borderBottomColor;o.borderLeftWidth&&"0px"!==o.borderLeftWidth||delete o.borderLeftColor;o.borderRightWidth&&"0px"!==o.borderRightWidth||delete o.borderRightColor,this._addStylesToStyleElement(s,t.element,o,`:not(.${applySysAttrPrefix("no-hover")}):hover`,!0)}t.placeholderStyleAttributes&&this._addStylesToStyleElement(s,t.element,t.placeholderStyleAttributes,"::placeholder"),this._addFontStylesToStyleElement(s,this.getShared()),this.stylesAppliedToElement(e,t,s)}},this.applySharedClassesToElementModel=e=>{const t=this.documentModel.getShared();return applySharedClasses(e,t)},this.getModel=()=>this.model,this._addStylesToStyleElement=(e,t,s,o="",r)=>{const i=Object.keys(s).reduce((e,t)=>e+` ${CaseTransformer.camelCaseToDashCase(t)}: ${s[t]}${r?" !important;":";"}`,"");insertHtmlIntoElement({element:e,html:`[${applySysAttrPrefix("element")}="${t}"]${o} { ${i} }`,appendHtml:!0})},this._addFontStylesToStyleElement=(e,t)=>{insertHtmlIntoElement({element:e,html:`[cl-type] {font-family:${t.textFontFamily||"inherit"}}`,appendHtml:!0})},this._addLinkColor=(e,t)=>{var s,o,r,i;t.linkColor&&insertHtmlIntoElement({element:e,html:`a {color: ${t.linkColor}}, a:visited {color: ${t.linkColor}}`,appendHtml:!0}),(null===(s=t.linkParams)||void 0===s?void 0:s.color)&&insertHtmlIntoElement({element:e,html:`a {color: ${null===(o=t.linkParams)||void 0===o?void 0:o.color}}, a:visited {color: ${null===(r=t.linkParams)||void 0===r?void 0:r.color}}`,appendHtml:!0}),(null===(i=t.linkParams)||void 0===i?void 0:i.removeUnderline)&&insertHtmlIntoElement({element:e,html:"a {text-decoration: none}, a:visited {text-decoration: none}",appendHtml:!0})},this._setClassAttributes=(e,t)=>{Array.from(e.classList).filter(e=>e!==applySysClassPrefix("hovered")&&e!==applySysClassPrefix("focused")).forEach(t=>{t.startsWith(RenderConstants.SYSTEM_CLASS_PREFIX)&&e.classList.remove(t)});const s=((e.getAttribute("class")||"")+" "+t.classes).trim();e.setAttribute("class",s)},this.getParentComponent=()=>recursiveFindParentNodeByAttribute(this.parentNode,applySysAttrPrefix("element"),"host"),this.getWidgetContainerNode=()=>{const e=null==this?void 0:this.getAttribute(applySysAttrPrefix("path"));return e&&1===e.split(",").length?this.parentNode:recursiveFindParentNodeByAttribute(this.parentNode,applySysAttrPrefix("path"),void 0,e=>e&&1===e.split(",").length)},this.getWidgetLanguages=()=>getWidgetLanguages(this.services.config),this.getPreferredWidgetLanguage=()=>this.getWidgetLanguages()[0],this.getTranslationsMap=e=>getTranslationsMap(e,this.getWidgetLanguages()),this.stylesAppliedToElement=(e,t,s)=>{},this.updateContext=()=>{var e;const t=this.getModel();this.services.context.updateRecord(t.id,{label:this.getContextRecordLabel(t.props),viewIndex:null===(e=t.path)||void 0===e?void 0:e[0]})},this.addContextRecord=()=>{var e;const t=this.getModel();this.services.context.addRecord(t.id,{recordKey:t.id,id:t.props.control.name,label:this.getContextRecordLabel(t.props),value:t.props.control.defaultValue||"",viewIndex:null===(e=t.path)||void 0===e?void 0:e[0],sourceId:"FORM",initialData:{fallbackValue:"",exampleValue:this.getContextRecordExampleValue(t.props)}})},this.getContextRecordLabel=e=>{var t,s,o,r,i,n;const l=e.control.name;if(["email","first_name","last_name"].includes(l))return l.toUpperCase();if((null===(t=e.content)||void 0===t?void 0:t.label)&&(null===(r=null===(o=null===(s=e.adaptiveStyles)||void 0===s?void 0:s.desktop.find(e=>"label"===e.element))||void 0===o?void 0:o.params)||void 0===r?void 0:r.enabled)){const t=(new DOMParser).parseFromString(e.content.label,"text/html");return this.capitalizeFirstLetter(t.body.textContent||"")}return(null===(i=e.content)||void 0===i?void 0:i.placeholder)?this.capitalizeFirstLetter(e.content.placeholder):(null===(n=e.control)||void 0===n?void 0:n.integrationName)?this.capitalizeFirstLetter(e.control.integrationName).replace(new RegExp("_","g")," "):void 0},this.capitalizeFirstLetter=e=>e.charAt(0).toUpperCase()+e.slice(1),this.getContextRecordExampleValue=e=>{var t;switch(null===(t=e.control)||void 0===t?void 0:t.name){case"email":return"myemail@example.com";case"first_name":return"Maria";case"last_name":return"Taylor";default:return this.getContextRecordLabel(e)}},this.completeSubmitAction=e=>{const t=e||{},s=this.services.actionRegister.getRegisteredActions().find(e=>e.category===ActionCategory.SUBMIT);s?null==s||s.execute(void 0,void 0,!0,t):this.services.actionFactory.get({type:SysActionTypes.REQUEST}).execute(void 0,void 0,!0,t)},this.getHandlers=()=>{var e;return(null===(e=this.getProps())||void 0===e?void 0:e.handlers)&&this.getProps().handlers.length?[...this.getProps().handlers]:[]},this.assets=(e="")=>`${this.services.config.getConfig("staticResourcesUrl").replace(/\/$/,"")}/${this.manifest.name}/assets${e?`/${e}`:""}`,this.attachShadow({mode:"open"}),this.manifest=this.manifest||(null===(e=this.define)||void 0===e?void 0:e.manifest)||(null===(t=this.constructor.define)||void 0===t?void 0:t.manifest)}connectedCallback(){this.construct(),this.registerComponentResourceManagement(),Promise.resolve().then(()=>{this.attachHandlers()})}disconnectedCallback(){var e;this.observers.clear(),this.subscriptions.off(),this.state.destroy(),this.componentEventEmitter.destroy(),null===(e=this.mergeTagsProcessor)||void 0===e||e.destroy()}}WcElement._resolveTogglableStylesForElementModel=e=>{const t=Object.assign({},e);return Object.keys(t).forEach(e=>{e.toLowerCase().includes("styleattributes")&&(t[e]=WcElement._resolveTogglableStyles(t[e]))}),t},WcElement._resolveTogglableStyles=e=>{const t=Object.assign({},e),s=(e,s,o)=>{s in t&&(e.forEach(e=>{e in t&&(t[e]=t[s]?t[e]:o)}),delete t[s])};return s(["marginTop","marginBottom","marginLeft","marginRight"],"_marginEnabled","0px"),s(["paddingTop","paddingBottom","paddingLeft","paddingRight"],"_paddingEnabled","0px"),t};
1
+ import HandlerFactory from"../handler/HandlerFactory";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import addEventListenerToElement from"@claspo/common/utils/addEventListener";import DefaultState from"../common/DefaultState";import{DocumentModelUpdateType}from"../document-model/DocumentModelService";import DefaultMediaQueryListener from"../renderer/style/DefaultMediaQueryListener";import{applySysAttrPrefix,applySysClassPrefix,RenderConstants}from"../renderer/RenderConstants";import StyleAttributeAccessor from"./accessor/StyleAttributeAccessor";import CommonStylesService from"../renderer/style/CommonStylesService";import ColorSchemaListener from"../renderer/style/ColorSchemaListener";import HttpClient from"@claspo/common/network/HttpClient";import omitKeys from"@claspo/common/object/omitKeys";import{CaseTransformer}from"@claspo/common/utils/CaseTransformer";import ComponentResourceManager from"../resource-management/ComponentResourceManager";import createObservers from"../wc-renderer/observers/createObservers";import observerType from"../wc-renderer/observers/observerType";import createSubscriptions from"../wc-renderer/subscriptions/createSubscriptions";import recursiveFindParentNodeByAttribute from"@claspo/common/element/recursiveFindParentNodeByAttribute";import{getTranslationsMap,getWidgetLanguages}from"./TranslationUtils";import ActionCategory from"../action/actions/ActionCategory";import SysActionTypes from"../action/SysActionTypes";import mergeAdaptiveStylesWithEnvIndependentStyles from"../document-model/MergeAdaptiveStylesWithEnvIndependentStyles";import{applySharedClasses,getAdaptiveStylesForPlatform}from"./ModelStyleUtils";import insertHtmlIntoElement from"@claspo/common/dom/insertHtmlIntoElement";import{PayloadEvent}from"./PayloadEvent";import{RenderMode}from"@claspo/common/RenderMode";class WcElement extends HTMLElement{constructor(){var e,t;super(),this.construct=()=>{let e;const t=this.getAttribute(applySysAttrPrefix("id")),s=this.getWidgetContainerNode();if(!s)throw new Error("Widget container not found in construct");const o=s.closest(`[${applySysAttrPrefix("widget-id")}]`);let r;o&&(r=o.getAttribute(applySysAttrPrefix("widget-id")));let i=new PayloadEvent("cl-props-request",{nodeName:this.nodeName,path:this.getAttribute(applySysAttrPrefix("path")),id:t,widgetId:r},{bubbles:!0,composed:!0});this.dispatchEvent(i),e=i.detail.props,Object.assign(this,e),this.observers=createObservers(observerType.PROPS,observerType.SHARED,observerType.ENVIRONMENT),this.subscriptions=createSubscriptions(),this.state=new DefaultState({}),this.componentEventEmitter=new DefaultEventEmitter,this.componentResourceManager=new ComponentResourceManager(this.model.id,this.services.eventEmitter,this.isStaticRenderMode()),this.mergeTagsProcessor=this.services.mergeTagsProcessorFactory.create(),this._actionFactory=this.services.actionFactory,this._handlerFactory=new HandlerFactory(this._actionFactory,this.services.actionRegister),this.prevProps=this.model.props,this.prevEnvironment=this.getEnvironment(),this.documentModel.on(`${DocumentModelUpdateType.COMPONENT_PROPS_UPDATE}_${this.model.id}`,e=>{this.model.props=e,this.observers.get(observerType.PROPS).forEach(t=>t(this.prevProps,e)),this.prevProps=e;const t=this.getHostElement(),s=applySysAttrPrefix("floating");e.floating&&!t.getAttribute(s)?t.setAttribute(s,"true"):!e.floating&&t.getAttribute(s)&&t.removeAttribute(s)}),this.documentModel.on(`${DocumentModelUpdateType.COMPONENT_UPDATE}_${this.model.id}`,e=>{Object.assign(this.model,e)}),this.documentModel.on(DocumentModelUpdateType.SHARED_UPDATE_ALL,()=>{this.applyAutoAdaptiveStyles(this.prevProps.adaptiveStyles,this.prevProps.styles),this.observers.get(observerType.SHARED).forEach(e=>e(this.getShared()))}),this.model.props.backgroundDynamicInlineSVGElements&&(this.colorSchemaListener=new ColorSchemaListener(this.documentModel,this.getHostElement(),()=>this.getShared(),()=>this.model.props,()=>this.getEnvironment(),HttpClient),this.colorSchemaListener.apply(this.getEnvironment()).then(()=>{this.subscriptions.push(this.colorSchemaListener.on())})),this.prevProps.adaptiveStyles&&this.subscriptions.push(this.resizeListener.on(DefaultMediaQueryListener.changeEventName,()=>{this.applyAutoAdaptiveStyles(this.prevProps.adaptiveStyles,this.prevProps.styles);const e=this.getEnvironment();this.observers.get(observerType.ENVIRONMENT).forEach(t=>t(this.prevEnvironment,e)),this.prevEnvironment=e}))},this.attachHandlers=()=>{this.getHandlers().map(e=>this._handlerFactory.get(e)).map(e=>()=>e.activate(this.state,this.componentEventEmitter,this.getHostElement.bind(this))).forEach(e=>e())},this.postponeHandlers=()=>{var e;null===(e=this.handlers)||void 0===e||e.forEach(e=>e.postpone())},this.releaseHandlers=()=>{var e;null===(e=this.handlers)||void 0===e||e.forEach(e=>e.release())},this.getProps=()=>{var e;return null===(e=this.getModel())||void 0===e?void 0:e.props},this.getShared=()=>this.documentModel.getShared(),this.getEnvironment=()=>this.resizeListener.isMobile()?"mobile":"desktop",this.isStaticRenderMode=()=>this.services.config.getConfig("renderMode")===RenderMode.STATIC,this.isUpdatingRenderMode=()=>this.services.config.getConfig("renderMode")===RenderMode.UPDATING,this.getRootElement=()=>this.shadowRoot?this.shadowRoot:this,this.getHostElement=()=>this,this.observeProps=e=>{this.observers.get(observerType.PROPS).push(e),e(null,this.prevProps)},this.observeShared=e=>{this.observers.get(observerType.SHARED).push(e),e(this.getShared())},this.observeEnvironment=e=>{this.observers.get(observerType.ENVIRONMENT).push(e),e(null,this.getEnvironment())},this.getElements=()=>[this.getHostElement(),...Array.from(this.getRootElement().querySelectorAll(`[${applySysAttrPrefix("element")}]`)).filter(e=>!e.hasAttribute(applySysAttrPrefix("component")))],this.getElement=(e,t)=>this.getElements().find(s=>t?s.getAttribute(applySysAttrPrefix("element"))===e&&s.id===t:s.getAttribute(applySysAttrPrefix("element"))===e),this.applyAutoAdaptiveStyles=(e,t)=>{if(!e&&!t)return;const s=this.getElements();if(!s.length)return;const o=mergeAdaptiveStylesWithEnvIndependentStyles(e,t),r=applySysAttrPrefix("type"),i="element-styles";let n=this.getRootElement().querySelector(`style[${r}="${i}"]`);n||(n=document.createElement("style"),n.setAttribute(r,i),this.getRootElement().appendChild(n)),insertHtmlIntoElement({element:n,html:""}),s.forEach(e=>{let t=e.getAttribute(applySysAttrPrefix("element"));const s=this.getEnvironment();let r=getAdaptiveStylesForPlatform(o,s,t);if(r){if(this.resizeListener.isMobile()){const e=getAdaptiveStylesForPlatform(o,"desktop",t);e&&(r=Object.assign(Object.assign({},r),{styleAttributes:Object.assign(Object.assign({},e.styleAttributes),r.styleAttributes)}))}this.applyStylesToElement(e,this.applySharedClassesToElementModel(r),n)}}),this._addLinkColor(n,this.getShared())},this.registerComponentResourceManagement=()=>{this.viewResourceManager.registerComponent(this.model.id,this.componentResourceManager)},this.applyStyles=(e,t={})=>{if(!e||!e.style)return!1;for(const[s,o]of Object.entries(t))e.style[s]=o;return!0},this.applyStylesToElement=(e,t,s)=>{var o,r;const i=[];if("host"===(t=WcElement._resolveTogglableStylesForElementModel(t)).element){CommonStylesService.applyHostStyles(this.model.type,e,null,this.layoutType);!!("desktop"===this.getEnvironment()&&(null===(o=this.model.props.backgroundDynamicInlineSVGElements)||void 0===o?void 0:o.desktop)||"mobile"===this.getEnvironment()&&(null===(r=this.model.props.backgroundDynamicInlineSVGElements)||void 0===r?void 0:r.mobile))&&(this.colorSchemaListener.apply(this.getEnvironment()),i.push("background"))}let n=t.styleAttributes.background,l=n&&n.match(/url\("([^"]*)"\)/);if(this.manifest.waitForResourcesLoad&&l){this.componentResourceManager.getPending().increment();const e=new Image;e.src=l[1],addEventListenerToElement(e,"load",()=>{this.componentResourceManager.getPending().decrement()}),addEventListenerToElement(e,"error",()=>{this.componentResourceManager.onResourceLoadFailure(e.src),this.isUpdatingRenderMode&&this.componentResourceManager.getPending().decrement()})}const a=Object.assign(Object.assign({},t),{styleAttributes:omitKeys(t.styleAttributes,i)});if(StyleAttributeAccessor.set(e,a),this._setClassAttributes(e,t),s){if(t.hoverStyleAttributes){let o=Object.assign({},t.hoverStyleAttributes);if("FILL_UP"===t.hoverAnimationType){e.style.boxShadow="inset 0px 0px 0px 0px rgb(0, 0, 0, 0)",e.style.overflow="hidden";const s=e.tagName.toLowerCase(),r=`flip-up-animation-${t.element}`;let i=this.getRootElement().querySelector(`#${r}`);i||(i=document.createElement("style"),i.id=r,e.appendChild(i)),insertHtmlIntoElement({element:i,html:`\n ${s}::before {\n content: '';\n background: ${o.background};\n position: absolute;\n left: 0;\n top: ${e.getBoundingClientRect().height}px;\n height: ${e.getBoundingClientRect().height}px;\n width: 100%;\n z-index: -10;\n }\n ${s}:hover::before {\n top: 0;\n transition: 0.3s;\n }\n `}),o=Object.assign(Object.assign({},t.hoverStyleAttributes),{background:"transparent",position:"relative"})}o.borderTopWidth&&"0px"!==o.borderTopWidth||delete o.borderTopColor;o.borderBottomWidth&&"0px"!==o.borderBottomWidth||delete o.borderBottomColor;o.borderLeftWidth&&"0px"!==o.borderLeftWidth||delete o.borderLeftColor;o.borderRightWidth&&"0px"!==o.borderRightWidth||delete o.borderRightColor,this._addStylesToStyleElement(s,t.element,o,`:not(.${applySysAttrPrefix("no-hover")}):hover`,!0)}t.placeholderStyleAttributes&&this._addStylesToStyleElement(s,t.element,t.placeholderStyleAttributes,"::placeholder"),this._addFontStylesToStyleElement(s,this.getShared()),this.stylesAppliedToElement(e,t,s)}},this.applySharedClassesToElementModel=e=>{const t=this.documentModel.getShared();return applySharedClasses(e,t)},this.getModel=()=>this.model,this._addStylesToStyleElement=(e,t,s,o="",r)=>{const i=Object.keys(s).reduce((e,t)=>e+` ${CaseTransformer.camelCaseToDashCase(t)}: ${s[t]}${r?" !important;":";"}`,"");insertHtmlIntoElement({element:e,html:`[${applySysAttrPrefix("element")}="${t}"]${o} { ${i} }`,appendHtml:!0})},this._addFontStylesToStyleElement=(e,t)=>{insertHtmlIntoElement({element:e,html:`[cl-type] {font-family:${t.textFontFamily||"inherit"}}`,appendHtml:!0})},this._addLinkColor=(e,t)=>{var s,o,r,i;t.linkColor&&insertHtmlIntoElement({element:e,html:`a {color: ${t.linkColor}}, a:visited {color: ${t.linkColor}}`,appendHtml:!0}),(null===(s=t.linkParams)||void 0===s?void 0:s.color)&&insertHtmlIntoElement({element:e,html:`a {color: ${null===(o=t.linkParams)||void 0===o?void 0:o.color}}, a:visited {color: ${null===(r=t.linkParams)||void 0===r?void 0:r.color}}`,appendHtml:!0}),(null===(i=t.linkParams)||void 0===i?void 0:i.removeUnderline)&&insertHtmlIntoElement({element:e,html:"a {text-decoration: none}, a:visited {text-decoration: none}",appendHtml:!0})},this._setClassAttributes=(e,t)=>{Array.from(e.classList).filter(e=>e!==applySysClassPrefix("hovered")&&e!==applySysClassPrefix("focused")).forEach(t=>{t.startsWith(RenderConstants.SYSTEM_CLASS_PREFIX)&&e.classList.remove(t)});const s=((e.getAttribute("class")||"")+" "+t.classes).trim();e.setAttribute("class",s)},this.getParentComponent=()=>recursiveFindParentNodeByAttribute(this.parentNode,applySysAttrPrefix("element"),"host"),this.getWidgetContainerNode=()=>{const e=null==this?void 0:this.getAttribute(applySysAttrPrefix("path"));return e&&1===e.split(",").length?this.parentNode:recursiveFindParentNodeByAttribute(this.parentNode,applySysAttrPrefix("path"),void 0,e=>e&&1===e.split(",").length)},this.getWidgetLanguages=()=>getWidgetLanguages(this.services.config),this.getPreferredWidgetLanguage=()=>this.getWidgetLanguages()[0],this.getTranslationsMap=e=>getTranslationsMap(e,this.getWidgetLanguages()),this.stylesAppliedToElement=(e,t,s)=>{},this.updateContext=()=>{var e;const t=this.getModel();this.services.context.updateRecord(t.id,{label:this.getContextRecordLabel(t.props),viewIndex:null===(e=t.path)||void 0===e?void 0:e[0]})},this.addContextRecord=()=>{var e;const t=this.getModel();this.services.context.addRecord(t.id,{recordKey:t.id,id:t.props.control.name,label:this.getContextRecordLabel(t.props),value:t.props.control.defaultValue||"",viewIndex:null===(e=t.path)||void 0===e?void 0:e[0],sourceId:"FORM",initialData:{fallbackValue:"",exampleValue:this.getContextRecordExampleValue(t.props)}})},this.getContextRecordLabel=e=>{var t,s,o,r,i,n;const l=e.control.name;if(["email","first_name","last_name"].includes(l))return l.toUpperCase();if((null===(t=e.content)||void 0===t?void 0:t.label)&&(null===(r=null===(o=null===(s=e.adaptiveStyles)||void 0===s?void 0:s.desktop.find(e=>"label"===e.element))||void 0===o?void 0:o.params)||void 0===r?void 0:r.enabled)){const t=(new DOMParser).parseFromString(e.content.label,"text/html");return this.capitalizeFirstLetter(t.body.textContent||"")}return(null===(i=e.content)||void 0===i?void 0:i.placeholder)?this.capitalizeFirstLetter(e.content.placeholder):(null===(n=e.control)||void 0===n?void 0:n.integrationName)?this.capitalizeFirstLetter(e.control.integrationName).replace(new RegExp("_","g")," "):void 0},this.capitalizeFirstLetter=e=>e.charAt(0).toUpperCase()+e.slice(1),this.getContextRecordExampleValue=e=>{var t;switch(null===(t=e.control)||void 0===t?void 0:t.name){case"email":return"myemail@example.com";case"first_name":return"Maria";case"last_name":return"Taylor";default:return this.getContextRecordLabel(e)}},this.completeSubmitAction=e=>{const t=e||{},s=this.services.actionRegister.getRegisteredActions().find(e=>e.category===ActionCategory.SUBMIT);s?null==s||s.execute(void 0,void 0,!0,t):this.services.actionFactory.get({type:SysActionTypes.REQUEST}).execute(void 0,void 0,!0,t)},this.getHandlers=()=>{var e;return(null===(e=this.getProps())||void 0===e?void 0:e.handlers)&&this.getProps().handlers.length?[...this.getProps().handlers]:[]},this.assets=(e="")=>`${this.services.config.getConfig("staticResourcesUrl").replace(/\/$/,"")}/${this.manifest.name}/assets${e?`/${e}`:""}`,this.attachShadow({mode:"open"}),this.manifest=this.manifest||(null===(e=this.define)||void 0===e?void 0:e.manifest)||(null===(t=this.constructor.define)||void 0===t?void 0:t.manifest)}connectedCallback(){this.construct(),this.registerComponentResourceManagement(),Promise.resolve().then(()=>{this.attachHandlers()})}disconnectedCallback(){var e;this.observers.clear(),this.subscriptions.off(),this.state.destroy(),this.componentEventEmitter.destroy(),null===(e=this.mergeTagsProcessor)||void 0===e||e.destroy()}}WcElement._resolveTogglableStylesForElementModel=e=>{const t=Object.assign({},e);return Object.keys(t).forEach(e=>{e.toLowerCase().includes("styleattributes")&&(t[e]=WcElement._resolveTogglableStyles(t[e]))}),t},WcElement._resolveTogglableStyles=e=>{const t=Object.assign({},e),s=(e,s,o)=>{s in t&&(e.forEach(e=>{e in t&&(t[e]=t[s]?t[e]:o)}),delete t[s])};return s(["marginTop","marginBottom","marginLeft","marginRight"],"_marginEnabled","0px"),s(["paddingTop","paddingBottom","paddingLeft","paddingRight"],"_paddingEnabled","0px"),t};export default WcElement;
@@ -1 +1 @@
1
- export default class StyleAttributeAccessor{static set(t,e){const s=t[StyleAttributeAccessor.accumulatorPropertyName]||{};t[StyleAttributeAccessor.accumulatorPropertyName]=Object.assign(Object.assign({},s),e.styleAttributes),Object.keys(t[StyleAttributeAccessor.accumulatorPropertyName]).forEach(s=>{s.includes("--")?t.style.setProperty(s,e.styleAttributes[s]||""):t.style[s]=e.styleAttributes[s]?e.styleAttributes[s]:""})}}StyleAttributeAccessor.accumulatorPropertyName="clStyleAttributes";
1
+ class StyleAttributeAccessor{static set(t,e){const s=t[StyleAttributeAccessor.accumulatorPropertyName]||{};t[StyleAttributeAccessor.accumulatorPropertyName]=Object.assign(Object.assign({},s),e.styleAttributes),Object.keys(t[StyleAttributeAccessor.accumulatorPropertyName]).forEach(s=>{s.includes("--")?t.style.setProperty(s,e.styleAttributes[s]||""):t.style[s]=e.styleAttributes[s]?e.styleAttributes[s]:""})}}StyleAttributeAccessor.accumulatorPropertyName="clStyleAttributes";export default StyleAttributeAccessor;
@@ -1 +1 @@
1
- import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import isDictionary from"@claspo/common/object/isDictionary";import flatMap from"@claspo/common/utils/flatMap";function getPropPathArray(r){return r?flatMap(r.value.split(".").map(r=>r.trim()).map(r=>r.split(/[\[\]]/)),r=>r).filter(r=>!!r):[]}export default class DataLayerSource extends DefaultEventEmitter{constructor(){super()}subscribe(r){}getValue(r){return r?{processor:(r,t)=>DataLayerSource.processModel(t)}:{}}static processModel(r,t){if(!r.arguments)return"";const e=r.arguments.find(r=>"dataLayerEventName"===r.name),a=r.arguments.find(r=>"dataLayerPropPath"===r.name),o=!!(null==e?void 0:e.value);if(!window.dataLayer)return"";let n;for(let i=window.dataLayer.length-1;i>=0;i--){const u=window.dataLayer[i];if(o){if((null==u?void 0:u.event)===e.value){n=u;break}if("event"===(null==u?void 0:u[0])&&(null==u?void 0:u[1])===e.value){n=u[2];break}}else{const e=getPropPathArray(a),o=DataLayerSource.getValueByPropPath(u,e,r,t);if(o)return o}}if(!n)return"";const i=getPropPathArray(a);return DataLayerSource.getValueByPropPath(n,i,r,t)}static getValueByPropPath(r,t,e,a){try{const e=t.reduce((r,t)=>{if(isDictionary(r)||Array.isArray(r))return r[t];throw new Error(`Tried to access non object data by propName "${t}". Data: ${r}`)},r);return Array.isArray(e)&&!a?e.join(", "):e}catch(r){return console.error("DataLayerSource: error while getting data by prop path. Model: ",e,"Error: ",r),""}}}DataLayerSource.sourceId="DATA_LAYER";
1
+ import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import isDictionary from"@claspo/common/object/isDictionary";import flatMap from"@claspo/common/utils/flatMap";function getPropPathArray(r){return r?flatMap(r.value.split(".").map(r=>r.trim()).map(r=>r.split(/[\[\]]/)),r=>r).filter(r=>!!r):[]}class DataLayerSource extends DefaultEventEmitter{constructor(){super()}subscribe(r){}getValue(r){return r?{processor:(r,e)=>DataLayerSource.processModel(e)}:{}}static processModel(r,e){if(!r.arguments)return"";const t=r.arguments.find(r=>"dataLayerEventName"===r.name),a=r.arguments.find(r=>"dataLayerPropPath"===r.name),o=!!(null==t?void 0:t.value);if(!window.dataLayer)return"";let n;for(let i=window.dataLayer.length-1;i>=0;i--){const u=window.dataLayer[i];if(o){if((null==u?void 0:u.event)===t.value){n=u;break}if("event"===(null==u?void 0:u[0])&&(null==u?void 0:u[1])===t.value){n=u[2];break}}else{const t=getPropPathArray(a),o=DataLayerSource.getValueByPropPath(u,t,r,e);if(o)return o}}if(!n)return"";const i=getPropPathArray(a);return DataLayerSource.getValueByPropPath(n,i,r,e)}static getValueByPropPath(r,e,t,a){try{const t=e.reduce((r,e)=>{if(isDictionary(r)||Array.isArray(r))return r[e];throw new Error(`Tried to access non object data by propName "${e}". Data: ${r}`)},r);return Array.isArray(t)&&!a?t.join(", "):t}catch(r){return console.error("DataLayerSource: error while getting data by prop path. Model: ",t,"Error: ",r),""}}}DataLayerSource.sourceId="DATA_LAYER";export default DataLayerSource;
@@ -1 +1 @@
1
- import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";export default class JSApiVariablesSource extends DefaultEventEmitter{constructor(e={}){super(),this.instanceName=e.instanceName}subscribe(e){}getValue(e){return e?{processor:(e,r)=>JSApiVariablesSource.processModel(r,this.instanceName)}:{}}static processModel(e,r){var a;if(!e.arguments)return"";const t=e.arguments.find(e=>"JavaScriptVariable"===e.name);if(!(null==t?void 0:t.value)||!r||!(null===(a=window[r])||void 0===a?void 0:a.variables))return"";try{return window[r].variables[t.value]||""}catch(r){return console.error("JSApiVariablesSource: error while getting variable. Model: ",e,"Error: ",r),""}}}JSApiVariablesSource.sourceId="JS_API_VARIABLE";
1
+ import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";class JSApiVariablesSource extends DefaultEventEmitter{constructor(e={}){super(),this.instanceName=e.instanceName}subscribe(e){}getValue(e){return e?{processor:(e,r)=>JSApiVariablesSource.processModel(r,this.instanceName)}:{}}static processModel(e,r){var a;if(!e.arguments)return"";const t=e.arguments.find(e=>"JavaScriptVariable"===e.name);if(!(null==t?void 0:t.value)||!r||!(null===(a=window[r])||void 0===a?void 0:a.variables))return"";try{return window[r].variables[t.value]||""}catch(r){return console.error("JSApiVariablesSource: error while getting variable. Model: ",e,"Error: ",r),""}}}JSApiVariablesSource.sourceId="JS_API_VARIABLE";export default JSApiVariablesSource;
@@ -1 +1 @@
1
- import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";export default class UrlQueryParamsSource extends DefaultEventEmitter{constructor(e={}){super(),this.config=e}subscribe(e){}getValue(e){return e?{processor:(e,r)=>UrlQueryParamsSource.processModel(r,this.config.sessionUrlSearchParams)}:{}}static processModel(e,r){if(!e.arguments)return"";const t=e.arguments.find(e=>"urlQueryParamName"===e.name);if(!r){r=[new URL(window.location.href).search]}if(!t||!t.value)return"";let a;for(let e=r.length-1;e>=0;e--){const s=new URLSearchParams(r[e]).getAll(t.value).filter(Boolean);if(s.length){a=s;break}}return a?a.join(", "):""}}UrlQueryParamsSource.sourceId="URL_QUERY_PARAMS";
1
+ import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";class UrlQueryParamsSource extends DefaultEventEmitter{constructor(e={}){super(),this.config=e}subscribe(e){}getValue(e){return e?{processor:(e,r)=>UrlQueryParamsSource.processModel(r,this.config.sessionUrlSearchParams)}:{}}static processModel(e,r){if(!e.arguments)return"";const t=e.arguments.find(e=>"urlQueryParamName"===e.name);if(!r){r=[new URL(window.location.href).search]}if(!t||!t.value)return"";let a;for(let e=r.length-1;e>=0;e--){const s=new URLSearchParams(r[e]).getAll(t.value).filter(Boolean);if(s.length){a=s;break}}return a?a.join(", "):""}}UrlQueryParamsSource.sourceId="URL_QUERY_PARAMS";export default UrlQueryParamsSource;
@@ -1,5 +1,8 @@
1
1
  export declare const REQUIRED_SYMBOL: unique symbol;
2
- export declare function required(errorKey?: string): (value: any) => {
3
- isValid: any;
4
- errorKey: string;
2
+ export declare function required(errorKey?: string): {
3
+ (value: any): {
4
+ isValid: any;
5
+ errorKey: string;
6
+ };
7
+ [REQUIRED_SYMBOL]: boolean;
5
8
  };