@claspo/renderer 18.8.0-nonlinear4 → 18.8.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.
- package/ViewRouter.d.ts +3 -1
- package/ViewRouter.js +1 -1
- package/action/ActionFactory.js +1 -1
- package/action/actions/BaseRequestAction.js +1 -1
- package/action/actions/GoToViewAction.d.ts +4 -1
- package/action/actions/GoToViewAction.js +1 -1
- package/document-model/DocumentModelService.js +1 -1
- package/form/FormControl.js +1 -1
- package/lead-capture/ActivePathTracker.js +1 -1
- package/lead-capture/FinishCoordinator.d.ts +2 -0
- package/lead-capture/FinishCoordinator.js +1 -1
- package/lead-capture/NavigationLeadCollector.js +1 -1
- package/package.json +2 -2
- package/sdk/WcControlledElement.d.ts +1 -0
- package/sdk/WcControlledElement.js +1 -1
- package/sdk/WcElement.d.ts +7 -0
- package/sdk/WcElement.js +1 -1
- package/sdk/autofill/InputFieldsAutofillHydrator.d.ts +9 -0
- package/sdk/autofill/InputFieldsAutofillHydrator.js +1 -0
- package/sdk/hidden-fields/HiddenFieldsContextHydrator.d.ts +0 -1
- package/sdk/hidden-fields/HiddenFieldsContextHydrator.js +1 -1
- package/sdk/source/resolveSourceValue.d.ts +4 -0
- package/sdk/source/resolveSourceValue.js +1 -0
- package/sdk/source/sources/JSApiVariablesSource.d.ts +1 -1
- package/sdk/source/sources/JSApiVariablesSource.js +1 -1
package/ViewRouter.d.ts
CHANGED
|
@@ -13,7 +13,9 @@ export default class ViewRouter extends DefaultEventEmitter {
|
|
|
13
13
|
getCurrentViewIndex(): any;
|
|
14
14
|
start(viewIndex: any): any;
|
|
15
15
|
destroy(): void;
|
|
16
|
-
navigate(index: any, routeState?: {
|
|
16
|
+
navigate(index: any, routeState?: {
|
|
17
|
+
isForward?: boolean;
|
|
18
|
+
} | null): void;
|
|
17
19
|
viewDestroy(): void;
|
|
18
20
|
getDocumentContainer(): any;
|
|
19
21
|
getLastTransition(): any;
|
package/ViewRouter.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import SysActionTypes from"./action/SysActionTypes";import SysEventTypes from"./common/SysEventTypes";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import SysRouterEvent from"./RouterEvent";export default class ViewRouter extends DefaultEventEmitter{constructor(t,e,n,i,
|
|
1
|
+
import SysActionTypes from"./action/SysActionTypes";import SysEventTypes from"./common/SysEventTypes";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import SysRouterEvent from"./RouterEvent";export default class ViewRouter extends DefaultEventEmitter{constructor(t,e,n,i,r){super(),this.eventEmitter=t,this.documentModel=e,this.viewRenderer=n,this.optionalDocumentStyles=i,this.services=r,this.currentViewIndex=null,this.currentViewComponentRef=null,this.eventEmitter.on(SysEventTypes.TOO_MANY_REQUESTS,()=>{this.viewDestroy(),this.documentContainer.innerText="Too many requests"}),this.transitions=[]}getCurrentViewIndex(){return this.currentViewIndex}start(t){this.documentContainer=window.document.createElement("div"),this.documentContainer.setAttribute("cl-document",""),this.optionalDocumentStyles&&Object.keys(this.optionalDocumentStyles).forEach(t=>{this.documentContainer.style[t]=this.optionalDocumentStyles[t]}),this.navigate(t||0);return this.eventEmitter.on(SysActionTypes.GO_TO_VIEW,(t,e,n)=>{const i="number"==typeof t?t:this.documentModel.getModel().views.findIndex(e=>e.id===t);-1===i?this.eventEmitter.emit("WIDGET_NAVIGATION_STATE_NOT_FOUND",{viewPointer:t}):this.navigate(i,n)}),this.eventEmitter.on(SysActionTypes.GO_TO_PREVIOUS_VIEW,t=>{"number"!=typeof t?this.getCurrentViewIndex()<=0||this.navigate(this.getCurrentViewIndex()-1,{isForward:!1}):this.navigate(t,{isForward:!1})}),this.eventEmitter.on(SysActionTypes.GO_TO_NEXT_VIEW,()=>{this.documentModel.getModel().views[this.getCurrentViewIndex()+1]&&this.navigate(this.getCurrentViewIndex()+1,{isForward:!0})}),this.documentContainer}destroy(){this.viewDestroy(),this.documentContainer&&this.documentContainer.remove()}navigate(t,e={}){var n;let i=this.documentModel.getView(t);const r=this.currentViewIndex;if(this.currentViewIndex===t)return;if(!i)throw this.eventEmitter.emit("WIDGET_NAVIGATION_STATE_NOT_FOUND",{navigateTo:t}),new Error("View was not found by index: "+t);const o=this.viewRenderer.render(i,t);this.viewDestroy(),this.documentContainer.appendChild(o),this.currentViewComponentRef=o,this.currentViewIndex=t,this.transitions.push({prevViewIndex:r,currentViewIndex:t,currentViewComponentRef:o,contactDataSubmitted:null===(n=this.services.submitState)||void 0===n?void 0:n.hasSubmitAttemptSinceLastChange(),routeState:e});const s="boolean"==typeof(null==e?void 0:e.isForward)?e.isForward:null!==r&&t>r;this.eventEmitter.emit(SysRouterEvent.NAVIGATION_END,t,{isForward:s})}viewDestroy(){this.currentViewComponentRef&&this.viewRenderer.destroy(this.currentViewComponentRef)}getDocumentContainer(){return this.documentContainer}getLastTransition(){return this.transitions[this.transitions.length-1]}}
|
package/action/ActionFactory.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import SysActionTypes from"./SysActionTypes";import SubscribeContactAction from"./actions/SubscribeContactAction";import RequestAction from"./actions/RequestAction";import DispatchEventAction from"./actions/DispatchEventAction";import GoToPreviousViewAction from"./actions/GoToPreviousViewAction";import GoToNextViewAction from"./actions/GoToNextViewAction";import GoToViewAction from"./actions/GoToViewAction";import HttpClient from"@claspo/common/network/HttpClient";import ShowWidgetAction from"./actions/ShowWidgetAction";import OpenLinkAction from"./actions/OpenLinkAction";import CloseWidgetAction from"./actions/CloseWidgetAction";export default class ActionFactory{constructor(t,i,e,o,n,s
|
|
1
|
+
import SysActionTypes from"./SysActionTypes";import SubscribeContactAction from"./actions/SubscribeContactAction";import RequestAction from"./actions/RequestAction";import DispatchEventAction from"./actions/DispatchEventAction";import GoToPreviousViewAction from"./actions/GoToPreviousViewAction";import GoToNextViewAction from"./actions/GoToNextViewAction";import GoToViewAction from"./actions/GoToViewAction";import HttpClient from"@claspo/common/network/HttpClient";import ShowWidgetAction from"./actions/ShowWidgetAction";import OpenLinkAction from"./actions/OpenLinkAction";import CloseWidgetAction from"./actions/CloseWidgetAction";export default class ActionFactory{constructor(t,i,e,o,n,c,s){this.eventEmitter=t,this.form=i,this.configService=e,this.tracking=o,this.stateService=n,this.context=c,this.getServices=s}get(t){switch(t.type){case SysActionTypes.SUBSCRIBE_CONTACT:return new SubscribeContactAction(this.eventEmitter,this.form,t,HttpClient,this.configService,this.tracking,this.stateService,this.context,this.getServices);case SysActionTypes.REQUEST:return new RequestAction(this.eventEmitter,this.form,t,HttpClient,this.configService,this.tracking,this.stateService,this.context,this.getServices);case SysActionTypes.DISPATCH_EVENT:return new DispatchEventAction(this.eventEmitter,t);case SysActionTypes.GO_TO_VIEW:return new GoToViewAction(this.eventEmitter,t,this.configService,this.form,this.getServices().viewRouter,this.getServices().documentModel,this.tracking,this.getServices().activePathTracker);case SysActionTypes.GO_TO_PREVIOUS_VIEW:return new GoToPreviousViewAction(this.eventEmitter,t,this.tracking,this.getServices().activePathTracker);case SysActionTypes.GO_TO_NEXT_VIEW:return new GoToNextViewAction(this.eventEmitter,this.form,t,this.tracking);case SysActionTypes.SHOW_WIDGET:return new ShowWidgetAction(this.eventEmitter,t,this.tracking);case SysActionTypes.OPEN_LINK:return new OpenLinkAction(t,this.configService,this.tracking);case SysActionTypes.CLOSE_WIDGET:return new CloseWidgetAction(this.eventEmitter,t,this.configService,this.tracking);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 h=this.getServices().documentModel.getViews()[r];if(!u.skipNavigation&&m&&getComponentCountOnView(h,"SysNetPromoterScoreComponent")+getComponentCountOnView(h,"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 l=null!==(s=u.formValue)&&void 0!==s?s:this.form.getControlsMap(),g=this.getContextValue(u);if(!u.skipNavigation&&c&&(viewHasControls(E)||!Object.keys(l).length&&!Object.keys(g).length))return this.goToView(r+1,u),void t(!0);if(!Object.keys(l).length&&!Object.keys(g).length)return void t(!0);const T=UTMParamsExtractor.extractTrackingParams(this.context),v=this.constructRequestPayload({contextValue:g,formValue:l,utmParams:T}),R=null===(n=null===(o=this.getServices().navigationLeadCollector)||void 0===o?void 0:o.getLatestNavigationData)||void 0===n?void 0:n.call(o);R&&(v.navigationData=R),this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_STARTED,v),this.eventEmitter.emit("CONTACT_DATA_SUBMIT",v);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(v).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 i=this.getTrackingMessageByStatus(e.state);if(i&&this.tracking.send(i),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){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,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())}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 h=this.getServices().documentModel.getViews()[r];if(!u.skipNavigation&&m&&getComponentCountOnView(h,"SysNetPromoterScoreComponent")+getComponentCountOnView(h,"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 l=null!==(s=u.formValue)&&void 0!==s?s:this.form.getControlsMap(),g=this.getContextValue(u);if(!u.skipNavigation&&c&&(viewHasControls(E)||!Object.keys(l).length&&!Object.keys(g).length))return this.goToView(r+1,u),void t(!0);if(!Object.keys(l).length&&!Object.keys(g).length)return void t(!0);const T=UTMParamsExtractor.extractTrackingParams(this.context),v=this.constructRequestPayload({contextValue:g,formValue:l,utmParams:T}),R=null===(n=null===(o=this.getServices().navigationLeadCollector)||void 0===o?void 0:o.getLatestNavigationData)||void 0===n?void 0:n.call(o);R&&(v.navigationData=R),this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_STARTED,v),this.eventEmitter.emit("CONTACT_DATA_SUBMIT",v);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(v).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 i=this.getTrackingMessageByStatus(e.state);if(i&&this.tracking.send(i),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){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)}}
|
|
@@ -6,7 +6,10 @@ export default class GoToViewAction {
|
|
|
6
6
|
viewRouter: any;
|
|
7
7
|
documentModel: any;
|
|
8
8
|
tracking: any;
|
|
9
|
+
activePathTracker: any;
|
|
9
10
|
type: SysActionTypes;
|
|
10
|
-
constructor(eventEmitter: any, actionConfig: any, configService: any, form: any, viewRouter: any, documentModel: any, tracking: any);
|
|
11
|
+
constructor(eventEmitter: any, actionConfig: any, configService: any, form: any, viewRouter: any, documentModel: any, tracking: any, activePathTracker: any);
|
|
11
12
|
execute(): Promise<boolean>;
|
|
13
|
+
private getTargetViewIndex;
|
|
14
|
+
private isForwardNavigation;
|
|
12
15
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import SysActionTypes from"../SysActionTypes";export default class GoToViewAction{constructor(i,
|
|
1
|
+
import SysActionTypes from"../SysActionTypes";import ErrorLogger from"../../error/ErrorLogger";export default class GoToViewAction{constructor(t,i,e,r,o,a,s,n){this.type=SysActionTypes.GO_TO_VIEW,this.eventEmitter=t,this.config=i,this.form=r,this.viewRouter=o,this.documentModel=a,this.tracking=s,this.activePathTracker=n}async execute(){var t;try{this.form.markAsTouched();const i=this.isForwardNavigation(this.getTargetViewIndex());if(i&&(null===(t=this.config.params.validateForm)||void 0===t||t)){if(!await this.form.waitForPendingValidationAndCheckIfValid())return this.eventEmitter.emit("INVALID_CONTACT_DATA_SUBMIT_ATTEMPT"),!1}return this.eventEmitter.emit(this.type,this.config.params.viewId||this.config.params.viewIndex,{isForward:i}),this.config.params.trackClick&&this.tracking.trackClick({params:this.config.params.trackClickParams,countAsTargetAction:this.config.params.countAsTargetAction}),!0}catch(t){return ErrorLogger.log(`GoToViewAction.execute failed: ${(null==t?void 0:t.stack)||t}`),!1}}getTargetViewIndex(){return this.config.params.viewId?this.documentModel.getViews().findIndex(t=>t.id===this.config.params.viewId):this.config.params.viewIndex}isForwardNavigation(t){var i,e,r;if("number"!=typeof t||t<0)return!1;const o=null!==(r=null===(e=null===(i=this.activePathTracker)||void 0===i?void 0:i.getActivePath)||void 0===e?void 0:e.call(i))&&void 0!==r?r:[];return o.length?!o.includes(t):this.viewRouter.getCurrentViewIndex()<t}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import ModulesComponentExtractor from"./ModulesComponentExtractor";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import DocumentUtils from"@claspo/common/document/DocumentUtils";import{buildViewNavigationGraph}from"@claspo/common/document/ViewNavigationGraph";export const EditorToWidgetEventType={COMPONENT_INSERT:"COMPONENT_INSERT",COMPONENT_REMOVE:"COMPONENT_REMOVE",COMPONENT_MOVE:"COMPONENT_MOVE",COMPONENT_UPDATE:"COMPONENT_UPDATE",COMPONENT_PROPS_UPDATE:"COMPONENT_PROPS_UPDATE",REMOVE_FOCUS:"REMOVE_FOCUS",SET_FOCUS:"SET_FOCUS",SHARED_UPDATE:"SHARED_UPDATE",MOBILE_BREAKPOINT_UPDATE:"MOBILE_BREAKPOINT_UPDATE",ENVIRONMENT_UPDATE:"ENVIRONMENT_UPDATE",TEXT_CLASS_ADDED:"TEXT_CLASS_ADDED",TEXT_CLASS_UPDATED:"TEXT_CLASS_UPDATED",TEXT_CLASS_REMOVED:"TEXT_CLASS_REMOVED",HEADER_FONT_FAMILY_UPDATE:"HEADER_FONT_FAMILY_UPDATE",TEXT_FONT_FAMILY_UPDATE:"TEXT_FONT_FAMILY_UPDATE",SHARED_UPDATE_ALL:"SHARED_UPDATE_ALL",COLOR_SCHEMA_UPDATE:"COLOR_SCHEMA_UPDATE",THEME_UPDATE:"THEME_UPDATE"};export default class DocumentModelService extends DefaultEventEmitter{constructor(t){super(),this.navigationGraph=null,this.json=t,this.flatJson=ModulesComponentExtractor.extract(this.json)}setComponentRef(t,e){DocumentUtils.getNodeById(this.getViews(),t).componentRef=e}getModel(){return this.flatJson}getView(t){return this.flatJson.views[t]}getViews(){return this.flatJson.views}getShared(){return this.flatJson.shared}getNavigationGraph(){
|
|
1
|
+
import ModulesComponentExtractor from"./ModulesComponentExtractor";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import DocumentUtils from"@claspo/common/document/DocumentUtils";import{buildViewNavigationGraph}from"@claspo/common/document/ViewNavigationGraph";import ErrorLogger from"../error/ErrorLogger";export const EditorToWidgetEventType={COMPONENT_INSERT:"COMPONENT_INSERT",COMPONENT_REMOVE:"COMPONENT_REMOVE",COMPONENT_MOVE:"COMPONENT_MOVE",COMPONENT_UPDATE:"COMPONENT_UPDATE",COMPONENT_PROPS_UPDATE:"COMPONENT_PROPS_UPDATE",REMOVE_FOCUS:"REMOVE_FOCUS",SET_FOCUS:"SET_FOCUS",SHARED_UPDATE:"SHARED_UPDATE",MOBILE_BREAKPOINT_UPDATE:"MOBILE_BREAKPOINT_UPDATE",ENVIRONMENT_UPDATE:"ENVIRONMENT_UPDATE",TEXT_CLASS_ADDED:"TEXT_CLASS_ADDED",TEXT_CLASS_UPDATED:"TEXT_CLASS_UPDATED",TEXT_CLASS_REMOVED:"TEXT_CLASS_REMOVED",HEADER_FONT_FAMILY_UPDATE:"HEADER_FONT_FAMILY_UPDATE",TEXT_FONT_FAMILY_UPDATE:"TEXT_FONT_FAMILY_UPDATE",SHARED_UPDATE_ALL:"SHARED_UPDATE_ALL",COLOR_SCHEMA_UPDATE:"COLOR_SCHEMA_UPDATE",THEME_UPDATE:"THEME_UPDATE"};export default class DocumentModelService extends DefaultEventEmitter{constructor(t){super(),this.navigationGraph=null,this.json=t,this.flatJson=ModulesComponentExtractor.extract(this.json)}setComponentRef(t,e){DocumentUtils.getNodeById(this.getViews(),t).componentRef=e}getModel(){return this.flatJson}getView(t){return this.flatJson.views[t]}getViews(){return this.flatJson.views}getShared(){return this.flatJson.shared}getNavigationGraph(){if(!this.navigationGraph)try{this.navigationGraph=buildViewNavigationGraph(this.getViews(),this.getShared())}catch(t){ErrorLogger.log(`buildViewNavigationGraph failed: ${(null==t?void 0:t.stack)||t}`),this.navigationGraph={nodes:[],edges:[]}}return this.navigationGraph}iterateViewModelAndExecute(t,e){const o=this.getView(t);DocumentUtils.iterateDepthFirst(o,e)}destroy(){}destroyView(t){console.warn("destroyView now should do nothing"),this.iterateViewModelAndExecute(t,t=>{t.componentRef&&(t.componentRef.remove(),t.componentRef=null)})}}
|
package/form/FormControl.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import FormControlValidator from"./FormControlValidator";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import FormControlEvents from"./FormControlEvents";import debounce from"@claspo/common/async/debounce";export class FormControl extends DefaultEventEmitter{constructor(e,t,i,s,n){super(),this.componentId=e.componentId,this.viewIdx=Number.isInteger(e.viewIdx)?e.viewIdx:null,this.name=e.name,this.defaultValue=e.defaultValue,this.value=e.defaultValue?e.defaultValue:void 0,this.validator=new FormControlValidator(this,e.validation,i,s),this.errorKeys=this.validator.getSyncErrorKeys(this.getValue()),this.valid=!this.errorKeys.length,this.disabled=!1,this.pending=!1,this.debounceValue=e.hasOwnProperty("debounceValue")?e.debounceValue:300,this.tracking=n,this.touched=!1,this.valueChanged=!1,this.elementRef=null,this.debouncedValidate=()=>{},this._init(e,t)}inputElementValueChanged(e){this.tracking.send("FormStartFilling_[Name]"),this.setValue(e)}setDisabled(){this.disabled=!0,this.elementRef&&this.elementRef.setAttribute("disabled","disabled")}setEnabled(){this.disabled=!1,this.elementRef&&this.elementRef.removeAttribute("disabled")}setPending(e){this.pending=e}getName(){return this.name}getValue(){return this.value}getComponentId(){return this.componentId}setValue(e="",t={silent:!1,skipValidation:!1,skipElementUpdate:!1}){t.skipElementUpdate||(this.valueChanged=this.value!==e),this.value=e,this.elementRef&&!t.skipElementUpdate&&("checkbox"===this.elementRef.getAttribute("type")?this.elementRef.checked=!!e:this.elementRef.value=e),t.skipValidation?!t.silent&&this.valueChanged&&this.emit(FormControlEvents.valueChanged,e):(this.pending=!0,this.emit(FormControlEvents.validationStatusChanged,"pending"),this.debouncedValidate(t)),t.silent||t.skipValidation||this.elementRef||this.markAsTouched()}isValid(){return this.valid}isPending(){return this.pending}async validate(e={silent:!1}){this.pending=!0;const t=await this.validator.getErrorKeys(this.getValue());return this.valid=!t.length,this.errorKeys=t,this.pending=!1,e.silent||(this.emit(FormControlEvents.validationStatusChanged,this.valid?"valid":"invalid"),this.valueChanged&&(this.emit(FormControlEvents.valueChanged,this.getValue()),this.valueChanged=!1)),this.valid}adoptValidationState(e){e&&(
|
|
1
|
+
import FormControlValidator from"./FormControlValidator";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import FormControlEvents from"./FormControlEvents";import debounce from"@claspo/common/async/debounce";export class FormControl extends DefaultEventEmitter{constructor(e,t,i,s,n){super(),this.componentId=e.componentId,this.viewIdx=Number.isInteger(e.viewIdx)?e.viewIdx:null,this.name=e.name,this.defaultValue=e.defaultValue,this.value=e.defaultValue?e.defaultValue:void 0,this.validator=new FormControlValidator(this,e.validation,i,s),this.errorKeys=this.validator.getSyncErrorKeys(this.getValue()),this.valid=!this.errorKeys.length,this.disabled=!1,this.pending=!1,this.debounceValue=e.hasOwnProperty("debounceValue")?e.debounceValue:300,this.tracking=n,this.touched=!1,this.valueChanged=!1,this.elementRef=null,this.debouncedValidate=()=>{},this._init(e,t)}inputElementValueChanged(e){this.tracking.send("FormStartFilling_[Name]"),this.setValue(e)}setDisabled(){this.disabled=!0,this.elementRef&&this.elementRef.setAttribute("disabled","disabled")}setEnabled(){this.disabled=!1,this.elementRef&&this.elementRef.removeAttribute("disabled")}setPending(e){this.pending=e}getName(){return this.name}getValue(){return this.value}getComponentId(){return this.componentId}setValue(e="",t={silent:!1,skipValidation:!1,skipElementUpdate:!1}){t.skipElementUpdate||(this.valueChanged=this.value!==e),this.value=e,this.elementRef&&!t.skipElementUpdate&&("checkbox"===this.elementRef.getAttribute("type")?this.elementRef.checked=!!e:this.elementRef.value=e),t.skipValidation?!t.silent&&this.valueChanged&&this.emit(FormControlEvents.valueChanged,e):(this.pending=!0,this.emit(FormControlEvents.validationStatusChanged,"pending"),this.debouncedValidate(t)),t.silent||t.skipValidation||this.elementRef||this.markAsTouched()}isValid(){return this.valid}isPending(){return this.pending}async validate(e={silent:!1}){this.pending=!0;const t=await this.validator.getErrorKeys(this.getValue());return this.valid=!t.length,this.errorKeys=t,this.pending=!1,e.silent||(this.emit(FormControlEvents.validationStatusChanged,this.valid?"valid":"invalid"),this.valueChanged&&(this.emit(FormControlEvents.valueChanged,this.getValue()),this.valueChanged=!1)),this.valid}adoptValidationState(e){e&&(e.isPending()?this.validate():this.valid&&!e.isValid()&&(this.valid=!1,this.errorKeys=e.getErrorKeys()))}markAsTouched(){this.touched=!0,this.emit(FormControlEvents.touchedStatusChanged,null)}isTouched(){return this.touched}getErrorKeys(){return this.errorKeys}destroy(){super.destroy()}_init(e,t){const i=t?t.getAttribute("type"):null;if(t&&e.defaultValue&&("checkbox"===i?t.checked=e.defaultValue:t.value=e.defaultValue),t){const s=e.triggerEvent?e.triggerEvent:"input",n="checkbox"===i;t.addEventListener(s,e=>{const t=e.target;this.inputElementValueChanged(n?t.checked:t.value)}),t.addEventListener("blur",()=>{this.markAsTouched()}),this.elementRef=t}this.debouncedValidate=this.debounceValue?debounce(e=>this.validate(e),this.debounceValue):this.validate.bind(this)}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import SysRouterEvent from"../RouterEvent";import FormGroupEvents from"../form/FormGroupEvents";import FormSource from"../sdk/source/sources/FormSource";export default class ActivePathTracker{constructor(e,t,i,s){this.activePath=[],this.pendingTail=[],this.stashedValues=new Map,this.form=t,this.context=i,this.state=s,this.subscriptions=[e.on(SysRouterEvent.NAVIGATION_END,e=>this.onNavigationEnd(e)),t.on(FormGroupEvents.controlRegistered,e=>this.reseedStashedValue(e))]}getActivePath(){return[...this.activePath]}destroy(){this.subscriptions.forEach(e=>{var t;return null===(t=null==e?void 0:e.off)||void 0===t?void 0:t.call(e)}),this.subscriptions=[]}onNavigationEnd(e){if(!this.activePath.length)return void this.activePath.push(e);if(this.activePath[this.activePath.length-1]===e)return;const t=this.activePath.indexOf(e);if(-1!==t){const e=this.activePath.splice(t+1);return this.stashTailControls(e),void(this.pendingTail=[...e,...this.pendingTail])}if(this.pendingTail.length){const t=this.pendingTail.indexOf(e);if(-1===t)this.pruneAbandonedTail(this.pendingTail),this.pendingTail=[];else{const e=this.pendingTail.slice(0,t);e.length&&this.pruneAbandonedTail(e),this.pendingTail=this.pendingTail.slice(t+1)}}this.activePath.push(e)}stashTailControls(e){this.form.getControlsAsArray().forEach(t=>{if(null===t.viewIdx||!e.includes(t.viewIdx))return;const i=t.getValue();void 0!==i&&""!==i&&this.stashedValues.set(t.getName(),{value:i,viewIdx:t.viewIdx}),this.form.removeControl(t.getName())})}reseedStashedValue(e){const t=this.stashedValues.get(e.getName());t
|
|
1
|
+
import SysRouterEvent from"../RouterEvent";import FormGroupEvents from"../form/FormGroupEvents";import FormSource from"../sdk/source/sources/FormSource";import ErrorLogger from"../error/ErrorLogger";export default class ActivePathTracker{constructor(e,t,i,s){this.activePath=[],this.pendingTail=[],this.stashedValues=new Map,this.form=t,this.context=i,this.state=s,this.subscriptions=[e.on(SysRouterEvent.NAVIGATION_END,e=>this.onNavigationEnd(e)),t.on(FormGroupEvents.controlRegistered,e=>this.reseedStashedValue(e))]}getActivePath(){return[...this.activePath]}destroy(){this.subscriptions.forEach(e=>{var t;return null===(t=null==e?void 0:e.off)||void 0===t?void 0:t.call(e)}),this.subscriptions=[]}onNavigationEnd(e){try{if(!this.activePath.length)return void this.activePath.push(e);if(this.activePath[this.activePath.length-1]===e)return;const t=this.activePath.indexOf(e);if(-1!==t){const e=this.activePath.splice(t+1);return this.stashTailControls(e),void(this.pendingTail=[...e,...this.pendingTail])}if(this.pendingTail.length){const t=this.pendingTail.indexOf(e);if(-1===t)this.pruneAbandonedTail(this.pendingTail),this.pendingTail=[];else{const e=this.pendingTail.slice(0,t);e.length&&this.pruneAbandonedTail(e),this.pendingTail=this.pendingTail.slice(t+1)}}this.activePath.push(e)}catch(e){ErrorLogger.log(`ActivePathTracker.onNavigationEnd failed: ${(null==e?void 0:e.stack)||e}`)}}stashTailControls(e){this.form.getControlsAsArray().forEach(t=>{if(null===t.viewIdx||!e.includes(t.viewIdx))return;const i=t.getValue();void 0!==i&&""!==i&&this.stashedValues.set(t.getName(),{value:i,viewIdx:t.viewIdx}),this.form.removeControl(t.getName())})}reseedStashedValue(e){try{const t=this.stashedValues.get(e.getName());if(!t||t.viewIdx!==e.viewIdx)return;this.stashedValues.delete(e.getName()),e.setValue(t.value)}catch(e){ErrorLogger.log(`ActivePathTracker.reseedStashedValue failed: ${(null==e?void 0:e.stack)||e}`)}}pruneAbandonedTail(e){Array.from(this.stashedValues.entries()).forEach(([t,i])=>{e.includes(i.viewIdx)&&this.stashedValues.delete(t)}),this.form.getControlsAsArray().forEach(t=>{null!==t.viewIdx&&e.includes(t.viewIdx)&&this.form.removeControl(t.getName())});const t=this.context.getRecordsMap();Object.keys(t).forEach(i=>{var s;const r=null===(s=t[i])||void 0===s?void 0:s.getValue();r&&r.sourceId===FormSource.sourceId&&void 0!==r.viewIndex&&e.includes(r.viewIndex)&&this.context.deleteRecord(i,!0)}),this.state.setState({conditionalRedirectViewId:null})}}
|
|
@@ -12,6 +12,8 @@ export default class FinishCoordinator {
|
|
|
12
12
|
private graph;
|
|
13
13
|
private finished;
|
|
14
14
|
private inFlight;
|
|
15
|
+
private executingCommit;
|
|
16
|
+
private lastSubmitAttemptWasOwnFailedCommit;
|
|
15
17
|
private subscriptions;
|
|
16
18
|
constructor(eventEmitter: DefaultEventEmitter, documentModel: DocumentModelService, getServices: () => any);
|
|
17
19
|
destroy(): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import SysRouterEvent from"../RouterEvent";import SysEventTypes from"../common/SysEventTypes";import SysActionTypes from"../action/SysActionTypes";import ActionCategory from"../action/actions/ActionCategory";import{SubmitState}from"../submit-state/SubmitStateService";import{isAutoCommitTerminal,isMultiViewFlow}from"@claspo/common/document/ViewNavigationGraph";export var FinishTrigger;!function(t){t.TERMINAL="terminal",t.CLOSE="close"}(FinishTrigger||(FinishTrigger={}));export default class FinishCoordinator{constructor(t,i,e){this.finished=!1,this.inFlight=!1,this.getServices=e,this.graph=i.getNavigationGraph(),this.subscriptions=[t.on(SysRouterEvent.NAVIGATION_END,t=>this.onNavigationEnd(t)),t.on(SysEventTypes.SUBMIT_REQUEST_FINISHED,t=>{(null==t?void 0:t.success)&&(this.finished=!0)})]}destroy(){this.subscriptions.forEach(t=>{var i;return null===(i=null==t?void 0:t.off)||void 0===i?void 0:i.call(t)}),this.subscriptions=[]}async attemptCommit(t,i){var e,o;const
|
|
1
|
+
import SysRouterEvent from"../RouterEvent";import SysEventTypes from"../common/SysEventTypes";import SysActionTypes from"../action/SysActionTypes";import ActionCategory from"../action/actions/ActionCategory";import{SubmitState}from"../submit-state/SubmitStateService";import{isAutoCommitTerminal,isMultiViewFlow}from"@claspo/common/document/ViewNavigationGraph";import ErrorLogger from"../error/ErrorLogger";export var FinishTrigger;!function(t){t.TERMINAL="terminal",t.CLOSE="close"}(FinishTrigger||(FinishTrigger={}));export default class FinishCoordinator{constructor(t,i,e){this.finished=!1,this.inFlight=!1,this.executingCommit=!1,this.lastSubmitAttemptWasOwnFailedCommit=!1,this.getServices=e,this.graph=i.getNavigationGraph(),this.subscriptions=[t.on(SysRouterEvent.NAVIGATION_END,t=>this.onNavigationEnd(t)),t.on(SysEventTypes.SUBMIT_REQUEST_STARTED,()=>{this.executingCommit||(this.lastSubmitAttemptWasOwnFailedCommit=!1)}),t.on(SysEventTypes.SUBMIT_REQUEST_FINISHED,t=>{(null==t?void 0:t.success)&&(this.finished=!0,this.lastSubmitAttemptWasOwnFailedCommit=!1)})]}destroy(){this.subscriptions.forEach(t=>{var i;return null===(i=null==t?void 0:t.off)||void 0===i?void 0:i.call(t)}),this.subscriptions=[]}async attemptCommit(t,i){var e,o;const r=this.getServices(),s=null==r?void 0:r.submitState;if(!s||this.finished||this.inFlight)return!1;if(s.hasSubmitAttemptSinceLastChange()&&!this.lastSubmitAttemptWasOwnFailedCommit)return!1;if(t===FinishTrigger.CLOSE&&(!s.hasDirtyFormData()||s.getState()!==SubmitState.DIRTY&&!this.lastSubmitAttemptWasOwnFailedCommit))return!1;this.inFlight=!0;try{const t=await s.prepareAutoSubmitFormValue();if(this.finished||s.hasSubmitAttemptSinceLastChange()&&!this.lastSubmitAttemptWasOwnFailedCommit)return!1;if(!t||!Object.values(t).length)return!1;this.lastSubmitAttemptWasOwnFailedCommit=!1,null===(e=null==i?void 0:i.beforeExecute)||void 0===e||e.call(i,t);const n=(null===(o=r.actionRegister)||void 0===o?void 0:o.getRegisteredActions().find(t=>t.category===ActionCategory.SUBMIT))||r.actionFactory.get({type:SysActionTypes.REQUEST});let a;this.executingCommit=!0;try{a=await n.execute(void 0,void 0,!0,{skipValidation:!0,skipNavigation:!0,excludeFormContext:!0,formValue:t})}catch(t){ErrorLogger.log(`FinishCoordinator commit execute failed: ${(null==t?void 0:t.stack)||t}`),a=!1}finally{this.executingCommit=!1}return!1===a?(this.lastSubmitAttemptWasOwnFailedCommit=!0,!1):(this.finished=!0,!0)}catch(t){return ErrorLogger.log(`FinishCoordinator.attemptCommit failed: ${(null==t?void 0:t.stack)||t}`),!1}finally{this.inFlight=!1}}onNavigationEnd(t){try{if(!isMultiViewFlow(this.graph))return;if(!isAutoCommitTerminal(this.graph,t))return;this.attemptCommit(FinishTrigger.TERMINAL).catch(t=>{ErrorLogger.log(`FinishCoordinator terminal commit rejected: ${(null==t?void 0:t.stack)||t}`)})}catch(t){ErrorLogger.log(`FinishCoordinator.onNavigationEnd failed: ${(null==t?void 0:t.stack)||t}`)}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import SysRouterEvent from"../RouterEvent";import SysEventTypes from"../common/SysEventTypes";import UTMParamsExtractor from"../action/UTMParamsExtractor";import{constructRequestPayload,extractContextValue}from"../action/RequestPayloadBuilder";import{hasMeaningfulValue}from"../submit-state/SubmitStateService";import{isAutoCommitTerminal,isMultiViewFlow}from"@claspo/common/document/ViewNavigationGraph";function stableStringify(t){var i;if(Array.isArray(t))return`[${t.map(stableStringify).join(",")}]`;if(t&&"object"==typeof t){return`{${Object.keys(t).sort().map(i=>`${JSON.stringify(i)}:${stableStringify(t[i])}`).join(",")}}`}return null!==(i=JSON.stringify(t))&&void 0!==i?i:"undefined"}export default class NavigationLeadCollector{constructor(t,i,e,
|
|
1
|
+
import SysRouterEvent from"../RouterEvent";import SysEventTypes from"../common/SysEventTypes";import UTMParamsExtractor from"../action/UTMParamsExtractor";import{constructRequestPayload,extractContextValue}from"../action/RequestPayloadBuilder";import{hasMeaningfulValue}from"../submit-state/SubmitStateService";import{isAutoCommitTerminal,isMultiViewFlow}from"@claspo/common/document/ViewNavigationGraph";import ErrorLogger from"../error/ErrorLogger";function stableStringify(t){var i;if(Array.isArray(t))return`[${t.map(stableStringify).join(",")}]`;if(t&&"object"==typeof t){return`{${Object.keys(t).sort().map(i=>`${JSON.stringify(i)}:${stableStringify(t[i])}`).join(",")}}`}return null!==(i=JSON.stringify(t))&&void 0!==i?i:"undefined"}export default class NavigationLeadCollector{constructor(t,i,r,e,a){this.previousViewIndex=null,this.lastSentSignature=null,this.latestForwardNavigationData=null,this.eventEmitter=t,this.form=r,this.context=e,this.views=i.getViews(),this.graph=i.getNavigationGraph(),this.triggeredBy=a,this.subscriptions=[t.on(SysRouterEvent.NAVIGATION_END,(t,i,r)=>this.onNavigationEnd(t,r))]}destroy(){this.subscriptions.forEach(t=>{var i;return null===(i=null==t?void 0:t.off)||void 0===i?void 0:i.call(t)}),this.subscriptions=[]}getLatestNavigationData(){return this.latestForwardNavigationData}onNavigationEnd(t,i){var r,e;try{const a=this.previousViewIndex;if(this.previousViewIndex=t,!isMultiViewFlow(this.graph))return;const o="boolean"==typeof(null==i?void 0:i.isForward)?i.isForward:null!==a&&t>a;if(null===a||!o)return;if(this.latestForwardNavigationData={previousViewId:null===(r=this.views[a])||void 0===r?void 0:r.id,currentViewId:null===(e=this.views[t])||void 0===e?void 0:e.id},isAutoCommitTerminal(this.graph,t))return;const n=this.buildFormValue(),s=extractContextValue(this.context,!0);if(!Object.keys(n).length&&!Object.keys(s).length)return;const l=stableStringify({contextValue:s,formValue:n});if(l===this.lastSentSignature)return;const u=constructRequestPayload({contextValue:s,formValue:n,utmParams:UTMParamsExtractor.extractTrackingParams(this.context),referrer:window.location.href,triggeredBy:this.triggeredBy});u.ignoreTracking=!0,u.navigationData=this.latestForwardNavigationData,this.lastSentSignature=l,this.eventEmitter.emit(SysEventTypes.LEAD_PROGRESS,u)}catch(t){ErrorLogger.log(`NavigationLeadCollector.onNavigationEnd failed: ${(null==t?void 0:t.stack)||t}`)}}buildFormValue(){return this.form.getControlsAsArray().reduce((t,i)=>{const r=i.getValue();return hasMeaningfulValue(r)&&i.isValid()&&(t[i.getName()]=r),t},{})}}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@claspo/renderer",
|
|
3
|
-
"version": "18.8.0
|
|
3
|
+
"version": "18.8.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.4.0
|
|
18
|
+
"@claspo/common": "7.4.0",
|
|
19
19
|
"@testing-library/dom": "^10.4.0"
|
|
20
20
|
},
|
|
21
21
|
"devDependencies": {
|
|
@@ -44,6 +44,7 @@ export interface AsyncValidatorsMapI {
|
|
|
44
44
|
}
|
|
45
45
|
export default class WcControlledElement extends WcElement {
|
|
46
46
|
_createControl: (config?: CreateControlConfigI, ...restControlArgs: any[]) => FormControl;
|
|
47
|
+
_validateAutofilledValue: (control: FormControl) => void;
|
|
47
48
|
createControlWithValidation: (validators?: ValidatorFnT[], options?: ControlValidationOptionsI) => FormControl;
|
|
48
49
|
_prepareAsyncValidators: (validators?: ValidatorFnT[]) => AsyncValidatorsMapI;
|
|
49
50
|
_handleControlStatusChange: (params: ControlStatusHandlerParamsI) => void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var __rest=this&&this.__rest||function(t,e){var o={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(o[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var l=0;for(n=Object.getOwnPropertySymbols(t);l<n.length;l++)e.indexOf(n[l])<0&&Object.prototype.propertyIsEnumerable.call(t,n[l])&&(o[n[l]]=t[n[l]])}return o};import FormControlEvents from"../form/FormControlEvents";import{setInvalidStyle,setValidStyles,setPendingStyle}from"./FormUtils";import{getTranslation}from"./TranslationUtils";import WcElement from"./WcElement";import{REQUIRED_SYMBOL,required}from"./validators/required";function noop(){}export const ControlStatus={PENDING:"pending",VALID:"valid",INVALID:"invalid"};export default class WcControlledElement extends WcElement{constructor(){super(...arguments),this._createControl=(t={},...e)=>{const{element:o}=t,n=__rest(t,["element"]),l=this.getProps(),i=this.getModel(),a=Object.assign(Object.assign(Object.assign({},l.control),{componentId:i.id,viewIdx:i.path[0]}),n),r=this.services.form,
|
|
1
|
+
var __rest=this&&this.__rest||function(t,e){var o={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(o[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var l=0;for(n=Object.getOwnPropertySymbols(t);l<n.length;l++)e.indexOf(n[l])<0&&Object.prototype.propertyIsEnumerable.call(t,n[l])&&(o[n[l]]=t[n[l]])}return o};import FormControlEvents from"../form/FormControlEvents";import{setInvalidStyle,setValidStyles,setPendingStyle}from"./FormUtils";import{getTranslation}from"./TranslationUtils";import WcElement from"./WcElement";import{REQUIRED_SYMBOL,required}from"./validators/required";function noop(){}export const ControlStatus={PENDING:"pending",VALID:"valid",INVALID:"invalid"};export default class WcControlledElement extends WcElement{constructor(){super(...arguments),this._createControl=(t={},...e)=>{const{element:o}=t,n=__rest(t,["element"]),l=this.getProps(),i=this.getModel(),a=Object.assign(Object.assign(Object.assign({},l.control),{componentId:i.id,viewIdx:i.path[0]}),n),r=this.getAutofillValue();void 0!==r&&(a.defaultValue=r);const s=this.services.form,c=[a,o,...e],d=s.hasControl(l.control.name)?s.updateControl(...c):s.registerControl(...c);return void 0!==r&&d.getValue()===r&&this._validateAutofilledValue(d),d},this._validateAutofilledValue=t=>{t.validate({silent:!0}).then(e=>{e||t.markAsTouched(),this.syncAutofillContextRecord(e,t.getValue())})},this.createControlWithValidation=(t=[],e={})=>{const{element:o=this.getElement("input"),tooltipElement:n=this.getRootElement().querySelector(".input-tooltip"),validCallback:l=noop,invalidCallback:i=noop,pendingCallback:a=noop,elementToListen:r=o,validationMap:s={},listenStatusChange:c=!0}=e,d=__rest(e,["element","tooltipElement","validCallback","invalidCallback","pendingCallback","elementToListen","validationMap","listenStatusChange"]);if(n&&(n.style.visibility="hidden"),!t||!Array.isArray(t))throw new Error("Validators should be an array");const u=this.getProps().control.validation,h=(null==u?void 0:u.validator)?s[u.validator]:void 0,p=t.some(t=>t[REQUIRED_SYMBOL]),m=!!(null==u?void 0:u.required),v=m||p,C=[...t];m&&!p&&C.unshift(required()),h&&C.push(h);const g=this._prepareAsyncValidators(C),f=this._createControl({element:o,validation:{validator:"custom",required:v}},void 0,g);return c&&this._handleControlStatusChange(Object.assign({control:f,element:r,tooltipElement:n,configService:this.services.config,i18n:this.manifest.i18n,validCallback:l,invalidCallback:i,pendingCallback:a},d)),f},this._prepareAsyncValidators=(t=[])=>t.reduce((t,e,o)=>{if("function"!=typeof e)return console.warn(`Validator ${o} should be a function, so it will be skipped`),t;return t[`custom_${o}`]=async(...t)=>{const o=await Promise.resolve(e(...t));return"object"==typeof o&&"isValid"in o?Object.assign(Object.assign({},o),{errorKey:o.isValid?null:o.errorKey}):{isValid:!1,errorKey:"INVALID_VALIDATOR_RESPONSE"}},t},{}),this._handleControlStatusChange=t=>{t.control.on(FormControlEvents.validationStatusChanged,e=>{this._handleValidationStatus(t,e)}),t.control.on(FormControlEvents.touchedStatusChanged,()=>{let e=ControlStatus.PENDING;switch(!0){case t.control.pending:e=ControlStatus.PENDING;break;case t.control.valid:e=ControlStatus.VALID;break;default:e=ControlStatus.INVALID}this._handleValidationStatus(t,e)})},this._handleValidationStatus=(t,e)=>{const{control:o,element:n,tooltipElement:l,validCallback:i,invalidCallback:a,errorMessageMapper:r,pendingCallback:s}=t,c=this.services.config,d=this.manifest.i18n;switch(e){case ControlStatus.VALID:setValidStyles(n,l),i&&i();break;case ControlStatus.INVALID:if(o.touched){const t=o.getErrorKeys();if(!t)break;const e=t[0];let i=getTranslation(c,d,e);r&&(i=r(e,i)),setInvalidStyle(n,l,i,this.htmlDocumentObject),a&&a()}break;case ControlStatus.PENDING:o.touched&&(setPendingStyle(n,l),s&&s())}}}}
|
package/sdk/WcElement.d.ts
CHANGED
|
@@ -9,6 +9,7 @@ import { ObserversI } from "../wc-renderer/observers/createObservers";
|
|
|
9
9
|
import { SubscriptionsI } from "../wc-renderer/subscriptions/createSubscriptions";
|
|
10
10
|
import { ComponentManifestI } from '@claspo/common/component-manifest/ComponentManifest.interface';
|
|
11
11
|
import ConfigService from '../common/ConfigService';
|
|
12
|
+
import { AutofillI } from '@claspo/common/document/autofill.interface';
|
|
12
13
|
import { MergeTagsProcessorFactory } from './merge-tags/MergeTagsProcessorFactory';
|
|
13
14
|
import ContextSDK from './context/ContextSDK';
|
|
14
15
|
import FormGroup from '../form/FormGroup';
|
|
@@ -26,6 +27,7 @@ export interface ControlConfigI {
|
|
|
26
27
|
defaultValue?: string;
|
|
27
28
|
integrationName?: string;
|
|
28
29
|
validation?: ValidationConfigI;
|
|
30
|
+
autofill?: AutofillI;
|
|
29
31
|
[key: string]: any;
|
|
30
32
|
}
|
|
31
33
|
export interface ValidationConfigI {
|
|
@@ -82,6 +84,8 @@ export default class WcElement extends HTMLElement {
|
|
|
82
84
|
handlers: HandlerInstanceI[] | null;
|
|
83
85
|
htmlDocumentObject: Document;
|
|
84
86
|
skipGameBlur: boolean;
|
|
87
|
+
isAutofillValidated: boolean;
|
|
88
|
+
validatedAutofillValue: string | undefined;
|
|
85
89
|
static define: {
|
|
86
90
|
name: string;
|
|
87
91
|
model: string;
|
|
@@ -125,6 +129,9 @@ export default class WcElement extends HTMLElement {
|
|
|
125
129
|
static _resolveTogglableStylesForElementModel: (elementModel: ClBaseComponentElementParamsI) => ClBaseComponentElementParamsI;
|
|
126
130
|
static _resolveTogglableStyles: (styles: ClComponentStyleAttributesI) => ClComponentStyleAttributesI;
|
|
127
131
|
updateContext: () => void;
|
|
132
|
+
getAutofillValue: () => string | undefined;
|
|
133
|
+
getValidatedAutofillValue: () => string | undefined;
|
|
134
|
+
syncAutofillContextRecord: (isValid: boolean, value: string) => void;
|
|
128
135
|
addContextRecord: () => void;
|
|
129
136
|
getContextRecordLabel: (props: ClBaseComponentPropsI) => string | undefined;
|
|
130
137
|
capitalizeFirstLetter: (string: string) => string;
|
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{EditorToWidgetEventType}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";import{WidgetToEditorEventType}from"../renderer/WidgetToEditorEventType";class WcElement extends HTMLElement{constructor(){var e;super(),this.skipGameBlur=!0,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(`${EditorToWidgetEventType.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(`${EditorToWidgetEventType.COMPONENT_UPDATE}_${this.model.id}`,e=>{Object.assign(this.model,e)}),this.documentModel.on(EditorToWidgetEventType.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.subscriptions.push(this.services.eventEmitter.on(WidgetToEditorEventType.GAME_PHASE_READY_TO_PLAY,()=>{this.skipGameBlur||this.getHostElement().classList.add("cl-game-spotlight-component")})),this.subscriptions.push(this.services.eventEmitter.on(WidgetToEditorEventType.GAME_PHASE_COMPLETED,()=>{this.skipGameBlur||this.getHostElement().classList.remove("cl-game-spotlight-component")}))},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 1===(null==e?void 0:e.split(",").length)?this.parentNode:recursiveFindParentNodeByAttribute(this.parentNode,applySysAttrPrefix("path"),void 0,e=>1===(null==e?void 0: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.constructor.define)||void 0===e?void 0:e.manifest)}connectedCallback(){this.construct(),this.registerComponentResourceManagement(),Promise.resolve().then(()=>{this.attachHandlers()});const e=document.createElement("style");e.textContent='\n :host(.cl-game-spotlight-component)::after {\n content: "";\n position: absolute;\n background-size: 100% 100%;\n background-repeat: no-repeat;\n overflow: visible;\n \n backdrop-filter: blur(4px);\n \n inset: -30px;\n mask-image: \n linear-gradient(to bottom, transparent, grey 30px, grey calc(100% - 30px), transparent),\n linear-gradient(to right, transparent, grey 30px, grey calc(100% - 30px), transparent);\n mask-composite: intersect;\n -webkit-mask-composite: source-in; /* for Chrome/Safari */\n \n transition: opacity 0.35s ease;\n pointer-events: auto;\n }\n ',this.getRootElement().prepend(e)}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
|
+
import HandlerFactory from"../handler/HandlerFactory";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import addEventListenerToElement from"@claspo/common/utils/addEventListener";import DefaultState from"../common/DefaultState";import{EditorToWidgetEventType}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";import InputFieldsAutofillHydrator from"./autofill/InputFieldsAutofillHydrator";import{WidgetToEditorEventType}from"../renderer/WidgetToEditorEventType";class WcElement extends HTMLElement{constructor(){var e;super(),this.skipGameBlur=!0,this.isAutofillValidated=!1,this.validatedAutofillValue=void 0,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 i;o&&(i=o.getAttribute(applySysAttrPrefix("widget-id")));let r=new PayloadEvent("cl-props-request",{nodeName:this.nodeName,path:this.getAttribute(applySysAttrPrefix("path")),id:t,widgetId:i},{bubbles:!0,composed:!0});this.dispatchEvent(r),e=r.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(`${EditorToWidgetEventType.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(`${EditorToWidgetEventType.COMPONENT_UPDATE}_${this.model.id}`,e=>{Object.assign(this.model,e)}),this.documentModel.on(EditorToWidgetEventType.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.subscriptions.push(this.services.eventEmitter.on(WidgetToEditorEventType.GAME_PHASE_READY_TO_PLAY,()=>{this.skipGameBlur||this.getHostElement().classList.add("cl-game-spotlight-component")})),this.subscriptions.push(this.services.eventEmitter.on(WidgetToEditorEventType.GAME_PHASE_COMPLETED,()=>{this.skipGameBlur||this.getHostElement().classList.remove("cl-game-spotlight-component")}))},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),i=applySysAttrPrefix("type"),r="element-styles";let n=this.getRootElement().querySelector(`style[${i}="${r}"]`);n||(n=document.createElement("style"),n.setAttribute(i,r),this.getRootElement().appendChild(n)),insertHtmlIntoElement({element:n,html:""}),s.forEach(e=>{let t=e.getAttribute(applySysAttrPrefix("element"));const s=this.getEnvironment();let i=getAdaptiveStylesForPlatform(o,s,t);if(i){if(this.resizeListener.isMobile()){const e=getAdaptiveStylesForPlatform(o,"desktop",t);e&&(i=Object.assign(Object.assign({},i),{styleAttributes:Object.assign(Object.assign({},e.styleAttributes),i.styleAttributes)}))}this.applyStylesToElement(e,this.applySharedClassesToElementModel(i),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,i;const r=[];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===(i=this.model.props.backgroundDynamicInlineSVGElements)||void 0===i?void 0:i.mobile))&&(this.colorSchemaListener.apply(this.getEnvironment()),r.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,r)});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(),i=`flip-up-animation-${t.element}`;let r=this.getRootElement().querySelector(`#${i}`);r||(r=document.createElement("style"),r.id=i,e.appendChild(r)),insertHtmlIntoElement({element:r,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="",i)=>{const r=Object.keys(s).reduce((e,t)=>e+` ${CaseTransformer.camelCaseToDashCase(t)}: ${s[t]}${i?" !important;":";"}`,"");insertHtmlIntoElement({element:e,html:`[${applySysAttrPrefix("element")}="${t}"]${o} { ${r} }`,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,i,r;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===(i=t.linkParams)||void 0===i?void 0:i.color}}`,appendHtml:!0}),(null===(r=t.linkParams)||void 0===r?void 0:r.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 1===(null==e?void 0:e.split(",").length)?this.parentNode:recursiveFindParentNodeByAttribute(this.parentNode,applySysAttrPrefix("path"),void 0,e=>1===(null==e?void 0: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.getAutofillValue=()=>{var e;const t=this.getModel();return new InputFieldsAutofillHydrator(this.services.config,this.services.context.getRegistry()).resolveValue(null===(e=t.props.control)||void 0===e?void 0:e.autofill,t.id)},this.getValidatedAutofillValue=()=>this.isAutofillValidated?this.validatedAutofillValue:void 0,this.syncAutofillContextRecord=(e,t)=>{this.isAutofillValidated=!0,this.validatedAutofillValue=e?t:void 0,e&&this.services.context.updateRecord(this.getModel().id,{value:t})},this.addContextRecord=()=>{var e,t;const s=this.getModel();this.services.context.addRecord(s.id,{recordKey:s.id,id:s.props.control.name,label:this.getContextRecordLabel(s.props),value:null!==(e=this.getValidatedAutofillValue())&&void 0!==e?e:s.props.control.defaultValue||"",viewIndex:null===(t=s.path)||void 0===t?void 0:t[0],sourceId:"FORM",initialData:{fallbackValue:"",exampleValue:this.getContextRecordExampleValue(s.props)}})},this.getContextRecordLabel=e=>{var t,s,o,i,r,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===(i=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===i?void 0:i.enabled)){const t=(new DOMParser).parseFromString(e.content.label,"text/html");return this.capitalizeFirstLetter(t.body.textContent||"")}return(null===(r=e.content)||void 0===r?void 0:r.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.constructor.define)||void 0===e?void 0:e.manifest)}connectedCallback(){this.construct(),this.registerComponentResourceManagement(),Promise.resolve().then(()=>{this.attachHandlers()});const e=document.createElement("style");e.textContent='\n :host(.cl-game-spotlight-component)::after {\n content: "";\n position: absolute;\n background-size: 100% 100%;\n background-repeat: no-repeat;\n overflow: visible;\n \n backdrop-filter: blur(4px);\n \n inset: -30px;\n mask-image: \n linear-gradient(to bottom, transparent, grey 30px, grey calc(100% - 30px), transparent),\n linear-gradient(to right, transparent, grey 30px, grey calc(100% - 30px), transparent);\n mask-composite: intersect;\n -webkit-mask-composite: source-in; /* for Chrome/Safari */\n \n transition: opacity 0.35s ease;\n pointer-events: auto;\n }\n ',this.getRootElement().prepend(e)}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;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { AutofillI } from '@claspo/common/document/autofill.interface';
|
|
2
|
+
import ConfigService from '../../common/ConfigService';
|
|
3
|
+
import SourceRegistry from '../source/SourceRegistry';
|
|
4
|
+
export default class InputFieldsAutofillHydrator {
|
|
5
|
+
configService: ConfigService;
|
|
6
|
+
registry: SourceRegistry;
|
|
7
|
+
constructor(configService: ConfigService, registry: SourceRegistry);
|
|
8
|
+
resolveValue(autofill: AutofillI | undefined, key: string): string | undefined;
|
|
9
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{RenderMode}from"@claspo/common/RenderMode";import{resolveSourceValue}from"../source/resolveSourceValue";export default class InputFieldsAutofillHydrator{constructor(e,r){this.configService=e,this.registry=r}resolveValue(e,r){if(!(null==e?void 0:e.enabled)||!e.sourceType||this.configService.getConfig("renderMode")===RenderMode.UPDATING)return;const o=resolveSourceValue(this.registry,e.sourceType,e.config,r);if(void 0===o)return;const i=o.trim();return""===i?void 0:i}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{resolveSourceValue}from"../source/resolveSourceValue";export default class HiddenFieldsContextHydrator{constructor(e,d=[]){this.context=e,this.hiddenFields=d||[]}hydrate(e=this.hiddenFields){this.hiddenFields=e||[],this.hiddenFields.forEach(e=>{const d=this.resolveFieldValue(e);void 0!==d&&this.context.addRecord(e.id,{recordKey:e.id,id:e.name,label:e.label,value:d})})}resolveFieldValue(e){if((null==e?void 0:e.name)&&e.sourceType)return resolveSourceValue(this.context.getRegistry(),e.sourceType,e.config,e.id)}}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { SourceArgumentsConfigI, SourceType, StaticSourceConfigI } from '@claspo/common/document/source.interface';
|
|
2
|
+
import SourceRegistry from './SourceRegistry';
|
|
3
|
+
export declare function normalizeSourceValue(value: any): string | undefined;
|
|
4
|
+
export declare function resolveSourceValue(registry: SourceRegistry, sourceType: SourceType, config: StaticSourceConfigI | SourceArgumentsConfigI, key: string): string | undefined;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SourceType}from"@claspo/common/document/source.interface";export function normalizeSourceValue(e){if(null!=e&&""!==e)return"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):String(e)}export function resolveSourceValue(e,o,r,u){if(!o)return;if(o===SourceType.STATIC)return normalizeSourceValue(null==r?void 0:r.value);const n=e.getSource(o);if(!n)return;const t=n.getValue(u);return normalizeSourceValue("function"==typeof(null==t?void 0:t.processor)?t.processor(n,Object.assign({id:u},r)):null==t?void 0:t.value)}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import DefaultEventEmitter from "@claspo/common/DefaultEventEmitter";
|
|
2
2
|
import { SourceUpdateDataI } from '../../context/ContextSDK';
|
|
3
|
-
import { SourceType } from "@claspo/common/document/
|
|
3
|
+
import { SourceType } from "@claspo/common/document/source.interface";
|
|
4
4
|
declare global {
|
|
5
5
|
interface Window {
|
|
6
6
|
[key: string]: any;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{SourceType}from"@claspo/common/document/
|
|
1
|
+
import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{SourceType}from"@claspo/common/document/source.interface";import resolveVariableValue from"./resolveVariableValue";class JSApiVariablesSource extends DefaultEventEmitter{constructor(e={}){super(),this.instanceName=e.instanceName}get appInstance(){return window[this.instanceName]}get variables(){var e;return(null===(e=this.appInstance)||void 0===e?void 0:e.variables)||{}}subscribe(e){this.on("CHANGE",({values:r})=>{for(let a in r)e({key:a,value:r[a]})})}getValue(e){return e?{processor:(e,r)=>JSApiVariablesSource.processModel(r,this.instanceName)}:{}}addValues(e){if(!this.appInstance)throw new Error("Instatiate first");if(!e||"object"!=typeof e)throw new Error("Values should be object");Object.keys(e).length&&(this.appInstance.variables=Object.assign(Object.assign({},this.variables),e),this.emit("CHANGE",{values:e}))}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{const e=resolveVariableValue(window[r].variables,t.value);return null==e?"":e}catch(r){return console.error("JSApiVariablesSource: error while getting variable. Model: ",e,"Error: ",r),""}}}JSApiVariablesSource.sourceId=SourceType.JS_API_VARIABLE;export default JSApiVariablesSource;
|