@claspo/renderer 18.1.2 → 18.3.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.
Files changed (39) hide show
  1. package/CompositionRoot.d.ts +1 -1
  2. package/CompositionRoot.js +1 -1
  3. package/StaticEntryModule.js +1 -1
  4. package/UpdatingEntryModule.js +1 -1
  5. package/ViewRouter.d.ts +1 -0
  6. package/ViewRouter.js +1 -1
  7. package/action/UTMParamsExtractor.d.ts +4 -1
  8. package/action/UTMParamsExtractor.js +1 -1
  9. package/action/actions/BaseRequestAction.d.ts +0 -1
  10. package/action/actions/BaseRequestAction.js +1 -1
  11. package/common/ConfigService.js +1 -1
  12. package/common/SysEventTypes.d.ts +1 -3
  13. package/common/SysEventTypes.js +1 -1
  14. package/document-model/DocumentModelService.d.ts +3 -1
  15. package/document-model/DocumentModelService.js +1 -1
  16. package/document-model/DocumentService.js +1 -1
  17. package/package.json +2 -2
  18. package/renderer/DragEventListener.js +1 -1
  19. package/renderer/{ViewRendererActionType.d.ts → WidgetToEditorEventType.d.ts} +2 -3
  20. package/renderer/WidgetToEditorEventType.js +1 -0
  21. package/renderer/style/ClDocumentResizeListener.js +1 -1
  22. package/renderer/style/ColorSchemaListener.js +1 -1
  23. package/renderer/style/DefaultMediaQueryListener.js +1 -1
  24. package/renderer/style/MobileDeviceOrientationListener.js +1 -1
  25. package/resource-management/ViewResourcesManager.js +1 -1
  26. package/sdk/WcElement.js +1 -1
  27. package/sdk/source/Source.d.ts +2 -0
  28. package/sdk/source/Source.js +1 -1
  29. package/sdk/source/sources/UrlQueryParamsSource.d.ts +1 -0
  30. package/sdk/source/sources/UrlQueryParamsSource.js +1 -1
  31. package/sdk.d.ts +3 -3
  32. package/sdk.js +1 -1
  33. package/wc-renderer/WcResolver.d.ts +0 -1
  34. package/wc-renderer/WcResolver.js +1 -1
  35. package/wc-renderer/WcViewRenderer.js +1 -1
  36. package/wc-renderer/decorators/wcUpdatingDecorator.js +1 -1
  37. package/renderer/ViewRendererActionType.js +0 -1
  38. package/submit-state/SubmitStateService.d.ts +0 -29
  39. package/submit-state/SubmitStateService.js +0 -1
@@ -1,5 +1,5 @@
1
1
  export default class CompositionRoot {
2
2
  services: any;
3
- constructor(json: any, config: any, trackingService: any, containerElement: any, componentCommonStyles: any, layoutType: any, renderMode: any, componentRegister: any, htmlDocumentObject: any, componentResolver: any);
3
+ constructor(json: any, config: any, trackingService: any, containerElement: any, componentCommonStyles: any, layoutType: any, renderMode: any, componentRegister: any, htmlDocumentObject: any);
4
4
  destroy(): void;
5
5
  }
@@ -1 +1 @@
1
- import DefaultState from"./common/DefaultState";import FormGroup from"./form/FormGroup";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import DocumentModelService from"./document-model/DocumentModelService";import ConfigService from"./common/ConfigService";import ClDocumentResizeListener from"./renderer/style/ClDocumentResizeListener";import MobileDeviceOrientationListener from"./renderer/style/MobileDeviceOrientationListener";import DefaultMediaQueryListener from"./renderer/style/DefaultMediaQueryListener";import DocumentService from"./document-model/DocumentService";import CommonStylesService from"./renderer/style/CommonStylesService";import WcFactory from"./wc-renderer/WcFactory";import WcViewRenderer from"./wc-renderer/WcViewRenderer";import ActionFactory from"./action/ActionFactory";import PrizePoolFactory from"./prize-pool/PrizePoolFactory";import httpClient from"@claspo/common/network/HttpClient";import{ActionRegister}from"./action/ActionRegister";import ContextSDK from"./sdk/context/ContextSDK";import{MergeTagsProcessorFactory}from"./sdk/merge-tags/MergeTagsProcessorFactory";import SourceRegistry from"./sdk/source/SourceRegistry";import ContextData from"./sdk/context/ContextData";import SubmitStateService from"./submit-state/SubmitStateService";export default class CompositionRoot{constructor(e,t,r,o,i,n,c,m,s,a){var l;const u=new DocumentModelService(e),y=!o,f=y?new DefaultMediaQueryListener(u,t):new ClDocumentResizeListener(u,o),S=new DefaultState,v=new ConfigService(t),p=new MobileDeviceOrientationListener(u,v),d=new CommonStylesService;d.setStyles(i);const D=new DefaultEventEmitter,g=new FormGroup(r),w=new SubmitStateService(g,D,a),F=new SourceRegistry(g,t),C=new ContextData,R=new ContextSDK(F,C,y),M=new(null!==(l=t.actionFactoryClass)&&void 0!==l?l:ActionFactory)(D,g,v,r,S,R,()=>this.services),L=new ActionRegister(D,()=>this.services),P=new PrizePoolFactory(httpClient,v),b=new MergeTagsProcessorFactory(y,R,v),h=new WcFactory({state:S,eventEmitter:D,form:g,documentModel:u,resizeListener:f,config:v,commonStylesService:d,trackingService:r,layoutType:n,actionFactory:M,actionRegister:L,prizePoolFactory:P,context:R,mergeTagsProcessorFactory:b,mobileDeviceOrientationListener:p,componentRegister:m,htmlDocumentObject:s}),x=new WcViewRenderer(u,f,t,h,D),z=new DocumentService(u,x,c);this.services={documentService:z,documentModel:u,state:S,form:g,eventEmitter:D,config:v,resizeListener:f,mobileDeviceOrientationListener:p,componentFactory:h,viewRenderer:x,commonStylesService:d,tracking:r,actionFactory:M,actionRegister:L,submitState:w,prizePoolFactory:P,context:R,mergeTagsProcessorFactory:b}}destroy(){Object.keys(this.services).filter(e=>"viewRenderer"!==e).forEach(e=>this.services[e]&&this.services[e].destroy&&this.services[e].destroy())}}
1
+ import DefaultState from"./common/DefaultState";import FormGroup from"./form/FormGroup";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import DocumentModelService from"./document-model/DocumentModelService";import ConfigService from"./common/ConfigService";import ClDocumentResizeListener from"./renderer/style/ClDocumentResizeListener";import MobileDeviceOrientationListener from"./renderer/style/MobileDeviceOrientationListener";import DefaultMediaQueryListener from"./renderer/style/DefaultMediaQueryListener";import DocumentService from"./document-model/DocumentService";import CommonStylesService from"./renderer/style/CommonStylesService";import WcFactory from"./wc-renderer/WcFactory";import WcViewRenderer from"./wc-renderer/WcViewRenderer";import ActionFactory from"./action/ActionFactory";import PrizePoolFactory from"./prize-pool/PrizePoolFactory";import httpClient from"@claspo/common/network/HttpClient";import{ActionRegister}from"./action/ActionRegister";import ContextSDK from"./sdk/context/ContextSDK";import{MergeTagsProcessorFactory}from"./sdk/merge-tags/MergeTagsProcessorFactory";import SourceRegistry from"./sdk/source/SourceRegistry";import ContextData from"./sdk/context/ContextData";export default class CompositionRoot{constructor(e,t,o,r,i,n,c,s,m){var a;const l=new DocumentModelService(e),y=!r,f=y?new DefaultMediaQueryListener(l,t):new ClDocumentResizeListener(l,r),u=new DefaultState,p=new ConfigService(t),v=new MobileDeviceOrientationListener(l,p),d=new CommonStylesService;d.setStyles(i);const S=new DefaultEventEmitter,D=new FormGroup(o),g=new SourceRegistry(D,t),w=new ContextData,F=new ContextSDK(g,w,y),C=new(null!==(a=t.actionFactoryClass)&&void 0!==a?a:ActionFactory)(S,D,p,o,u,F,()=>this.services),R=new ActionRegister(S,()=>this.services),M=new PrizePoolFactory(httpClient,p),L=new MergeTagsProcessorFactory(y,F,p),P=new WcFactory({state:u,eventEmitter:S,form:D,documentModel:l,resizeListener:f,config:p,commonStylesService:d,trackingService:o,layoutType:n,actionFactory:C,actionRegister:R,prizePoolFactory:M,context:F,mergeTagsProcessorFactory:L,mobileDeviceOrientationListener:v,componentRegister:s,htmlDocumentObject:m}),h=new WcViewRenderer(l,f,t,P,S),x=new DocumentService(l,h,c);this.services={documentService:x,documentModel:l,state:u,form:D,eventEmitter:S,config:p,resizeListener:f,mobileDeviceOrientationListener:v,componentFactory:P,viewRenderer:h,commonStylesService:d,tracking:o,actionFactory:C,actionRegister:R,prizePoolFactory:M,context:F,mergeTagsProcessorFactory:L}}destroy(){Object.keys(this.services).filter(e=>"viewRenderer"!==e).forEach(e=>this.services[e]&&this.services[e].destroy&&this.services[e].destroy())}}
@@ -1 +1 @@
1
- import CompositionRoot from"./CompositionRoot";import ViewRouter from"./ViewRouter";import TranslateUtils from"./i18n/TranslateUtils";import{DocumentModelUpdateType}from"./document-model/DocumentModelService";import CssVarsOperations from"@claspo/common/element/CssVarsOperations";import wcStaticDecorator from"./wc-renderer/decorators/wcStaticDecorator";import{RenderMode}from"@claspo/common/RenderMode";export default class StaticEntryModule{constructor(e,t,o,i,s,r,n){this.renderMode=RenderMode.STATIC,this.componentResolver=t,this.componentRegister=o,this.config=Object.assign(Object.assign({},i),{renderMode:this.renderMode}),this.documentJson=e,this.translations=s,this.compositionRoot=null,this.viewRenderer=null,this.viewRouter=null,this.trackingService=r||{send:()=>{},trackClick:()=>{},trackTargetAction:()=>{}},this.layoutType=n,this.componentFactory=null,o.register(wcStaticDecorator,this.renderMode)}init(e){const t=e||document;this.documentJson=TranslateUtils.applyTranslationObjectToComponentsIfNeeded(JSON.parse(JSON.stringify(this.documentJson)),this.componentResolver.getComponentManifests(),this.translations);const o=new CompositionRoot(this.documentJson,this.config,this.trackingService,null,"",this.layoutType,this.renderMode,this.componentRegister,t,this.componentResolver),i=new ViewRouter(o.services.eventEmitter,o.services.documentModel,o.services.viewRenderer,this.config&&this.config.optionalDocumentStyles,o.services);return o.services.viewRouter=i,this.compositionRoot=o,this.viewRenderer=o.services.viewRenderer,this.componentFactory=o.services.componentFactory,this.viewRouter=i,i.start(this.config.viewIndex)}destroy(){var e,t;null===(e=this.viewRouter)||void 0===e||e.destroy(),null===(t=this.compositionRoot)||void 0===t||t.destroy()}performAction(e,t){const o=this.compositionRoot.services.documentService.handleModelUpdate(e,t);switch(e){case DocumentModelUpdateType.COLOR_SCHEMA_UPDATE:{const e=this.compositionRoot.services.documentModel.getShared().cssVars;CssVarsOperations.override(e,this.viewRouter.getDocumentContainer());break}}return o}listenAction(e,t){this.compositionRoot.services.eventEmitter.on(e,(e,o)=>{t(e,o)})}}
1
+ import CompositionRoot from"./CompositionRoot";import ViewRouter from"./ViewRouter";import TranslateUtils from"./i18n/TranslateUtils";import{EditorToWidgetEventType}from"./document-model/DocumentModelService";import CssVarsOperations from"@claspo/common/element/CssVarsOperations";import wcStaticDecorator from"./wc-renderer/decorators/wcStaticDecorator";import{RenderMode}from"@claspo/common/RenderMode";export default class StaticEntryModule{constructor(e,t,o,i,s,r,n){this.renderMode=RenderMode.STATIC,this.componentResolver=t,this.componentRegister=o,this.config=Object.assign(Object.assign({},i),{renderMode:this.renderMode}),this.documentJson=e,this.translations=s,this.compositionRoot=null,this.viewRenderer=null,this.viewRouter=null,this.trackingService=r||{send:()=>{},trackClick:()=>{},trackTargetAction:()=>{}},this.layoutType=n,this.componentFactory=null,o.register(wcStaticDecorator,this.renderMode)}init(e){const t=e||document;this.documentJson=TranslateUtils.applyTranslationObjectToComponentsIfNeeded(JSON.parse(JSON.stringify(this.documentJson)),this.componentResolver.getComponentManifests(),this.translations);const o=new CompositionRoot(this.documentJson,this.config,this.trackingService,null,"",this.layoutType,this.renderMode,this.componentRegister,t),i=new ViewRouter(o.services.eventEmitter,o.services.documentModel,o.services.viewRenderer,this.config&&this.config.optionalDocumentStyles,o.services);return o.services.viewRouter=i,this.compositionRoot=o,this.viewRenderer=o.services.viewRenderer,this.componentFactory=o.services.componentFactory,this.viewRouter=i,i.start(this.config.viewIndex)}destroy(){var e,t;null===(e=this.viewRouter)||void 0===e||e.destroy(),null===(t=this.compositionRoot)||void 0===t||t.destroy()}performAction(e,t){const o=this.compositionRoot.services.documentService.handleModelUpdate(e,t);switch(e){case EditorToWidgetEventType.COLOR_SCHEMA_UPDATE:{const e=this.compositionRoot.services.documentModel.getShared().cssVars;CssVarsOperations.override(e,this.viewRouter.getDocumentContainer());break}}return o}listenAction(e,t){this.compositionRoot.services.eventEmitter.on(e,(e,o)=>{t(e,o)})}}
@@ -1 +1 @@
1
- import CompositionRoot from"./CompositionRoot";import{DocumentModelUpdateType}from"./document-model/DocumentModelService";import DocumentUtils from"@claspo/common/document/DocumentUtils";import DragEventListener from"./renderer/DragEventListener";import{RenderMode}from"@claspo/common/RenderMode";import{asyncActionEmitter}from"./action/asyncAction";import CssVarsOperations from"@claspo/common/element/CssVarsOperations";export default class UpdatingEntryModule{constructor(e,o,t,i,s={},n){this.renderMode=RenderMode.UPDATING,this.documentJson=JSON.parse(JSON.stringify(e)),this.componentResolver=o,this.componentRegister=t,this.componentCommonStyles=i,this.config=Object.assign(Object.assign({},s),{renderMode:this.renderMode}),this.compositionRoot=null,this.viewRenderer=null,this.viewComponents=[],this.layoutType=n}init(e){const o=new CompositionRoot(this.documentJson,this.config,{send:()=>{}},e,this.componentCommonStyles,this.layoutType,this.renderMode,this.componentRegister,document,this.componentResolver);return this.compositionRoot=o,this.viewRenderer=o.services.viewRenderer,this.componentFactory=o.services.componentFactory,this.containerElement=e,this.dragEventListener=new DragEventListener(this.compositionRoot.services.eventEmitter,this.compositionRoot.services.documentModel),this.viewComponents=this.compositionRoot.services.documentModel.getViews().map((e,o)=>this.viewRenderer.render(e,o,this.config.renderMode)),this.viewComponents}destroy(){var e,o;this.viewComponents.forEach(e=>e.remove()),null===(e=this.dragEventListener)||void 0===e||e.destroy(),null===(o=this.compositionRoot)||void 0===o||o.destroy()}performAction(e,o){switch(e){case DocumentModelUpdateType.COMPONENT_REMOVE:case DocumentModelUpdateType.COMPONENT_MOVE:case DocumentModelUpdateType.COMPONENT_INSERT:case DocumentModelUpdateType.COMPONENT_PROPS_UPDATE:case DocumentModelUpdateType.COMPONENT_UPDATE:case DocumentModelUpdateType.MOBILE_BREAKPOINT_UPDATE:case DocumentModelUpdateType.ENVIRONMENT_UPDATE:case DocumentModelUpdateType.TEXT_CLASS_ADDED:case DocumentModelUpdateType.TEXT_CLASS_UPDATED:case DocumentModelUpdateType.TEXT_CLASS_REMOVED:case DocumentModelUpdateType.HEADER_FONT_FAMILY_UPDATE:case DocumentModelUpdateType.TEXT_FONT_FAMILY_UPDATE:case DocumentModelUpdateType.SHARED_UPDATE:return asyncActionEmitter(this.compositionRoot.services.eventEmitter.emit.bind(this.compositionRoot.services.eventEmitter))(this.compositionRoot.services.documentService.handleModelUpdate.bind(this.compositionRoot.services.documentService),e)(e,o);case DocumentModelUpdateType.COLOR_SCHEMA_UPDATE:{const e=this.compositionRoot.services.documentModel.getShared().cssVars;this.viewComponents.forEach(o=>{CssVarsOperations.override(e,o)});break}case DocumentModelUpdateType.THEME_UPDATE:return asyncActionEmitter(this.compositionRoot.services.eventEmitter.emit.bind(this.compositionRoot.services.eventEmitter))(this.compositionRoot.services.documentService.handleModelUpdate.bind(this.compositionRoot.services.documentService),e)(e,o);default:this.compositionRoot.services.eventEmitter.emit(e,o)}}listenAction(e,o){this.compositionRoot.services.eventEmitter.on(e,(e,t)=>{o(e,t)})}getHostElementById(e){const o=DocumentUtils.getNodeById(this.viewComponents.map(e=>e.getModel()),e);return o&&o.componentRef}getHostElementByPath(e){const o=DocumentUtils.getNodeByPath(this.viewComponents.map(e=>e.getModel()),e);return o&&o.componentRef}getContextRecordsMap(){var e;return(null===(e=this.compositionRoot)||void 0===e?void 0:e.services.context.getRecordsMap())||{}}listenContextAction(e,o){this.compositionRoot.services.context.on(e,(e,t)=>{o(e,t)})}}
1
+ import CompositionRoot from"./CompositionRoot";import{EditorToWidgetEventType}from"./document-model/DocumentModelService";import DocumentUtils from"@claspo/common/document/DocumentUtils";import DragEventListener from"./renderer/DragEventListener";import{RenderMode}from"@claspo/common/RenderMode";import{asyncActionEmitter}from"./action/asyncAction";import CssVarsOperations from"@claspo/common/element/CssVarsOperations";export default class UpdatingEntryModule{constructor(e,t,o,i,s={},n){this.renderMode=RenderMode.UPDATING,this.documentJson=JSON.parse(JSON.stringify(e)),this.componentResolver=t,this.componentRegister=o,this.componentCommonStyles=i,this.config=Object.assign(Object.assign({},s),{renderMode:this.renderMode}),this.compositionRoot=null,this.viewRenderer=null,this.viewComponents=[],this.layoutType=n}init(e){const t=new CompositionRoot(this.documentJson,this.config,{send:()=>{}},e,this.componentCommonStyles,this.layoutType,this.renderMode,this.componentRegister,document);return this.compositionRoot=t,this.viewRenderer=t.services.viewRenderer,this.componentFactory=t.services.componentFactory,this.containerElement=e,this.dragEventListener=new DragEventListener(this.compositionRoot.services.eventEmitter,this.compositionRoot.services.documentModel),this.viewComponents=this.compositionRoot.services.documentModel.getViews().map((e,t)=>this.viewRenderer.render(e,t,this.config.renderMode)),this.viewComponents}destroy(){var e,t;this.viewComponents.forEach(e=>e.remove()),null===(e=this.dragEventListener)||void 0===e||e.destroy(),null===(t=this.compositionRoot)||void 0===t||t.destroy()}performAction(e,t){switch(e){case EditorToWidgetEventType.COMPONENT_REMOVE:case EditorToWidgetEventType.COMPONENT_MOVE:case EditorToWidgetEventType.COMPONENT_INSERT:case EditorToWidgetEventType.COMPONENT_PROPS_UPDATE:case EditorToWidgetEventType.COMPONENT_UPDATE:case EditorToWidgetEventType.MOBILE_BREAKPOINT_UPDATE:case EditorToWidgetEventType.ENVIRONMENT_UPDATE:case EditorToWidgetEventType.TEXT_CLASS_ADDED:case EditorToWidgetEventType.TEXT_CLASS_UPDATED:case EditorToWidgetEventType.TEXT_CLASS_REMOVED:case EditorToWidgetEventType.HEADER_FONT_FAMILY_UPDATE:case EditorToWidgetEventType.TEXT_FONT_FAMILY_UPDATE:case EditorToWidgetEventType.SHARED_UPDATE:return asyncActionEmitter(this.compositionRoot.services.eventEmitter.emit.bind(this.compositionRoot.services.eventEmitter))(this.compositionRoot.services.documentService.handleModelUpdate.bind(this.compositionRoot.services.documentService),e)(e,t);case EditorToWidgetEventType.COLOR_SCHEMA_UPDATE:{const e=this.compositionRoot.services.documentModel.getShared().cssVars;this.viewComponents.forEach(t=>{CssVarsOperations.override(e,t)});break}case EditorToWidgetEventType.THEME_UPDATE:return asyncActionEmitter(this.compositionRoot.services.eventEmitter.emit.bind(this.compositionRoot.services.eventEmitter))(this.compositionRoot.services.documentService.handleModelUpdate.bind(this.compositionRoot.services.documentService),e)(e,t);default:this.compositionRoot.services.eventEmitter.emit(e,t)}}listenAction(e,t){this.compositionRoot.services.eventEmitter.on(e,(e,o)=>{t(e,o)})}getHostElementById(e){const t=DocumentUtils.getNodeById(this.viewComponents.map(e=>e.getModel()),e);return t&&t.componentRef}getHostElementByPath(e){const t=DocumentUtils.getNodeByPath(this.viewComponents.map(e=>e.getModel()),e);return t&&t.componentRef}getContextRecordsMap(){var e;return(null===(e=this.compositionRoot)||void 0===e?void 0:e.services.context.getRecordsMap())||{}}listenContextAction(e,t){this.compositionRoot.services.context.on(e,(e,o)=>{t(e,o)})}}
package/ViewRouter.d.ts CHANGED
@@ -9,6 +9,7 @@ export default class ViewRouter extends DefaultEventEmitter {
9
9
  currentViewComponentRef: any;
10
10
  transitions: any;
11
11
  documentContainer: any;
12
+ contactDataSubmitted: any;
12
13
  constructor(eventEmitter: any, documentModel: any, viewRenderer: any, optionalDocumentStyles: any, services: any);
13
14
  getCurrentViewIndex(): any;
14
15
  start(viewIndex: any): 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";import systemResultStateNames from"./document-model/systemResultStateNames";export default class ViewRouter extends DefaultEventEmitter{constructor(t,e,i,n,s){super(),this.eventEmitter=t,this.documentModel=e,this.viewRenderer=i,this.optionalDocumentStyles=n,this.services=s,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,i)=>{const n="number"==typeof t?t:this.documentModel.getModel().views.findIndex(e=>e.id===t);-1===n?this.eventEmitter.emit("WIDGET_NAVIGATION_STATE_NOT_FOUND",{viewPointer:t}):this.navigate(n,i,n<this.currentViewIndex?this._previousViewDestroyedCb.bind(this):()=>{})}),this.eventEmitter.on(SysActionTypes.GO_TO_PREVIOUS_VIEW,()=>{this.getCurrentViewIndex()<=0||this.navigate(this.getCurrentViewIndex()-1,{},this._previousViewDestroyedCb.bind(this))}),this.eventEmitter.on(SysActionTypes.GO_TO_NEXT_VIEW,()=>{this.documentModel.getModel().views[this.getCurrentViewIndex()+1]&&this.navigate(this.getCurrentViewIndex()+1)}),this.documentContainer}destroy(){this.viewDestroy(),this.documentContainer&&this.documentContainer.remove()}navigate(t,e={},i=()=>{}){var n;let s=this.documentModel.getView(t);const r=this.currentViewIndex;if(this.currentViewIndex===t)return;if(!s)throw this.eventEmitter.emit("WIDGET_NAVIGATION_STATE_NOT_FOUND",{navigateTo:t}),new Error("View was not found by index: "+t);setTimeout(()=>{var t;const e=systemResultStateNames.includes(s.label),i=null===(t=this.services.submitState)||void 0===t?void 0:t.hasSubmitAttemptSinceLastChange(),n=this.services.form.getControlsAsArray().length>0;e&&n&&!i&&(this.eventEmitter.emit("WIDGET_NAVIGATION_STATE_NOT_FOUND",{toSystemStateWithoutSubmitFromIndex:r,ctx:this.services.context.getKVMap()}),this.services.actionFactory.get({type:SysActionTypes.REQUEST}).execute(void 0,void 0,!0,{skipValidation:!0}))},300);const o=this.viewRenderer.render(s,t);this.viewDestroy(),i(),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}),this.eventEmitter.emit(SysRouterEvent.NAVIGATION_END,t)}viewDestroy(){this.currentViewComponentRef&&this.viewRenderer.destroy(this.currentViewComponentRef)}getDocumentContainer(){return this.documentContainer}getLastTransition(){return this.transitions[this.transitions.length-1]}_previousViewDestroyedCb(){this.services.form.getControlsAsArray().forEach(t=>{t.viewIdx===this.currentViewIndex&&this.services.form.removeControl(t.name)}),this.services.state.setState({conditionalRedirectViewId:null})}}
1
+ import SysActionTypes from"./action/SysActionTypes";import SysEventTypes from"./common/SysEventTypes";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import SysRouterEvent from"./RouterEvent";import systemResultStateNames from"./document-model/systemResultStateNames";import FormGroupEvents from"./form/FormGroupEvents";export default class ViewRouter extends DefaultEventEmitter{constructor(t,e,i,n,s){super(),this.eventEmitter=t,this.documentModel=e,this.viewRenderer=i,this.optionalDocumentStyles=n,this.services=s,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,i)=>{const n="number"==typeof t?t:this.documentModel.getModel().views.findIndex(e=>e.id===t);-1===n?this.eventEmitter.emit("WIDGET_NAVIGATION_STATE_NOT_FOUND",{viewPointer:t}):this.navigate(n,i,n<this.currentViewIndex?this._previousViewDestroyedCb.bind(this):()=>{})}),this.eventEmitter.on(SysActionTypes.GO_TO_PREVIOUS_VIEW,()=>{this.getCurrentViewIndex()<=0||(this.contactDataSubmitted=!1,this.navigate(this.getCurrentViewIndex()-1,{},this._previousViewDestroyedCb.bind(this)))}),this.eventEmitter.on(SysActionTypes.GO_TO_NEXT_VIEW,()=>{this.documentModel.getModel().views[this.getCurrentViewIndex()+1]&&this.navigate(this.getCurrentViewIndex()+1)}),this.eventEmitter.on("CONTACT_DATA_SUBMIT",()=>{this.contactDataSubmitted=!0}),this.services.form.on(FormGroupEvents.valueChanged,()=>{this.contactDataSubmitted&&(this.contactDataSubmitted=!1)}),this.documentContainer}destroy(){this.viewDestroy(),this.documentContainer&&this.documentContainer.remove()}navigate(t,e={},i=()=>{}){let n=this.documentModel.getView(t);const s=this.currentViewIndex;if(this.currentViewIndex===t)return;if(!n)throw this.eventEmitter.emit("WIDGET_NAVIGATION_STATE_NOT_FOUND",{navigateTo:t}),new Error("View was not found by index: "+t);setTimeout(()=>{const t=systemResultStateNames.includes(n.label),e=this.contactDataSubmitted,i=this.services.form.getControlsAsArray().length>0;t&&i&&!e&&(this.eventEmitter.emit("WIDGET_NAVIGATION_STATE_NOT_FOUND",{toSystemStateWithoutSubmitFromIndex:s,ctx:this.services.context.getKVMap()}),this.services.actionFactory.get({type:SysActionTypes.REQUEST}).execute(void 0,void 0,!0,{skipValidation:!0}))},300);const o=this.viewRenderer.render(n,t);this.viewDestroy(),i(),this.documentContainer.appendChild(o),this.currentViewComponentRef=o,this.currentViewIndex=t,this.transitions.push({prevViewIndex:s,currentViewIndex:t,currentViewComponentRef:o,contactDataSubmitted:this.contactDataSubmitted,routeState:e}),this.eventEmitter.emit(SysRouterEvent.NAVIGATION_END,t)}viewDestroy(){this.currentViewComponentRef&&this.viewRenderer.destroy(this.currentViewComponentRef)}getDocumentContainer(){return this.documentContainer}getLastTransition(){return this.transitions[this.transitions.length-1]}_previousViewDestroyedCb(){this.services.form.getControlsAsArray().forEach(t=>{t.viewIdx===this.currentViewIndex&&this.services.form.removeControl(t.name)}),this.services.state.setState({conditionalRedirectViewId:null})}}
@@ -1,3 +1,6 @@
1
+ import ContextSDK from '../sdk/context/ContextSDK';
1
2
  export default class UTMParamsExtractor {
2
- static extractUtmParams(context: any): {};
3
+ static extractTrackingParams(context: ContextSDK): {};
4
+ static extractUtmParams(context: ContextSDK): {};
5
+ static extractMarTechParams(context: ContextSDK): {};
3
6
  }
