@claspo/renderer 18.12.1 → 18.13.0-mto1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
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,o=TranslateUtils.applyTranslationObjectToComponentsIfNeeded(JSON.parse(JSON.stringify(this.documentJson)),this.componentResolver.getComponentManifests(),this.translations),i=new CompositionRoot(o,this.config,this.trackingService,null,"",this.layoutType,this.renderMode,this.componentRegister,t,this.componentResolver),s=new ViewRouter(i.services.eventEmitter,i.services.documentModel,i.services.viewRenderer,this.config&&this.config.optionalDocumentStyles,i.services);return i.services.viewRouter=s,this.compositionRoot=i,this.viewRenderer=i.services.viewRenderer,this.componentFactory=i.services.componentFactory,this.viewRouter=s,s.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
+ import CompositionRoot from"./CompositionRoot";import ViewRouter from"./ViewRouter";import TranslateUtils from"./i18n/TranslateUtils";import{EditorToWidgetEventType}from"./document-model/EditorToWidgetEventType";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,o=TranslateUtils.applyTranslationObjectToComponentsIfNeeded(JSON.parse(JSON.stringify(this.documentJson)),this.componentResolver.getComponentManifests(),this.translations),i=new CompositionRoot(o,this.config,this.trackingService,null,"",this.layoutType,this.renderMode,this.componentRegister,t,this.componentResolver),s=new ViewRouter(i.services.eventEmitter,i.services.documentModel,i.services.viewRenderer,this.config&&this.config.optionalDocumentStyles,i.services);return i.services.viewRouter=s,this.compositionRoot=i,this.viewRenderer=i.services.viewRenderer,this.componentFactory=i.services.componentFactory,this.viewRouter=s,s.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{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,this.componentResolver);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)})}}
1
+ import CompositionRoot from"./CompositionRoot";import{EditorToWidgetEventType}from"./document-model/EditorToWidgetEventType";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,this.componentResolver);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)})}}
@@ -1,26 +1,6 @@
1
1
  import DefaultEventEmitter from "@claspo/common/DefaultEventEmitter";
2
2
  import { ClBaseComponentI, ClDocumentI, ClDocumentSharedI } from '@claspo/common/document/Document.interface';
3
3
  import { ViewNavGraphI } from '@claspo/common/document/ViewNavigationGraph';
4
- export declare const EditorToWidgetEventType: {
5
- COMPONENT_INSERT: string;
6
- COMPONENT_REMOVE: string;
7
- COMPONENT_MOVE: string;
8
- COMPONENT_UPDATE: string;
9
- COMPONENT_PROPS_UPDATE: string;
10
- REMOVE_FOCUS: string;
11
- SET_FOCUS: string;
12
- SHARED_UPDATE: string;
13
- MOBILE_BREAKPOINT_UPDATE: string;
14
- ENVIRONMENT_UPDATE: string;
15
- TEXT_CLASS_ADDED: string;
16
- TEXT_CLASS_UPDATED: string;
17
- TEXT_CLASS_REMOVED: string;
18
- HEADER_FONT_FAMILY_UPDATE: string;
19
- TEXT_FONT_FAMILY_UPDATE: string;
20
- SHARED_UPDATE_ALL: string;
21
- COLOR_SCHEMA_UPDATE: string;
22
- THEME_UPDATE: string;
23
- };
24
4
  export default class DocumentModelService extends DefaultEventEmitter {
25
5
  json: ClDocumentI;
26
6
  flatJson: ClDocumentI;
@@ -1 +1 @@
1
- import ModulesComponentExtractor from"./ModulesComponentExtractor";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import DocumentUtils from"@claspo/common/document/DocumentUtils";import{buildViewNavigationGraph}from"@claspo/common/document/ViewNavigationGraph";import ErrorLogger from"../error/ErrorLogger";export const EditorToWidgetEventType={COMPONENT_INSERT:"COMPONENT_INSERT",COMPONENT_REMOVE:"COMPONENT_REMOVE",COMPONENT_MOVE:"COMPONENT_MOVE",COMPONENT_UPDATE:"COMPONENT_UPDATE",COMPONENT_PROPS_UPDATE:"COMPONENT_PROPS_UPDATE",REMOVE_FOCUS:"REMOVE_FOCUS",SET_FOCUS:"SET_FOCUS",SHARED_UPDATE:"SHARED_UPDATE",MOBILE_BREAKPOINT_UPDATE:"MOBILE_BREAKPOINT_UPDATE",ENVIRONMENT_UPDATE:"ENVIRONMENT_UPDATE",TEXT_CLASS_ADDED:"TEXT_CLASS_ADDED",TEXT_CLASS_UPDATED:"TEXT_CLASS_UPDATED",TEXT_CLASS_REMOVED:"TEXT_CLASS_REMOVED",HEADER_FONT_FAMILY_UPDATE:"HEADER_FONT_FAMILY_UPDATE",TEXT_FONT_FAMILY_UPDATE:"TEXT_FONT_FAMILY_UPDATE",SHARED_UPDATE_ALL:"SHARED_UPDATE_ALL",COLOR_SCHEMA_UPDATE:"COLOR_SCHEMA_UPDATE",THEME_UPDATE:"THEME_UPDATE"};export default class DocumentModelService extends DefaultEventEmitter{constructor(t){super(),this.navigationGraph=null,this.prizeNavigationTargetsByViewId=new Map,this.json=t,this.flatJson=ModulesComponentExtractor.extract(this.json)}setComponentRef(t,e){DocumentUtils.getNodeById(this.getViews(),t).componentRef=e}getModel(){return this.flatJson}getView(t){return this.flatJson.views[t]}getViews(){return this.flatJson.views}getShared(){return this.flatJson.shared}getNavigationGraph(){if(!this.navigationGraph)try{this.navigationGraph=buildViewNavigationGraph(this.getViews(),this.getShared(),this.buildPrizeNavigationTargets())}catch(t){ErrorLogger.log(`buildViewNavigationGraph failed: ${(null==t?void 0:t.stack)||t}`),this.navigationGraph={nodes:[],edges:[]}}return this.navigationGraph}setPrizeNavigationTargets(t,e){const i=e.filter(t=>!!t);this.prizeNavigationTargetsByViewId.set(t,i),this.navigationGraph=null}buildPrizeNavigationTargets(){const t=[];return this.prizeNavigationTargetsByViewId.forEach((e,i)=>{e.forEach(e=>t.push({fromViewId:i,toViewId:e}))}),t}iterateViewModelAndExecute(t,e){const i=this.getView(t);DocumentUtils.iterateDepthFirst(i,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";import{buildViewNavigationGraph}from"@claspo/common/document/ViewNavigationGraph";import ErrorLogger from"../error/ErrorLogger";export default class DocumentModelService extends DefaultEventEmitter{constructor(t){super(),this.navigationGraph=null,this.prizeNavigationTargetsByViewId=new Map,this.json=t,this.flatJson=ModulesComponentExtractor.extract(this.json)}setComponentRef(t,e){DocumentUtils.getNodeById(this.getViews(),t).componentRef=e}getModel(){return this.flatJson}getView(t){return this.flatJson.views[t]}getViews(){return this.flatJson.views}getShared(){return this.flatJson.shared}getNavigationGraph(){if(!this.navigationGraph)try{this.navigationGraph=buildViewNavigationGraph(this.getViews(),this.getShared(),this.buildPrizeNavigationTargets())}catch(t){ErrorLogger.log(`buildViewNavigationGraph failed: ${(null==t?void 0:t.stack)||t}`),this.navigationGraph={nodes:[],edges:[]}}return this.navigationGraph}setPrizeNavigationTargets(t,e){const i=e.filter(t=>!!t);this.prizeNavigationTargetsByViewId.set(t,i),this.navigationGraph=null}buildPrizeNavigationTargets(){const t=[];return this.prizeNavigationTargetsByViewId.forEach((e,i)=>{e.forEach(e=>t.push({fromViewId:i,toViewId:e}))}),t}iterateViewModelAndExecute(t,e){const i=this.getView(t);DocumentUtils.iterateDepthFirst(i,e)}destroy(){}destroyView(t){console.warn("destroyView now should do nothing"),this.iterateViewModelAndExecute(t,t=>{t.componentRef&&(t.componentRef.remove(),t.componentRef=null)})}}
@@ -1 +1 @@
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)}}
1
+ import DocumentUtils from"@claspo/common/document/DocumentUtils";import{ComponentInsertType}from"@claspo/common/document/ComponentInsertType";import{EditorToWidgetEventType}from"./EditorToWidgetEventType";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)}}
@@ -0,0 +1,20 @@
1
+ export declare const EditorToWidgetEventType: {
2
+ COMPONENT_INSERT: string;
3
+ COMPONENT_REMOVE: string;
4
+ COMPONENT_MOVE: string;
5
+ COMPONENT_UPDATE: string;
6
+ COMPONENT_PROPS_UPDATE: string;
7
+ REMOVE_FOCUS: string;
8
+ SET_FOCUS: string;
9
+ SHARED_UPDATE: string;
10
+ MOBILE_BREAKPOINT_UPDATE: string;
11
+ ENVIRONMENT_UPDATE: string;
12
+ TEXT_CLASS_ADDED: string;
13
+ TEXT_CLASS_UPDATED: string;
14
+ TEXT_CLASS_REMOVED: string;
15
+ HEADER_FONT_FAMILY_UPDATE: string;
16
+ TEXT_FONT_FAMILY_UPDATE: string;
17
+ SHARED_UPDATE_ALL: string;
18
+ COLOR_SCHEMA_UPDATE: string;
19
+ THEME_UPDATE: string;
20
+ };
@@ -0,0 +1 @@
1
+ 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"};
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "@claspo/renderer",
3
- "version": "18.12.1",
3
+ "version": "18.13.0-mto1",
4
+ "sideEffects": false,
4
5
  "scripts": {
5
6
  "dev": " tsc --project tsconfig.json --watch",
6
7
  "build": "rm -rf out && tsc --project tsconfig.json && npm run minify",
@@ -15,7 +16,7 @@
15
16
  "node": ">=18.16.0"
16
17
  },
