@claspo/renderer 18.9.0-sp9 → 18.9.0

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.
@@ -1,10 +1,7 @@
1
- export default class InAppActionFactory {
2
- eventEmitter: any;
3
- constructor(eventEmitter: any);
1
+ import ActionFactory from "./ActionFactory";
2
+ export default class InAppActionFactory extends ActionFactory {
4
3
  executeAction(actionType: any, { params }?: any): {
5
4
  execute: (state: any, e: any) => Promise<boolean>;
6
5
  };
7
- get(action: any): {
8
- execute: (state: any, e: any) => Promise<boolean>;
9
- };
6
+ get(action: any): any;
10
7
  }
@@ -1 +1 @@
1
- import SysActionTypes from"./SysActionTypes";import DispatchEventAction from"./actions/DispatchEventAction";import InAppOpenLinkAction from"./actions/InAppOpenLinkAction";export default class InAppActionFactory{constructor(t){this.eventEmitter=t}executeAction(t,{params:e}={}){return{execute:(n,i)=>{var s;return this.eventEmitter.emit(t,Object.assign(Object.assign({},e),{targetComponentId:null===(s=null==i?void 0:i.target)||void 0===s?void 0:s.getAttribute("cl-id")})),Promise.resolve(!0)}}}get(t){switch(t.type){case SysActionTypes.DISPATCH_EVENT:return new DispatchEventAction(this.eventEmitter,t);case SysActionTypes.OPEN_LINK:return new InAppOpenLinkAction(this.eventEmitter,t);case SysActionTypes.CLOSE_WIDGET:return this.executeAction(SysActionTypes.CLOSE_WIDGET,t);case SysActionTypes.CLICK:return this.executeAction(SysActionTypes.CLICK,t);default:throw new Error(`Not supported action type ${t.type}`)}}}
1
+ import SysActionTypes from"./SysActionTypes";import DispatchEventAction from"./actions/DispatchEventAction";import InAppOpenLinkAction from"./actions/InAppOpenLinkAction";import ActionFactory from"./ActionFactory";export default class InAppActionFactory extends ActionFactory{executeAction(t,{params:e}={}){return{execute:(n,i)=>{var s;return this.eventEmitter.emit(t,Object.assign(Object.assign({},e),{targetComponentId:null===(s=null==i?void 0:i.target)||void 0===s?void 0:s.getAttribute("cl-id")})),Promise.resolve(!0)}}}get(t){switch(t.type){case SysActionTypes.DISPATCH_EVENT:return new DispatchEventAction(this.eventEmitter,t);case SysActionTypes.OPEN_LINK:return new InAppOpenLinkAction(this.eventEmitter,t);case SysActionTypes.CLOSE_WIDGET:return this.executeAction(SysActionTypes.CLOSE_WIDGET,t);case SysActionTypes.CLICK:return this.executeAction(SysActionTypes.CLICK,t);case SysActionTypes.GO_TO_VIEW:case SysActionTypes.GO_TO_NEXT_VIEW:case SysActionTypes.GO_TO_PREVIOUS_VIEW:return super.get(t);default:throw new Error(`Not supported action type ${t.type}`)}}}
@@ -1 +1 @@
1
- import SysActionTypes from"../SysActionTypes";import SysEventTypes from"../../common/SysEventTypes";import{HttpStatus}from"@claspo/common/network/HttpStatus";import ActionCategory from"./ActionCategory";import{SYSTEM_RESULT_STATE_LABELS,submitAdvancesToNextStep}from"@claspo/common/document/ViewNavigationGraph";import getConfiguredResultViewIds from"../../document-model/getConfiguredResultViewIds";import DocumentUtils from"@claspo/common/document/DocumentUtils";import getComponentCountOnView from"../../sdk/getComponentCountOnView";import UTMParamsExtractor from"../UTMParamsExtractor";import{constructDataToSent,constructRequestHeaders,constructRequestPayload,extractContextValue}from"../RequestPayloadBuilder";function componentModelHasSubmitAction(t){var e,i;try{return!!(null===(i=null===(e=t.props)||void 0===e?void 0:e.handlers)||void 0===i?void 0:i.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 isResultView(t,e){return!!t&&(SYSTEM_RESULT_STATE_LABELS.includes(t.label)||e.includes(t.id))}export const RequestStatus={SUCCESS:"SUCCESS",ALREADY_SUBSCRIBED:"ALREADY_SUBSCRIBED",ERROR:"ERROR",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS"};export default class BaseRequestAction{constructor(t,e,i,s,o,n,r,a,c){this.skipHttpRequest=!0,this.id=i.id,this.params=i.params,this.form=e,this.eventEmitter=t,this.httpClient=s,this.configService=o,this.formEventsListener=null,this.tracking=n,this.stateService=r,this.context=a,this.getServices=c,this.category=ActionCategory.SUBMIT}setInitiatorComponentId(t){this.initiatorComponentId=t}emitSubmitLifecycleEvent(t,e=void 0){this.eventEmitter.emit(t,e,{initiatorComponentId:this.initiatorComponentId})}getTrackingMessageBeforeSentData(){return""}getTrackingMessageByStatus(t){return""}async execute(t,e,i,s){var o;if(this.formEventsListener&&this.formEventsListener.off(),this.form.submitQueuedAfterPending)return;if(this.form.preventSubmit)return void(this.form.submitQueuedAfterPending=!1);if(this.form.isPending()&&(this.form.submitQueuedAfterPending=!0,await this.form.waitForPendingValidationAndCheckIfValid()),this.form.submitQueuedAfterPending=!1,this.form.preventSubmit)return;const n=new Promise(t=>{this.submit(t,i,s)});return null===(o=this.getServices().submitState)||void 0===o||o.trackSubmission(n),n}submit(t,e,i){var s,o,n;const r=this.getServices().viewRouter.getCurrentViewIndex(),a=getConfiguredResultViewIds(this.getServices().documentModel.getShared(),this.hasFormControls()),c=submitAdvancesToNextStep(this.getServices().documentModel.getNavigationGraph(),this.getServices().documentModel.getViews(),r,a),u=Object.assign(Object.assign({},this.params),i);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()&&!u.skipValidation)return this.eventEmitter.emit("INVALID_CONTACT_DATA_SUBMIT_ATTEMPT"),void t(!1);const S=this.stateService,d=S.getState().conditionalRedirectViewId,m=u.conditionalRedirectViewId||d;d&&(u.conditionalRedirectViewId=d,S.setState({conditionalRedirectViewId:null}));let E=this.getServices().documentModel.getViews()[r+1];const l=this.getServices().documentModel.getViews()[r];if(!u.skipNavigation&&m&&getComponentCountOnView(l,"SysNetPromoterScoreComponent")+getComponentCountOnView(l,"SysFeedbackComponent")===1&&(E=this.getServices().documentModel.getViews().find(t=>t.id===u.conditionalRedirectViewId),viewHasControls(E)||isResultView(E,a)))return this.goToView(E.path[0],u),void t(!0);const h=null!==(s=u.formValue)&&void 0!==s?s:this.form.getControlsMap(),g=this.getContextValue(u);if(!u.skipNavigation&&c&&(viewHasControls(E)||!Object.keys(h).length&&!Object.keys(g).length))return this.goToView(r+1,u),void t(!0);if(!Object.keys(h).length&&!Object.keys(g).length)return void t(!0);const v=UTMParamsExtractor.extractTrackingParams(this.context),T=this.constructRequestPayload({contextValue:g,formValue:h,utmParams:v}),R=null===(n=null===(o=this.getServices().navigationLeadCollector)||void 0===o?void 0:o.getLatestNavigationData)||void 0===n?void 0:n.call(o);R&&(T.navigationData=R),this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_STARTED,T),this.eventEmitter.emit("CONTACT_DATA_SUBMIT",T);if(this.getTrackingMessageBeforeSentData()&&this.tracking.send("FormFinish_[Name]"),this.configService.getConfig("isBot"))return this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_FINISHED,{state:RequestStatus.SUCCESS,success:!0,skipped:!0}),void t();this.sendRequest(T).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=>{var i,s;const o=this.getTrackingMessageByStatus(e.state);if(o&&this.tracking.send(o),u.skipNavigation)return e.state===RequestStatus.TOO_MANY_REQUESTS&&this.eventEmitter.emit(SysEventTypes.TOO_MANY_REQUESTS),e.contactId&&"0"!==e.contactId&&this.eventEmitter.emit("CONTACT_ID_WAS_RECEIVED",e.contactId),this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_FINISHED,Object.assign(Object.assign({},e),{success:e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED})),void t(e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED);switch(e.state!==RequestStatus.SUCCESS&&e.state!==RequestStatus.ALREADY_SUBSCRIBED||null===(s=null===(i=this.getServices().navigationLeadCollector)||void 0===i?void 0:i.recordCommittedLead)||void 0===s||s.call(i),e.state){case RequestStatus.SUCCESS:c&&E?this.goToView(E.path[0]):this.runPostSubmitActionOrGoToView(()=>this.getSuccessViewIndex());break;case RequestStatus.ALREADY_SUBSCRIBED:m&&E?this.goToView(E.path[0]):this.runPostSubmitActionOrGoToView(()=>this.getAlreadySubscribedViewIndex());break;case RequestStatus.ERROR:m&&E?this.goToView(E.path[0]):this.handleErrorResponse();break;case RequestStatus.TOO_MANY_REQUESTS:this.goToView(m&&E?E.path[0]:this.getErrorViewIndex()),this.eventEmitter.emit(SysEventTypes.TOO_MANY_REQUESTS)}e.contactId&&"0"!==e.contactId&&this.eventEmitter.emit("CONTACT_ID_WAS_RECEIVED",e.contactId),this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_FINISHED,Object.assign(Object.assign({},e),{success:e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED})),t(e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED)}).catch(()=>{this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_FINISHED,{state:RequestStatus.ERROR,success:!1}),u.skipNavigation||this.handleErrorResponse(),t(!1)})}getContextValue(t){return extractContextValue(this.context,t.excludeFormContext)}constructDataToSent({contextValue:t,formValue:e,utmParams:i}){return constructDataToSent({contextValue:t,formValue:e,utmParams:i})}constructRequestPayload({contextValue:t,formValue:e,utmParams:i}){return constructRequestPayload({contextValue:t,formValue:e,utmParams:i,referrer:window.location.href,triggeredBy:this.configService.getConfig("triggeredBy"),widgetDebugMode:this.configService.getConfig("widgetDebugMode")})}constructRequestHeaders(){return constructRequestHeaders({clCustomerId:this.configService.getConfig("clCustomerId")})}goToView(t,e){this.eventEmitter.emit(SysActionTypes.GO_TO_VIEW,t,Object.assign(Object.assign({},e),{isForward:!0}))}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())}getSuccessViewIndex(){return this.resolveResultViewIndex("successViewId",["DOCUMENT_VIEW_TYPE_SUCCESS","DOCUMENT_VIEW_TYPE_SUCCESSFUL_REQUEST","REQUEST_FORM_VIEW_TYPE_SUCCESS"])}getErrorViewIndex(){return this.resolveResultViewIndex("errorViewId",["DOCUMENT_VIEW_TYPE_ERROR"])}getAlreadySubscribedViewIndex(){const t=this.getActiveSubmitActionParams();return t&&!t.alreadySubscribedViewId?this.getSuccessViewIndex():this.resolveResultViewIndex("alreadySubscribedViewId",["DOCUMENT_VIEW_TYPE_SUBSCRIBED"])}resolveResultViewIndex(t,e){var i;const s=this.getServices().documentModel.getViews(),o=null===(i=this.getActiveSubmitActionParams())||void 0===i?void 0:i[t];if(o){const t=s.findIndex(t=>t.id===o);if(-1!==t)return t}return s.findIndex(t=>e.includes(t.label))}hasFormControls(){return this.form.getControlsAsArray().length>0}getActiveSubmitActionParams(){if(this.hasFormControls())return this.getServices().documentModel.getShared().submitActionParams}runPostSubmitActionOrGoToView(t){var e;const i=null===(e=this.getActiveSubmitActionParams())||void 0===e?void 0:e.runAction;i?setTimeout(()=>{this.getServices().actionFactory.get(i).execute(this.stateService.getState())},1500):this.goToView(t())}handleErrorResponse(){const t=this.getErrorViewIndex();-1!==t?this.goToView(t):this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_ERROR_WITHOUT_VIEW)}}
1
+ import SysActionTypes from"../SysActionTypes";import SysEventTypes from"../../common/SysEventTypes";import{HttpStatus}from"@claspo/common/network/HttpStatus";import ActionCategory from"./ActionCategory";import{SYSTEM_RESULT_STATE_LABELS,submitAdvancesToNextStep}from"@claspo/common/document/ViewNavigationGraph";import getConfiguredResultViewIds from"../../document-model/getConfiguredResultViewIds";import DocumentUtils from"@claspo/common/document/DocumentUtils";import getComponentCountOnView from"../../sdk/getComponentCountOnView";import UTMParamsExtractor from"../UTMParamsExtractor";import{constructDataToSent,constructRequestHeaders,constructRequestPayload,extractContextValue}from"../RequestPayloadBuilder";function componentModelHasSubmitAction(t){var e,i;try{return!!(null===(i=null===(e=t.props)||void 0===e?void 0:e.handlers)||void 0===i?void 0:i.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 isResultView(t,e){return!!t&&(SYSTEM_RESULT_STATE_LABELS.includes(t.label)||e.includes(t.id))}export const RequestStatus={SUCCESS:"SUCCESS",ALREADY_SUBSCRIBED:"ALREADY_SUBSCRIBED",ERROR:"ERROR",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS"};export default class BaseRequestAction{constructor(t,e,i,s,o,n,r,a,c){this.skipHttpRequest=!0,this.id=i.id,this.params=i.params,this.form=e,this.eventEmitter=t,this.httpClient=s,this.configService=o,this.formEventsListener=null,this.tracking=n,this.stateService=r,this.context=a,this.getServices=c,this.category=ActionCategory.SUBMIT}setInitiatorComponentId(t){this.initiatorComponentId=t}emitSubmitLifecycleEvent(t,e=void 0){this.eventEmitter.emit(t,e,{initiatorComponentId:this.initiatorComponentId})}getTrackingMessageBeforeSentData(){return""}getTrackingMessageByStatus(t){return""}async execute(t,e,i,s){var o;if(this.formEventsListener&&this.formEventsListener.off(),this.form.submitQueuedAfterPending)return;if(this.form.preventSubmit)return void(this.form.submitQueuedAfterPending=!1);if(this.form.isPending()&&(this.form.submitQueuedAfterPending=!0,await this.form.waitForPendingValidationAndCheckIfValid()),this.form.submitQueuedAfterPending=!1,this.form.preventSubmit)return;const n=new Promise(t=>{this.submit(t,i,s)});return null===(o=this.getServices().submitState)||void 0===o||o.trackSubmission(n),n}submit(t,e,i){var s,o,n;const r=this.getServices().viewRouter.getCurrentViewIndex(),a=getConfiguredResultViewIds(this.getServices().documentModel.getShared(),this.hasFormControls()),c=submitAdvancesToNextStep(this.getServices().documentModel.getNavigationGraph(),this.getServices().documentModel.getViews(),r,a),u=Object.assign(Object.assign({},this.params),i);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()&&!u.skipValidation)return this.eventEmitter.emit("INVALID_CONTACT_DATA_SUBMIT_ATTEMPT"),void t(!1);const S=this.stateService,d=S.getState().conditionalRedirectViewId,m=u.conditionalRedirectViewId||d;d&&(u.conditionalRedirectViewId=d,S.setState({conditionalRedirectViewId:null}));let E=this.getServices().documentModel.getViews()[r+1];const l=this.getServices().documentModel.getViews()[r];if(!u.skipNavigation&&m&&getComponentCountOnView(l,"SysNetPromoterScoreComponent")+getComponentCountOnView(l,"SysFeedbackComponent")===1&&(E=this.getServices().documentModel.getViews().find(t=>t.id===u.conditionalRedirectViewId),viewHasControls(E)||isResultView(E,a)))return this.goToView(E.path[0],u),void t(!0);const h=null!==(s=u.formValue)&&void 0!==s?s:this.form.getControlsMap(),g=this.getContextValue(u);if(!u.skipNavigation&&c&&(viewHasControls(E)||!Object.keys(h).length&&!Object.keys(g).length))return this.goToView(r+1,u),void t(!0);if(!Object.keys(h).length&&!Object.keys(g).length)return void t(!0);const v=UTMParamsExtractor.extractTrackingParams(this.context),T=this.constructRequestPayload({contextValue:g,formValue:h,utmParams:v}),R=null===(n=null===(o=this.getServices().navigationLeadCollector)||void 0===o?void 0:o.getLatestNavigationData)||void 0===n?void 0:n.call(o);R&&(T.navigationData=R),this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_STARTED,T),this.eventEmitter.emit("CONTACT_DATA_SUBMIT",T);if(this.getTrackingMessageBeforeSentData()&&this.tracking.send("FormFinish_[Name]"),this.configService.getConfig("isBot"))return this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_FINISHED,{state:RequestStatus.SUCCESS,success:!0,skipped:!0}),void t();this.sendRequest(T).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=>{var i,s;const o=this.getTrackingMessageByStatus(e.state);if(o&&this.tracking.send(o),u.skipNavigation)return e.state===RequestStatus.TOO_MANY_REQUESTS&&this.eventEmitter.emit(SysEventTypes.TOO_MANY_REQUESTS),e.contactId&&"0"!==e.contactId&&this.eventEmitter.emit("CONTACT_ID_WAS_RECEIVED",e.contactId),this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_FINISHED,Object.assign(Object.assign({},e),{success:e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED})),void t(e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED);switch(e.state!==RequestStatus.SUCCESS&&e.state!==RequestStatus.ALREADY_SUBSCRIBED||null===(s=null===(i=this.getServices().navigationLeadCollector)||void 0===i?void 0:i.recordCommittedLead)||void 0===s||s.call(i),e.state){case RequestStatus.SUCCESS:c&&E?this.goToView(E.path[0]):this.runPostSubmitActionOrGoToView(()=>this.getSuccessViewIndex());break;case RequestStatus.ALREADY_SUBSCRIBED:m&&E?this.goToView(E.path[0]):this.runPostSubmitActionOrGoToView(()=>this.getAlreadySubscribedViewIndex());break;case RequestStatus.ERROR:m&&E?this.goToView(E.path[0]):this.handleErrorResponse();break;case RequestStatus.TOO_MANY_REQUESTS:this.goToView(m&&E?E.path[0]:this.getErrorViewIndex()),this.eventEmitter.emit(SysEventTypes.TOO_MANY_REQUESTS)}e.contactId&&"0"!==e.contactId&&this.eventEmitter.emit("CONTACT_ID_WAS_RECEIVED",e.contactId),this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_FINISHED,Object.assign(Object.assign({},e),{success:e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED})),t(e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED)}).catch(()=>{this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_FINISHED,{state:RequestStatus.ERROR,success:!1}),u.skipNavigation||this.handleErrorResponse(),t(!1)})}getContextValue(t){return extractContextValue(this.context,t.excludeFormContext)}constructDataToSent({contextValue:t,formValue:e,utmParams:i}){return constructDataToSent({contextValue:t,formValue:e,utmParams:i})}constructRequestPayload({contextValue:t,formValue:e,utmParams:i}){return constructRequestPayload({contextValue:t,formValue:e,utmParams:i,referrer:window.location.href,triggeredBy:this.configService.getConfig("triggeredBy"),widgetDebugMode:this.configService.getConfig("widgetDebugMode")})}constructRequestHeaders(){return constructRequestHeaders({clCustomerId:this.configService.getConfig("clCustomerId")})}goToView(t,e){this.eventEmitter.emit(SysActionTypes.GO_TO_VIEW,t,Object.assign(Object.assign({},e),{isForward:!0}))}sendRequest(t){return this.skipHttpRequest?Promise.resolve({status:200,json:()=>Promise.resolve({next:{type:RequestStatus.SUCCESS}})}):this.httpClient.execute({url:this.configService.getConfig("subscribeContactUrl"),method:"POST",body:t,headers:this.constructRequestHeaders()})}getSuccessViewIndex(){return this.resolveResultViewIndex("successViewId",["DOCUMENT_VIEW_TYPE_SUCCESS","DOCUMENT_VIEW_TYPE_SUCCESSFUL_REQUEST","REQUEST_FORM_VIEW_TYPE_SUCCESS"])}getErrorViewIndex(){return this.resolveResultViewIndex("errorViewId",["DOCUMENT_VIEW_TYPE_ERROR"])}getAlreadySubscribedViewIndex(){const t=this.getActiveSubmitActionParams();return t&&!t.alreadySubscribedViewId?this.getSuccessViewIndex():this.resolveResultViewIndex("alreadySubscribedViewId",["DOCUMENT_VIEW_TYPE_SUBSCRIBED"])}resolveResultViewIndex(t,e){var i;const s=this.getServices().documentModel.getViews(),o=null===(i=this.getActiveSubmitActionParams())||void 0===i?void 0:i[t];if(o){const t=s.findIndex(t=>t.id===o);if(-1!==t)return t}return s.findIndex(t=>e.includes(t.label))}hasFormControls(){return this.form.getControlsAsArray().length>0}getActiveSubmitActionParams(){if(this.hasFormControls())return this.getServices().documentModel.getShared().submitActionParams}runPostSubmitActionOrGoToView(t){var e;const i=null===(e=this.getActiveSubmitActionParams())||void 0===e?void 0:e.runAction;i?setTimeout(()=>{this.getServices().actionFactory.get(i).execute(this.stateService.getState())},1500):this.goToView(t())}handleErrorResponse(){const t=this.getErrorViewIndex();-1!==t?this.goToView(t):this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_ERROR_WITHOUT_VIEW)}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@claspo/renderer",
3
- "version": "18.9.0-sp9",
3
+ "version": "18.9.0",
4
4
  "scripts": {
5
5
  "dev": " tsc --project tsconfig.json --watch",
6
6
  "build": "rm -rf out && tsc --project tsconfig.json && npm run minify",
@@ -15,7 +15,7 @@
15
15
  "node": ">=18.16.0"
16
16
  },
17
17
  "dependencies": {
18
- "@claspo/common": "7.5.0-sp5",
18
+ "@claspo/common": "7.5.0",
19
19
  "@testing-library/dom": "^10.4.0"
20
20
  },
21
21
  "devDependencies": {
@@ -8,7 +8,7 @@ export default class PrizePool {
8
8
  load(): Promise<void>;
9
9
  _fetchReward(url: any, options: any): Promise<any>;
10
10
  _mergeRewardIntoOption(reward: any, options: any): any;
11
- _fetchPool(url: any): Promise<any>;
11
+ _fetchPool(url: string, prizePoolId: string): Promise<any>;
12
12
  _fetchJson(url: any, headers?: any): Promise<any>;
13
13
  getModel(): any;
14
14
  getPrize(): Promise<any>;
@@ -1 +1 @@
1
- import sum from"@claspo/common/math/sum";import RandomDistributor from"@claspo/common/math/RandomDistributor";import{PrizeCodeType,PrizeOptionValueType,PrizeSourceType}from"@claspo/common/PrizePool.interface";import{PreviewMode}from"../sdk/PreviewMode";const FETCHABLE_SOURCE_TYPES=[PrizeSourceType.MANUAL,PrizeSourceType.SHOPIFY],drawnPrizeCodePlaceholder="CLXXXXXXXX";export default class PrizePool{constructor(e,i,t){if(this.httpClient=i,this.configService=t,this.instanceModel=e||{},"FIXED"!==this.instanceModel.model){const e=this.configService.getConfig("prizePoolModels");if(e&&this.instanceModel.id){const i=e.find(e=>e.id===this.instanceModel.id);i&&(this.instanceModel=i)}}this.prizeOption=null,this.randomDistributor=new RandomDistributor}async load(){const{id:e,model:i,sourceType:t,options:o}=this.instanceModel;if(!(!o&&!!e&&"FIXED"!==i&&(!t||FETCHABLE_SOURCE_TYPES.includes(t))))return;const n=this.configService.getConfig("widgetId");try{const i=this.configService.getConfig("hostUrl"),o=`${i}forms/v2/prize/pool/${e}`,s=`${i}forms/v1/prizePool/${e}/reward?widgetId=${n}`;if(this._isPreview()){const e=await this._fetchPool(o);if(this.instanceModel=Object.assign(Object.assign({},this.instanceModel),{sourceType:t||e.sourceType,options:e.options}),this._mintsCodePerWinner(e.options))return;return void(this.prizeOption=await this._fetchReward(s,e.options))}const[r,c]=await Promise.all([this._fetchPool(o),this._fetchJson(s,{"cl-customer-id":this.configService.getConfig("clCustomerId")})]);this.instanceModel=Object.assign(Object.assign({},this.instanceModel),{sourceType:t||r.sourceType,options:r.options}),this.prizeOption=this._mergeRewardIntoOption(c,r.options)}catch(i){throw console.error(`PrizePool: failed to load pool or reward for widgetId "${n}" with poolId "${e}"`,i),i}}async _fetchReward(e,i){const t=await this._fetchJson(e,{"cl-customer-id":this.configService.getConfig("clCustomerId")});return this._mergeRewardIntoOption(t,i)}_mergeRewardIntoOption(e,i){return Object.assign(Object.assign({},i.find(i=>i.id===e.id)),e)}async _fetchPool(e){const i=await this._fetchJson(e);if(!1===(null==i?void 0:i.available))throw new Error("PrizePool: the pool is not available and cannot be handed out");return i}async _fetchJson(e,i){const t=await(i?this.httpClient.execute(e,"GET",null,i):this.httpClient.execute(e,"GET"));if(!t.ok)throw new Error(`PrizePool: request failed with status ${t.status} - ${e}`);return t.json()}getModel(){return this.instanceModel}async getPrize(){return this.instanceModel?"FIXED"===this.instanceModel.model?this.instanceModel.data:FETCHABLE_SOURCE_TYPES.includes(this.instanceModel.sourceType)?(this.instanceModel.options&&!this.prizeOption&&(this.prizeOption=this._calculatePrize()),this.prizeOption?this.mapPrizeOption(this.prizeOption):null):null:null}submitPrize(){}mapPrizeOption(e){const i=e.valueType===PrizeOptionValueType.PROMOCODE?e.value||"":this._mapLabelSuffix(e.value,e.valueType);return{id:e.id,label:i,value:e.code}}_calculatePrize(){const e=sum(this.instanceModel.options.map(e=>parseFloat(e.weight))),i=this.randomDistributor.calculateFromWeights(this.instanceModel.options,e);return i&&this._isCodeMintedPerWinner(i)?Object.assign(Object.assign({},i),{code:"CLXXXXXXXX"}):i}_mintsCodePerWinner(e){return(e||[]).some(e=>this._isCodeMintedPerWinner(e))}_isPreview(){return!!(this.configService.getConfig(PreviewMode.CABINET_PREVIEW)||this.configService.getConfig(PreviewMode.EDITOR_PREVIEW)||this.configService.getConfig(PreviewMode.DEMO))}_isCodeMintedPerWinner(e){var i;return(null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.codeType)===PrizeCodeType.UNIQUE}_mapLabelSuffix(e,i){return i===PrizeOptionValueType.DISCOUNT_PERCENTAGE?`${e}%`:e}}
1
+ import sum from"@claspo/common/math/sum";import RandomDistributor from"@claspo/common/math/RandomDistributor";import{PrizeCodeType,PrizeOptionValueType,PrizeSourceType}from"@claspo/common/PrizePool.interface";import{PreviewMode}from"../sdk/PreviewMode";import ErrorLogger from"../error/ErrorLogger";const FETCHABLE_SOURCE_TYPES=[PrizeSourceType.MANUAL,PrizeSourceType.SHOPIFY],drawnPrizeCodePlaceholder="CLXXXXXXXX";export default class PrizePool{constructor(e,i,o){if(this.httpClient=i,this.configService=o,this.instanceModel=e||{},"FIXED"!==this.instanceModel.model){const e=this.configService.getConfig("prizePoolModels");if(e&&this.instanceModel.id){const i=e.find(e=>e.id===this.instanceModel.id);i&&(this.instanceModel=i)}}this.prizeOption=null,this.randomDistributor=new RandomDistributor}async load(){const{id:e,model:i,sourceType:o,options:t}=this.instanceModel;if(!(!t&&!!e&&"FIXED"!==i&&(!o||FETCHABLE_SOURCE_TYPES.includes(o))))return;const n=this.configService.getConfig("widgetId");try{const i=this.configService.getConfig("hostUrl"),t=`${i}forms/v2/prize/pool/${e}`,r=`${i}forms/v1/prizePool/${e}/reward?widgetId=${n}`;if(this._isPreview()){const i=await this._fetchPool(t,e);if(this.instanceModel=Object.assign(Object.assign({},this.instanceModel),{sourceType:o||i.sourceType,options:i.options}),this._mintsCodePerWinner(i.options))return;return void(this.prizeOption=await this._fetchReward(r,i.options))}const[s,a]=await Promise.all([this._fetchPool(t,e),this._fetchJson(r,{"cl-customer-id":this.configService.getConfig("clCustomerId")})]);this.instanceModel=Object.assign(Object.assign({},this.instanceModel),{sourceType:o||s.sourceType,options:s.options}),this.prizeOption=this._mergeRewardIntoOption(a,s.options)}catch(i){throw console.error(`PrizePool: failed to load pool or reward for widgetId "${n}" with poolId "${e}"`,i),i}}async _fetchReward(e,i){const o=await this._fetchJson(e,{"cl-customer-id":this.configService.getConfig("clCustomerId")});return this._mergeRewardIntoOption(o,i)}_mergeRewardIntoOption(e,i){return Object.assign(Object.assign({},i.find(i=>i.id===e.id)),e)}async _fetchPool(e,i){const o=await this._fetchJson(e);if(!1===(null==o?void 0:o.available))throw ErrorLogger.log(`PrizePool: the pool ${i} is not available and cannot be handed out with a reason "${o.unavailableReason}"`),new Error("PrizePool: the pool is not available and cannot be handed out");return o}async _fetchJson(e,i){const o=await this.httpClient.execute({url:e,headers:i});if(!o.ok)throw new Error(`PrizePool: request failed with status ${o.status} - ${e}`);return o.json()}getModel(){return this.instanceModel}async getPrize(){return this.instanceModel?"FIXED"===this.instanceModel.model?this.instanceModel.data:FETCHABLE_SOURCE_TYPES.includes(this.instanceModel.sourceType)?(this.instanceModel.options&&!this.prizeOption&&(this.prizeOption=this._calculatePrize()),this.prizeOption?this.mapPrizeOption(this.prizeOption):null):null:null}submitPrize(){}mapPrizeOption(e){const i=e.valueType===PrizeOptionValueType.PROMOCODE?e.value||"":this._mapLabelSuffix(e.value,e.valueType);return{id:e.id,label:i,value:e.code}}_calculatePrize(){const e=sum(this.instanceModel.options.map(e=>parseFloat(e.weight))),i=this.randomDistributor.calculateFromWeights(this.instanceModel.options,e);return i&&this._isCodeMintedPerWinner(i)?Object.assign(Object.assign({},i),{code:"CLXXXXXXXX"}):i}_mintsCodePerWinner(e){return(e||[]).some(e=>this._isCodeMintedPerWinner(e))}_isPreview(){return!!(this.configService.getConfig(PreviewMode.CABINET_PREVIEW)||this.configService.getConfig(PreviewMode.EDITOR_PREVIEW)||this.configService.getConfig(PreviewMode.DEMO))}_isCodeMintedPerWinner(e){var i;return(null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.codeType)===PrizeCodeType.UNIQUE}_mapLabelSuffix(e,i){return i===PrizeOptionValueType.DISCOUNT_PERCENTAGE?`${e}%`:e}}
@@ -1 +1 @@
1
- import{EditorToWidgetEventType}from"../../document-model/DocumentModelService";import ErrorLogger from"../../error/ErrorLogger";import{fromCssVarToSchemaToken,toCssVarToken}from"@claspo/common/theme/theme.utils";export default class ColorSchemaListener{constructor(e,t,o,s,n,r){this.hostElement=t,this.documentModel=e,this.getSharedCb=o,this.getPropsCb=s,this.getEnvCb=n,this.httpClient=r,this.schemaSubscription=null,this.themeSubscription=null,this.envUrlMaps={desktop:new Map,mobile:new Map}}parseBackground(e){const t=String(e||"");if(t.includes("url")){const[e,o]=t.split("(")[1].split(")");return{url:e.replace(/['"]+/g,""),positionOptions:o.replace(";","")}}return{url:null,positionOptions:null}}apply(e){const t=this.getPropsCb();return t.backgroundDynamicInlineSVGElements[e].forEach(o=>{var s,n,r,i,l;const a=null===(n=null===(s=t.adaptiveStyles)||void 0===s?void 0:s[e])||void 0===n?void 0:n.find(e=>e.element===o),c=(null===(r=t.styles)||void 0===r?void 0:r.find(e=>e.element===o))||{},h=(null===(i=null==c?void 0:c.styleAttributes)||void 0===i?void 0:i.background)||(null===(l=null==a?void 0:a.styleAttributes)||void 0===l?void 0:l.background),m=this.parseBackground(h);m.url&&this.envUrlMaps[e].set(o,{originalSVGResourceURL:m.url,inlineSvgString:null,positionOptions:m.positionOptions})}),Promise.all([...this.envUrlMaps[e].entries()].map(([t,o])=>this.httpClient.execute(o.originalSVGResourceURL).then(e=>e.text()).then(s=>{this.envUrlMaps[e].set(t,Object.assign(Object.assign({},o),{inlineSvgString:s}))}))).then(()=>{var t;const o=this.getSharedCb();return Object.keys((null===(t=o.theme)||void 0===t?void 0:t.schema)||{}).length>0?this._applyHostElementBackgroundFromTheme(this.envUrlMaps[e].get("host"),o.theme.schema):this._applyHostElementBackgroundFromCssVars(this.envUrlMaps[e].get("host"),o.cssVars)}).catch(e=>{console.error(e),ErrorLogger.log(`Failed to load/apply backgroundDynamicInlineSVGElements[${this.getPropsCb().backgroundDynamicInlineSVGElements}] ${e}`)})}on(){return this.schemaSubscription=this.documentModel.on(EditorToWidgetEventType.COLOR_SCHEMA_UPDATE,e=>{this._applyHostElementBackgroundFromCssVars(this.envUrlMaps[this.getEnvCb()].get("host"),e)}),this.themeSubscription=this.documentModel.on(EditorToWidgetEventType.THEME_UPDATE,e=>{this._applyHostElementBackgroundFromTheme(this.envUrlMaps[this.getEnvCb()].get("host"),e.schema)}),this}_applyHostElementBackgroundFromCssVars(e,t){e&&t&&(this.hostElement.style.background=this._buildBackgroundUrlFromCssVars(e,t))}_applyHostElementBackgroundFromTheme(e,t){e&&t&&(this.hostElement.style.background=this._buildBackgroundUrlFromTheme(e,t))}_buildBackgroundUrlFromCssVars(e,t){const o=e.inlineSvgString.trim().replace("var(--cl-schema-accent)",t["cl-schema-accent"]);return`url('data:image/svg+xml,${encodeURIComponent(o)}')${e.positionOptions}`}_buildBackgroundUrlFromTheme(e,t){const o=e.inlineSvgString.trim();let s=o;[...o.matchAll(/var\(--cl-schema-([^)]+)\)/g)].forEach(e=>{const o=fromCssVarToSchemaToken(e[1]);s=s.replace(`var(--${toCssVarToken(o)})`,t[o])});return`url('data:image/svg+xml,${encodeURIComponent(s)}')${e.positionOptions}`}off(){var e,t;null===(e=this.schemaSubscription)||void 0===e||e.off(),null===(t=this.themeSubscription)||void 0===t||t.off()}}
1
+ import{EditorToWidgetEventType}from"../../document-model/DocumentModelService";import ErrorLogger from"../../error/ErrorLogger";import{fromCssVarToSchemaToken,toCssVarToken}from"@claspo/common/theme/theme.utils";export default class ColorSchemaListener{constructor(e,t,o,s,n,r){this.hostElement=t,this.documentModel=e,this.getSharedCb=o,this.getPropsCb=s,this.getEnvCb=n,this.httpClient=r,this.schemaSubscription=null,this.themeSubscription=null,this.envUrlMaps={desktop:new Map,mobile:new Map}}parseBackground(e){const t=String(e||"");if(t.includes("url")){const[e,o]=t.split("(")[1].split(")");return{url:e.replace(/['"]+/g,""),positionOptions:o.replace(";","")}}return{url:null,positionOptions:null}}apply(e){const t=this.getPropsCb();return t.backgroundDynamicInlineSVGElements[e].forEach(o=>{var s,n,r,i,l;const a=null===(n=null===(s=t.adaptiveStyles)||void 0===s?void 0:s[e])||void 0===n?void 0:n.find(e=>e.element===o),c=(null===(r=t.styles)||void 0===r?void 0:r.find(e=>e.element===o))||{},h=(null===(i=null==c?void 0:c.styleAttributes)||void 0===i?void 0:i.background)||(null===(l=null==a?void 0:a.styleAttributes)||void 0===l?void 0:l.background),m=this.parseBackground(h);m.url&&this.envUrlMaps[e].set(o,{originalSVGResourceURL:m.url,inlineSvgString:null,positionOptions:m.positionOptions})}),Promise.all([...this.envUrlMaps[e].entries()].map(([t,o])=>this.httpClient.execute({url:o.originalSVGResourceURL}).then(e=>e.text()).then(s=>{this.envUrlMaps[e].set(t,Object.assign(Object.assign({},o),{inlineSvgString:s}))}))).then(()=>{var t;const o=this.getSharedCb();return Object.keys((null===(t=o.theme)||void 0===t?void 0:t.schema)||{}).length>0?this._applyHostElementBackgroundFromTheme(this.envUrlMaps[e].get("host"),o.theme.schema):this._applyHostElementBackgroundFromCssVars(this.envUrlMaps[e].get("host"),o.cssVars)}).catch(e=>{console.error(e),ErrorLogger.log(`Failed to load/apply backgroundDynamicInlineSVGElements[${this.getPropsCb().backgroundDynamicInlineSVGElements}] ${e}`)})}on(){return this.schemaSubscription=this.documentModel.on(EditorToWidgetEventType.COLOR_SCHEMA_UPDATE,e=>{this._applyHostElementBackgroundFromCssVars(this.envUrlMaps[this.getEnvCb()].get("host"),e)}),this.themeSubscription=this.documentModel.on(EditorToWidgetEventType.THEME_UPDATE,e=>{this._applyHostElementBackgroundFromTheme(this.envUrlMaps[this.getEnvCb()].get("host"),e.schema)}),this}_applyHostElementBackgroundFromCssVars(e,t){e&&t&&(this.hostElement.style.background=this._buildBackgroundUrlFromCssVars(e,t))}_applyHostElementBackgroundFromTheme(e,t){e&&t&&(this.hostElement.style.background=this._buildBackgroundUrlFromTheme(e,t))}_buildBackgroundUrlFromCssVars(e,t){const o=e.inlineSvgString.trim().replace("var(--cl-schema-accent)",t["cl-schema-accent"]);return`url('data:image/svg+xml,${encodeURIComponent(o)}')${e.positionOptions}`}_buildBackgroundUrlFromTheme(e,t){const o=e.inlineSvgString.trim();let s=o;[...o.matchAll(/var\(--cl-schema-([^)]+)\)/g)].forEach(e=>{const o=fromCssVarToSchemaToken(e[1]);s=s.replace(`var(--${toCssVarToken(o)})`,t[o])});return`url('data:image/svg+xml,${encodeURIComponent(s)}')${e.positionOptions}`}off(){var e,t;null===(e=this.schemaSubscription)||void 0===e||e.off(),null===(t=this.themeSubscription)||void 0===t||t.off()}}