@@ -1 +1 @@
1
- import UrlQueryParamsSource from"../sdk/source/sources/UrlQueryParamsSource";export default class UTMParamsExtractor{static extractUtmParams(e){const r={id:"id",fallbackValue:"",exampleValue:"exampleValue",sourceId:UrlQueryParamsSource.sourceId,arguments:[{type:"string",name:"urlQueryParamName",value:""}]},a={},t=e.getRegistry().getSource(r.sourceId),u=t.getValue("utm");return["utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id"].forEach(e=>{const s=u.processor(t,Object.assign(Object.assign({},r),{arguments:[Object.assign(Object.assign({},r.arguments[0]),{value:e})]}));s&&(a[e]=s)}),a}}
1
+ import UrlQueryParamsSource from"../sdk/source/sources/UrlQueryParamsSource";function getLastMarTechValue(t,e){for(let r=t.length-1;r>=0;r--){const a=new URLSearchParams(t[r]),c=[];for(const[t,r]of a.entries())e.includes(t)&&r&&c.push(r);if(c.length)return c[c.length-1]}return""}export default class UTMParamsExtractor{static extractTrackingParams(t){return Object.assign(Object.assign({},UTMParamsExtractor.extractUtmParams(t)),UTMParamsExtractor.extractMarTechParams(t))}static extractUtmParams(t){const e={id:"id",fallbackValue:"",exampleValue:"exampleValue",sourceId:UrlQueryParamsSource.sourceId,arguments:[{type:"string",name:"urlQueryParamName",value:""}]},r={},a=t.getRegistry().getSource(e.sourceId),c=a.getValue("utm");return["utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id"].forEach(t=>{const s=c.processor(a,Object.assign(Object.assign({},e),{arguments:[Object.assign(Object.assign({},e.arguments[0]),{value:t})]}));s&&(r[t]=s)}),r}static extractMarTechParams(t){const e=t.getRegistry().getSource(UrlQueryParamsSource.sourceId).getSessionHistory(),r={};return Object.entries({rdt_cid:["rdt_cid"],sccid:["sccid","ScCid"],gclid:["gclid"],fbclid:["fbclid"],ttclid:["ttclid"],li_fat_id:["li_fat_id"],ascsubtag:["ascsubtag"],msclkid:["msclkid"],twclid:["twclid"],epik:["epik"]}).forEach(([t,a])=>{const c=getLastMarTechValue(e,a);c&&(r[t]=c)}),r}}
@@ -23,7 +23,6 @@ export default class BaseRequestAction {
23
23
  getTrackingMessageByStatus(_: any): string;
24
24
  execute(isSubmitQueuedAfterPending: any, outerResolve: any, force: any, overrideParams: any): Promise<unknown>;
25
25
  submit(resolve: any, force: any, overrideParams: any): void;
26
- getContextValue(nextParams: any): any;
27
26
  constructDataToSent({ contextValue, formValue, utmParams }: {
28
27
  contextValue: any;
29
28
  formValue: any;
@@ -1 +1 @@
1
- import SysActionTypes from"../SysActionTypes";import SysEventTypes from"../../common/SysEventTypes";import{HttpStatus}from"@claspo/common/network/HttpStatus";import ActionCategory from"./ActionCategory";import systemResultStateNames from"../../document-model/systemResultStateNames";import DocumentUtils from"@claspo/common/document/DocumentUtils";import getComponentCountOnView from"../../sdk/getComponentCountOnView";import UTMParamsExtractor from"../UTMParamsExtractor";import isDictionary from"@claspo/common/object/isDictionary";function componentModelHasSubmitAction(t){var e,s;try{return!!(null===(s=null===(e=t.props)||void 0===e?void 0:e.handlers)||void 0===s?void 0:s.find(t=>{var e;return null===(e=null==t?void 0:t.actions)||void 0===e?void 0:e.find(t=>[SysActionTypes.REQUEST,SysActionTypes.SUBSCRIBE_CONTACT].includes(t.type))}))}catch(t){return!1}}function viewHasControls(t){if(!t)return!1;let e=0;return DocumentUtils.iterateDepthFirst(t,t=>{(["INPUT","MULTIPLE_INPUT","PRIZE_BASED_GAMING"].includes(t.type)||componentModelHasSubmitAction(t))&&e++}),e>0}function isSystemView(t){return t&&systemResultStateNames.includes(t.label)}export const RequestStatus={SUCCESS:"SUCCESS",ALREADY_SUBSCRIBED:"ALREADY_SUBSCRIBED",ERROR:"ERROR",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS"};export default class BaseRequestAction{constructor(t,e,s,i,n,o,r,a,c){this.skipHttpRequest=!0,this.id=s.id,this.params=s.params,this.form=e,this.eventEmitter=t,this.httpClient=i,this.configService=n,this.formEventsListener=null,this.tracking=o,this.stateService=r,this.context=a,this.getServices=c,this.category=ActionCategory.SUBMIT}getTrackingMessageBeforeSentData(){return""}getTrackingMessageByStatus(t){return""}execute(t,e,s,i){var n;if(this.formEventsListener&&this.formEventsListener.off(),this.form.submitQueuedAfterPending&&!0!==t)return;if(this.form.preventSubmit)return void(this.form.submitQueuedAfterPending=!1);const o=new Promise(n=>{if(!this.form.isPending()){this.form.submitQueuedAfterPending=!1;const o=!0===t?e:n;return this.submit(o,s,i)}this.form.submitQueuedAfterPending=!0,setTimeout(()=>this.execute(!0,n,s,i),500)});return null===(n=this.getServices().submitState)||void 0===n||n.trackSubmission(o),o}submit(t,e,s){var i;const n=this.getServices().viewRouter.getCurrentViewIndex(),o=this.getServices().documentModel.getViews().slice(n+1).filter(t=>!systemResultStateNames.includes(t.label)).length>0,r=Object.assign(Object.assign({},this.params),s);if(this.form.markAsTouched(),this.stateService.getState().emitActionOnSubmit&&this.eventEmitter.emit(this.stateService.getState().emitActionOnSubmit.eventName),this.stateService.getState().interceptSubmitActions&&!e)return;if(!this.form.isValid()&&!r.skipValidation)return this.eventEmitter.emit("INVALID_CONTACT_DATA_SUBMIT_ATTEMPT"),void t(!1);const a=this.stateService,c=a.getState().conditionalRedirectViewId,u=r.conditionalRedirectViewId||c;c&&(r.conditionalRedirectViewId=c,a.setState({conditionalRedirectViewId:null}));let S=this.getServices().documentModel.getViews()[n+1];const m=this.getServices().documentModel.getViews()[n];if(!r.skipNavigation&&u&&getComponentCountOnView(m,"SysNetPromoterScoreComponent")+getComponentCountOnView(m,"SysFeedbackComponent")===1&&(S=this.getServices().documentModel.getViews().find(t=>t.id===r.conditionalRedirectViewId),viewHasControls(S)||isSystemView(S)))return this.goToView(S.path[0],r),void t(!0);const E=null!==(i=r.formValue)&&void 0!==i?i:this.form.getControlsMap(),d=this.getContextValue(r);if(!r.skipNavigation&&o&&(viewHasControls(S)||!Object.keys(E).length&&!Object.keys(d).length))return this.goToView(n+1,r),void t(!0);if(!Object.keys(E).length&&!Object.keys(d).length)return void t(!0);const l=UTMParamsExtractor.extractUtmParams(this.context),g=this.constructRequestPayload({contextValue:d,formValue:E,utmParams:l});this.eventEmitter.emit(SysEventTypes.SUBMIT_REQUEST_STARTED,g),this.eventEmitter.emit("CONTACT_DATA_SUBMIT",g);if(this.getTrackingMessageBeforeSentData()&&this.tracking.send("FormFinish_[Name]"),this.configService.getConfig("isBot"))return this.eventEmitter.emit(SysEventTypes.SUBMIT_REQUEST_FINISHED,{state:RequestStatus.SUCCESS,success:!0,skipped:!0}),void t();this.sendRequest(g).then(t=>t.json().then(e=>t.status===HttpStatus.TOO_MANY_REQUESTS?{state:RequestStatus.TOO_MANY_REQUESTS}:{contactId:e.contactId,state:e&&e.next&&e.next.type}),()=>({state:RequestStatus.ERROR})).then(e=>{const s=this.getTrackingMessageByStatus(e.state);if(s&&this.tracking.send(s),r.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.eventEmitter.emit(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:this.goToView(o&&S?S.path[0]:this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_SUCCESS"===t.label||"DOCUMENT_VIEW_TYPE_SUCCESSFUL_REQUEST"===t.label||"REQUEST_FORM_VIEW_TYPE_SUCCESS"===t.label));break;case RequestStatus.ALREADY_SUBSCRIBED:this.goToView(u&&S?S.path[0]:this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_SUBSCRIBED"===t.label));break;case RequestStatus.ERROR:this.goToView(u&&S?S.path[0]:this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_ERROR"===t.label));break;case RequestStatus.TOO_MANY_REQUESTS:this.goToView(u&&S?S.path[0]:this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_ERROR"===t.label)),this.eventEmitter.emit(SysEventTypes.TOO_MANY_REQUESTS)}e.contactId&&"0"!==e.contactId&&this.eventEmitter.emit("CONTACT_ID_WAS_RECEIVED",e.contactId),this.eventEmitter.emit(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.eventEmitter.emit(SysEventTypes.SUBMIT_REQUEST_FINISHED,{state:RequestStatus.ERROR,success:!1}),r.skipNavigation||this.goToView(this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_ERROR"===t.label)),t(!1)})}getContextValue(t){var e,s;if(!t.excludeFormContext)return this.context.getKVMap();const i=(null===(s=(e=this.context).getRecordsMap)||void 0===s?void 0:s.call(e))||{};return Object.values(i).reduce((t,e)=>{var s;const i=null===(s=null==e?void 0:e.getValue)||void 0===s?void 0:s.call(e);return i&&"FORM"!==i.sourceId?(t[i.id]=i.value,t):t},{})}constructDataToSent({contextValue:t,formValue:e,utmParams:s}){const i=Object.assign({},t);return i.tracking=s,Object.keys(e).forEach(t=>{if(t.startsWith("clConsentId")){if(t.endsWith("_label"))return;const s={value:e[t]};e[`${t}_label`]&&(s.text=e[`${t}_label`]),i.consents?i.consents[t]=s:i.consents={[t]:s}}else{const s=e[t];i[t]=isDictionary(s)||Array.isArray(s)?JSON.stringify(s):s}}),i}constructRequestPayload({contextValue:t,formValue:e,utmParams:s}){let i={data:this.constructDataToSent({contextValue:t,formValue:e,utmParams:s}),referrer:window.location.href,triggeredBy:this.configService.getConfig("triggeredBy")};return this.configService.getConfig("widgetDebugMode")&&(i.ignoreTracking=!0),i}constructRequestHeaders(){const t={},e=this.configService.getConfig("clCustomerId");return e&&Object.assign(t,{"cl-customer-id":e}),t}goToView(t,e){this.eventEmitter.emit(SysActionTypes.GO_TO_VIEW,t,e)}sendRequest(t){return this.skipHttpRequest?Promise.resolve({status:200,json:()=>Promise.resolve({next:{type:RequestStatus.SUCCESS}})}):this.httpClient.execute(this.configService.getConfig("subscribeContactUrl"),"POST",t,this.constructRequestHeaders())}}
1
+ import SysActionTypes from"../SysActionTypes";import SysEventTypes from"../../common/SysEventTypes";import{HttpStatus}from"@claspo/common/network/HttpStatus";import ActionCategory from"./ActionCategory";import systemResultStateNames from"../../document-model/systemResultStateNames";import DocumentUtils from"@claspo/common/document/DocumentUtils";import getComponentCountOnView from"../../sdk/getComponentCountOnView";import UTMParamsExtractor from"../UTMParamsExtractor";import isDictionary from"@claspo/common/object/isDictionary";function componentModelHasSubmitAction(t){var e,s;try{return!!(null===(s=null===(e=t.props)||void 0===e?void 0:e.handlers)||void 0===s?void 0:s.find(t=>{var e;return null===(e=null==t?void 0:t.actions)||void 0===e?void 0:e.find(t=>[SysActionTypes.REQUEST,SysActionTypes.SUBSCRIBE_CONTACT].includes(t.type))}))}catch(t){return!1}}function viewHasControls(t){if(!t)return!1;let e=0;return DocumentUtils.iterateDepthFirst(t,t=>{(["INPUT","MULTIPLE_INPUT","PRIZE_BASED_GAMING"].includes(t.type)||componentModelHasSubmitAction(t))&&e++}),e>0}function isSystemView(t){return t&&systemResultStateNames.includes(t.label)}export const RequestStatus={SUCCESS:"SUCCESS",ALREADY_SUBSCRIBED:"ALREADY_SUBSCRIBED",ERROR:"ERROR",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS"};export default class BaseRequestAction{constructor(t,e,s,i,n,o,r,a,c){this.skipHttpRequest=!0,this.id=s.id,this.params=s.params,this.form=e,this.eventEmitter=t,this.httpClient=i,this.configService=n,this.formEventsListener=null,this.tracking=o,this.stateService=r,this.context=a,this.getServices=c,this.category=ActionCategory.SUBMIT}getTrackingMessageBeforeSentData(){return""}getTrackingMessageByStatus(t){return""}execute(t,e,s,i){if(this.formEventsListener&&this.formEventsListener.off(),!this.form.submitQueuedAfterPending||!0===t){if(!this.form.preventSubmit)return new Promise(n=>{if(!this.form.isPending()){this.form.submitQueuedAfterPending=!1;const o=!0===t?e:n;return this.submit(o,s,i)}this.form.submitQueuedAfterPending=!0,setTimeout(()=>this.execute(!0,n,s,i),500)});this.form.submitQueuedAfterPending=!1}}submit(t,e,s){const i=this.getServices().viewRouter.getCurrentViewIndex(),n=this.getServices().documentModel.getViews().slice(i+1).filter(t=>!systemResultStateNames.includes(t.label)).length>0,o=Object.assign(Object.assign({},this.params),s);if(this.form.markAsTouched(),this.stateService.getState().emitActionOnSubmit&&this.eventEmitter.emit(this.stateService.getState().emitActionOnSubmit.eventName),this.stateService.getState().interceptSubmitActions&&!e)return;if(!this.form.isValid()&&!o.skipValidation)return this.eventEmitter.emit("INVALID_CONTACT_DATA_SUBMIT_ATTEMPT"),void t(!1);const r=this.stateService,a=r.getState().conditionalRedirectViewId,c=o.conditionalRedirectViewId||a;a&&(o.conditionalRedirectViewId=a,r.setState({conditionalRedirectViewId:null}));let u=this.getServices().documentModel.getViews()[i+1];const m=this.getServices().documentModel.getViews()[i];if(c&&getComponentCountOnView(m,"SysNetPromoterScoreComponent")+getComponentCountOnView(m,"SysFeedbackComponent")===1&&(u=this.getServices().documentModel.getViews().find(t=>t.id===o.conditionalRedirectViewId),viewHasControls(u)||isSystemView(u)))return this.goToView(u.path[0],o),void t(!0);const S=this.form.getControlsMap(),d=this.context.getKVMap();if(n&&(viewHasControls(u)||!Object.keys(S).length&&!Object.keys(d).length))return this.goToView(i+1,o),void t(!0);if(!Object.keys(S).length&&!Object.keys(d).length)return void t(!0);const l=UTMParamsExtractor.extractTrackingParams(this.context),g=this.constructRequestPayload({contextValue:d,formValue:S,utmParams:l});this.eventEmitter.emit("CONTACT_DATA_SUBMIT",g);this.getTrackingMessageBeforeSentData()&&this.tracking.send("FormFinish_[Name]"),this.configService.getConfig("isBot")?t():this.sendRequest(g).then(t=>t.json().then(e=>t.status===HttpStatus.TOO_MANY_REQUESTS?{state:RequestStatus.TOO_MANY_REQUESTS}:{contactId:e.contactId,state:e&&e.next&&e.next.type}),()=>({state:RequestStatus.ERROR})).then(e=>{const s=this.getTrackingMessageByStatus(e.state);switch(e.state){case RequestStatus.SUCCESS:s&&this.tracking.send(s),this.goToView(n&&u?u.path[0]:this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_SUCCESS"===t.label||"DOCUMENT_VIEW_TYPE_SUCCESSFUL_REQUEST"===t.label||"REQUEST_FORM_VIEW_TYPE_SUCCESS"===t.label));break;case RequestStatus.ALREADY_SUBSCRIBED:s&&this.tracking.send(s),this.goToView(c&&u?u.path[0]:this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_SUBSCRIBED"===t.label));break;case RequestStatus.ERROR:s&&this.tracking.send(s),this.goToView(c&&u?u.path[0]:this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_ERROR"===t.label));break;case RequestStatus.TOO_MANY_REQUESTS:s&&this.tracking.send(s),this.goToView(c&&u?u.path[0]:this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_ERROR"===t.label)),this.eventEmitter.emit(SysEventTypes.TOO_MANY_REQUESTS)}e.contactId&&"0"!==e.contactId&&this.eventEmitter.emit("CONTACT_ID_WAS_RECEIVED",e.contactId),t(e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED)}).catch(()=>{this.goToView(this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_ERROR"===t.label)),t(!1)})}constructDataToSent({contextValue:t,formValue:e,utmParams:s}){const i=Object.assign({},t);return i.tracking=s,Object.keys(e).forEach(t=>{if(t.startsWith("clConsentId")){if(t.endsWith("_label"))return;const s={value:e[t]};e[`${t}_label`]&&(s.text=e[`${t}_label`]),i.consents?i.consents[t]=s:i.consents={[t]:s}}else{const s=e[t];i[t]=isDictionary(s)||Array.isArray(s)?JSON.stringify(s):s}}),i}constructRequestPayload({contextValue:t,formValue:e,utmParams:s}){let i={data:this.constructDataToSent({contextValue:t,formValue:e,utmParams:s}),referrer:window.location.href,triggeredBy:this.configService.getConfig("triggeredBy")};return this.configService.getConfig("widgetDebugMode")&&(i.ignoreTracking=!0),i}constructRequestHeaders(){const t={},e=this.configService.getConfig("clCustomerId");return e&&Object.assign(t,{"cl-customer-id":e}),t}goToView(t,e){this.eventEmitter.emit(SysActionTypes.GO_TO_VIEW,t,e)}sendRequest(t){return this.skipHttpRequest?Promise.resolve({status:200,json:()=>Promise.resolve({next:{type:RequestStatus.SUCCESS}})}):this.httpClient.execute(this.configService.getConfig("subscribeContactUrl"),"POST",t,this.constructRequestHeaders())}}
@@ -1 +1 @@
1
- export default class ConfigService{constructor(e){this.config=Object.assign(Object.assign({},{subscribeContactUrl:"",submitOnClose:{enabled:!1,skipValidation:!0}}),e)}getConfig(e){return e?"entryModuleType"===e?this.config.renderMode:this.config[e]:this.config}}
1
+ export default class ConfigService{constructor(e){this.config=Object.assign(Object.assign({},{subscribeContactUrl:""}),e)}getConfig(e){return e?"entryModuleType"===e?this.config.renderMode:this.config[e]:this.config}}
@@ -2,8 +2,6 @@ declare enum SysEventTypes {
2
2
  TOO_MANY_REQUESTS = "TOO_MANY_REQUESTS",
3
3
  COMPONENT_RESOURCES_LOADED = "COMPONENT_RESOURCES_LOADED",
4
4
  FAILED_TO_LOAD_COMPONENT_RESOURCE = "FAILED_TO_LOAD_COMPONENT_RESOURCE",
5
- EXECUTE_ACTION_BY_PREDICATE = "EXECUTE_ACTION_BY_PREDICATE",
6
- SUBMIT_REQUEST_STARTED = "SUBMIT_REQUEST_STARTED",
7
- SUBMIT_REQUEST_FINISHED = "SUBMIT_REQUEST_FINISHED"
5
+ EXECUTE_ACTION_BY_PREDICATE = "EXECUTE_ACTION_BY_PREDICATE"
8
6
  }