17
18
  "dependencies": {
18
- "@claspo/common": "7.5.9",
19
+ "@claspo/common": "7.5.11-mto1",
19
20
  "@testing-library/dom": "^10.4.0"
20
21
  },
21
22
  "devDependencies": {
@@ -1 +1 @@
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
+ import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{EditorToWidgetEventType}from"../../document-model/EditorToWidgetEventType";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{EditorToWidgetEventType}from"../../document-model/DocumentModelService";import ErrorLogger from"../../error/ErrorLogger";import{fromCssVarToSchemaToken,toCssVarToken}from"@claspo/common/theme/theme.utils";export default class ColorSchemaListener{constructor(e,t,o,s,n,r){this.hostElement=t,this.documentModel=e,this.getSharedCb=o,this.getPropsCb=s,this.getEnvCb=n,this.httpClient=r,this.schemaSubscription=null,this.themeSubscription=null,this.envUrlMaps={desktop:new Map,mobile:new Map}}parseBackground(e){const t=String(e||"");if(t.includes("url")){const[e,o]=t.split("(")[1].split(")");return{url:e.replace(/['"]+/g,""),positionOptions:o.replace(";","")}}return{url:null,positionOptions:null}}apply(e){const t=this.getPropsCb();return t.backgroundDynamicInlineSVGElements[e].forEach(o=>{var s,n,r,i,l;const a=null===(n=null===(s=t.adaptiveStyles)||void 0===s?void 0:s[e])||void 0===n?void 0:n.find(e=>e.element===o),c=(null===(r=t.styles)||void 0===r?void 0:r.find(e=>e.element===o))||{},h=(null===(i=null==c?void 0:c.styleAttributes)||void 0===i?void 0:i.background)||(null===(l=null==a?void 0:a.styleAttributes)||void 0===l?void 0:l.background),m=this.parseBackground(h);m.url&&this.envUrlMaps[e].set(o,{originalSVGResourceURL:m.url,inlineSvgString:null,positionOptions:m.positionOptions})}),Promise.all([...this.envUrlMaps[e].entries()].map(([t,o])=>this.httpClient.execute({url:o.originalSVGResourceURL}).then(e=>e.text()).then(s=>{this.envUrlMaps[e].set(t,Object.assign(Object.assign({},o),{inlineSvgString:s}))}))).then(()=>{var t;const o=this.getSharedCb();return Object.keys((null===(t=o.theme)||void 0===t?void 0:t.schema)||{}).length>0?this._applyHostElementBackgroundFromTheme(this.envUrlMaps[e].get("host"),o.theme.schema):this._applyHostElementBackgroundFromCssVars(this.envUrlMaps[e].get("host"),o.cssVars)}).catch(e=>{console.error(e),ErrorLogger.log(`Failed to load/apply backgroundDynamicInlineSVGElements[${this.getPropsCb().backgroundDynamicInlineSVGElements}] ${e}`)})}on(){return this.schemaSubscription=this.documentModel.on(EditorToWidgetEventType.COLOR_SCHEMA_UPDATE,e=>{this._applyHostElementBackgroundFromCssVars(this.envUrlMaps[this.getEnvCb()].get("host"),e)}),this.themeSubscription=this.documentModel.on(EditorToWidgetEventType.THEME_UPDATE,e=>{this._applyHostElementBackgroundFromTheme(this.envUrlMaps[this.getEnvCb()].get("host"),e.schema)}),this}_applyHostElementBackgroundFromCssVars(e,t){e&&t&&(this.hostElement.style.background=this._buildBackgroundUrlFromCssVars(e,t))}_applyHostElementBackgroundFromTheme(e,t){e&&t&&(this.hostElement.style.background=this._buildBackgroundUrlFromTheme(e,t))}_buildBackgroundUrlFromCssVars(e,t){const o=e.inlineSvgString.trim().replace("var(--cl-schema-accent)",t["cl-schema-accent"]);return`url('data:image/svg+xml,${encodeURIComponent(o)}')${e.positionOptions}`}_buildBackgroundUrlFromTheme(e,t){const o=e.inlineSvgString.trim();let s=o;[...o.matchAll(/var\(--cl-schema-([^)]+)\)/g)].forEach(e=>{const o=fromCssVarToSchemaToken(e[1]);s=s.replace(`var(--${toCssVarToken(o)})`,t[o])});return`url('data:image/svg+xml,${encodeURIComponent(s)}')${e.positionOptions}`}off(){var e,t;null===(e=this.schemaSubscription)||void 0===e||e.off(),null===(t=this.themeSubscription)||void 0===t||t.off()}}
1
+ import{EditorToWidgetEventType}from"../../document-model/EditorToWidgetEventType";import ErrorLogger from"../../error/ErrorLogger";import{fromCssVarToSchemaToken,toCssVarToken}from"@claspo/common/theme/theme.utils";export default class ColorSchemaListener{constructor(t,e,o,s,n,r){this.hostElement=e,this.documentModel=t,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(t){const e=String(t||"");if(e.includes("url")){const[t,o]=e.split("(")[1].split(")");return{url:t.replace(/['"]+/g,""),positionOptions:o.replace(";","")}}return{url:null,positionOptions:null}}apply(t){const e=this.getPropsCb();return e.backgroundDynamicInlineSVGElements[t].forEach(o=>{var s,n,r,i,l;const a=null===(n=null===(s=e.adaptiveStyles)||void 0===s?void 0:s[t])||void 0===n?void 0:n.find(t=>t.element===o),c=(null===(r=e.styles)||void 0===r?void 0:r.find(t=>t.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[t].set(o,{originalSVGResourceURL:m.url,inlineSvgString:null,positionOptions:m.positionOptions})}),Promise.all([...this.envUrlMaps[t].entries()].map(([e,o])=>this.httpClient.execute({url:o.originalSVGResourceURL}).then(t=>t.text()).then(s=>{this.envUrlMaps[t].set(e,Object.assign(Object.assign({},o),{inlineSvgString:s}))}))).then(()=>{var e;const o=this.getSharedCb();return Object.keys((null===(e=o.theme)||void 0===e?void 0:e.schema)||{}).length>0?this._applyHostElementBackgroundFromTheme(this.envUrlMaps[t].get("host"),o.theme.schema):this._applyHostElementBackgroundFromCssVars(this.envUrlMaps[t].get("host"),o.cssVars)}).catch(t=>{console.error(t),ErrorLogger.log(`Failed to load/apply backgroundDynamicInlineSVGElements[${this.getPropsCb().backgroundDynamicInlineSVGElements}] ${t}`)})}on(){return this.schemaSubscription=this.documentModel.on(EditorToWidgetEventType.COLOR_SCHEMA_UPDATE,t=>{this._applyHostElementBackgroundFromCssVars(this.envUrlMaps[this.getEnvCb()].get("host"),t)}),this.themeSubscription=this.documentModel.on(EditorToWidgetEventType.THEME_UPDATE,t=>{this._applyHostElementBackgroundFromTheme(this.envUrlMaps[this.getEnvCb()].get("host"),t.schema)}),this}_applyHostElementBackgroundFromCssVars(t,e){t&&e&&(this.hostElement.style.background=this._buildBackgroundUrlFromCssVars(t,e))}_applyHostElementBackgroundFromTheme(t,e){t&&e&&(this.hostElement.style.background=this._buildBackgroundUrlFromTheme(t,e))}_buildBackgroundUrlFromCssVars(t,e){const o=t.inlineSvgString.trim().replace("var(--cl-schema-accent)",e["cl-schema-accent"]);return`url('data:image/svg+xml,${encodeURIComponent(o)}')${t.positionOptions}`}_buildBackgroundUrlFromTheme(t,e){const o=t.inlineSvgString.trim();let s=o;[...o.matchAll(/var\(--cl-schema-([^)]+)\)/g)].forEach(t=>{const o=fromCssVarToSchemaToken(t[1]);s=s.replace(`var(--${toCssVarToken(o)})`,e[o])});return`url('data:image/svg+xml,${encodeURIComponent(s)}')${t.positionOptions}`}off(){var t,e;null===(t=this.schemaSubscription)||void 0===t||t.off(),null===(e=this.themeSubscription)||void 0===e||e.off()}}
@@ -1 +1 @@
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
+ import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{EditorToWidgetEventType}from"../../document-model/EditorToWidgetEventType";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{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
+ 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/EditorToWidgetEventType";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,11 +1,12 @@
1
1
  import { PlatformEnvT } from './WcElement';
2
- import { BaseComponentAdaptiveStylesI, ClBaseComponentElementParamsI, ClComponentStyleAttributesI, ClDocumentSharedI } from '@claspo/common/document/Document.interface';
2
+ import { BaseComponentAdaptiveStylesI, ClBaseComponentElementParamsI, ClComponentStyleAttributesI, ClDocumentSharedI, ClDocumentSharedTextClassI } from '@claspo/common/document/Document.interface';
3
3
  export declare function getAdaptiveStylesForPlatform(adaptiveStyles: BaseComponentAdaptiveStylesI | undefined, platform: PlatformEnvT, element: string): ClBaseComponentElementParamsI | undefined;
4
4
  export declare function cloneAdaptiveStyles(adaptiveStyles?: ClBaseComponentElementParamsI[]): ClBaseComponentElementParamsI[];
5
5
  export declare function replaceStyleAttributes(adaptiveStyles: BaseComponentAdaptiveStylesI, platform: PlatformEnvT, element: string, styles?: ClComponentStyleAttributesI): BaseComponentAdaptiveStylesI;
6
6
  export declare function patchStyleAttributes(adaptiveStyles: BaseComponentAdaptiveStylesI, platform: PlatformEnvT, element: string, styles?: ClComponentStyleAttributesI): BaseComponentAdaptiveStylesI;
7
7
  export declare function cloneStylesToAllEnvs(value: ClBaseComponentElementParamsI[]): BaseComponentAdaptiveStylesI;
8
- export declare function applySharedClasses(elementModel: ClBaseComponentElementParamsI, shared: ClDocumentSharedI): ClBaseComponentElementParamsI;
8
+ export declare function getEffectiveTextClassAttributes(textClassModel: ClDocumentSharedTextClassI, isMobile: boolean): Pick<ClBaseComponentElementParamsI, 'styleAttributes' | 'placeholderStyleAttributes'>;
9
+ export declare function applySharedClasses(elementModel: ClBaseComponentElementParamsI, shared: ClDocumentSharedI, isMobile?: boolean): ClBaseComponentElementParamsI;
9
10
  export declare function getPlaceholderColor(props: {
10
11
  adaptiveStyles: BaseComponentAdaptiveStylesI;
11
12
  }, env: PlatformEnvT, shared: ClDocumentSharedI): string;
@@ -1 +1 @@
1
- import{PLATFORMS}from"../wc-renderer/utils/platforms";import{RenderConstants}from"../renderer/RenderConstants";export function getAdaptiveStylesForPlatform(t,e,s){var i;return null===(i=null==t?void 0:t[e])||void 0===i?void 0:i.find(t=>t.element===s)}export function cloneAdaptiveStyles(t=[]){return t.map(t=>Object.assign(Object.assign({},t),{styleAttributes:Object.assign({},t.styleAttributes)}))}export function replaceStyleAttributes(t,e,s,i={}){return Object.assign(Object.assign({},t),{[e]:t[e].map(t=>t.element===s?Object.assign(Object.assign({},t),{styleAttributes:Object.assign({},i)}):t)})}export function patchStyleAttributes(t,e,s,i={}){return Object.assign(Object.assign({},t),{[e]:t[e].map(t=>t.element===s?Object.assign(Object.assign({},t),{styleAttributes:Object.assign(Object.assign({},t.styleAttributes),i)}):t)})}export function cloneStylesToAllEnvs(t){return Object.values(PLATFORMS).reduce((e,s)=>Object.assign(e,{[s]:cloneAdaptiveStyles(t)}),{desktop:[],mobile:[]})}export function applySharedClasses(t,e){let s=t;return(s.classes||"").split(" ").filter(t=>t.startsWith(RenderConstants.SYSTEM_CLASS_PREFIX)).forEach(t=>{var i;let l=null===(i=e.textClasses)||void 0===i?void 0:i[t];l&&(l.styleAttributes.fontFamily||(l.isHeader&&e.headerFontFamily&&(l=Object.assign(Object.assign({},l),{styleAttributes:Object.assign(Object.assign({},l.styleAttributes),{fontFamily:e.headerFontFamily})})),!l.isHeader&&e.textFontFamily&&(l=Object.assign(Object.assign({},l),{styleAttributes:Object.assign(Object.assign({},l.styleAttributes),{fontFamily:e.textFontFamily})}))),s=Object.assign(Object.assign({},s),{styleAttributes:Object.assign(Object.assign({},s.styleAttributes),l.styleAttributes),placeholderStyleAttributes:Object.assign(Object.assign({},s.placeholderStyleAttributes),l.placeholderStyleAttributes)}))}),s.styleAttributes.fontFamily||(s=Object.assign(Object.assign({},s),{styleAttributes:Object.assign(Object.assign({},s.styleAttributes),{fontFamily:e.textFontFamily})})),s}export function getPlaceholderColor(t,e,s){var i;let l="rgb(0, 0, 0)";const r=t.adaptiveStyles[e].find(t=>"input"===t.element);if(!r)return l;if(r.placeholderStyleAttributes&&r.placeholderStyleAttributes.color)return r.placeholderStyleAttributes.color;const n=(r.classes||"").split(" ").filter(t=>t.startsWith(RenderConstants.SYSTEM_CLASS_PREFIX));if(!n.length)return l;let a=null===(i=s.textClasses)||void 0===i?void 0:i[n[0]];return a&&a.placeholderStyleAttributes&&a.placeholderStyleAttributes.color?a.placeholderStyleAttributes.color:l}
1
+ import{PLATFORMS}from"../wc-renderer/utils/platforms";import{RenderConstants}from"../renderer/RenderConstants";export function getAdaptiveStylesForPlatform(t,e,s){var i;return null===(i=null==t?void 0:t[e])||void 0===i?void 0:i.find(t=>t.element===s)}export function cloneAdaptiveStyles(t=[]){return t.map(t=>Object.assign(Object.assign({},t),{styleAttributes:Object.assign({},t.styleAttributes)}))}export function replaceStyleAttributes(t,e,s,i={}){return Object.assign(Object.assign({},t),{[e]:t[e].map(t=>t.element===s?Object.assign(Object.assign({},t),{styleAttributes:Object.assign({},i)}):t)})}export function patchStyleAttributes(t,e,s,i={}){return Object.assign(Object.assign({},t),{[e]:t[e].map(t=>t.element===s?Object.assign(Object.assign({},t),{styleAttributes:Object.assign(Object.assign({},t.styleAttributes),i)}):t)})}export function cloneStylesToAllEnvs(t){return Object.values(PLATFORMS).reduce((e,s)=>Object.assign(e,{[s]:cloneAdaptiveStyles(t)}),{desktop:[],mobile:[]})}export function getEffectiveTextClassAttributes(t,e){return{styleAttributes:Object.assign(Object.assign({},t.styleAttributes),e?t.mobileStyleAttributes:{}),placeholderStyleAttributes:Object.assign(Object.assign({},t.placeholderStyleAttributes),e?t.mobilePlaceholderStyleAttributes:{})}}export function applySharedClasses(t,e,s=!1){let i=t;return(i.classes||"").split(" ").filter(t=>t.startsWith(RenderConstants.SYSTEM_CLASS_PREFIX)).forEach(t=>{var r;const l=null===(r=e.textClasses)||void 0===r?void 0:r[t];if(!l)return;let n=getEffectiveTextClassAttributes(l,s);n.styleAttributes.fontFamily||(l.isHeader&&e.headerFontFamily&&(n=Object.assign(Object.assign({},n),{styleAttributes:Object.assign(Object.assign({},n.styleAttributes),{fontFamily:e.headerFontFamily})})),!l.isHeader&&e.textFontFamily&&(n=Object.assign(Object.assign({},n),{styleAttributes:Object.assign(Object.assign({},n.styleAttributes),{fontFamily:e.textFontFamily})}))),i=Object.assign(Object.assign({},i),{styleAttributes:Object.assign(Object.assign({},i.styleAttributes),n.styleAttributes),placeholderStyleAttributes:Object.assign(Object.assign({},i.placeholderStyleAttributes),n.placeholderStyleAttributes)})}),i.styleAttributes.fontFamily||(i=Object.assign(Object.assign({},i),{styleAttributes:Object.assign(Object.assign({},i.styleAttributes),{fontFamily:e.textFontFamily})})),i}export function getPlaceholderColor(t,e,s){var i;let r="rgb(0, 0, 0)";const l=t.adaptiveStyles[e].find(t=>"input"===t.element);if(!l)return r;if(l.placeholderStyleAttributes&&l.placeholderStyleAttributes.color)return l.placeholderStyleAttributes.color;const n=(l.classes||"").split(" ").filter(t=>t.startsWith(RenderConstants.SYSTEM_CLASS_PREFIX));if(!n.length)return r;const a=null===(i=s.textClasses)||void 0===i?void 0:i[n[0]];if(!a)return r;const{placeholderStyleAttributes:o}=getEffectiveTextClassAttributes(a,"mobile"===e);return o&&o.color?o.color:r}
package/sdk/WcElement.js CHANGED
@@ -1 +1 @@
1
- import HandlerFactory from"../handler/HandlerFactory";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import addEventListenerToElement from"@claspo/common/utils/addEventListener";import DefaultState from"../common/DefaultState";import{EditorToWidgetEventType}from"../document-model/DocumentModelService";import DefaultMediaQueryListener from"../renderer/style/DefaultMediaQueryListener";import{applySysAttrPrefix,applySysClassPrefix,RenderConstants}from"../renderer/RenderConstants";import StyleAttributeAccessor from"./accessor/StyleAttributeAccessor";import CommonStylesService from"../renderer/style/CommonStylesService";import ColorSchemaListener from"../renderer/style/ColorSchemaListener";import HttpClient from"@claspo/common/network/HttpClient";import omitKeys from"@claspo/common/object/omitKeys";import{CaseTransformer}from"@claspo/common/utils/CaseTransformer";import ComponentResourceManager from"../resource-management/ComponentResourceManager";import createObservers from"../wc-renderer/observers/createObservers";import observerType from"../wc-renderer/observers/observerType";import createSubscriptions from"../wc-renderer/subscriptions/createSubscriptions";import recursiveFindParentNodeByAttribute from"@claspo/common/element/recursiveFindParentNodeByAttribute";import{getTranslationsMap,getWidgetLanguages}from"./TranslationUtils";import ActionCategory from"../action/actions/ActionCategory";import SysActionTypes from"../action/SysActionTypes";import mergeAdaptiveStylesWithEnvIndependentStyles from"../document-model/MergeAdaptiveStylesWithEnvIndependentStyles";import{applySharedClasses,getAdaptiveStylesForPlatform}from"./ModelStyleUtils";import insertHtmlIntoElement from"@claspo/common/dom/insertHtmlIntoElement";import{PayloadEvent}from"./PayloadEvent";import{RenderMode}from"@claspo/common/RenderMode";import InputFieldsAutofillHydrator from"./autofill/InputFieldsAutofillHydrator";import{WidgetToEditorEventType}from"../renderer/WidgetToEditorEventType";class WcElement extends HTMLElement{constructor(){var e;super(),this.skipGameBlur=!0,this.isAutofillValidated=!1,this.validatedAutofillValue=void 0,this.construct=()=>{let e;const t=this.getAttribute(applySysAttrPrefix("id")),s=this.getWidgetContainerNode();if(!s)throw new Error("Widget container not found in construct");const o=s.closest(`[${applySysAttrPrefix("widget-id")}]`);let i;o&&(i=o.getAttribute(applySysAttrPrefix("widget-id")));let r=new PayloadEvent("cl-props-request",{nodeName:this.nodeName,path:this.getAttribute(applySysAttrPrefix("path")),id:t,widgetId:i},{bubbles:!0,composed:!0});this.dispatchEvent(r),e=r.detail.props,Object.assign(this,e),this.observers=createObservers(observerType.PROPS,observerType.SHARED,observerType.ENVIRONMENT),this.subscriptions=createSubscriptions(),this.state=new DefaultState({}),this.componentEventEmitter=new DefaultEventEmitter,this.componentResourceManager=new ComponentResourceManager(this.model.id,this.services.eventEmitter,this.isStaticRenderMode()),this.mergeTagsProcessor=this.services.mergeTagsProcessorFactory.create(),this._actionFactory=this.services.actionFactory,this._handlerFactory=new HandlerFactory(this._actionFactory,this.services.actionRegister),this.prevProps=this.model.props,this.prevEnvironment=this.getEnvironment(),this.documentModel.on(`${EditorToWidgetEventType.COMPONENT_PROPS_UPDATE}_${this.model.id}`,e=>{this.model.props=e,this.observers.get(observerType.PROPS).forEach(t=>t(this.prevProps,e)),this.prevProps=e;const t=this.getHostElement(),s=applySysAttrPrefix("floating");e.floating&&!t.getAttribute(s)?t.setAttribute(s,"true"):!e.floating&&t.getAttribute(s)&&t.removeAttribute(s)}),this.documentModel.on(`${EditorToWidgetEventType.COMPONENT_UPDATE}_${this.model.id}`,e=>{Object.assign(this.model,e)}),this.documentModel.on(EditorToWidgetEventType.SHARED_UPDATE_ALL,()=>{this.applyAutoAdaptiveStyles(this.prevProps.adaptiveStyles,this.prevProps.styles),this.observers.get(observerType.SHARED).forEach(e=>e(this.getShared()))}),this.model.props.backgroundDynamicInlineSVGElements&&(this.colorSchemaListener=new ColorSchemaListener(this.documentModel,this.getHostElement(),()=>this.getShared(),()=>this.model.props,()=>this.getEnvironment(),HttpClient),this.colorSchemaListener.apply(this.getEnvironment()).then(()=>{this.subscriptions.push(this.colorSchemaListener.on())})),this.prevProps.adaptiveStyles&&this.subscriptions.push(this.resizeListener.on(DefaultMediaQueryListener.changeEventName,()=>{this.applyAutoAdaptiveStyles(this.prevProps.adaptiveStyles,this.prevProps.styles);const e=this.getEnvironment();this.observers.get(observerType.ENVIRONMENT).forEach(t=>t(this.prevEnvironment,e)),this.prevEnvironment=e})),this.subscriptions.push(this.services.eventEmitter.on(WidgetToEditorEventType.GAME_PHASE_READY_TO_PLAY,()=>{this.skipGameBlur||this.getHostElement().classList.add("cl-game-spotlight-component")})),this.subscriptions.push(this.services.eventEmitter.on(WidgetToEditorEventType.GAME_PHASE_COMPLETED,()=>{this.skipGameBlur||this.getHostElement().classList.remove("cl-game-spotlight-component")}))},this.attachHandlers=()=>{this.getHandlers().map(e=>this._handlerFactory.get(e)).map(e=>()=>e.activate(this.state,this.componentEventEmitter,this.getHostElement.bind(this))).forEach(e=>e())},this.postponeHandlers=()=>{var e;null===(e=this.handlers)||void 0===e||e.forEach(e=>e.postpone())},this.releaseHandlers=()=>{var e;null===(e=this.handlers)||void 0===e||e.forEach(e=>e.release())},this.getProps=()=>{var e;return null===(e=this.getModel())||void 0===e?void 0:e.props},this.getShared=()=>this.documentModel.getShared(),this.getEnvironment=()=>this.resizeListener.isMobile()?"mobile":"desktop",this.isStaticRenderMode=()=>this.services.config.getConfig("renderMode")===RenderMode.STATIC,this.isUpdatingRenderMode=()=>this.services.config.getConfig("renderMode")===RenderMode.UPDATING,this.getRootElement=()=>this.shadowRoot?this.shadowRoot:this,this.getHostElement=()=>this,this.observeProps=e=>{this.observers.get(observerType.PROPS).push(e),e(null,this.prevProps)},this.observeShared=e=>{this.observers.get(observerType.SHARED).push(e),e(this.getShared())},this.observeEnvironment=e=>{this.observers.get(observerType.ENVIRONMENT).push(e),e(null,this.getEnvironment())},this.getElements=()=>[this.getHostElement(),...Array.from(this.getRootElement().querySelectorAll(`[${applySysAttrPrefix("element")}]`)).filter(e=>!e.hasAttribute(applySysAttrPrefix("component")))],this.getElement=(e,t)=>this.getElements().find(s=>t?s.getAttribute(applySysAttrPrefix("element"))===e&&s.id===t:s.getAttribute(applySysAttrPrefix("element"))===e),this.applyAutoAdaptiveStyles=(e,t)=>{if(!e&&!t)return;const s=this.getElements();if(!s.length)return;const o=mergeAdaptiveStylesWithEnvIndependentStyles(e,t),i=applySysAttrPrefix("type"),r="element-styles";let n=this.getRootElement().querySelector(`style[${i}="${r}"]`);n||(n=document.createElement("style"),n.setAttribute(i,r),this.getRootElement().appendChild(n)),insertHtmlIntoElement({element:n,html:""}),s.forEach(e=>{let t=e.getAttribute(applySysAttrPrefix("element"));const s=this.getEnvironment();let i=getAdaptiveStylesForPlatform(o,s,t);if(i){if(this.resizeListener.isMobile()){const e=getAdaptiveStylesForPlatform(o,"desktop",t);e&&(i=Object.assign(Object.assign({},i),{styleAttributes:Object.assign(Object.assign({},e.styleAttributes),i.styleAttributes)}))}this.applyStylesToElement(e,this.applySharedClassesToElementModel(i),n)}}),this._addLinkColor(n,this.getShared())},this.registerComponentResourceManagement=()=>{this.viewResourceManager.registerComponent(this.model.id,this.componentResourceManager)},this.applyStyles=(e,t={})=>{if(!e||!e.style)return!1;for(const[s,o]of Object.entries(t))e.style[s]=o;return!0},this.applyStylesToElement=(e,t,s)=>{var o,i;const r=[];if("host"===(t=WcElement._resolveTogglableStylesForElementModel(t)).element){CommonStylesService.applyHostStyles(this.model.type,e,null,this.layoutType);!!("desktop"===this.getEnvironment()&&(null===(o=this.model.props.backgroundDynamicInlineSVGElements)||void 0===o?void 0:o.desktop)||"mobile"===this.getEnvironment()&&(null===(i=this.model.props.backgroundDynamicInlineSVGElements)||void 0===i?void 0:i.mobile))&&(this.colorSchemaListener.apply(this.getEnvironment()),r.push("background"))}let n=t.styleAttributes.background,l=n&&n.match(/url\("([^"]*)"\)/);if(this.manifest.waitForResourcesLoad&&l){this.componentResourceManager.getPending().increment();const e=new Image;e.src=l[1],addEventListenerToElement(e,"load",()=>{this.componentResourceManager.getPending().decrement()}),addEventListenerToElement(e,"error",()=>{this.componentResourceManager.onResourceLoadFailure(e.src),this.isUpdatingRenderMode&&this.componentResourceManager.getPending().decrement()})}const a=Object.assign(Object.assign({},t),{styleAttributes:omitKeys(t.styleAttributes,r)});if(StyleAttributeAccessor.set(e,a),this._setClassAttributes(e,t),s){if(t.hoverStyleAttributes){let o=Object.assign({},t.hoverStyleAttributes);if("FILL_UP"===t.hoverAnimationType){e.style.boxShadow="inset 0px 0px 0px 0px rgb(0, 0, 0, 0)",e.style.overflow="hidden";const s=e.tagName.toLowerCase(),i=`flip-up-animation-${t.element}`;let r=this.getRootElement().querySelector(`#${i}`);r||(r=document.createElement("style"),r.id=i,e.appendChild(r)),insertHtmlIntoElement({element:r,html:`\n ${s}::before {\n content: '';\n background: ${o.background};\n position: absolute;\n left: 0;\n top: ${e.getBoundingClientRect().height}px;\n height: ${e.getBoundingClientRect().height}px;\n width: 100%;\n z-index: -10;\n }\n ${s}:hover::before {\n top: 0;\n transition: 0.3s;\n }\n `}),o=Object.assign(Object.assign({},t.hoverStyleAttributes),{background:"transparent",position:"relative"})}o.borderTopWidth&&"0px"!==o.borderTopWidth||delete o.borderTopColor;o.borderBottomWidth&&"0px"!==o.borderBottomWidth||delete o.borderBottomColor;o.borderLeftWidth&&"0px"!==o.borderLeftWidth||delete o.borderLeftColor;o.borderRightWidth&&"0px"!==o.borderRightWidth||delete o.borderRightColor,this._addStylesToStyleElement(s,t.element,o,`:not(.${applySysAttrPrefix("no-hover")}):hover`,!0)}t.placeholderStyleAttributes&&this._addStylesToStyleElement(s,t.element,t.placeholderStyleAttributes,"::placeholder"),this._addFontStylesToStyleElement(s,this.getShared()),this.stylesAppliedToElement(e,t,s)}},this.applySharedClassesToElementModel=e=>{const t=this.documentModel.getShared();return applySharedClasses(e,t)},this.getModel=()=>this.model,this._addStylesToStyleElement=(e,t,s,o="",i)=>{const r=Object.keys(s).reduce((e,t)=>e+` ${CaseTransformer.camelCaseToDashCase(t)}: ${s[t]}${i?" !important;":";"}`,"");insertHtmlIntoElement({element:e,html:`[${applySysAttrPrefix("element")}="${t}"]${o} { ${r} }`,appendHtml:!0})},this._addFontStylesToStyleElement=(e,t)=>{insertHtmlIntoElement({element:e,html:`[cl-type] {font-family:${t.textFontFamily||"inherit"}}`,appendHtml:!0})},this._addLinkColor=(e,t)=>{var s,o,i,r;t.linkColor&&insertHtmlIntoElement({element:e,html:`a {color: ${t.linkColor}}, a:visited {color: ${t.linkColor}}`,appendHtml:!0}),(null===(s=t.linkParams)||void 0===s?void 0:s.color)&&insertHtmlIntoElement({element:e,html:`a {color: ${null===(o=t.linkParams)||void 0===o?void 0:o.color}}, a:visited {color: ${null===(i=t.linkParams)||void 0===i?void 0:i.color}}`,appendHtml:!0}),(null===(r=t.linkParams)||void 0===r?void 0:r.removeUnderline)&&insertHtmlIntoElement({element:e,html:"a {text-decoration: none}, a:visited {text-decoration: none}",appendHtml:!0})},this._setClassAttributes=(e,t)=>{Array.from(e.classList).filter(e=>e!==applySysClassPrefix("hovered")&&e!==applySysClassPrefix("focused")).forEach(t=>{t.startsWith(RenderConstants.SYSTEM_CLASS_PREFIX)&&e.classList.remove(t)});const s=((e.getAttribute("class")||"")+" "+t.classes).trim();e.setAttribute("class",s)},this.getParentComponent=()=>recursiveFindParentNodeByAttribute(this.parentNode,applySysAttrPrefix("element"),"host"),this.getWidgetContainerNode=()=>{const e=null==this?void 0:this.getAttribute(applySysAttrPrefix("path"));return 1===(null==e?void 0:e.split(",").length)?this.parentNode:recursiveFindParentNodeByAttribute(this.parentNode,applySysAttrPrefix("path"),void 0,e=>1===(null==e?void 0:e.split(",").length))},this.getWidgetLanguages=()=>getWidgetLanguages(this.services.config),this.getPreferredWidgetLanguage=()=>this.getWidgetLanguages()[0],this.getTranslationsMap=e=>getTranslationsMap(e,this.getWidgetLanguages()),this.stylesAppliedToElement=(e,t,s)=>{},this.updateContext=()=>{var e;const t=this.getModel();this.services.context.updateRecord(t.id,{label:this.getContextRecordLabel(t.props),viewIndex:null===(e=t.path)||void 0===e?void 0:e[0]})},this.getAutofillValue=()=>{var e;const t=this.getModel();return new InputFieldsAutofillHydrator(this.services.config,this.services.context.getRegistry()).resolveValue(null===(e=t.props.control)||void 0===e?void 0:e.autofill,t.id)},this.getValidatedAutofillValue=()=>this.isAutofillValidated?this.validatedAutofillValue:void 0,this.syncAutofillContextRecord=(e,t)=>{this.isAutofillValidated=!0,this.validatedAutofillValue=e?t:void 0,e&&this.services.context.updateRecord(this.getModel().id,{value:t})},this.addContextRecord=()=>{var e,t;const s=this.getModel();this.services.context.addRecord(s.id,{recordKey:s.id,id:s.props.control.name,label:this.getContextRecordLabel(s.props),value:null!==(e=this.getValidatedAutofillValue())&&void 0!==e?e:s.props.control.defaultValue||"",viewIndex:null===(t=s.path)||void 0===t?void 0:t[0],sourceId:"FORM",initialData:{fallbackValue:"",exampleValue:this.getContextRecordExampleValue(s.props)}})},this.getContextRecordLabel=e=>{var t,s,o,i,r,n;const l=e.control.name;if(["email","first_name","last_name"].includes(l))return l.toUpperCase();if((null===(t=e.content)||void 0===t?void 0:t.label)&&(null===(i=null===(o=null===(s=e.adaptiveStyles)||void 0===s?void 0:s.desktop.find(e=>"label"===e.element))||void 0===o?void 0:o.params)||void 0===i?void 0:i.enabled)){const t=(new DOMParser).parseFromString(e.content.label,"text/html");return this.capitalizeFirstLetter(t.body.textContent||"")}return(null===(r=e.content)||void 0===r?void 0:r.placeholder)?this.capitalizeFirstLetter(e.content.placeholder):(null===(n=e.control)||void 0===n?void 0:n.integrationName)?this.capitalizeFirstLetter(e.control.integrationName).replace(new RegExp("_","g")," "):void 0},this.capitalizeFirstLetter=e=>e.charAt(0).toUpperCase()+e.slice(1),this.getContextRecordExampleValue=e=>{var t;switch(null===(t=e.control)||void 0===t?void 0:t.name){case"email":return"myemail@example.com";case"first_name":return"Maria";case"last_name":return"Taylor";default:return this.getContextRecordLabel(e)}},this.completeSubmitAction=e=>{const t=e||{},s=this.services.actionRegister.getRegisteredActions().find(e=>e.category===ActionCategory.SUBMIT);s?null==s||s.execute(void 0,void 0,!0,t):this.services.actionFactory.get({type:SysActionTypes.REQUEST}).execute(void 0,void 0,!0,t)},this.getHandlers=()=>{var e;return(null===(e=this.getProps())||void 0===e?void 0:e.handlers)&&this.getProps().handlers.length?[...this.getProps().handlers]:[]},this.assets=(e="")=>`${this.services.config.getConfig("staticResourcesUrl").replace(/\/$/,"")}/${this.manifest.name}/assets${e?`/${e}`:""}`,this.attachShadow({mode:"open"}),this.manifest=this.manifest||(null===(e=this.constructor.define)||void 0===e?void 0:e.manifest)}connectedCallback(){this.construct(),this.registerComponentResourceManagement(),Promise.resolve().then(()=>{this.attachHandlers()});const e=document.createElement("style");e.textContent='\n :host(.cl-game-spotlight-component)::after {\n content: "";\n position: absolute;\n background-size: 100% 100%;\n background-repeat: no-repeat;\n overflow: visible;\n \n backdrop-filter: blur(4px);\n \n inset: -30px;\n mask-image: \n linear-gradient(to bottom, transparent, grey 30px, grey calc(100% - 30px), transparent),\n linear-gradient(to right, transparent, grey 30px, grey calc(100% - 30px), transparent);\n mask-composite: intersect;\n -webkit-mask-composite: source-in; /* for Chrome/Safari */\n \n transition: opacity 0.35s ease;\n pointer-events: auto;\n }\n ',this.getRootElement().prepend(e)}disconnectedCallback(){var e;this.observers.clear(),this.subscriptions.off(),this.state.destroy(),this.componentEventEmitter.destroy(),null===(e=this.mergeTagsProcessor)||void 0===e||e.destroy()}}WcElement._resolveTogglableStylesForElementModel=e=>{const t=Object.assign({},e);return Object.keys(t).forEach(e=>{e.toLowerCase().includes("styleattributes")&&(t[e]=WcElement._resolveTogglableStyles(t[e]))}),t},WcElement._resolveTogglableStyles=e=>{const t=Object.assign({},e),s=(e,s,o)=>{s in t&&(e.forEach(e=>{e in t&&(t[e]=t[s]?t[e]:o)}),delete t[s])};return s(["marginTop","marginBottom","marginLeft","marginRight"],"_marginEnabled","0px"),s(["paddingTop","paddingBottom","paddingLeft","paddingRight"],"_paddingEnabled","0px"),t};export default WcElement;
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/EditorToWidgetEventType";import DefaultMediaQueryListener from"../renderer/style/DefaultMediaQueryListener";import{applySysAttrPrefix,applySysClassPrefix,RenderConstants}from"../renderer/RenderConstants";import StyleAttributeAccessor from"./accessor/StyleAttributeAccessor";import CommonStylesService from"../renderer/style/CommonStylesService";import ColorSchemaListener from"../renderer/style/ColorSchemaListener";import HttpClient from"@claspo/common/network/HttpClient";import omitKeys from"@claspo/common/object/omitKeys";import{CaseTransformer}from"@claspo/common/utils/CaseTransformer";import ComponentResourceManager from"../resource-management/ComponentResourceManager";import createObservers from"../wc-renderer/observers/createObservers";import observerType from"../wc-renderer/observers/observerType";import createSubscriptions from"../wc-renderer/subscriptions/createSubscriptions";import recursiveFindParentNodeByAttribute from"@claspo/common/element/recursiveFindParentNodeByAttribute";import{getTranslationsMap,getWidgetLanguages}from"./TranslationUtils";import ActionCategory from"../action/actions/ActionCategory";import SysActionTypes from"../action/SysActionTypes";import mergeAdaptiveStylesWithEnvIndependentStyles from"../document-model/MergeAdaptiveStylesWithEnvIndependentStyles";import{applySharedClasses,getAdaptiveStylesForPlatform}from"./ModelStyleUtils";import insertHtmlIntoElement from"@claspo/common/dom/insertHtmlIntoElement";import{PayloadEvent}from"./PayloadEvent";import{RenderMode}from"@claspo/common/RenderMode";import InputFieldsAutofillHydrator from"./autofill/InputFieldsAutofillHydrator";import{WidgetToEditorEventType}from"../renderer/WidgetToEditorEventType";class WcElement extends HTMLElement{constructor(){var e;super(),this.skipGameBlur=!0,this.isAutofillValidated=!1,this.validatedAutofillValue=void 0,this.construct=()=>{let e;const t=this.getAttribute(applySysAttrPrefix("id")),s=this.getWidgetContainerNode();if(!s)throw new Error("Widget container not found in construct");const o=s.closest(`[${applySysAttrPrefix("widget-id")}]`);let i;o&&(i=o.getAttribute(applySysAttrPrefix("widget-id")));let r=new PayloadEvent("cl-props-request",{nodeName:this.nodeName,path:this.getAttribute(applySysAttrPrefix("path")),id:t,widgetId:i},{bubbles:!0,composed:!0});this.dispatchEvent(r),e=r.detail.props,Object.assign(this,e),this.observers=createObservers(observerType.PROPS,observerType.SHARED,observerType.ENVIRONMENT),this.subscriptions=createSubscriptions(),this.state=new DefaultState({}),this.componentEventEmitter=new DefaultEventEmitter,this.componentResourceManager=new ComponentResourceManager(this.model.id,this.services.eventEmitter,this.isStaticRenderMode()),this.mergeTagsProcessor=this.services.mergeTagsProcessorFactory.create(),this._actionFactory=this.services.actionFactory,this._handlerFactory=new HandlerFactory(this._actionFactory,this.services.actionRegister),this.prevProps=this.model.props,this.prevEnvironment=this.getEnvironment(),this.documentModel.on(`${EditorToWidgetEventType.COMPONENT_PROPS_UPDATE}_${this.model.id}`,e=>{this.model.props=e,this.observers.get(observerType.PROPS).forEach(t=>t(this.prevProps,e)),this.prevProps=e;const t=this.getHostElement(),s=applySysAttrPrefix("floating");e.floating&&!t.getAttribute(s)?t.setAttribute(s,"true"):!e.floating&&t.getAttribute(s)&&t.removeAttribute(s)}),this.documentModel.on(`${EditorToWidgetEventType.COMPONENT_UPDATE}_${this.model.id}`,e=>{Object.assign(this.model,e)}),this.documentModel.on(EditorToWidgetEventType.SHARED_UPDATE_ALL,()=>{this.applyAutoAdaptiveStyles(this.prevProps.adaptiveStyles,this.prevProps.styles),this.observers.get(observerType.SHARED).forEach(e=>e(this.getShared()))}),this.model.props.backgroundDynamicInlineSVGElements&&(this.colorSchemaListener=new ColorSchemaListener(this.documentModel,this.getHostElement(),()=>this.getShared(),()=>this.model.props,()=>this.getEnvironment(),HttpClient),this.colorSchemaListener.apply(this.getEnvironment()).then(()=>{this.subscriptions.push(this.colorSchemaListener.on())})),this.prevProps.adaptiveStyles&&this.subscriptions.push(this.resizeListener.on(DefaultMediaQueryListener.changeEventName,()=>{this.applyAutoAdaptiveStyles(this.prevProps.adaptiveStyles,this.prevProps.styles);const e=this.getEnvironment();this.observers.get(observerType.ENVIRONMENT).forEach(t=>t(this.prevEnvironment,e)),this.prevEnvironment=e})),this.subscriptions.push(this.services.eventEmitter.on(WidgetToEditorEventType.GAME_PHASE_READY_TO_PLAY,()=>{this.skipGameBlur||this.getHostElement().classList.add("cl-game-spotlight-component")})),this.subscriptions.push(this.services.eventEmitter.on(WidgetToEditorEventType.GAME_PHASE_COMPLETED,()=>{this.skipGameBlur||this.getHostElement().classList.remove("cl-game-spotlight-component")}))},this.attachHandlers=()=>{this.getHandlers().map(e=>this._handlerFactory.get(e)).map(e=>()=>e.activate(this.state,this.componentEventEmitter,this.getHostElement.bind(this))).forEach(e=>e())},this.postponeHandlers=()=>{var e;null===(e=this.handlers)||void 0===e||e.forEach(e=>e.postpone())},this.releaseHandlers=()=>{var e;null===(e=this.handlers)||void 0===e||e.forEach(e=>e.release())},this.getProps=()=>{var e;return null===(e=this.getModel())||void 0===e?void 0:e.props},this.getShared=()=>this.documentModel.getShared(),this.getEnvironment=()=>this.resizeListener.isMobile()?"mobile":"desktop",this.isStaticRenderMode=()=>this.services.config.getConfig("renderMode")===RenderMode.STATIC,this.isUpdatingRenderMode=()=>this.services.config.getConfig("renderMode")===RenderMode.UPDATING,this.getRootElement=()=>this.shadowRoot?this.shadowRoot:this,this.getHostElement=()=>this,this.observeProps=e=>{this.observers.get(observerType.PROPS).push(e),e(null,this.prevProps)},this.observeShared=e=>{this.observers.get(observerType.SHARED).push(e),e(this.getShared())},this.observeEnvironment=e=>{this.observers.get(observerType.ENVIRONMENT).push(e),e(null,this.getEnvironment())},this.getElements=()=>[this.getHostElement(),...Array.from(this.getRootElement().querySelectorAll(`[${applySysAttrPrefix("element")}]`)).filter(e=>!e.hasAttribute(applySysAttrPrefix("component")))],this.getElement=(e,t)=>this.getElements().find(s=>t?s.getAttribute(applySysAttrPrefix("element"))===e&&s.id===t:s.getAttribute(applySysAttrPrefix("element"))===e),this.applyAutoAdaptiveStyles=(e,t)=>{if(!e&&!t)return;const s=this.getElements();if(!s.length)return;const o=mergeAdaptiveStylesWithEnvIndependentStyles(e,t),i=applySysAttrPrefix("type"),r="element-styles";let n=this.getRootElement().querySelector(`style[${i}="${r}"]`);n||(n=document.createElement("style"),n.setAttribute(i,r),this.getRootElement().appendChild(n)),insertHtmlIntoElement({element:n,html:""}),s.forEach(e=>{let t=e.getAttribute(applySysAttrPrefix("element"));const s=this.getEnvironment();let i=getAdaptiveStylesForPlatform(o,s,t);if(i){if(this.resizeListener.isMobile()){const e=getAdaptiveStylesForPlatform(o,"desktop",t);e&&(i=Object.assign(Object.assign({},i),{styleAttributes:Object.assign(Object.assign({},e.styleAttributes),i.styleAttributes)}))}this.applyStylesToElement(e,this.applySharedClassesToElementModel(i),n)}}),this._addLinkColor(n,this.getShared())},this.registerComponentResourceManagement=()=>{this.viewResourceManager.registerComponent(this.model.id,this.componentResourceManager)},this.applyStyles=(e,t={})=>{if(!e||!e.style)return!1;for(const[s,o]of Object.entries(t))e.style[s]=o;return!0},this.applyStylesToElement=(e,t,s)=>{var o,i;const r=[];if("host"===(t=WcElement._resolveTogglableStylesForElementModel(t)).element){CommonStylesService.applyHostStyles(this.model.type,e,null,this.layoutType);!!("desktop"===this.getEnvironment()&&(null===(o=this.model.props.backgroundDynamicInlineSVGElements)||void 0===o?void 0:o.desktop)||"mobile"===this.getEnvironment()&&(null===(i=this.model.props.backgroundDynamicInlineSVGElements)||void 0===i?void 0:i.mobile))&&(this.colorSchemaListener.apply(this.getEnvironment()),r.push("background"))}let n=t.styleAttributes.background,l=n&&n.match(/url\("([^"]*)"\)/);if(this.manifest.waitForResourcesLoad&&l){this.componentResourceManager.getPending().increment();const e=new Image;e.src=l[1],addEventListenerToElement(e,"load",()=>{this.componentResourceManager.getPending().decrement()}),addEventListenerToElement(e,"error",()=>{this.componentResourceManager.onResourceLoadFailure(e.src),this.isUpdatingRenderMode&&this.componentResourceManager.getPending().decrement()})}const a=Object.assign(Object.assign({},t),{styleAttributes:omitKeys(t.styleAttributes,r)});if(StyleAttributeAccessor.set(e,a),this._setClassAttributes(e,t),s){if(t.hoverStyleAttributes){let o=Object.assign({},t.hoverStyleAttributes);if("FILL_UP"===t.hoverAnimationType){e.style.boxShadow="inset 0px 0px 0px 0px rgb(0, 0, 0, 0)",e.style.overflow="hidden";const s=e.tagName.toLowerCase(),i=`flip-up-animation-${t.element}`;let r=this.getRootElement().querySelector(`#${i}`);r||(r=document.createElement("style"),r.id=i,e.appendChild(r)),insertHtmlIntoElement({element:r,html:`\n ${s}::before {\n content: '';\n background: ${o.background};\n position: absolute;\n left: 0;\n top: ${e.getBoundingClientRect().height}px;\n height: ${e.getBoundingClientRect().height}px;\n width: 100%;\n z-index: -10;\n }\n ${s}:hover::before {\n top: 0;\n transition: 0.3s;\n }\n `}),o=Object.assign(Object.assign({},t.hoverStyleAttributes),{background:"transparent",position:"relative"})}o.borderTopWidth&&"0px"!==o.borderTopWidth||delete o.borderTopColor;o.borderBottomWidth&&"0px"!==o.borderBottomWidth||delete o.borderBottomColor;o.borderLeftWidth&&"0px"!==o.borderLeftWidth||delete o.borderLeftColor;o.borderRightWidth&&"0px"!==o.borderRightWidth||delete o.borderRightColor,this._addStylesToStyleElement(s,t.element,o,`:not(.${applySysAttrPrefix("no-hover")}):hover`,!0)}t.placeholderStyleAttributes&&this._addStylesToStyleElement(s,t.element,t.placeholderStyleAttributes,"::placeholder"),this._addFontStylesToStyleElement(s,this.getShared()),this.stylesAppliedToElement(e,t,s)}},this.applySharedClassesToElementModel=e=>{const t=this.documentModel.getShared();return applySharedClasses(e,t,this.resizeListener.isMobile())},this.getModel=()=>this.model,this._addStylesToStyleElement=(e,t,s,o="",i)=>{const r=Object.keys(s).reduce((e,t)=>e+` ${CaseTransformer.camelCaseToDashCase(t)}: ${s[t]}${i?" !important;":";"}`,"");insertHtmlIntoElement({element:e,html:`[${applySysAttrPrefix("element")}="${t}"]${o} { ${r} }`,appendHtml:!0})},this._addFontStylesToStyleElement=(e,t)=>{insertHtmlIntoElement({element:e,html:`[cl-type] {font-family:${t.textFontFamily||"inherit"}}`,appendHtml:!0})},this._addLinkColor=(e,t)=>{var s,o,i,r;t.linkColor&&insertHtmlIntoElement({element:e,html:`a {color: ${t.linkColor}}, a:visited {color: ${t.linkColor}}`,appendHtml:!0}),(null===(s=t.linkParams)||void 0===s?void 0:s.color)&&insertHtmlIntoElement({element:e,html:`a {color: ${null===(o=t.linkParams)||void 0===o?void 0:o.color}}, a:visited {color: ${null===(i=t.linkParams)||void 0===i?void 0:i.color}}`,appendHtml:!0}),(null===(r=t.linkParams)||void 0===r?void 0:r.removeUnderline)&&insertHtmlIntoElement({element:e,html:"a {text-decoration: none}, a:visited {text-decoration: none}",appendHtml:!0})},this._setClassAttributes=(e,t)=>{Array.from(e.classList).filter(e=>e!==applySysClassPrefix("hovered")&&e!==applySysClassPrefix("focused")).forEach(t=>{t.startsWith(RenderConstants.SYSTEM_CLASS_PREFIX)&&e.classList.remove(t)});const s=((e.getAttribute("class")||"")+" "+t.classes).trim();e.setAttribute("class",s)},this.getParentComponent=()=>recursiveFindParentNodeByAttribute(this.parentNode,applySysAttrPrefix("element"),"host"),this.getWidgetContainerNode=()=>{const e=null==this?void 0:this.getAttribute(applySysAttrPrefix("path"));return 1===(null==e?void 0:e.split(",").length)?this.parentNode:recursiveFindParentNodeByAttribute(this.parentNode,applySysAttrPrefix("path"),void 0,e=>1===(null==e?void 0:e.split(",").length))},this.getWidgetLanguages=()=>getWidgetLanguages(this.services.config),this.getPreferredWidgetLanguage=()=>this.getWidgetLanguages()[0],this.getTranslationsMap=e=>getTranslationsMap(e,this.getWidgetLanguages()),this.stylesAppliedToElement=(e,t,s)=>{},this.updateContext=()=>{var e;const t=this.getModel();this.services.context.updateRecord(t.id,{label:this.getContextRecordLabel(t.props),viewIndex:null===(e=t.path)||void 0===e?void 0:e[0]})},this.getAutofillValue=()=>{var e;const t=this.getModel();return new InputFieldsAutofillHydrator(this.services.config,this.services.context.getRegistry()).resolveValue(null===(e=t.props.control)||void 0===e?void 0:e.autofill,t.id)},this.getValidatedAutofillValue=()=>this.isAutofillValidated?this.validatedAutofillValue:void 0,this.syncAutofillContextRecord=(e,t)=>{this.isAutofillValidated=!0,this.validatedAutofillValue=e?t:void 0,e&&this.services.context.updateRecord(this.getModel().id,{value:t})},this.addContextRecord=()=>{var e,t;const s=this.getModel();this.services.context.addRecord(s.id,{recordKey:s.id,id:s.props.control.name,label:this.getContextRecordLabel(s.props),value:null!==(e=this.getValidatedAutofillValue())&&void 0!==e?e:s.props.control.defaultValue||"",viewIndex:null===(t=s.path)||void 0===t?void 0:t[0],sourceId:"FORM",initialData:{fallbackValue:"",exampleValue:this.getContextRecordExampleValue(s.props)}})},this.getContextRecordLabel=e=>{var t,s,o,i,r,n;const l=e.control.name;if(["email","first_name","last_name"].includes(l))return l.toUpperCase();if((null===(t=e.content)||void 0===t?void 0:t.label)&&(null===(i=null===(o=null===(s=e.adaptiveStyles)||void 0===s?void 0:s.desktop.find(e=>"label"===e.element))||void 0===o?void 0:o.params)||void 0===i?void 0:i.enabled)){const t=(new DOMParser).parseFromString(e.content.label,"text/html");return this.capitalizeFirstLetter(t.body.textContent||"")}return(null===(r=e.content)||void 0===r?void 0:r.placeholder)?this.capitalizeFirstLetter(e.content.placeholder):(null===(n=e.control)||void 0===n?void 0:n.integrationName)?this.capitalizeFirstLetter(e.control.integrationName).replace(new RegExp("_","g")," "):void 0},this.capitalizeFirstLetter=e=>e.charAt(0).toUpperCase()+e.slice(1),this.getContextRecordExampleValue=e=>{var t;switch(null===(t=e.control)||void 0===t?void 0:t.name){case"email":return"myemail@example.com";case"first_name":return"Maria";case"last_name":return"Taylor";default:return this.getContextRecordLabel(e)}},this.completeSubmitAction=e=>{const t=e||{},s=this.services.actionRegister.getRegisteredActions().find(e=>e.category===ActionCategory.SUBMIT);s?null==s||s.execute(void 0,void 0,!0,t):this.services.actionFactory.get({type:SysActionTypes.REQUEST}).execute(void 0,void 0,!0,t)},this.getHandlers=()=>{var e;return(null===(e=this.getProps())||void 0===e?void 0:e.handlers)&&this.getProps().handlers.length?[...this.getProps().handlers]:[]},this.assets=(e="")=>`${this.services.config.getConfig("staticResourcesUrl").replace(/\/$/,"")}/${this.manifest.name}/assets${e?`/${e}`:""}`,this.attachShadow({mode:"open"}),this.manifest=this.manifest||(null===(e=this.constructor.define)||void 0===e?void 0:e.manifest)}connectedCallback(){this.construct(),this.registerComponentResourceManagement(),Promise.resolve().then(()=>{this.attachHandlers()});const e=document.createElement("style");e.textContent='\n :host(.cl-game-spotlight-component)::after {\n content: "";\n position: absolute;\n background-size: 100% 100%;\n background-repeat: no-repeat;\n overflow: visible;\n \n backdrop-filter: blur(4px);\n \n inset: -30px;\n mask-image: \n linear-gradient(to bottom, transparent, grey 30px, grey calc(100% - 30px), transparent),\n linear-gradient(to right, transparent, grey 30px, grey calc(100% - 30px), transparent);\n mask-composite: intersect;\n -webkit-mask-composite: source-in; /* for Chrome/Safari */\n \n transition: opacity 0.35s ease;\n pointer-events: auto;\n }\n ',this.getRootElement().prepend(e)}disconnectedCallback(){var e;this.observers.clear(),this.subscriptions.off(),this.state.destroy(),this.componentEventEmitter.destroy(),null===(e=this.mergeTagsProcessor)||void 0===e||e.destroy()}}WcElement._resolveTogglableStylesForElementModel=e=>{const t=Object.assign({},e);return Object.keys(t).forEach(e=>{e.toLowerCase().includes("styleattributes")&&(t[e]=WcElement._resolveTogglableStyles(t[e]))}),t},WcElement._resolveTogglableStyles=e=>{const t=Object.assign({},e),s=(e,s,o)=>{s in t&&(e.forEach(e=>{e in t&&(t[e]=t[s]?t[e]:o)}),delete t[s])};return s(["marginTop","marginBottom","marginLeft","marginRight"],"_marginEnabled","0px"),s(["paddingTop","paddingBottom","paddingLeft","paddingRight"],"_paddingEnabled","0px"),t};export default WcElement;
@@ -1 +1 @@
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();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:t=>{t||(e.preventDefault(),this.services.eventEmitter.emit(WidgetToEditorEventType.COMPONENT_DRAGEND))}})}_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
+ 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/EditorToWidgetEventType";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();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:t=>{t||(e.preventDefault(),this.services.eventEmitter.emit(WidgetToEditorEventType.COMPONENT_DRAGEND))}})}_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")))}}}
package/sdk.d.ts DELETED
@@ -1,11 +0,0 @@
1
- import UpdatingEntryModule from "./UpdatingEntryModule";
2
- import StaticEntryModule from "./StaticEntryModule";
3
- import CompositionRoot from "./CompositionRoot";
4
- import ViewRouter from "./ViewRouter";
5
- import ViewEntryType from "./document-model/ViewEntryType";
6
- import ComponentType from './sdk/ComponentType';
7
- import { EditorToWidgetEventType } from "./document-model/DocumentModelService";
8
- import { RenderConstants } from "./renderer/RenderConstants";
9
- import { WidgetToEditorEventType } from "./renderer/WidgetToEditorEventType";
10
- import { LoopAnimationStylesService } from "./renderer/style/LoopAnimationStylesService";
11
- export { UpdatingEntryModule, StaticEntryModule, ViewRouter, CompositionRoot, ComponentType, ViewEntryType, EditorToWidgetEventType, RenderConstants, WidgetToEditorEventType, LoopAnimationStylesService };
package/sdk.js DELETED
@@ -1 +0,0 @@
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};