9
7
  export default SysEventTypes;
@@ -1 +1 @@
1
- var SysEventTypes;!function(E){E.TOO_MANY_REQUESTS="TOO_MANY_REQUESTS",E.COMPONENT_RESOURCES_LOADED="COMPONENT_RESOURCES_LOADED",E.FAILED_TO_LOAD_COMPONENT_RESOURCE="FAILED_TO_LOAD_COMPONENT_RESOURCE",E.EXECUTE_ACTION_BY_PREDICATE="EXECUTE_ACTION_BY_PREDICATE",E.SUBMIT_REQUEST_STARTED="SUBMIT_REQUEST_STARTED",E.SUBMIT_REQUEST_FINISHED="SUBMIT_REQUEST_FINISHED"}(SysEventTypes||(SysEventTypes={}));export default SysEventTypes;
1
+ var SysEventTypes;!function(E){E.TOO_MANY_REQUESTS="TOO_MANY_REQUESTS",E.COMPONENT_RESOURCES_LOADED="COMPONENT_RESOURCES_LOADED",E.FAILED_TO_LOAD_COMPONENT_RESOURCE="FAILED_TO_LOAD_COMPONENT_RESOURCE",E.EXECUTE_ACTION_BY_PREDICATE="EXECUTE_ACTION_BY_PREDICATE"}(SysEventTypes||(SysEventTypes={}));export default SysEventTypes;
@@ -1,11 +1,13 @@
1
1
  import DefaultEventEmitter from "@claspo/common/DefaultEventEmitter";
2
2
  import { ClBaseComponentI, ClDocumentI, ClDocumentSharedI } from '@claspo/common/document/Document.interface';
3
- export declare const DocumentModelUpdateType: {
3
+ export declare const EditorToWidgetEventType: {
4
4
  COMPONENT_INSERT: string;
5
5
  COMPONENT_REMOVE: string;
6
6
  COMPONENT_MOVE: string;
7
7
  COMPONENT_UPDATE: string;
8
8
  COMPONENT_PROPS_UPDATE: string;
9
+ REMOVE_FOCUS: string;
10
+ SET_FOCUS: string;
9
11
  SHARED_UPDATE: string;
10
12
  MOBILE_BREAKPOINT_UPDATE: string;
11
13
  ENVIRONMENT_UPDATE: string;
@@ -1 +1 @@
1
- import ModulesComponentExtractor from"./ModulesComponentExtractor";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import DocumentUtils from"@claspo/common/document/DocumentUtils";export const DocumentModelUpdateType={COMPONENT_INSERT:"COMPONENT_INSERT",COMPONENT_REMOVE:"COMPONENT_REMOVE",COMPONENT_MOVE:"COMPONENT_MOVE",COMPONENT_UPDATE:"COMPONENT_UPDATE",COMPONENT_PROPS_UPDATE:"COMPONENT_PROPS_UPDATE",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.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}iterateViewModelAndExecute(t,e){const E=this.getView(t);DocumentUtils.iterateDepthFirst(E,e)}destroy(){}destroyView(t){console.warn("destroyView now should do nothing"),this.iterateViewModelAndExecute(t,t=>{t.componentRef&&(t.componentRef.remove(),t.componentRef=null)})}}
1
+ import ModulesComponentExtractor from"./ModulesComponentExtractor";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import DocumentUtils from"@claspo/common/document/DocumentUtils";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(E){super(),this.json=E,this.flatJson=ModulesComponentExtractor.extract(this.json)}setComponentRef(E,t){DocumentUtils.getNodeById(this.getViews(),E).componentRef=t}getModel(){return this.flatJson}getView(E){return this.flatJson.views[E]}getViews(){return this.flatJson.views}getShared(){return this.flatJson.shared}iterateViewModelAndExecute(E,t){const e=this.getView(E);DocumentUtils.iterateDepthFirst(e,t)}destroy(){}destroyView(E){console.warn("destroyView now should do nothing"),this.iterateViewModelAndExecute(E,E=>{E.componentRef&&(E.componentRef.remove(),E.componentRef=null)})}}
@@ -1 +1 @@
1
- import DocumentUtils from"@claspo/common/document/DocumentUtils";import{ComponentInsertType}from"@claspo/common/document/ComponentInsertType";import{DocumentModelUpdateType}from"./DocumentModelService";export default class DocumentService{constructor(e,t,o){this.documentModel=e,this.viewRenderer=t,this.renderMode=o}handleModelUpdate(e,t){switch(e){case DocumentModelUpdateType.COMPONENT_PROPS_UPDATE:{const{id:e,data:o}=t,d=DocumentUtils.getNodeById(this.documentModel.getViews(),e);if(!d)return void console.warn("Attempt to update unexisting component props");const n=d.path,i=n.reduce((e,t,o)=>0===o?this.documentModel.getViews()[t]:e.children[t],this.documentModel.getViews());return i?(i.props=Object.assign({},o),void this.documentModel.emit(`${DocumentModelUpdateType.COMPONENT_PROPS_UPDATE}_${e}`,o)):void console.error("Model not found by path ["+n+"]")}case DocumentModelUpdateType.COMPONENT_UPDATE:{const{id:e,data:o}=t,d=DocumentUtils.getNodeById(this.documentModel.getViews(),e);return d?(Object.assign(d,o),void this.documentModel.emit(`${DocumentModelUpdateType.COMPONENT_UPDATE}_${e}`,o)):void console.warn("Attempt to update unexisting component props")}case DocumentModelUpdateType.SHARED_UPDATE:{const e=this.documentModel.getShared();return Object.assign(e,t),void this.documentModel.emit(DocumentModelUpdateType.SHARED_UPDATE_ALL)}case DocumentModelUpdateType.MOBILE_BREAKPOINT_UPDATE:return void(this.documentModel.getShared().mobileBreakpointWidth=t.mobileBreakpointWidth);case DocumentModelUpdateType.ENVIRONMENT_UPDATE:return void this.documentModel.emit(DocumentModelUpdateType.ENVIRONMENT_UPDATE,t);case DocumentModelUpdateType.TEXT_CLASS_ADDED:return void(this.documentModel.getShared().textClasses[t.id]=t);case DocumentModelUpdateType.TEXT_CLASS_UPDATED:return this.documentModel.getShared().textClasses[t.id]=t,void this.documentModel.emit(DocumentModelUpdateType.SHARED_UPDATE_ALL);case DocumentModelUpdateType.TEXT_CLASS_REMOVED:return void delete this.documentModel.getShared().textClasses[t];case DocumentModelUpdateType.HEADER_FONT_FAMILY_UPDATE:return this.documentModel.getShared().headerFontFamily=t,void this.documentModel.emit(DocumentModelUpdateType.SHARED_UPDATE_ALL);case DocumentModelUpdateType.TEXT_FONT_FAMILY_UPDATE:return this.documentModel.getShared().textFontFamily=t,void this.documentModel.emit(DocumentModelUpdateType.SHARED_UPDATE_ALL);case DocumentModelUpdateType.COLOR_SCHEMA_UPDATE:return this.documentModel.getShared().cssVars=t,void this.documentModel.emit(DocumentModelUpdateType.COLOR_SCHEMA_UPDATE,t);case DocumentModelUpdateType.THEME_UPDATE:return this.documentModel.getShared().theme=t,this.documentModel.emit(DocumentModelUpdateType.THEME_UPDATE,t),void this.documentModel.emit(DocumentModelUpdateType.SHARED_UPDATE_ALL);case DocumentModelUpdateType.COMPONENT_REMOVE:{const e=t.path;return void this.removeComponent(e)}case DocumentModelUpdateType.COMPONENT_INSERT:{let{insertPosition:e,targetPath:o,model:d}=t,n=DocumentUtils.getNodeByPath(this.documentModel.getViews(),o);if(!n&&e!==ComponentInsertType.INSIDE){const t=o.slice(0,-1),d=DocumentUtils.getNodeByPath(this.documentModel.getViews(),t);e=ComponentInsertType.INSIDE,n=d,o=t}return DocumentUtils.insertNode(d,o,this.documentModel.getViews(),e),void this.viewRenderer.renderComponent(n,d,this.renderMode,e)}case DocumentModelUpdateType.COMPONENT_MOVE:{const{fromPath:e,insertPosition:o,targetPath:d}=t,n=d[0],i=this.documentModel.getViews()[n],s=DocumentUtils.getNodeByPath(this.documentModel.getViews(),d);if(!s)return;const c=this.removeComponent(e),m=DocumentUtils.getNodeById([i],s.id).path;return DocumentUtils.insertNode(c,m,this.documentModel.getViews(),o),void this.viewRenderer.renderComponent(s,c,this.renderMode,o)}default:return}}removeComponent(e){const t=DocumentUtils.getNodeByPath(this.documentModel.getViews(),e);if(t)return t.componentRef.remove(),DocumentUtils.removeNode(this.documentModel.getViews(),e)}}
1
+ import DocumentUtils from"@claspo/common/document/DocumentUtils";import{ComponentInsertType}from"@claspo/common/document/ComponentInsertType";import{EditorToWidgetEventType}from"./DocumentModelService";export default class DocumentService{constructor(e,t,o){this.documentModel=e,this.viewRenderer=t,this.renderMode=o}handleModelUpdate(e,t){switch(e){case EditorToWidgetEventType.COMPONENT_PROPS_UPDATE:{const{id:e,data:o}=t,d=DocumentUtils.getNodeById(this.documentModel.getViews(),e);if(!d)return void console.warn("Attempt to update unexisting component props");const i=d.path,n=i.reduce((e,t,o)=>0===o?this.documentModel.getViews()[t]:e.children[t],this.documentModel.getViews());return n?(n.props=Object.assign({},o),void this.documentModel.emit(`${EditorToWidgetEventType.COMPONENT_PROPS_UPDATE}_${e}`,o)):void console.error("Model not found by path ["+i+"]")}case EditorToWidgetEventType.COMPONENT_UPDATE:{const{id:e,data:o}=t,d=DocumentUtils.getNodeById(this.documentModel.getViews(),e);return d?(Object.assign(d,o),void this.documentModel.emit(`${EditorToWidgetEventType.COMPONENT_UPDATE}_${e}`,o)):void console.warn("Attempt to update unexisting component props")}case EditorToWidgetEventType.SHARED_UPDATE:{const e=this.documentModel.getShared();return Object.assign(e,t),void this.documentModel.emit(EditorToWidgetEventType.SHARED_UPDATE_ALL)}case EditorToWidgetEventType.MOBILE_BREAKPOINT_UPDATE:return void(this.documentModel.getShared().mobileBreakpointWidth=t.mobileBreakpointWidth);case EditorToWidgetEventType.ENVIRONMENT_UPDATE:return void this.documentModel.emit(EditorToWidgetEventType.ENVIRONMENT_UPDATE,t);case EditorToWidgetEventType.TEXT_CLASS_ADDED:return void(this.documentModel.getShared().textClasses[t.id]=t);case EditorToWidgetEventType.TEXT_CLASS_UPDATED:return this.documentModel.getShared().textClasses[t.id]=t,void this.documentModel.emit(EditorToWidgetEventType.SHARED_UPDATE_ALL);case EditorToWidgetEventType.TEXT_CLASS_REMOVED:return void delete this.documentModel.getShared().textClasses[t];case EditorToWidgetEventType.HEADER_FONT_FAMILY_UPDATE:return this.documentModel.getShared().headerFontFamily=t,void this.documentModel.emit(EditorToWidgetEventType.SHARED_UPDATE_ALL);case EditorToWidgetEventType.TEXT_FONT_FAMILY_UPDATE:return this.documentModel.getShared().textFontFamily=t,void this.documentModel.emit(EditorToWidgetEventType.SHARED_UPDATE_ALL);case EditorToWidgetEventType.COLOR_SCHEMA_UPDATE:return this.documentModel.getShared().cssVars=t,void this.documentModel.emit(EditorToWidgetEventType.COLOR_SCHEMA_UPDATE,t);case EditorToWidgetEventType.THEME_UPDATE:return this.documentModel.getShared().theme=t,this.documentModel.emit(EditorToWidgetEventType.THEME_UPDATE,t),void this.documentModel.emit(EditorToWidgetEventType.SHARED_UPDATE_ALL);case EditorToWidgetEventType.COMPONENT_REMOVE:{const e=t.path;return void this.removeComponent(e)}case EditorToWidgetEventType.COMPONENT_INSERT:{let{insertPosition:e,targetPath:o,model:d}=t,i=DocumentUtils.getNodeByPath(this.documentModel.getViews(),o);if(!i&&e!==ComponentInsertType.INSIDE){const t=o.slice(0,-1),d=DocumentUtils.getNodeByPath(this.documentModel.getViews(),t);e=ComponentInsertType.INSIDE,i=d,o=t}return DocumentUtils.insertNode(d,o,this.documentModel.getViews(),e),void this.viewRenderer.renderComponent(i,d,this.renderMode,e)}case EditorToWidgetEventType.COMPONENT_MOVE:{const{fromPath:e,insertPosition:o,targetPath:d}=t,i=d[0],n=this.documentModel.getViews()[i],s=DocumentUtils.getNodeByPath(this.documentModel.getViews(),d);if(!s)return;const r=this.removeComponent(e),E=DocumentUtils.getNodeById([n],s.id).path;return DocumentUtils.insertNode(r,E,this.documentModel.getViews(),o),void this.viewRenderer.renderComponent(s,r,this.renderMode,o)}default:return}}removeComponent(e){const t=DocumentUtils.getNodeByPath(this.documentModel.getViews(),e);if(t)return t.componentRef.remove(),DocumentUtils.removeNode(this.documentModel.getViews(),e)}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@claspo/renderer",
3
- "version": "18.1.2",
3
+ "version": "18.3.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.0.4",
18
+ "@claspo/common": "7.1.1",
19
19
  "@testing-library/dom": "^10.4.0"
20
20
  },
21
21
  "devDependencies": {
@@ -1 +1 @@
1
- import{ViewRendererActionType}from"./ViewRendererActionType";import{applySysAttrPrefix}from"./RenderConstants";export default class DragEventListener{constructor(e,t){this.eventEmitter=e,this.documentModel=t,this.dragStartSubscription=this.eventEmitter.on(ViewRendererActionType.COMPONENT_DRAGSTART,()=>{this.updateHovered("add")}),this.dragEndSubscription=this.eventEmitter.on(ViewRendererActionType.COMPONENT_DRAGEND,()=>{this.updateHovered("remove")})}updateHovered(e){this.documentModel.getViews().forEach((t,r)=>{this.documentModel.iterateViewModelAndExecute(r,t=>{var r;const i=null===(r=t.componentRef)||void 0===r?void 0:r.getHostElement();i&&i.classList[e](applySysAttrPrefix("hovered"),applySysAttrPrefix("drag-over"))})})}destroy(){this.dragStartSubscription.off(),this.dragEndSubscription.off()}}
1
+ import{WidgetToEditorEventType}from"./WidgetToEditorEventType";import{applySysAttrPrefix}from"./RenderConstants";export default class DragEventListener{constructor(t,e){this.eventEmitter=t,this.documentModel=e,this.dragStartSubscription=this.eventEmitter.on(WidgetToEditorEventType.COMPONENT_DRAGSTART,()=>{this.updateHovered("add")}),this.dragEndSubscription=this.eventEmitter.on(WidgetToEditorEventType.COMPONENT_DRAGEND,()=>{this.updateHovered("remove")})}updateHovered(t){this.documentModel.getViews().forEach((e,o)=>{this.documentModel.iterateViewModelAndExecute(o,e=>{var o;const r=null===(o=e.componentRef)||void 0===o?void 0:o.getHostElement();r&&r.classList[t](applySysAttrPrefix("hovered"),applySysAttrPrefix("drag-over"))})})}destroy(){this.dragStartSubscription.off(),this.dragEndSubscription.off()}}
@@ -1,7 +1,5 @@
1
- export declare const ViewRendererActionType: {
1
+ export declare const WidgetToEditorEventType: {
2
2
  COMPONENT_FOCUSED: string;
3
- REMOVE_FOCUS: string;
4
- SET_FOCUS: string;
5
3
  COMPONENT_MOUSE_MOVE: string;
6
4
  COMPONENT_CLICKED: string;
7
5
  COMPONENT_DOUBLE_CLICKED: string;
@@ -15,4 +13,5 @@ export declare const ViewRendererActionType: {
15
13
  GAME_PHASE_READY_TO_PLAY: string;
16
14
  GAME_PHASE_COMPLETED: string;
17
15
  GAME_PHASE_IDLE: string;
16
+ COMPONENT_PROPS_UPDATE: string;
18
17
  };
@@ -0,0 +1 @@
1
+ export const WidgetToEditorEventType={COMPONENT_FOCUSED:"COMPONENT_FOCUSED",COMPONENT_MOUSE_MOVE:"COMPONENT_MOUSE_MOVE",COMPONENT_CLICKED:"COMPONENT_CLICKED",COMPONENT_DOUBLE_CLICKED:"COMPONENT_DOUBLE_CLICKED",COMPONENT_DRAGSTART:"COMPONENT_DRAGSTART",COMPONENT_DRAGEND:"COMPONENT_DRAGEND",COMPONENT_DRAGOVER:"COMPONENT_DRAGOVER",DOCUMENT_DROP:"DOCUMENT_DROP",SHOW_INLINE_EDIT:"SHOW_INLINE_EDIT",VIEW_COMPONENT_RESOURCES_LOADED:"VIEW_COMPONENT_RESOURCES_LOADED",FAILED_TO_LOAD_COMPONENT_RESOURCE:"FAILED_TO_LOAD_COMPONENT_RESOURCE",GAME_PHASE_READY_TO_PLAY:"GAME_PHASE_READY_TO_PLAY",GAME_PHASE_COMPLETED:"GAME_PHASE_COMPLETED",GAME_PHASE_IDLE:"GAME_PHASE_IDLE",COMPONENT_PROPS_UPDATE:"COMPONENT_PROPS_UPDATE_FROM_WIDGET"};
@@ -1 +1 @@
1
- import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{DocumentModelUpdateType}from"../../document-model/DocumentModelService";class ClDocumentResizeListener extends DefaultEventEmitter{constructor(e,t){super(),this.documentModel=e,this.containerElement=t,this.mobileBreakpointWidth=this.documentModel.getShared().mobileBreakpointWidth,this._isMobile=this._calculateMobileFlag(),this.documentModel.on(DocumentModelUpdateType.ENVIRONMENT_UPDATE,e=>{this._isMobile=e.isMobileEnv,this.emit(ClDocumentResizeListener.changeEventName,this._isMobile)})}isMobile(){return this._isMobile}destroy(){super.destroy()}_calculateMobileFlag(){return this._getElementsWidthPx(this.containerElement)<=this.mobileBreakpointWidth}_getElementsWidthPx(e){return parseInt(getComputedStyle(e).width)}}ClDocumentResizeListener.changeEventName="CHANGE";export default ClDocumentResizeListener;
1
+ import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{EditorToWidgetEventType}from"../../document-model/DocumentModelService";class ClDocumentResizeListener extends DefaultEventEmitter{constructor(e,t){super(),this.documentModel=e,this.containerElement=t,this.mobileBreakpointWidth=this.documentModel.getShared().mobileBreakpointWidth,this._isMobile=this._calculateMobileFlag(),this.documentModel.on(EditorToWidgetEventType.ENVIRONMENT_UPDATE,e=>{this._isMobile=e.isMobileEnv,this.emit(ClDocumentResizeListener.changeEventName,this._isMobile)})}isMobile(){return this._isMobile}destroy(){super.destroy()}_calculateMobileFlag(){return this._getElementsWidthPx(this.containerElement)<=this.mobileBreakpointWidth}_getElementsWidthPx(e){return parseInt(getComputedStyle(e).width)}}ClDocumentResizeListener.changeEventName="CHANGE";export default ClDocumentResizeListener;
@@ -1 +1 @@
1
- import{DocumentModelUpdateType}from"../../document-model/DocumentModelService";import ErrorLogger from"../../error/ErrorLogger";import{fromCssVarToSchemaToken,toCssVarToken}from"@claspo/common/theme/theme.utils";export default class ColorSchemaListener{constructor(e,t,o,s,n,r){this.hostElement=t,this.documentModel=e,this.getSharedCb=o,this.getPropsCb=s,this.getEnvCb=n,this.httpClient=r,this.schemaSubscription=null,this.themeSubscription=null,this.envUrlMaps={desktop:new Map,mobile:new Map}}parseBackground(e){const t=String(e||"");if(t.includes("url")){const[e,o]=t.split("(")[1].split(")");return{url:e.replace(/['"]+/g,""),positionOptions:o.replace(";","")}}return{url:null,positionOptions:null}}apply(e){const t=this.getPropsCb();return t.backgroundDynamicInlineSVGElements[e].forEach(o=>{var s,n,r,i,l;const a=null===(n=null===(s=t.adaptiveStyles)||void 0===s?void 0:s[e])||void 0===n?void 0:n.find(e=>e.element===o),c=(null===(r=t.styles)||void 0===r?void 0:r.find(e=>e.element===o))||{},m=(null===(i=null==c?void 0:c.styleAttributes)||void 0===i?void 0:i.background)||(null===(l=null==a?void 0:a.styleAttributes)||void 0===l?void 0:l.background),h=this.parseBackground(m);h.url&&this.envUrlMaps[e].set(o,{originalSVGResourceURL:h.url,inlineSvgString:null,positionOptions:h.positionOptions})}),Promise.all([...this.envUrlMaps[e].entries()].map(([t,o])=>this.httpClient.execute(o.originalSVGResourceURL).then(e=>e.text()).then(s=>{this.envUrlMaps[e].set(t,Object.assign(Object.assign({},o),{inlineSvgString:s}))}))).then(()=>{var t;const o=this.getSharedCb();return Object.keys((null===(t=o.theme)||void 0===t?void 0:t.schema)||{}).length>0?this._applyHostElementBackgroundFromTheme(this.envUrlMaps[e].get("host"),o.theme.schema):this._applyHostElementBackgroundFromCssVars(this.envUrlMaps[e].get("host"),o.cssVars)}).catch(e=>{console.error(e),ErrorLogger.log(`Failed to load/apply backgroundDynamicInlineSVGElements[${this.getPropsCb().backgroundDynamicInlineSVGElements}] ${e}`)})}on(){return this.schemaSubscription=this.documentModel.on(DocumentModelUpdateType.COLOR_SCHEMA_UPDATE,e=>{this._applyHostElementBackgroundFromCssVars(this.envUrlMaps[this.getEnvCb()].get("host"),e)}),this.themeSubscription=this.documentModel.on(DocumentModelUpdateType.THEME_UPDATE,e=>{this._applyHostElementBackgroundFromTheme(this.envUrlMaps[this.getEnvCb()].get("host"),e.schema)}),this}_applyHostElementBackgroundFromCssVars(e,t){e&&t&&(this.hostElement.style.background=this._buildBackgroundUrlFromCssVars(e,t))}_applyHostElementBackgroundFromTheme(e,t){e&&t&&(this.hostElement.style.background=this._buildBackgroundUrlFromTheme(e,t))}_buildBackgroundUrlFromCssVars(e,t){const o=e.inlineSvgString.trim().replace("var(--cl-schema-accent)",t["cl-schema-accent"]);return`url('data:image/svg+xml,${encodeURIComponent(o)}')${e.positionOptions}`}_buildBackgroundUrlFromTheme(e,t){const o=e.inlineSvgString.trim();let s=o;[...o.matchAll(/var\(--cl-schema-([^)]+)\)/g)].forEach(e=>{const o=fromCssVarToSchemaToken(e[1]);s=s.replace(`var(--${toCssVarToken(o)})`,t[o])});return`url('data:image/svg+xml,${encodeURIComponent(s)}')${e.positionOptions}`}off(){var e,t;null===(e=this.schemaSubscription)||void 0===e||e.off(),null===(t=this.themeSubscription)||void 0===t||t.off()}}
1
+ import{EditorToWidgetEventType}from"../../document-model/DocumentModelService";import ErrorLogger from"../../error/ErrorLogger";import{fromCssVarToSchemaToken,toCssVarToken}from"@claspo/common/theme/theme.utils";export default class ColorSchemaListener{constructor(e,t,o,s,n,r){this.hostElement=t,this.documentModel=e,this.getSharedCb=o,this.getPropsCb=s,this.getEnvCb=n,this.httpClient=r,this.schemaSubscription=null,this.themeSubscription=null,this.envUrlMaps={desktop:new Map,mobile:new Map}}parseBackground(e){const t=String(e||"");if(t.includes("url")){const[e,o]=t.split("(")[1].split(")");return{url:e.replace(/['"]+/g,""),positionOptions:o.replace(";","")}}return{url:null,positionOptions:null}}apply(e){const t=this.getPropsCb();return t.backgroundDynamicInlineSVGElements[e].forEach(o=>{var s,n,r,i,l;const a=null===(n=null===(s=t.adaptiveStyles)||void 0===s?void 0:s[e])||void 0===n?void 0:n.find(e=>e.element===o),c=(null===(r=t.styles)||void 0===r?void 0:r.find(e=>e.element===o))||{},h=(null===(i=null==c?void 0:c.styleAttributes)||void 0===i?void 0:i.background)||(null===(l=null==a?void 0:a.styleAttributes)||void 0===l?void 0:l.background),m=this.parseBackground(h);m.url&&this.envUrlMaps[e].set(o,{originalSVGResourceURL:m.url,inlineSvgString:null,positionOptions:m.positionOptions})}),Promise.all([...this.envUrlMaps[e].entries()].map(([t,o])=>this.httpClient.execute(o.originalSVGResourceURL).then(e=>e.text()).then(s=>{this.envUrlMaps[e].set(t,Object.assign(Object.assign({},o),{inlineSvgString:s}))}))).then(()=>{var t;const o=this.getSharedCb();return Object.keys((null===(t=o.theme)||void 0===t?void 0:t.schema)||{}).length>0?this._applyHostElementBackgroundFromTheme(this.envUrlMaps[e].get("host"),o.theme.schema):this._applyHostElementBackgroundFromCssVars(this.envUrlMaps[e].get("host"),o.cssVars)}).catch(e=>{console.error(e),ErrorLogger.log(`Failed to load/apply backgroundDynamicInlineSVGElements[${this.getPropsCb().backgroundDynamicInlineSVGElements}] ${e}`)})}on(){return this.schemaSubscription=this.documentModel.on(EditorToWidgetEventType.COLOR_SCHEMA_UPDATE,e=>{this._applyHostElementBackgroundFromCssVars(this.envUrlMaps[this.getEnvCb()].get("host"),e)}),this.themeSubscription=this.documentModel.on(EditorToWidgetEventType.THEME_UPDATE,e=>{this._applyHostElementBackgroundFromTheme(this.envUrlMaps[this.getEnvCb()].get("host"),e.schema)}),this}_applyHostElementBackgroundFromCssVars(e,t){e&&t&&(this.hostElement.style.background=this._buildBackgroundUrlFromCssVars(e,t))}_applyHostElementBackgroundFromTheme(e,t){e&&t&&(this.hostElement.style.background=this._buildBackgroundUrlFromTheme(e,t))}_buildBackgroundUrlFromCssVars(e,t){const o=e.inlineSvgString.trim().replace("var(--cl-schema-accent)",t["cl-schema-accent"]);return`url('data:image/svg+xml,${encodeURIComponent(o)}')${e.positionOptions}`}_buildBackgroundUrlFromTheme(e,t){const o=e.inlineSvgString.trim();let s=o;[...o.matchAll(/var\(--cl-schema-([^)]+)\)/g)].forEach(e=>{const o=fromCssVarToSchemaToken(e[1]);s=s.replace(`var(--${toCssVarToken(o)})`,t[o])});return`url('data:image/svg+xml,${encodeURIComponent(s)}')${e.positionOptions}`}off(){var e,t;null===(e=this.schemaSubscription)||void 0===e||e.off(),null===(t=this.themeSubscription)||void 0===t||t.off()}}
@@ -1 +1 @@
1
- import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{DocumentModelUpdateType}from"../../document-model/DocumentModelService";class DefaultMediaQueryListener extends DefaultEventEmitter{constructor(e,i){super(),this.config=i,this.handleMobileBreakpoint(e.getShared().mobileBreakpointWidth),e.on(DocumentModelUpdateType.ENVIRONMENT_UPDATE,({isMobileEnv:e})=>{this._isMobile=e,this.emit(DefaultMediaQueryListener.changeEventName,this._isMobile)})}handleMobileBreakpoint(e){this.mobileBreakpointWidth=e;const i=Number.isInteger(this.mobileBreakpointWidth)?`${this.mobileBreakpointWidth}px`:this.mobileBreakpointWidth;this.mediaQueryList=window.matchMedia(`(max-width: ${i})`),this.mediaQueryList.addListener(this.listener.bind(this)),this._isMobile=this.mediaQueryList.matches,this.emit(DefaultMediaQueryListener.changeEventName,this._isMobile)}isMobile(){return this.config.forceMobileEnv||this._isMobile}listener(e){this._isMobile=e.matches,this.emit(DefaultMediaQueryListener.changeEventName,this._isMobile)}destroy(){super.destroy(),this.mediaQueryList.removeListener(this.listener.bind(this))}}DefaultMediaQueryListener.changeEventName="CHANGE";export default DefaultMediaQueryListener;
1
+ import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{EditorToWidgetEventType}from"../../document-model/DocumentModelService";class DefaultMediaQueryListener extends DefaultEventEmitter{constructor(e,i){super(),this.config=i,this.handleMobileBreakpoint(e.getShared().mobileBreakpointWidth),e.on(EditorToWidgetEventType.ENVIRONMENT_UPDATE,({isMobileEnv:e})=>{this._isMobile=e,this.emit(DefaultMediaQueryListener.changeEventName,this._isMobile)})}handleMobileBreakpoint(e){this.mobileBreakpointWidth=e;const i=Number.isInteger(this.mobileBreakpointWidth)?`${this.mobileBreakpointWidth}px`:this.mobileBreakpointWidth;this.mediaQueryList=window.matchMedia(`(max-width: ${i})`),this.mediaQueryList.addListener(this.listener.bind(this)),this._isMobile=this.mediaQueryList.matches,this.emit(DefaultMediaQueryListener.changeEventName,this._isMobile)}isMobile(){return this.config.forceMobileEnv||this._isMobile}listener(e){this._isMobile=e.matches,this.emit(DefaultMediaQueryListener.changeEventName,this._isMobile)}destroy(){super.destroy(),this.mediaQueryList.removeListener(this.listener.bind(this))}}DefaultMediaQueryListener.changeEventName="CHANGE";export default DefaultMediaQueryListener;
@@ -1 +1 @@
1
- import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{detectOrientation}from"@claspo/common/utils/orientationUtils";import{isIOS}from"@claspo/common/utils/deviceUtils";import{DocumentModelUpdateType}from"../../document-model/DocumentModelService";class MobileDeviceOrientationListener extends DefaultEventEmitter{constructor(e,t){var n;super(),this.documentModel=e,this._orientation=null!==(n=t.config.defaultOrientation)&&void 0!==n?n:detectOrientation(),this.documentModel.on(DocumentModelUpdateType.ENVIRONMENT_UPDATE,e=>{e.orientation&&(this._orientation=e.orientation,this.emit(MobileDeviceOrientationListener.changeEventName,this._orientation))}),this.handleOrientationChangeBound=this.handleOrientationChange.bind(this),this.addOrientationChangeListener()}isPortrait(){return"PORTRAIT"===this._orientation}handleOrientationChange(e){var t,n;this._orientation=null!==(n=null===(t=null==e?void 0:e.detail)||void 0===t?void 0:t.orientation)&&void 0!==n?n:detectOrientation(),this.emit(MobileDeviceOrientationListener.changeEventName,this._orientation)}addOrientationChangeListener(){!isIOS()&&window.screen.orientation?window.screen.orientation.addEventListener("change",this.handleOrientationChangeBound):"orientation"in window&&window.addEventListener("orientationchange",this.handleOrientationChangeBound)}removeOrientationChangeListener(){!isIOS()&&window.screen.orientation?window.screen.orientation.removeEventListener("change",this.handleOrientationChangeBound):"orientation"in window&&window.removeEventListener("orientationchange",this.handleOrientationChangeBound)}destroy(){super.destroy(),this.removeOrientationChangeListener()}}MobileDeviceOrientationListener.changeEventName="CHANGE";export default MobileDeviceOrientationListener;
1
+ import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{detectOrientation}from"@claspo/common/utils/orientationUtils";import{isIOS}from"@claspo/common/utils/deviceUtils";import{EditorToWidgetEventType}from"../../document-model/DocumentModelService";class MobileDeviceOrientationListener extends DefaultEventEmitter{constructor(e,t){var n;super(),this.documentModel=e,this._orientation=null!==(n=t.config.defaultOrientation)&&void 0!==n?n:detectOrientation(),this.documentModel.on(EditorToWidgetEventType.ENVIRONMENT_UPDATE,e=>{e.orientation&&(this._orientation=e.orientation,this.emit(MobileDeviceOrientationListener.changeEventName,this._orientation))}),this.handleOrientationChangeBound=this.handleOrientationChange.bind(this),this.addOrientationChangeListener()}isPortrait(){return"PORTRAIT"===this._orientation}handleOrientationChange(e){var t,n;this._orientation=null!==(n=null===(t=null==e?void 0:e.detail)||void 0===t?void 0:t.orientation)&&void 0!==n?n:detectOrientation(),this.emit(MobileDeviceOrientationListener.changeEventName,this._orientation)}addOrientationChangeListener(){!isIOS()&&window.screen.orientation?window.screen.orientation.addEventListener("change",this.handleOrientationChangeBound):"orientation"in window&&window.addEventListener("orientationchange",this.handleOrientationChangeBound)}removeOrientationChangeListener(){!isIOS()&&window.screen.orientation?window.screen.orientation.removeEventListener("change",this.handleOrientationChangeBound):"orientation"in window&&window.removeEventListener("orientationchange",this.handleOrientationChangeBound)}destroy(){super.destroy(),this.removeOrientationChangeListener()}}MobileDeviceOrientationListener.changeEventName="CHANGE";export default MobileDeviceOrientationListener;
@@ -1 +1 @@
1
- import SysEventTypes from"../common/SysEventTypes";import{ViewRendererActionType}from"../renderer/ViewRendererActionType";export default class ViewResourcesManager{constructor(e){this._onComponentResourcesLoaded=e=>{this.componentResourcesMap.delete(e),this.viewHasPendingResources()||this.systemEventEmitter.emit(ViewRendererActionType.VIEW_COMPONENT_RESOURCES_LOADED)},this.systemEventEmitter=e,this.componentResourcesMap=new Map,this.systemEventEmitter.on(SysEventTypes.COMPONENT_RESOURCES_LOADED,this._onComponentResourcesLoaded)}registerComponent(e,t){this.componentResourcesMap.set(e,t)}viewHasPendingResources(){return[...this.componentResourcesMap.entries()].filter(([e,t])=>t.getPending().count()>0).length>0}}
1
+ import SysEventTypes from"../common/SysEventTypes";import{WidgetToEditorEventType}from"../renderer/WidgetToEditorEventType";export default class ViewResourcesManager{constructor(e){this._onComponentResourcesLoaded=e=>{this.componentResourcesMap.delete(e),this.viewHasPendingResources()||this.systemEventEmitter.emit(WidgetToEditorEventType.VIEW_COMPONENT_RESOURCES_LOADED)},this.systemEventEmitter=e,this.componentResourcesMap=new Map,this.systemEventEmitter.on(SysEventTypes.COMPONENT_RESOURCES_LOADED,this._onComponentResourcesLoaded)}registerComponent(e,t){this.componentResourcesMap.set(e,t)}viewHasPendingResources(){return[...this.componentResourcesMap.entries()].filter(([e,t])=>t.getPending().count()>0).length>0}}
package/sdk/WcElement.js CHANGED
@@ -1 +1 @@
1
- import HandlerFactory from"../handler/HandlerFactory";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import addEventListenerToElement from"@claspo/common/utils/addEventListener";import DefaultState from"../common/DefaultState";import{DocumentModelUpdateType}from"../document-model/DocumentModelService";import DefaultMediaQueryListener from"../renderer/style/DefaultMediaQueryListener";import{applySysAttrPrefix,applySysClassPrefix,RenderConstants}from"../renderer/RenderConstants";import StyleAttributeAccessor from"./accessor/StyleAttributeAccessor";import CommonStylesService from"../renderer/style/CommonStylesService";import ColorSchemaListener from"../renderer/style/ColorSchemaListener";import HttpClient from"@claspo/common/network/HttpClient";import omitKeys from"@claspo/common/object/omitKeys";import{CaseTransformer}from"@claspo/common/utils/CaseTransformer";import ComponentResourceManager from"../resource-management/ComponentResourceManager";import createObservers from"../wc-renderer/observers/createObservers";import observerType from"../wc-renderer/observers/observerType";import createSubscriptions from"../wc-renderer/subscriptions/createSubscriptions";import recursiveFindParentNodeByAttribute from"@claspo/common/element/recursiveFindParentNodeByAttribute";import{getTranslationsMap,getWidgetLanguages}from"./TranslationUtils";import ActionCategory from"../action/actions/ActionCategory";import SysActionTypes from"../action/SysActionTypes";import mergeAdaptiveStylesWithEnvIndependentStyles from"../document-model/MergeAdaptiveStylesWithEnvIndependentStyles";import{applySharedClasses,getAdaptiveStylesForPlatform}from"./ModelStyleUtils";import insertHtmlIntoElement from"@claspo/common/dom/insertHtmlIntoElement";import{PayloadEvent}from"./PayloadEvent";import{RenderMode}from"@claspo/common/RenderMode";import{ViewRendererActionType}from"../renderer/ViewRendererActionType";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(`${DocumentModelUpdateType.COMPONENT_PROPS_UPDATE}_${this.model.id}`,e=>{this.model.props=e,this.observers.get(observerType.PROPS).forEach(t=>t(this.prevProps,e)),this.prevProps=e;const t=this.getHostElement(),s=applySysAttrPrefix("floating");e.floating&&!t.getAttribute(s)?t.setAttribute(s,"true"):!e.floating&&t.getAttribute(s)&&t.removeAttribute(s)}),this.documentModel.on(`${DocumentModelUpdateType.COMPONENT_UPDATE}_${this.model.id}`,e=>{Object.assign(this.model,e)}),this.documentModel.on(DocumentModelUpdateType.SHARED_UPDATE_ALL,()=>{this.applyAutoAdaptiveStyles(this.prevProps.adaptiveStyles,this.prevProps.styles),this.observers.get(observerType.SHARED).forEach(e=>e(this.getShared()))}),this.model.props.backgroundDynamicInlineSVGElements&&(this.colorSchemaListener=new ColorSchemaListener(this.documentModel,this.getHostElement(),()=>this.getShared(),()=>this.model.props,()=>this.getEnvironment(),HttpClient),this.colorSchemaListener.apply(this.getEnvironment()).then(()=>{this.subscriptions.push(this.colorSchemaListener.on())})),this.prevProps.adaptiveStyles&&this.subscriptions.push(this.resizeListener.on(DefaultMediaQueryListener.changeEventName,()=>{this.applyAutoAdaptiveStyles(this.prevProps.adaptiveStyles,this.prevProps.styles);const e=this.getEnvironment();this.observers.get(observerType.ENVIRONMENT).forEach(t=>t(this.prevEnvironment,e)),this.prevEnvironment=e})),this.subscriptions.push(this.services.eventEmitter.on(ViewRendererActionType.GAME_PHASE_READY_TO_PLAY,()=>{this.skipGameBlur||this.getHostElement().classList.add("cl-game-spotlight-component")})),this.subscriptions.push(this.services.eventEmitter.on(ViewRendererActionType.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{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;
@@ -2,6 +2,7 @@ import { SourceUpdateDataI } from '../context/ContextSDK';
2
2
  export interface SubscriptionEntryI {
3
3
  subscribe(cb: (data: SourceUpdateDataI) => void): void;
4
4
  getValue(key?: string): any;
5
+ getSessionHistory?(): string[];
5
6
  }
6
7
  export interface SourceConfigI {
7
8
  [key: string]: any;
@@ -14,5 +15,6 @@ export default class Source {
14
15
  constructor(id: string, subscriptionEntry: SubscriptionEntryI, config?: SourceConfigI);
15
16
  subscribe(cb: (data: SourceUpdateDataI) => void): void;
16
17
  getValue(key?: string): any;
18
+ getSessionHistory(): string[];
17
19
  isSubscribed(): boolean;
18
20
  }
@@ -1 +1 @@
1
- export default class Source{constructor(s,i,t={}){this.id=s,this.subscriptionEntry=i,this.config=t,this.subscribed=!1}subscribe(s){this.subscribed=!0,this.subscriptionEntry.subscribe(s)}getValue(s){return this.subscriptionEntry.getValue(s)}isSubscribed(){return this.subscribed}}
1
+ export default class Source{constructor(s,i,t={}){this.id=s,this.subscriptionEntry=i,this.config=t,this.subscribed=!1}subscribe(s){this.subscribed=!0,this.subscriptionEntry.subscribe(s)}getValue(s){return this.subscriptionEntry.getValue(s)}getSessionHistory(){var s,i;return(null===(i=(s=this.subscriptionEntry).getSessionHistory)||void 0===i?void 0:i.call(s))||[new URL(window.location.href).search]}isSubscribed(){return this.subscribed}}
@@ -20,6 +20,7 @@ export default class UrlQueryParamsSource extends DefaultEventEmitter {
20
20
  config: UrlQueryParamsConfigI;
21
21
  constructor(config?: UrlQueryParamsConfigI);
22
22
  subscribe(cb: (data: SourceUpdateDataI) => void): void;
23
+ getSessionHistory(): string[];
23
24
  getValue(key?: string): UrlQueryParamsProcessorResultI | Record<string, never>;
24
25
  static processModel(model: UrlQueryParamsModelI, sessionUrlSearchParams?: string[]): string;
25
26
  }
@@ -1 +1 @@
1
- import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";class UrlQueryParamsSource extends DefaultEventEmitter{constructor(e={}){super(),this.config=e}subscribe(e){}getValue(e){return e?{processor:(e,r)=>UrlQueryParamsSource.processModel(r,this.config.sessionUrlSearchParams)}:{}}static processModel(e,r){if(!e.arguments)return"";const t=e.arguments.find(e=>"urlQueryParamName"===e.name);if(!r){r=[new URL(window.location.href).search]}if(!t||!t.value)return"";let a;for(let e=r.length-1;e>=0;e--){const s=new URLSearchParams(r[e]).getAll(t.value).filter(Boolean);if(s.length){a=s;break}}return a?a.join(", "):""}}UrlQueryParamsSource.sourceId="URL_QUERY_PARAMS";export default UrlQueryParamsSource;
1
+ import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";class UrlQueryParamsSource extends DefaultEventEmitter{constructor(e={}){super(),this.config=e}subscribe(e){}getSessionHistory(){return this.config.sessionUrlSearchParams||[new URL(window.location.href).search]}getValue(e){return e?{processor:(e,r)=>UrlQueryParamsSource.processModel(r,this.getSessionHistory())}:{}}static processModel(e,r){if(r||(r=[new URL(window.location.href).search]),!e.arguments)return"";const t=e.arguments.find(e=>"urlQueryParamName"===e.name);if(!t||!t.value)return"";let s;for(let e=r.length-1;e>=0;e--){const o=new URLSearchParams(r[e]).getAll(t.value).filter(Boolean);if(o.length){s=o;break}}return s?s.join(", "):""}}UrlQueryParamsSource.sourceId="URL_QUERY_PARAMS";export default UrlQueryParamsSource;
package/sdk.d.ts CHANGED
@@ -4,8 +4,8 @@ import CompositionRoot from "./CompositionRoot";
4
4
  import ViewRouter from "./ViewRouter";
5
5
  import ViewEntryType from "./document-model/ViewEntryType";
6
6
  import ComponentType from './sdk/ComponentType';
7
- import { DocumentModelUpdateType } from "./document-model/DocumentModelService";
7
+ import { EditorToWidgetEventType } from "./document-model/DocumentModelService";
8
8
  import { RenderConstants } from "./renderer/RenderConstants";
9
- import { ViewRendererActionType } from "./renderer/ViewRendererActionType";
9
+ import { WidgetToEditorEventType } from "./renderer/WidgetToEditorEventType";
10
10
  import { LoopAnimationStylesService } from "./renderer/style/LoopAnimationStylesService";
11
- export { UpdatingEntryModule, StaticEntryModule, ViewRouter, CompositionRoot, ComponentType, ViewEntryType, DocumentModelUpdateType, RenderConstants, ViewRendererActionType, LoopAnimationStylesService };
11
+ export { UpdatingEntryModule, StaticEntryModule, ViewRouter, CompositionRoot, ComponentType, ViewEntryType, EditorToWidgetEventType, RenderConstants, WidgetToEditorEventType, LoopAnimationStylesService };
package/sdk.js CHANGED
@@ -1 +1 @@
1
- import UpdatingEntryModule from"./UpdatingEntryModule";import StaticEntryModule from"./StaticEntryModule";import CompositionRoot from"./CompositionRoot";import ViewRouter from"./ViewRouter";import ViewEntryType from"./document-model/ViewEntryType";import ComponentType from"./sdk/ComponentType";import{DocumentModelUpdateType}from"./document-model/DocumentModelService";import{RenderConstants}from"./renderer/RenderConstants";import{ViewRendererActionType}from"./renderer/ViewRendererActionType";import{LoopAnimationStylesService}from"./renderer/style/LoopAnimationStylesService";export{UpdatingEntryModule,StaticEntryModule,ViewRouter,CompositionRoot,ComponentType,ViewEntryType,DocumentModelUpdateType,RenderConstants,ViewRendererActionType,LoopAnimationStylesService};
1
+ import UpdatingEntryModule from"./UpdatingEntryModule";import StaticEntryModule from"./StaticEntryModule";import CompositionRoot from"./CompositionRoot";import ViewRouter from"./ViewRouter";import ViewEntryType from"./document-model/ViewEntryType";import ComponentType from"./sdk/ComponentType";import{EditorToWidgetEventType}from"./document-model/DocumentModelService";import{RenderConstants}from"./renderer/RenderConstants";import{WidgetToEditorEventType}from"./renderer/WidgetToEditorEventType";import{LoopAnimationStylesService}from"./renderer/style/LoopAnimationStylesService";export{UpdatingEntryModule,StaticEntryModule,ViewRouter,CompositionRoot,ComponentType,ViewEntryType,EditorToWidgetEventType,RenderConstants,WidgetToEditorEventType,LoopAnimationStylesService};
@@ -15,7 +15,6 @@ export default class WcResolver {
15
15
  private productKeyPrefix;
16
16
  renderMode: RenderMode;
17
17
  wcRegister: WcRegister;
18
- presentComponentManifests: ComponentManifestI[];
19
18
  constructor(renderMode: RenderMode, wcRegister: WcRegister, productKeyPrefix?: string);
20
19
  getComponentManifests(): ComponentManifestI[];
21
20
  getAllComponents(): (CustomElementConstructor | undefined)[];
@@ -1 +1 @@
1
- import DocumentUtils from"@claspo/common/document/DocumentUtils";import{RenderMode}from"@claspo/common/RenderMode";export default class WcResolver{constructor(e=RenderMode.STATIC,t,o="cl"){this.productKeyPrefix=o,this.renderMode=e,this.wcRegister=t,this.presentComponentManifests=[]}getComponentManifests(){return this.getAllComponents().map(e=>{var t;return null===(t=e.define)||void 0===t?void 0:t.manifest}).filter(e=>!!e)}getAllComponents(){return Object.values(this.wcRegister.modelNameToTagMap).map(e=>this.wcRegister.getComponentTagName(e,this.renderMode)).map(e=>customElements.get(e)).filter(e=>!!e)}async loadComponentsIfNecessary(e,t){const o=new Set;e.views.forEach(e=>{DocumentUtils.iterateDepthFirst(e,e=>{o.add(e.name)})});const n=this.getComponentManifests(),s=n.map(e=>e.name),i=[...o].filter(e=>!s.includes(e));return i.length?(await this.loadComponents(i,t),this.presentComponentManifests=this.getComponentManifests(),{manifests:this.presentComponentManifests}):{manifests:n}}async loadComponents(e,t){const o=this.getComponentNamesToLoad(e),n=this.buildComponentFilePaths(o,t);await this.loadComponentClasses(n,o)}getComponentNamesToLoad(e){return e||[]}buildComponentFilePaths(e,t){return e.map(e=>`${t.replace(/\/$/,"")}/${e}/${e}.js`)}loadComponentClasses(e,t){return Promise.all(e.map((e,o)=>new Promise((n,s)=>{const i=t[o],r=`${this.productKeyPrefix}_${this.getWindowKeyForComponentClass(i)}`;if(window[r])this.wcRegister.registerComponent(window[r],this.renderMode),n(window[r]);else{const t=document.createElement("script");t.type="module",t.onload=()=>{const e=window[this.getWindowKeyForComponentClass(i)];window[r]=e,this.wcRegister.registerComponent(e,this.renderMode),n(e)},t.onerror=s,t.src=e,document.body.appendChild(t)}})))}getWindowKeyForComponentClass(e){return`clComponentClass_${e}`}}
1
+ import DocumentUtils from"@claspo/common/document/DocumentUtils";import{RenderMode}from"@claspo/common/RenderMode";export default class WcResolver{constructor(e=RenderMode.STATIC,t,o="cl"){this.productKeyPrefix=o,this.renderMode=e,this.wcRegister=t}getComponentManifests(){return this.getAllComponents().map(e=>{var t;return null===(t=e.define)||void 0===t?void 0:t.manifest}).filter(e=>!!e)}getAllComponents(){return Object.values(this.wcRegister.modelNameToTagMap).map(e=>this.wcRegister.getComponentTagName(e,this.renderMode)).map(e=>customElements.get(e)).filter(e=>!!e)}async loadComponentsIfNecessary(e,t){const o=new Set;e.views.forEach(e=>{DocumentUtils.iterateDepthFirst(e,e=>{o.add(e.name)})});const n=this.getComponentManifests(),s=n.map(e=>e.name),i=[...o].filter(e=>!s.includes(e));return i.length?(await this.loadComponents(i,t),{manifests:this.getComponentManifests()}):{manifests:n}}async loadComponents(e,t){const o=this.getComponentNamesToLoad(e),n=this.buildComponentFilePaths(o,t);await this.loadComponentClasses(n,o)}getComponentNamesToLoad(e){return e||[]}buildComponentFilePaths(e,t){return e.map(e=>`${t.replace(/\/$/,"")}/${e}/${e}.js`)}loadComponentClasses(e,t){return Promise.all(e.map((e,o)=>new Promise((n,s)=>{const i=t[o],r=`${this.productKeyPrefix}_${this.getWindowKeyForComponentClass(i)}`;if(window[r])this.wcRegister.registerComponent(window[r],this.renderMode),n(window[r]);else{const t=document.createElement("script");t.type="module",t.onload=()=>{const e=window[this.getWindowKeyForComponentClass(i)];window[r]=e,this.wcRegister.registerComponent(e,this.renderMode),n(e)},t.onerror=s,t.src=e,document.body.appendChild(t)}})))}getWindowKeyForComponentClass(e){return`clComponentClass_${e}`}}
@@ -1 +1 @@
1
- import{ComponentInsertType}from"@claspo/common/document/ComponentInsertType";import ViewEntryType from"../document-model/ViewEntryType";import{ViewRendererActionType}from"../renderer/ViewRendererActionType";import{applySysAttrPrefix}from"../renderer/RenderConstants";import ViewResourcesManager from"../resource-management/ViewResourcesManager";import{RenderMode}from"@claspo/common/RenderMode";export default class WcViewRenderer{constructor(e,t,n,o,r){this.isMobile=null,this.resizeListener=t,this.documentModel=e,this.factory=o,this.eventEmitter=r,this.viewResourceManager=new ViewResourcesManager(this.eventEmitter),this.destroy=this.destroy.bind(this)}render(e,t,n=RenderMode.STATIC){const o=this.factory.create(e,n,this.viewResourceManager);if(this.documentModel.setComponentRef(e.id,o),e.componentRef=o,e.type===ViewEntryType.VIEW&&"SysColumnsComponent"===e.name){const t=applySysAttrPrefix("content-container"),n=this.getRenderOutlet(e.componentRef.getRootElement());null==n||n.setAttribute(t,"")}return e.children.forEach(t=>{this.renderComponent(e,t,n)}),setTimeout(()=>{this.viewResourceManager.viewHasPendingResources()||this.eventEmitter.emit(ViewRendererActionType.VIEW_COMPONENT_RESOURCES_LOADED)},5),o}destroy(e){var t;if(!(null===(t=e.model)||void 0===t?void 0:t.path))return;const n=e.model.path[0];this.documentModel.destroyView(n)}renderComponent(e,t,n,o=ComponentInsertType.INSIDE){var r;const i=this.factory.create(t,n,this.viewResourceManager);this.documentModel.setComponentRef(t.id,i);const s=e.componentRef.getRootElement();let c=t.props.floating||"FLOATING_IMAGE"===t.type?s:this.selectElementToAppendTo(e.componentRef.contentContainer)||this.selectElementToAppendTo(s);if(o===ComponentInsertType.INSIDE)i.connect(o,c,i);else if(o===ComponentInsertType.INSTEAD){const n=(null===(r=t.prevPath)||void 0===r?void 0:r.at(-1))<t.path.at(-1)?ComponentInsertType.AFTER:ComponentInsertType.BEFORE;i.connect(n,e.componentRef,t.componentRef)}else i.connect(o,e.componentRef,t.componentRef);return t.children&&t.children.forEach(e=>this.renderComponent(t,e,n)),t}selectElementToAppendTo(e){return e?this.getRenderOutlet(e)||e:null}getRenderOutlet(e){return e.querySelector(`[${applySysAttrPrefix("render-outlet")}]`)}}
1
+ import{ComponentInsertType}from"@claspo/common/document/ComponentInsertType";import ViewEntryType from"../document-model/ViewEntryType";import{WidgetToEditorEventType}from"../renderer/WidgetToEditorEventType";import{applySysAttrPrefix}from"../renderer/RenderConstants";import ViewResourcesManager from"../resource-management/ViewResourcesManager";import{RenderMode}from"@claspo/common/RenderMode";export default class WcViewRenderer{constructor(e,t,n,o,r){this.isMobile=null,this.resizeListener=t,this.documentModel=e,this.factory=o,this.eventEmitter=r,this.viewResourceManager=new ViewResourcesManager(this.eventEmitter),this.destroy=this.destroy.bind(this)}render(e,t,n=RenderMode.STATIC){const o=this.factory.create(e,n,this.viewResourceManager);if(this.documentModel.setComponentRef(e.id,o),e.componentRef=o,e.type===ViewEntryType.VIEW&&"SysColumnsComponent"===e.name){const t=applySysAttrPrefix("content-container"),n=this.getRenderOutlet(e.componentRef.getRootElement());null==n||n.setAttribute(t,"")}return e.children.forEach(t=>{this.renderComponent(e,t,n)}),setTimeout(()=>{this.viewResourceManager.viewHasPendingResources()||this.eventEmitter.emit(WidgetToEditorEventType.VIEW_COMPONENT_RESOURCES_LOADED)},5),o}destroy(e){var t;if(!(null===(t=e.model)||void 0===t?void 0:t.path))return;const n=e.model.path[0];this.documentModel.destroyView(n)}renderComponent(e,t,n,o=ComponentInsertType.INSIDE){var r;const i=this.factory.create(t,n,this.viewResourceManager);this.documentModel.setComponentRef(t.id,i);const s=e.componentRef.getRootElement();let p=t.props.floating||"FLOATING_IMAGE"===t.type?s:this.selectElementToAppendTo(e.componentRef.contentContainer)||this.selectElementToAppendTo(s);if(o===ComponentInsertType.INSIDE)i.connect(o,p,i);else if(o===ComponentInsertType.INSTEAD){const n=(null===(r=t.prevPath)||void 0===r?void 0:r.at(-1))<t.path.at(-1)?ComponentInsertType.AFTER:ComponentInsertType.BEFORE;i.connect(n,e.componentRef,t.componentRef)}else i.connect(o,e.componentRef,t.componentRef);return t.children&&t.children.forEach(e=>this.renderComponent(t,e,n)),t}selectElementToAppendTo(e){return e?this.getRenderOutlet(e)||e:null}getRenderOutlet(e){return e.querySelector(`[${applySysAttrPrefix("render-outlet")}]`)}}
@@ -1 +1 @@
1
- import ViewEntryType from"../../document-model/ViewEntryType";import{ViewRendererActionType}from"../../renderer/ViewRendererActionType";import ComponentType from"../../sdk/ComponentType";import{applySysAttrPrefix,applySysClassPrefix}from"../../renderer/RenderConstants";import getParentHostElement from"../../sdk/getParentHostElement";import debounce from"@claspo/common/async/debounce";import wcStaticDecorator from"./wcStaticDecorator";export default function wcUpdatingDecorator(e){return class extends(wcStaticDecorator(e)){constructor(){super(),this.eventListeners=[],this.lastDragOverEvent=null,this.focusedElements=[],this.observer=null,this._observeChanges()}connectedCallback(){super.connectedCallback(),this._addAllListeners()}disconnectedCallback(){var e,t,s;super.disconnectedCallback(),this._deactivateEventListeners(),null===(e=this.removeFocusSubscription)||void 0===e||e.off(),null===(t=this.setFocusSubscription)||void 0===t||t.off(),null===(s=this.componentFocusedSubscription)||void 0===s||s.off(),this.observer.disconnect()}_addAllListeners(){this.observer.observe(this.getRootElement(),{childList:!0,subtree:!0}),this.model.type===ViewEntryType.VIEW&&(this.eventListeners.push({eventName:"mousemove",callback:this._mouseMoveEventListener.bind(this),element:this}),this.eventListeners.push({eventName:"mouseout",callback:this._mouseOutEventListener.bind(this),element:this})),this.removeFocusSubscription=this.services.eventEmitter.on(ViewRendererActionType.REMOVE_FOCUS,()=>{this._removeFocus()}),this.setFocusSubscription=this.services.eventEmitter.on(ViewRendererActionType.SET_FOCUS,e=>{this._removeFocus(),this.model.id===e&&this._setFocus("host")}),this.componentFocusedSubscription=this.services.eventEmitter.on(ViewRendererActionType.COMPONENT_FOCUSED,({id:e,targetElementName:t})=>{this._removeFocus(),this.model.id===e&&this._setFocus(t)}),this.manifest.preventDraggable||this.getHostElement().setAttribute("draggable","true"),this._setElementListeners(this.getHostElement()),this._setGlobalListeners(),this._setEventListeners(),this._activateEventListeners(),this._setFocusableElementsAttribute()}_observeChanges(){let e={addded:!1,removed:!1};const t=debounce(()=>{e.removed&&this._removeListenersForDisconnectedNodes(),e.addded&&(this._setEventListeners(),this._activateEventListeners(),this._setFocusableElementsAttribute(),this._updateFocusedElementClasses()),e={addded:!1,removed:!1}},500);this.observer=new MutationObserver(function(s){for(let i of s){for(let t of i.addedNodes)t instanceof HTMLElement&&"STYLE"!==t.nodeName&&!e.addded&&(e=Object.assign(Object.assign({},e),{addded:!0}));for(let t of i.removedNodes)t instanceof HTMLElement&&"STYLE"!==t.nodeName&&!e.removed&&(e=Object.assign(Object.assign({},e),{removed:!0}));t()}})}_setEventListeners(){this.getRootElement().querySelectorAll("[cl-inline-edit], [cl-inline-edit] *").forEach(e=>{this._isEventListenerPresent(e)||"STYLE"!==e.tagName&&(e.getAttribute("draggable")||e.setAttribute("draggable","true"),this._setElementListeners(e,!0))}),this.getRootElement().querySelectorAll(":not([cl-inline-edit]):not([cl-type]):not([cl-inline-edit] *)").forEach(e=>{if(!this._isEventListenerPresent(e)&&"STYLE"!==e.tagName){if(e.getAttribute("draggable")||e.setAttribute("draggable","true"),e instanceof HTMLElement){const t=e.tagName.toLowerCase();"input"!==t&&"textarea"!==t||"readonly"===!e.getAttribute("readonly")||e.setAttribute("readonly","readonly"),this.manifest.componentType===ComponentType.VIDEO&&e.classList.contains("video-overlay")&&(e.style.visibility="visible")}this._setElementListeners(e)}})}_removeListenersForDisconnectedNodes(){this.eventListeners=this.eventListeners.filter(e=>(e.element.isConnected||e.element.removeEventListener(e.eventName,e.callback),e.element.isConnected))}_setGlobalListeners(){this.eventListeners.push({eventName:"drop",callback:e=>this._documentDropListener(e),element:document})}_isEventListenerPresent(e){return!!this.eventListeners.find(t=>t.element===e)}_setElementListeners(e,t){[{eventName:"click",callback:e=>this._elementClickListener(e,t),element:e},{eventName:"dblclick",callback:this._elementDoubleClickListener.bind(this),element:e},{eventName:"dragstart",callback:this._elementDragStartListener.bind(this),element:e},{eventName:"dragend",callback:this._elementDragEndListener.bind(this),element:e},{eventName:"dragover",callback:this._elementDragOverListener.bind(this),element:e},{eventName:"blur",callback:this._blurEventListener.bind(this),element:e,useCapture:!0}].forEach(e=>this.eventListeners.push(e))}_elementClickListener(e,t){e.preventDefault(),e.stopImmediatePropagation();const s=e.composedPath()[0],i=this.getHostElement();if(t&&this.services.eventEmitter.emit(ViewRendererActionType.SHOW_INLINE_EDIT,{id:this.model.id,hostElement:i,targetElement:s}),this.model.focusParentOnClick){const e=getParentHostElement(i);this.services.eventEmitter.emit(ViewRendererActionType.COMPONENT_FOCUSED,{id:e.getAttribute(applySysAttrPrefix("id")),hostElement:e,targetElement:e,targetElementName:"host"})}else this.services.eventEmitter.emit(ViewRendererActionType.COMPONENT_FOCUSED,{id:this.model.id,hostElement:i,targetElement:s,targetElementName:this._getElementNameByNode(s)});this.services.eventEmitter.emit(ViewRendererActionType.COMPONENT_CLICKED,e)}_elementDoubleClickListener(e){e.preventDefault(),e.stopImmediatePropagation(),this.services.eventEmitter.emit(ViewRendererActionType.COMPONENT_DOUBLE_CLICKED,{id:this.model.id,hostElement:this.getHostElement(),targetElement:e.composedPath()[0]})}_elementDragStartListener(e){e.stopPropagation();const t=e.composedPath().find(e=>{var t;return null===(t=e.hasAttribute)||void 0===t?void 0:t.call(e,applySysAttrPrefix("type"))}),s=t.getAttribute(applySysAttrPrefix("type"));this.services.eventEmitter.emit(ViewRendererActionType.COMPONENT_DRAGSTART,{id:this.model.id,path:this.model.path,hostElement:this.getHostElement(),targetElement:e.composedPath()[0],event:e,checkIfAllowed:i=>{if(i){const i=t.getBoundingClientRect();if(this._isWidgetRotated(this.documentModel.getShared(),!this.resizeListener.isMobile())){const s=e.pageX-i.left-window.pageXOffset,n=e.pageY-i.top-window.pageYOffset;if(navigator.userAgent.match(/Firefox/i)){const i=t.style.transform,r=t.style.transformOrigin;t.style.transform="rotate(-90deg)",t.style.transformOrigin="left top",e.dataTransfer.setDragImage(t,s,n),requestAnimationFrame(()=>{t.style.transform=i,t.style.transformOrigin=r})}else{const t=this._createDragPreviewPlaceholder(i);document.body.appendChild(t),e.dataTransfer.setDragImage(t,s,n),setTimeout(()=>{t.remove()})}}else e.dataTransfer.setDragImage(t,e.pageX-i.left-window.pageXOffset,e.pageY-i.top-window.pageYOffset);if(s===ViewEntryType.SLIDER){const s=t.shadowRoot.querySelector(".slides-container"),n=new WebKitCSSMatrix(getComputedStyle(s).transform).m41;e.dataTransfer.setDragImage(t,e.pageX-i.left-n-window.pageXOffset,e.pageY-i.top-window.pageYOffset)}}else e.preventDefault(),this.services.eventEmitter.emit(ViewRendererActionType.COMPONENT_DRAGEND)}})}_createDragPreviewPlaceholder(e){const t=document.createElement("div");return t.style.width=`${e.width}px`,t.style.height=`${e.height}px`,t.style.background="rgba(159, 41, 176, 0.3)",t.style.display="flex",t.style.justifyContent="center",t.style.alignItems="center",t.innerHTML='<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">\n<g opacity="0.6" clip-path="url(#clip0_43446_120564)">\n<path d="M26.5566 11.7573L30.7993 16L26.5566 20.2426" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M20.2422 26.5564L15.9995 30.799L11.7569 26.5564" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M5.44336 20.2426L1.20072 16L5.44336 11.7573" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M11.7569 5.4436L15.9995 1.20096L20.2422 5.4436" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M30.7994 16H20.8999" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M15.9995 30.7989L15.9995 20.8994" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M1.20064 16H11.1001" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M15.9995 1.20113L15.9995 11.1006" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n</g>\n<defs>\n<clipPath id="clip0_43446_120564">\n<rect width="32" height="32" fill="white"/>\n</clipPath>\n</defs>\n</svg>',t.firstChild.style.width=.4*e.width+"px",t.firstChild.style.height=.4*e.height+"px",t}_isWidgetRotated(e,t){const s=this._getFloatingBoxParams(e,t);return!!s&&"CENTER"===s.verticalPosition}_getFloatingBoxParams(e,t){return e&&e.floatingBox?t?e.floatingBox:e.floatingBox.mobile:null}_elementDragEndListener(e){e.stopPropagation(),this.services.eventEmitter.emit(ViewRendererActionType.COMPONENT_DRAGEND,{id:this.model.id,path:this.model.path,hostElement:this.getHostElement(),targetElement:e.composedPath()[0],event:e})}_elementDragOverListener(e){e.preventDefault(),e.stopPropagation();const t=this.lastDragOverEvent;this.lastDragOverEvent=e,e.pageX&&e.pageY&&(t&&t.clientY===e.clientY&&t.clientX===e.clientX||this.services.eventEmitter.emit(ViewRendererActionType.COMPONENT_DRAGOVER,{id:this.model.id,hostElement:this.getHostElement(),targetElement:e.composedPath()[0],event:e}))}_documentDropListener(e){this.services.eventEmitter.emit(ViewRendererActionType.DOCUMENT_DROP,{id:this.model.id,hostElement:this.getHostElement(),targetElement:e.composedPath()[0],event:e})}_mouseMoveEventListener(e){const t=this._findClosestHostElement(e.composedPath());if(this.preHoveredElement&&this.preHoveredElement!==t&&this.preHoveredElement.classList.remove(applySysClassPrefix("hovered")),this.preHoveredElement=t,t){t.classList.add(applySysClassPrefix("hovered"));const s={id:t.getAttribute(applySysAttrPrefix("id")),hostElement:t,targetElement:e.composedPath()[0],event:e};this.services.eventEmitter.emit(ViewRendererActionType.COMPONENT_MOUSE_MOVE,s)}}_mouseOutEventListener(e){e.stopPropagation();const t=this._findClosestHostElement(e.composedPath());t&&t.classList.remove(applySysClassPrefix("hovered"))}_blurEventListener(e){e.stopImmediatePropagation()}_removeFocus(){this.focusedElements.length&&this.focusedElements.forEach(e=>{var t;return null===(t=e.classList)||void 0===t?void 0:t.remove(applySysClassPrefix("focused"))}),this.focusedElements=[]}_setFocus(e){const t=this.getHostElement();if(this.focusedElements=[t],t.classList.add(applySysClassPrefix("focused")),"host"!==e){const t=this.getElements().filter(t=>t.getAttribute(applySysAttrPrefix("element"))===e);t.forEach(e=>e.classList.add(applySysClassPrefix("focused"))),this.focusedElements=this.focusedElements.concat(t)}}_findClosestHostElement(e){const t=e.filter(e=>e instanceof HTMLElement).filter(e=>!!e.getAttribute(applySysAttrPrefix("component")));return t.length?t[0]:null}_activateEventListeners(){this.eventListeners.forEach(e=>{e.activated||(e.element.addEventListener(e.eventName,e.callback,e.useCapture),e.activated=!0)})}_deactivateEventListeners(){this.eventListeners.forEach(e=>{e.element.removeEventListener(e.eventName,e.callback)}),this.eventListeners=[]}_getElementNameByNode(e){var t;const s="host";if(!e)return s;const i=e.closest(`[${applySysAttrPrefix("element")}]`);if(!i)return s;const n=i.getAttribute(applySysAttrPrefix("element"));return"host"===n||(null===(t=this.manifest.focusableElements)||void 0===t?void 0:t.includes(n))?n:s}_setFocusableElementsAttribute(){this.getElements().forEach(e=>{var t;(null===(t=this.manifest.focusableElements)||void 0===t?void 0:t.includes(e.getAttribute(applySysAttrPrefix("element"))))&&e.setAttribute(applySysAttrPrefix("focusable-element"),"")})}_updateFocusedElementClasses(){if(this.focusedElements.length<2)return;const e=this.focusedElements.find(e=>e.hasAttribute(applySysAttrPrefix("focusable-element")));e&&this._setFocus(e.getAttribute(applySysAttrPrefix("element")))}}}
1
+ import ViewEntryType from"../../document-model/ViewEntryType";import{WidgetToEditorEventType}from"../../renderer/WidgetToEditorEventType";import ComponentType from"../../sdk/ComponentType";import{applySysAttrPrefix,applySysClassPrefix}from"../../renderer/RenderConstants";import getParentHostElement from"../../sdk/getParentHostElement";import debounce from"@claspo/common/async/debounce";import wcStaticDecorator from"./wcStaticDecorator";import{EditorToWidgetEventType}from"../../document-model/DocumentModelService";export default function wcUpdatingDecorator(e){return class extends(wcStaticDecorator(e)){constructor(){super(),this.eventListeners=[],this.lastDragOverEvent=null,this.focusedElements=[],this.observer=null,this._observeChanges()}connectedCallback(){super.connectedCallback(),this._addAllListeners()}disconnectedCallback(){var e,t,s;super.disconnectedCallback(),this._deactivateEventListeners(),null===(e=this.removeFocusSubscription)||void 0===e||e.off(),null===(t=this.setFocusSubscription)||void 0===t||t.off(),null===(s=this.componentFocusedSubscription)||void 0===s||s.off(),this.observer.disconnect()}_addAllListeners(){this.observer.observe(this.getRootElement(),{childList:!0,subtree:!0}),this.model.type===ViewEntryType.VIEW&&(this.eventListeners.push({eventName:"mousemove",callback:this._mouseMoveEventListener.bind(this),element:this}),this.eventListeners.push({eventName:"mouseout",callback:this._mouseOutEventListener.bind(this),element:this})),this.removeFocusSubscription=this.services.eventEmitter.on(EditorToWidgetEventType.REMOVE_FOCUS,()=>{this._removeFocus()}),this.setFocusSubscription=this.services.eventEmitter.on(EditorToWidgetEventType.SET_FOCUS,e=>{this._removeFocus(),this.model.id===e&&this._setFocus("host")}),this.componentFocusedSubscription=this.services.eventEmitter.on(WidgetToEditorEventType.COMPONENT_FOCUSED,({id:e,targetElementName:t})=>{this._removeFocus(),this.model.id===e&&this._setFocus(t)}),this.manifest.preventDraggable||this.getHostElement().setAttribute("draggable","true"),this._setElementListeners(this.getHostElement()),this._setGlobalListeners(),this._setEventListeners(),this._activateEventListeners(),this._setFocusableElementsAttribute()}_observeChanges(){let e={addded:!1,removed:!1};const t=debounce(()=>{e.removed&&this._removeListenersForDisconnectedNodes(),e.addded&&(this._setEventListeners(),this._activateEventListeners(),this._setFocusableElementsAttribute(),this._updateFocusedElementClasses()),e={addded:!1,removed:!1}},500);this.observer=new MutationObserver(function(s){for(let i of s){for(let t of i.addedNodes)t instanceof HTMLElement&&"STYLE"!==t.nodeName&&!e.addded&&(e=Object.assign(Object.assign({},e),{addded:!0}));for(let t of i.removedNodes)t instanceof HTMLElement&&"STYLE"!==t.nodeName&&!e.removed&&(e=Object.assign(Object.assign({},e),{removed:!0}));t()}})}_setEventListeners(){this.getRootElement().querySelectorAll("[cl-inline-edit], [cl-inline-edit] *").forEach(e=>{this._isEventListenerPresent(e)||"STYLE"!==e.tagName&&(e.getAttribute("draggable")||e.setAttribute("draggable","true"),this._setElementListeners(e,!0))}),this.getRootElement().querySelectorAll(":not([cl-inline-edit]):not([cl-type]):not([cl-inline-edit] *)").forEach(e=>{if(!this._isEventListenerPresent(e)&&"STYLE"!==e.tagName){if(e.getAttribute("draggable")||e.setAttribute("draggable","true"),e instanceof HTMLElement){const t=e.tagName.toLowerCase();"input"!==t&&"textarea"!==t||"readonly"===!e.getAttribute("readonly")||e.setAttribute("readonly","readonly"),this.manifest.componentType===ComponentType.VIDEO&&e.classList.contains("video-overlay")&&(e.style.visibility="visible")}this._setElementListeners(e)}})}_removeListenersForDisconnectedNodes(){this.eventListeners=this.eventListeners.filter(e=>(e.element.isConnected||e.element.removeEventListener(e.eventName,e.callback),e.element.isConnected))}_setGlobalListeners(){this.eventListeners.push({eventName:"drop",callback:e=>this._documentDropListener(e),element:document})}_isEventListenerPresent(e){return!!this.eventListeners.find(t=>t.element===e)}_setElementListeners(e,t){[{eventName:"click",callback:e=>this._elementClickListener(e,t),element:e},{eventName:"dblclick",callback:this._elementDoubleClickListener.bind(this),element:e},{eventName:"dragstart",callback:this._elementDragStartListener.bind(this),element:e},{eventName:"dragend",callback:this._elementDragEndListener.bind(this),element:e},{eventName:"dragover",callback:this._elementDragOverListener.bind(this),element:e},{eventName:"blur",callback:this._blurEventListener.bind(this),element:e,useCapture:!0}].forEach(e=>this.eventListeners.push(e))}_elementClickListener(e,t){e.preventDefault(),e.stopImmediatePropagation();const s=e.composedPath()[0],i=this.getHostElement();if(t&&this.services.eventEmitter.emit(WidgetToEditorEventType.SHOW_INLINE_EDIT,{id:this.model.id,hostElement:i,targetElement:s}),this.model.focusParentOnClick){const e=getParentHostElement(i);this.services.eventEmitter.emit(WidgetToEditorEventType.COMPONENT_FOCUSED,{id:e.getAttribute(applySysAttrPrefix("id")),hostElement:e,targetElement:e,targetElementName:"host"})}else{const e=this.focusedElements.length>0,t=e?this._getElementNameByNode(s):"host";this.services.eventEmitter.emit(WidgetToEditorEventType.COMPONENT_FOCUSED,{id:this.model.id,hostElement:i,targetElement:e?s:i,targetElementName:t})}this.services.eventEmitter.emit(WidgetToEditorEventType.COMPONENT_CLICKED,e)}_elementDoubleClickListener(e){e.preventDefault(),e.stopImmediatePropagation(),this.services.eventEmitter.emit(WidgetToEditorEventType.COMPONENT_DOUBLE_CLICKED,{id:this.model.id,hostElement:this.getHostElement(),targetElement:e.composedPath()[0]})}_elementDragStartListener(e){e.stopPropagation();const t=e.composedPath().find(e=>{var t;return null===(t=e.hasAttribute)||void 0===t?void 0:t.call(e,applySysAttrPrefix("type"))}),s=t.getAttribute(applySysAttrPrefix("type"));this.services.eventEmitter.emit(WidgetToEditorEventType.COMPONENT_DRAGSTART,{id:this.model.id,path:this.model.path,hostElement:this.getHostElement(),targetElement:e.composedPath()[0],event:e,checkIfAllowed:i=>{if(i){const i=t.getBoundingClientRect();if(this._isWidgetRotated(this.documentModel.getShared(),!this.resizeListener.isMobile())){const s=e.pageX-i.left-window.pageXOffset,n=e.pageY-i.top-window.pageYOffset;if(navigator.userAgent.match(/Firefox/i)){const i=t.style.transform,o=t.style.transformOrigin;t.style.transform="rotate(-90deg)",t.style.transformOrigin="left top",e.dataTransfer.setDragImage(t,s,n),requestAnimationFrame(()=>{t.style.transform=i,t.style.transformOrigin=o})}else{const t=this._createDragPreviewPlaceholder(i);document.body.appendChild(t),e.dataTransfer.setDragImage(t,s,n),setTimeout(()=>{t.remove()})}}else e.dataTransfer.setDragImage(t,e.pageX-i.left-window.pageXOffset,e.pageY-i.top-window.pageYOffset);if(s===ViewEntryType.SLIDER){const s=t.shadowRoot.querySelector(".slides-container"),n=new WebKitCSSMatrix(getComputedStyle(s).transform).m41;e.dataTransfer.setDragImage(t,e.pageX-i.left-n-window.pageXOffset,e.pageY-i.top-window.pageYOffset)}}else e.preventDefault(),this.services.eventEmitter.emit(WidgetToEditorEventType.COMPONENT_DRAGEND)}})}_createDragPreviewPlaceholder(e){const t=document.createElement("div");return t.style.width=`${e.width}px`,t.style.height=`${e.height}px`,t.style.background="rgba(159, 41, 176, 0.3)",t.style.display="flex",t.style.justifyContent="center",t.style.alignItems="center",t.innerHTML='<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">\n<g opacity="0.6" clip-path="url(#clip0_43446_120564)">\n<path d="M26.5566 11.7573L30.7993 16L26.5566 20.2426" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M20.2422 26.5564L15.9995 30.799L11.7569 26.5564" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M5.44336 20.2426L1.20072 16L5.44336 11.7573" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M11.7569 5.4436L15.9995 1.20096L20.2422 5.4436" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M30.7994 16H20.8999" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M15.9995 30.7989L15.9995 20.8994" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M1.20064 16H11.1001" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M15.9995 1.20113L15.9995 11.1006" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n</g>\n<defs>\n<clipPath id="clip0_43446_120564">\n<rect width="32" height="32" fill="white"/>\n</clipPath>\n</defs>\n</svg>',t.firstChild.style.width=.4*e.width+"px",t.firstChild.style.height=.4*e.height+"px",t}_isWidgetRotated(e,t){const s=this._getFloatingBoxParams(e,t);return!!s&&"CENTER"===s.verticalPosition}_getFloatingBoxParams(e,t){return e&&e.floatingBox?t?e.floatingBox:e.floatingBox.mobile:null}_elementDragEndListener(e){e.stopPropagation(),this.services.eventEmitter.emit(WidgetToEditorEventType.COMPONENT_DRAGEND,{id:this.model.id,path:this.model.path,hostElement:this.getHostElement(),targetElement:e.composedPath()[0],event:e})}_elementDragOverListener(e){e.preventDefault(),e.stopPropagation();const t=this.lastDragOverEvent;this.lastDragOverEvent=e,e.pageX&&e.pageY&&(t&&t.clientY===e.clientY&&t.clientX===e.clientX||this.services.eventEmitter.emit(WidgetToEditorEventType.COMPONENT_DRAGOVER,{id:this.model.id,hostElement:this.getHostElement(),targetElement:e.composedPath()[0],event:e}))}_documentDropListener(e){this.services.eventEmitter.emit(WidgetToEditorEventType.DOCUMENT_DROP,{id:this.model.id,hostElement:this.getHostElement(),targetElement:e.composedPath()[0],event:e})}_mouseMoveEventListener(e){const t=this._findClosestHostElement(e.composedPath());if(this.preHoveredElement&&this.preHoveredElement!==t&&this.preHoveredElement.classList.remove(applySysClassPrefix("hovered")),this.preHoveredElement=t,t){t.classList.add(applySysClassPrefix("hovered"));const s={id:t.getAttribute(applySysAttrPrefix("id")),hostElement:t,targetElement:e.composedPath()[0],event:e};this.services.eventEmitter.emit(WidgetToEditorEventType.COMPONENT_MOUSE_MOVE,s)}}_mouseOutEventListener(e){e.stopPropagation();const t=this._findClosestHostElement(e.composedPath());t&&t.classList.remove(applySysClassPrefix("hovered"))}_blurEventListener(e){e.stopImmediatePropagation()}_removeFocus(){this.focusedElements.length&&this.focusedElements.forEach(e=>{var t;return null===(t=e.classList)||void 0===t?void 0:t.remove(applySysClassPrefix("focused"))}),this.focusedElements=[]}_setFocus(e){const t=this.getHostElement();if(this.focusedElements=[t],t.classList.add(applySysClassPrefix("focused")),"host"!==e){const t=this.getElements().filter(t=>t.getAttribute(applySysAttrPrefix("element"))===e);t.forEach(e=>e.classList.add(applySysClassPrefix("focused"))),this.focusedElements=this.focusedElements.concat(t)}}_findClosestHostElement(e){const t=e.filter(e=>e instanceof HTMLElement).filter(e=>!!e.getAttribute(applySysAttrPrefix("component")));return t.length?t[0]:null}_activateEventListeners(){this.eventListeners.forEach(e=>{e.activated||(e.element.addEventListener(e.eventName,e.callback,e.useCapture),e.activated=!0)})}_deactivateEventListeners(){this.eventListeners.forEach(e=>{e.element.removeEventListener(e.eventName,e.callback)}),this.eventListeners=[]}_getElementNameByNode(e){var t;const s="host";if(!e)return s;const i=e.closest(`[${applySysAttrPrefix("element")}]`);if(!i)return s;const n=i.getAttribute(applySysAttrPrefix("element"));return"host"===n||(null===(t=this.manifest.focusableElements)||void 0===t?void 0:t.includes(n))?n:s}_setFocusableElementsAttribute(){this.getElements().forEach(e=>{var t;(null===(t=this.manifest.focusableElements)||void 0===t?void 0:t.includes(e.getAttribute(applySysAttrPrefix("element"))))&&e.setAttribute(applySysAttrPrefix("focusable-element"),"")})}_updateFocusedElementClasses(){if(this.focusedElements.length<2)return;const e=this.focusedElements.find(e=>e.hasAttribute(applySysAttrPrefix("focusable-element")));e&&this._setFocus(e.getAttribute(applySysAttrPrefix("element")))}}}
@@ -1 +0,0 @@
1
- export const ViewRendererActionType={COMPONENT_FOCUSED:"COMPONENT_FOCUSED",REMOVE_FOCUS:"REMOVE_FOCUS",SET_FOCUS:"SET_FOCUS",COMPONENT_MOUSE_MOVE:"COMPONENT_MOUSE_MOVE",COMPONENT_CLICKED:"COMPONENT_CLICKED",COMPONENT_DOUBLE_CLICKED:"COMPONENT_DOUBLE_CLICKED",COMPONENT_DRAGSTART:"COMPONENT_DRAGSTART",COMPONENT_DRAGEND:"COMPONENT_DRAGEND",COMPONENT_DRAGOVER:"COMPONENT_DRAGOVER",DOCUMENT_DROP:"DOCUMENT_DROP",SHOW_INLINE_EDIT:"SHOW_INLINE_EDIT",VIEW_COMPONENT_RESOURCES_LOADED:"VIEW_COMPONENT_RESOURCES_LOADED",FAILED_TO_LOAD_COMPONENT_RESOURCE:"FAILED_TO_LOAD_COMPONENT_RESOURCE",GAME_PHASE_READY_TO_PLAY:"GAME_PHASE_READY_TO_PLAY",GAME_PHASE_COMPLETED:"GAME_PHASE_COMPLETED",GAME_PHASE_IDLE:"GAME_PHASE_IDLE"};
@@ -1,29 +0,0 @@
1
- import DefaultEventEmitter from '@claspo/common/DefaultEventEmitter';
2
- import FormGroup from '../form/FormGroup';
3
- import WcResolver from "../wc-renderer/WcResolver";
4
- export declare const SubmitState: {
5
- readonly IDLE: "idle";
6
- readonly DIRTY: "dirty";
7
- readonly SUBMITTING: "submitting";
8
- readonly SUBMITTED: "submitted";
9
- readonly FAILED: "failed";
10
- };
11
- export type SubmitStateValue = typeof SubmitState[keyof typeof SubmitState];
12
- export default class SubmitStateService {
13
- form: FormGroup;
14
- eventEmitter: DefaultEventEmitter;
15
- componentResolver: WcResolver;
16
- state: SubmitStateValue;
17
- currentSubmission: Promise<boolean> | null;
18
- subscriptions: Array<{
19
- off: () => void;
20
- }>;
21
- constructor(form: FormGroup, eventEmitter: DefaultEventEmitter, componentResolver: WcResolver);
22
- getState(): SubmitStateValue;
23
- hasDirtyFormData(): boolean;
24
- hasSubmitAttemptSinceLastChange(): boolean;
25
- trackSubmission(promise: Promise<boolean>): void;
26
- waitForCurrentSubmission(): Promise<boolean>;
27
- prepareAutoSubmitFormValue(): Promise<Record<string, any>>;
28
- destroy(): void;
29
- }
@@ -1 +0,0 @@
1
- import FormGroupEvents from"../form/FormGroupEvents";import SysEventTypes from"../common/SysEventTypes";function hasMeaningfulValue(t){return null!=t&&("string"==typeof t?""!==t.trim():Array.isArray(t)?t.length>0:"object"!=typeof t||Object.keys(t).length>0)}export const SubmitState={IDLE:"idle",DIRTY:"dirty",SUBMITTING:"submitting",SUBMITTED:"submitted",FAILED:"failed"};export default class SubmitStateService{constructor(t,e,s){this.form=t,this.eventEmitter=e,this.componentResolver=s,this.state=SubmitState.IDLE,this.currentSubmission=null,this.subscriptions=[this.form.on(FormGroupEvents.valueChanged,()=>{this.state=SubmitState.DIRTY}),this.eventEmitter.on(SysEventTypes.SUBMIT_REQUEST_STARTED,()=>{this.state=SubmitState.SUBMITTING}),this.eventEmitter.on(SysEventTypes.SUBMIT_REQUEST_FINISHED,t=>{this.currentSubmission=null,this.state=(null==t?void 0:t.success)?SubmitState.SUBMITTED:SubmitState.FAILED})]}getState(){return this.state}hasDirtyFormData(){return this.form.getControlsAsArray().some(t=>t.isTouched())}hasSubmitAttemptSinceLastChange(){return[SubmitState.SUBMITTING,SubmitState.SUBMITTED,SubmitState.FAILED].includes(this.state)}trackSubmission(t){this.currentSubmission=t}waitForCurrentSubmission(){return this.currentSubmission||Promise.resolve(!1)}async prepareAutoSubmitFormValue(){const t=this.form.getControlsAsArray(),e=t.find(t=>t.getName().includes("clConsentId")&&!t.getName().includes("label"));if(e){if(!e.isValid())return{}}else if(this.componentResolver.presentComponentManifests.find(t=>"SysConsentComponent"===t.name))return{};const s=t.filter(t=>hasMeaningfulValue(t.getValue()));return(await Promise.all(s.map(async t=>({control:t,isValid:await t.validate({silent:!0})})))).reduce((t,{control:e,isValid:s})=>{const i=e.getValue();return s&&hasMeaningfulValue(i)?(t[e.getName()]=i,t):(t[e.getName()]=void 0,t)},{})}destroy(){this.subscriptions.forEach(t=>t.off()),this.subscriptions=[],this.currentSubmission=null}}