@claspo/renderer 18.0.8 → 18.0.9-marteh.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/StaticEntryModule.js +1 -1
- package/UpdatingEntryModule.js +1 -1
- package/action/UTMParamsExtractor.d.ts +4 -1
- package/action/UTMParamsExtractor.js +1 -1
- package/action/actions/BaseRequestAction.js +1 -1
- package/document-model/DocumentModelService.d.ts +1 -1
- package/document-model/DocumentModelService.js +1 -1
- package/document-model/DocumentService.js +1 -1
- package/package.json +2 -2
- package/renderer/DragEventListener.js +1 -1
- package/renderer/{ViewRendererActionType.d.ts → WidgetToEditorEventType.d.ts} +2 -1
- package/renderer/WidgetToEditorEventType.js +1 -0
- package/renderer/style/ClDocumentResizeListener.js +1 -1
- package/renderer/style/ColorSchemaListener.js +1 -1
- package/renderer/style/DefaultMediaQueryListener.js +1 -1
- package/renderer/style/MobileDeviceOrientationListener.js +1 -1
- package/resource-management/ViewResourcesManager.js +1 -1
- package/sdk/WcElement.js +1 -1
- package/sdk/source/sources/UrlQueryParamsSource.d.ts +2 -1
- package/sdk/source/sources/UrlQueryParamsSource.js +1 -1
- package/sdk.d.ts +3 -3
- package/sdk.js +1 -1
- package/wc-renderer/WcViewRenderer.js +1 -1
- package/wc-renderer/decorators/wcUpdatingDecorator.js +1 -1
- package/renderer/ViewRendererActionType.js +0 -1
package/StaticEntryModule.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import CompositionRoot from"./CompositionRoot";import ViewRouter from"./ViewRouter";import TranslateUtils from"./i18n/TranslateUtils";import{
|
|
1
|
+
import CompositionRoot from"./CompositionRoot";import ViewRouter from"./ViewRouter";import TranslateUtils from"./i18n/TranslateUtils";import{EditorToWidgetEventType}from"./document-model/DocumentModelService";import CssVarsOperations from"@claspo/common/element/CssVarsOperations";import wcStaticDecorator from"./wc-renderer/decorators/wcStaticDecorator";import{RenderMode}from"@claspo/common/RenderMode";export default class StaticEntryModule{constructor(e,t,o,i,s,r,n){this.renderMode=RenderMode.STATIC,this.componentResolver=t,this.componentRegister=o,this.config=Object.assign(Object.assign({},i),{renderMode:this.renderMode}),this.documentJson=e,this.translations=s,this.compositionRoot=null,this.viewRenderer=null,this.viewRouter=null,this.trackingService=r||{send:()=>{},trackClick:()=>{},trackTargetAction:()=>{}},this.layoutType=n,this.componentFactory=null,o.register(wcStaticDecorator,this.renderMode)}init(e){const t=e||document;this.documentJson=TranslateUtils.applyTranslationObjectToComponentsIfNeeded(JSON.parse(JSON.stringify(this.documentJson)),this.componentResolver.getComponentManifests(),this.translations);const o=new CompositionRoot(this.documentJson,this.config,this.trackingService,null,"",this.layoutType,this.renderMode,this.componentRegister,t),i=new ViewRouter(o.services.eventEmitter,o.services.documentModel,o.services.viewRenderer,this.config&&this.config.optionalDocumentStyles,o.services);return o.services.viewRouter=i,this.compositionRoot=o,this.viewRenderer=o.services.viewRenderer,this.componentFactory=o.services.componentFactory,this.viewRouter=i,i.start(this.config.viewIndex)}destroy(){var e,t;null===(e=this.viewRouter)||void 0===e||e.destroy(),null===(t=this.compositionRoot)||void 0===t||t.destroy()}performAction(e,t){const o=this.compositionRoot.services.documentService.handleModelUpdate(e,t);switch(e){case EditorToWidgetEventType.COLOR_SCHEMA_UPDATE:{const e=this.compositionRoot.services.documentModel.getShared().cssVars;CssVarsOperations.override(e,this.viewRouter.getDocumentContainer());break}}return o}listenAction(e,t){this.compositionRoot.services.eventEmitter.on(e,(e,o)=>{t(e,o)})}}
|
package/UpdatingEntryModule.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import CompositionRoot from"./CompositionRoot";import{
|
|
1
|
+
import CompositionRoot from"./CompositionRoot";import{EditorToWidgetEventType}from"./document-model/DocumentModelService";import DocumentUtils from"@claspo/common/document/DocumentUtils";import DragEventListener from"./renderer/DragEventListener";import{RenderMode}from"@claspo/common/RenderMode";import{asyncActionEmitter}from"./action/asyncAction";import CssVarsOperations from"@claspo/common/element/CssVarsOperations";export default class UpdatingEntryModule{constructor(e,t,o,i,s={},n){this.renderMode=RenderMode.UPDATING,this.documentJson=JSON.parse(JSON.stringify(e)),this.componentResolver=t,this.componentRegister=o,this.componentCommonStyles=i,this.config=Object.assign(Object.assign({},s),{renderMode:this.renderMode}),this.compositionRoot=null,this.viewRenderer=null,this.viewComponents=[],this.layoutType=n}init(e){const t=new CompositionRoot(this.documentJson,this.config,{send:()=>{}},e,this.componentCommonStyles,this.layoutType,this.renderMode,this.componentRegister,document);return this.compositionRoot=t,this.viewRenderer=t.services.viewRenderer,this.componentFactory=t.services.componentFactory,this.containerElement=e,this.dragEventListener=new DragEventListener(this.compositionRoot.services.eventEmitter,this.compositionRoot.services.documentModel),this.viewComponents=this.compositionRoot.services.documentModel.getViews().map((e,t)=>this.viewRenderer.render(e,t,this.config.renderMode)),this.viewComponents}destroy(){var e,t;this.viewComponents.forEach(e=>e.remove()),null===(e=this.dragEventListener)||void 0===e||e.destroy(),null===(t=this.compositionRoot)||void 0===t||t.destroy()}performAction(e,t){switch(e){case EditorToWidgetEventType.COMPONENT_REMOVE:case EditorToWidgetEventType.COMPONENT_MOVE:case EditorToWidgetEventType.COMPONENT_INSERT:case EditorToWidgetEventType.COMPONENT_PROPS_UPDATE:case EditorToWidgetEventType.COMPONENT_UPDATE:case EditorToWidgetEventType.MOBILE_BREAKPOINT_UPDATE:case EditorToWidgetEventType.ENVIRONMENT_UPDATE:case EditorToWidgetEventType.TEXT_CLASS_ADDED:case EditorToWidgetEventType.TEXT_CLASS_UPDATED:case EditorToWidgetEventType.TEXT_CLASS_REMOVED:case EditorToWidgetEventType.HEADER_FONT_FAMILY_UPDATE:case EditorToWidgetEventType.TEXT_FONT_FAMILY_UPDATE:case EditorToWidgetEventType.SHARED_UPDATE:return asyncActionEmitter(this.compositionRoot.services.eventEmitter.emit.bind(this.compositionRoot.services.eventEmitter))(this.compositionRoot.services.documentService.handleModelUpdate.bind(this.compositionRoot.services.documentService),e)(e,t);case EditorToWidgetEventType.COLOR_SCHEMA_UPDATE:{const e=this.compositionRoot.services.documentModel.getShared().cssVars;this.viewComponents.forEach(t=>{CssVarsOperations.override(e,t)});break}case EditorToWidgetEventType.THEME_UPDATE:return asyncActionEmitter(this.compositionRoot.services.eventEmitter.emit.bind(this.compositionRoot.services.eventEmitter))(this.compositionRoot.services.documentService.handleModelUpdate.bind(this.compositionRoot.services.documentService),e)(e,t);default:this.compositionRoot.services.eventEmitter.emit(e,t)}}listenAction(e,t){this.compositionRoot.services.eventEmitter.on(e,(e,o)=>{t(e,o)})}getHostElementById(e){const t=DocumentUtils.getNodeById(this.viewComponents.map(e=>e.getModel()),e);return t&&t.componentRef}getHostElementByPath(e){const t=DocumentUtils.getNodeByPath(this.viewComponents.map(e=>e.getModel()),e);return t&&t.componentRef}getContextRecordsMap(){var e;return(null===(e=this.compositionRoot)||void 0===e?void 0:e.services.context.getRecordsMap())||{}}listenContextAction(e,t){this.compositionRoot.services.context.on(e,(e,o)=>{t(e,o)})}}
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import ContextSDK from '../sdk/context/ContextSDK';
|
|
1
2
|
export default class UTMParamsExtractor {
|
|
2
|
-
static
|
|
3
|
+
static extractTrackingParams(context: ContextSDK): {};
|
|
4
|
+
static extractUtmParams(context: ContextSDK): {};
|
|
5
|
+
static extractMarTechParams(context: ContextSDK): {};
|
|
3
6
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import UrlQueryParamsSource from"../sdk/source/sources/UrlQueryParamsSource";export default class UTMParamsExtractor{static extractUtmParams(
|
|
1
|
+
import UrlQueryParamsSource from"../sdk/source/sources/UrlQueryParamsSource";function getLastMarTechValue(t,e){for(let r=t.length-1;r>=0;r--){const a=new URLSearchParams(t[r]),c=[];for(const[t,r]of a.entries())e.includes(t)&&r&&c.push(r);if(c.length)return c[c.length-1]}return""}export default class UTMParamsExtractor{static extractTrackingParams(t){return Object.assign(Object.assign({},UTMParamsExtractor.extractUtmParams(t)),UTMParamsExtractor.extractMarTechParams(t))}static extractUtmParams(t){const e={id:"id",fallbackValue:"",exampleValue:"exampleValue",sourceId:UrlQueryParamsSource.sourceId,arguments:[{type:"string",name:"urlQueryParamName",value:""}]},r={},a=t.getRegistry().getSource(e.sourceId),c=a.getValue("utm");return["utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id"].forEach(t=>{const s=c.processor(a,Object.assign(Object.assign({},e),{arguments:[Object.assign(Object.assign({},e.arguments[0]),{value:t})]}));s&&(r[t]=s)}),r}static extractMarTechParams(t){const e=t.getRegistry().getSource(UrlQueryParamsSource.sourceId).getSessionHistory(),r={};return Object.entries({rdt_cid:["rdt_cid"],sccid:["sccid","ScCid"],gclid:["gclid"],fbclid:["fbclid"],ttclid:["ttclid"],li_fat_id:["li_fat_id"],ascsubtag:["ascsubtag"],msclkid:["msclkid"],twclid:["twclid"],epik:["epik"]}).forEach(([t,a])=>{r[t]=getLastMarTechValue(e,a)}),r}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import SysActionTypes from"../SysActionTypes";import SysEventTypes from"../../common/SysEventTypes";import{HttpStatus}from"@claspo/common/network/HttpStatus";import ActionCategory from"./ActionCategory";import systemResultStateNames from"../../document-model/systemResultStateNames";import DocumentUtils from"@claspo/common/document/DocumentUtils";import getComponentCountOnView from"../../sdk/getComponentCountOnView";import UTMParamsExtractor from"../UTMParamsExtractor";import isDictionary from"@claspo/common/object/isDictionary";function componentModelHasSubmitAction(t){var e,s;try{return!!(null===(s=null===(e=t.props)||void 0===e?void 0:e.handlers)||void 0===s?void 0:s.find(t=>{var e;return null===(e=null==t?void 0:t.actions)||void 0===e?void 0:e.find(t=>[SysActionTypes.REQUEST,SysActionTypes.SUBSCRIBE_CONTACT].includes(t.type))}))}catch(t){return!1}}function viewHasControls(t){if(!t)return!1;let e=0;return DocumentUtils.iterateDepthFirst(t,t=>{(["INPUT","MULTIPLE_INPUT","PRIZE_BASED_GAMING"].includes(t.type)||componentModelHasSubmitAction(t))&&e++}),e>0}function isSystemView(t){return t&&systemResultStateNames.includes(t.label)}export const RequestStatus={SUCCESS:"SUCCESS",ALREADY_SUBSCRIBED:"ALREADY_SUBSCRIBED",ERROR:"ERROR",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS"};export default class BaseRequestAction{constructor(t,e,s,i,n,o,r,a,c){this.skipHttpRequest=!0,this.id=s.id,this.params=s.params,this.form=e,this.eventEmitter=t,this.httpClient=i,this.configService=n,this.formEventsListener=null,this.tracking=o,this.stateService=r,this.context=a,this.getServices=c,this.category=ActionCategory.SUBMIT}getTrackingMessageBeforeSentData(){return""}getTrackingMessageByStatus(t){return""}execute(t,e,s,i){if(this.formEventsListener&&this.formEventsListener.off(),!this.form.submitQueuedAfterPending||!0===t){if(!this.form.preventSubmit)return new Promise(n=>{if(!this.form.isPending()){this.form.submitQueuedAfterPending=!1;const o=!0===t?e:n;return this.submit(o,s,i)}this.form.submitQueuedAfterPending=!0,setTimeout(()=>this.execute(!0,n,s,i),500)});this.form.submitQueuedAfterPending=!1}}submit(t,e,s){const i=this.getServices().viewRouter.getCurrentViewIndex(),n=this.getServices().documentModel.getViews().slice(i+1).filter(t=>!systemResultStateNames.includes(t.label)).length>0,o=Object.assign(Object.assign({},this.params),s);if(this.form.markAsTouched(),this.stateService.getState().emitActionOnSubmit&&this.eventEmitter.emit(this.stateService.getState().emitActionOnSubmit.eventName),this.stateService.getState().interceptSubmitActions&&!e)return;if(!this.form.isValid()&&!o.skipValidation)return this.eventEmitter.emit("INVALID_CONTACT_DATA_SUBMIT_ATTEMPT"),void t(!1);const r=this.stateService,a=r.getState().conditionalRedirectViewId,c=o.conditionalRedirectViewId||a;a&&(o.conditionalRedirectViewId=a,r.setState({conditionalRedirectViewId:null}));let u=this.getServices().documentModel.getViews()[i+1];const m=this.getServices().documentModel.getViews()[i];if(c&&getComponentCountOnView(m,"SysNetPromoterScoreComponent")+getComponentCountOnView(m,"SysFeedbackComponent")===1&&(u=this.getServices().documentModel.getViews().find(t=>t.id===o.conditionalRedirectViewId),viewHasControls(u)||isSystemView(u)))return this.goToView(u.path[0],o),void t(!0);const S=this.form.getControlsMap(),d=this.context.getKVMap();if(n&&(viewHasControls(u)||!Object.keys(S).length&&!Object.keys(d).length))return this.goToView(i+1,o),void t(!0);if(!Object.keys(S).length&&!Object.keys(d).length)return void t(!0);const l=UTMParamsExtractor.
|
|
1
|
+
import SysActionTypes from"../SysActionTypes";import SysEventTypes from"../../common/SysEventTypes";import{HttpStatus}from"@claspo/common/network/HttpStatus";import ActionCategory from"./ActionCategory";import systemResultStateNames from"../../document-model/systemResultStateNames";import DocumentUtils from"@claspo/common/document/DocumentUtils";import getComponentCountOnView from"../../sdk/getComponentCountOnView";import UTMParamsExtractor from"../UTMParamsExtractor";import isDictionary from"@claspo/common/object/isDictionary";function componentModelHasSubmitAction(t){var e,s;try{return!!(null===(s=null===(e=t.props)||void 0===e?void 0:e.handlers)||void 0===s?void 0:s.find(t=>{var e;return null===(e=null==t?void 0:t.actions)||void 0===e?void 0:e.find(t=>[SysActionTypes.REQUEST,SysActionTypes.SUBSCRIBE_CONTACT].includes(t.type))}))}catch(t){return!1}}function viewHasControls(t){if(!t)return!1;let e=0;return DocumentUtils.iterateDepthFirst(t,t=>{(["INPUT","MULTIPLE_INPUT","PRIZE_BASED_GAMING"].includes(t.type)||componentModelHasSubmitAction(t))&&e++}),e>0}function isSystemView(t){return t&&systemResultStateNames.includes(t.label)}export const RequestStatus={SUCCESS:"SUCCESS",ALREADY_SUBSCRIBED:"ALREADY_SUBSCRIBED",ERROR:"ERROR",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS"};export default class BaseRequestAction{constructor(t,e,s,i,n,o,r,a,c){this.skipHttpRequest=!0,this.id=s.id,this.params=s.params,this.form=e,this.eventEmitter=t,this.httpClient=i,this.configService=n,this.formEventsListener=null,this.tracking=o,this.stateService=r,this.context=a,this.getServices=c,this.category=ActionCategory.SUBMIT}getTrackingMessageBeforeSentData(){return""}getTrackingMessageByStatus(t){return""}execute(t,e,s,i){if(this.formEventsListener&&this.formEventsListener.off(),!this.form.submitQueuedAfterPending||!0===t){if(!this.form.preventSubmit)return new Promise(n=>{if(!this.form.isPending()){this.form.submitQueuedAfterPending=!1;const o=!0===t?e:n;return this.submit(o,s,i)}this.form.submitQueuedAfterPending=!0,setTimeout(()=>this.execute(!0,n,s,i),500)});this.form.submitQueuedAfterPending=!1}}submit(t,e,s){const i=this.getServices().viewRouter.getCurrentViewIndex(),n=this.getServices().documentModel.getViews().slice(i+1).filter(t=>!systemResultStateNames.includes(t.label)).length>0,o=Object.assign(Object.assign({},this.params),s);if(this.form.markAsTouched(),this.stateService.getState().emitActionOnSubmit&&this.eventEmitter.emit(this.stateService.getState().emitActionOnSubmit.eventName),this.stateService.getState().interceptSubmitActions&&!e)return;if(!this.form.isValid()&&!o.skipValidation)return this.eventEmitter.emit("INVALID_CONTACT_DATA_SUBMIT_ATTEMPT"),void t(!1);const r=this.stateService,a=r.getState().conditionalRedirectViewId,c=o.conditionalRedirectViewId||a;a&&(o.conditionalRedirectViewId=a,r.setState({conditionalRedirectViewId:null}));let u=this.getServices().documentModel.getViews()[i+1];const m=this.getServices().documentModel.getViews()[i];if(c&&getComponentCountOnView(m,"SysNetPromoterScoreComponent")+getComponentCountOnView(m,"SysFeedbackComponent")===1&&(u=this.getServices().documentModel.getViews().find(t=>t.id===o.conditionalRedirectViewId),viewHasControls(u)||isSystemView(u)))return this.goToView(u.path[0],o),void t(!0);const S=this.form.getControlsMap(),d=this.context.getKVMap();if(n&&(viewHasControls(u)||!Object.keys(S).length&&!Object.keys(d).length))return this.goToView(i+1,o),void t(!0);if(!Object.keys(S).length&&!Object.keys(d).length)return void t(!0);const l=UTMParamsExtractor.extractTrackingParams(this.context),g=this.constructRequestPayload({contextValue:d,formValue:S,utmParams:l});this.eventEmitter.emit("CONTACT_DATA_SUBMIT",g);this.getTrackingMessageBeforeSentData()&&this.tracking.send("FormFinish_[Name]"),this.configService.getConfig("isBot")?t():this.sendRequest(g).then(t=>t.json().then(e=>t.status===HttpStatus.TOO_MANY_REQUESTS?{state:RequestStatus.TOO_MANY_REQUESTS}:{contactId:e.contactId,state:e&&e.next&&e.next.type}),()=>({state:RequestStatus.ERROR})).then(e=>{const s=this.getTrackingMessageByStatus(e.state);switch(e.state){case RequestStatus.SUCCESS:s&&this.tracking.send(s),this.goToView(n&&u?u.path[0]:this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_SUCCESS"===t.label||"DOCUMENT_VIEW_TYPE_SUCCESSFUL_REQUEST"===t.label||"REQUEST_FORM_VIEW_TYPE_SUCCESS"===t.label));break;case RequestStatus.ALREADY_SUBSCRIBED:s&&this.tracking.send(s),this.goToView(c&&u?u.path[0]:this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_SUBSCRIBED"===t.label));break;case RequestStatus.ERROR:s&&this.tracking.send(s),this.goToView(c&&u?u.path[0]:this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_ERROR"===t.label));break;case RequestStatus.TOO_MANY_REQUESTS:s&&this.tracking.send(s),this.goToView(c&&u?u.path[0]:this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_ERROR"===t.label)),this.eventEmitter.emit(SysEventTypes.TOO_MANY_REQUESTS)}e.contactId&&"0"!==e.contactId&&this.eventEmitter.emit("CONTACT_ID_WAS_RECEIVED",e.contactId),t(e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED)}).catch(()=>{this.goToView(this.getServices().documentModel.getViews().findIndex(t=>"DOCUMENT_VIEW_TYPE_ERROR"===t.label)),t(!1)})}constructDataToSent({contextValue:t,formValue:e,utmParams:s}){const i=Object.assign({},t);return i.tracking=s,Object.keys(e).forEach(t=>{if(t.startsWith("clConsentId")){if(t.endsWith("_label"))return;const s={value:e[t]};e[`${t}_label`]&&(s.text=e[`${t}_label`]),i.consents?i.consents[t]=s:i.consents={[t]:s}}else{const s=e[t];i[t]=isDictionary(s)||Array.isArray(s)?JSON.stringify(s):s}}),i}constructRequestPayload({contextValue:t,formValue:e,utmParams:s}){let i={data:this.constructDataToSent({contextValue:t,formValue:e,utmParams:s}),referrer:window.location.href,triggeredBy:this.configService.getConfig("triggeredBy")};return this.configService.getConfig("widgetDebugMode")&&(i.ignoreTracking=!0),i}constructRequestHeaders(){const t={},e=this.configService.getConfig("clCustomerId");return e&&Object.assign(t,{"cl-customer-id":e}),t}goToView(t,e){this.eventEmitter.emit(SysActionTypes.GO_TO_VIEW,t,e)}sendRequest(t){return this.skipHttpRequest?Promise.resolve({status:200,json:()=>Promise.resolve({next:{type:RequestStatus.SUCCESS}})}):this.httpClient.execute(this.configService.getConfig("subscribeContactUrl"),"POST",t,this.constructRequestHeaders())}}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import DefaultEventEmitter from "@claspo/common/DefaultEventEmitter";
|
|
2
2
|
import { ClBaseComponentI, ClDocumentI, ClDocumentSharedI } from '@claspo/common/document/Document.interface';
|
|
3
|
-
export declare const
|
|
3
|
+
export declare const EditorToWidgetEventType: {
|
|
4
4
|
COMPONENT_INSERT: string;
|
|
5
5
|
COMPONENT_REMOVE: string;
|
|
6
6
|
COMPONENT_MOVE: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import ModulesComponentExtractor from"./ModulesComponentExtractor";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import DocumentUtils from"@claspo/common/document/DocumentUtils";export const
|
|
1
|
+
import ModulesComponentExtractor from"./ModulesComponentExtractor";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import DocumentUtils from"@claspo/common/document/DocumentUtils";export const EditorToWidgetEventType={COMPONENT_INSERT:"COMPONENT_INSERT",COMPONENT_REMOVE:"COMPONENT_REMOVE",COMPONENT_MOVE:"COMPONENT_MOVE",COMPONENT_UPDATE:"COMPONENT_UPDATE",COMPONENT_PROPS_UPDATE:"COMPONENT_PROPS_UPDATE",SHARED_UPDATE:"SHARED_UPDATE",MOBILE_BREAKPOINT_UPDATE:"MOBILE_BREAKPOINT_UPDATE",ENVIRONMENT_UPDATE:"ENVIRONMENT_UPDATE",TEXT_CLASS_ADDED:"TEXT_CLASS_ADDED",TEXT_CLASS_UPDATED:"TEXT_CLASS_UPDATED",TEXT_CLASS_REMOVED:"TEXT_CLASS_REMOVED",HEADER_FONT_FAMILY_UPDATE:"HEADER_FONT_FAMILY_UPDATE",TEXT_FONT_FAMILY_UPDATE:"TEXT_FONT_FAMILY_UPDATE",SHARED_UPDATE_ALL:"SHARED_UPDATE_ALL",COLOR_SCHEMA_UPDATE:"COLOR_SCHEMA_UPDATE",THEME_UPDATE:"THEME_UPDATE"};export default class DocumentModelService extends DefaultEventEmitter{constructor(t){super(),this.json=t,this.flatJson=ModulesComponentExtractor.extract(this.json)}setComponentRef(t,e){DocumentUtils.getNodeById(this.getViews(),t).componentRef=e}getModel(){return this.flatJson}getView(t){return this.flatJson.views[t]}getViews(){return this.flatJson.views}getShared(){return this.flatJson.shared}iterateViewModelAndExecute(t,e){const E=this.getView(t);DocumentUtils.iterateDepthFirst(E,e)}destroy(){}destroyView(t){console.warn("destroyView now should do nothing"),this.iterateViewModelAndExecute(t,t=>{t.componentRef&&(t.componentRef.remove(),t.componentRef=null)})}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import DocumentUtils from"@claspo/common/document/DocumentUtils";import{ComponentInsertType}from"@claspo/common/document/ComponentInsertType";import{
|
|
1
|
+
import DocumentUtils from"@claspo/common/document/DocumentUtils";import{ComponentInsertType}from"@claspo/common/document/ComponentInsertType";import{EditorToWidgetEventType}from"./DocumentModelService";export default class DocumentService{constructor(e,t,o){this.documentModel=e,this.viewRenderer=t,this.renderMode=o}handleModelUpdate(e,t){switch(e){case EditorToWidgetEventType.COMPONENT_PROPS_UPDATE:{const{id:e,data:o}=t,d=DocumentUtils.getNodeById(this.documentModel.getViews(),e);if(!d)return void console.warn("Attempt to update unexisting component props");const i=d.path,n=i.reduce((e,t,o)=>0===o?this.documentModel.getViews()[t]:e.children[t],this.documentModel.getViews());return n?(n.props=Object.assign({},o),void this.documentModel.emit(`${EditorToWidgetEventType.COMPONENT_PROPS_UPDATE}_${e}`,o)):void console.error("Model not found by path ["+i+"]")}case EditorToWidgetEventType.COMPONENT_UPDATE:{const{id:e,data:o}=t,d=DocumentUtils.getNodeById(this.documentModel.getViews(),e);return d?(Object.assign(d,o),void this.documentModel.emit(`${EditorToWidgetEventType.COMPONENT_UPDATE}_${e}`,o)):void console.warn("Attempt to update unexisting component props")}case EditorToWidgetEventType.SHARED_UPDATE:{const e=this.documentModel.getShared();return Object.assign(e,t),void this.documentModel.emit(EditorToWidgetEventType.SHARED_UPDATE_ALL)}case EditorToWidgetEventType.MOBILE_BREAKPOINT_UPDATE:return void(this.documentModel.getShared().mobileBreakpointWidth=t.mobileBreakpointWidth);case EditorToWidgetEventType.ENVIRONMENT_UPDATE:return void this.documentModel.emit(EditorToWidgetEventType.ENVIRONMENT_UPDATE,t);case EditorToWidgetEventType.TEXT_CLASS_ADDED:return void(this.documentModel.getShared().textClasses[t.id]=t);case EditorToWidgetEventType.TEXT_CLASS_UPDATED:return this.documentModel.getShared().textClasses[t.id]=t,void this.documentModel.emit(EditorToWidgetEventType.SHARED_UPDATE_ALL);case EditorToWidgetEventType.TEXT_CLASS_REMOVED:return void delete this.documentModel.getShared().textClasses[t];case EditorToWidgetEventType.HEADER_FONT_FAMILY_UPDATE:return this.documentModel.getShared().headerFontFamily=t,void this.documentModel.emit(EditorToWidgetEventType.SHARED_UPDATE_ALL);case EditorToWidgetEventType.TEXT_FONT_FAMILY_UPDATE:return this.documentModel.getShared().textFontFamily=t,void this.documentModel.emit(EditorToWidgetEventType.SHARED_UPDATE_ALL);case EditorToWidgetEventType.COLOR_SCHEMA_UPDATE:return this.documentModel.getShared().cssVars=t,void this.documentModel.emit(EditorToWidgetEventType.COLOR_SCHEMA_UPDATE,t);case EditorToWidgetEventType.THEME_UPDATE:return this.documentModel.getShared().theme=t,this.documentModel.emit(EditorToWidgetEventType.THEME_UPDATE,t),void this.documentModel.emit(EditorToWidgetEventType.SHARED_UPDATE_ALL);case EditorToWidgetEventType.COMPONENT_REMOVE:{const e=t.path;return void this.removeComponent(e)}case EditorToWidgetEventType.COMPONENT_INSERT:{let{insertPosition:e,targetPath:o,model:d}=t,i=DocumentUtils.getNodeByPath(this.documentModel.getViews(),o);if(!i&&e!==ComponentInsertType.INSIDE){const t=o.slice(0,-1),d=DocumentUtils.getNodeByPath(this.documentModel.getViews(),t);e=ComponentInsertType.INSIDE,i=d,o=t}return DocumentUtils.insertNode(d,o,this.documentModel.getViews(),e),void this.viewRenderer.renderComponent(i,d,this.renderMode,e)}case EditorToWidgetEventType.COMPONENT_MOVE:{const{fromPath:e,insertPosition:o,targetPath:d}=t,i=d[0],n=this.documentModel.getViews()[i],s=DocumentUtils.getNodeByPath(this.documentModel.getViews(),d);if(!s)return;const r=this.removeComponent(e),E=DocumentUtils.getNodeById([n],s.id).path;return DocumentUtils.insertNode(r,E,this.documentModel.getViews(),o),void this.viewRenderer.renderComponent(s,r,this.renderMode,o)}default:return}}removeComponent(e){const t=DocumentUtils.getNodeByPath(this.documentModel.getViews(),e);if(t)return t.componentRef.remove(),DocumentUtils.removeNode(this.documentModel.getViews(),e)}}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@claspo/renderer",
|
|
3
|
-
"version": "18.0.
|
|
3
|
+
"version": "18.0.9-marteh.0",
|
|
4
4
|
"scripts": {
|
|
5
5
|
"dev": " tsc --project tsconfig.json --watch",
|
|
6
6
|
"build": "rm -rf out && tsc --project tsconfig.json && npm run minify",
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"node": ">=18.16.0"
|
|
16
16
|
},
|
|
17
17
|
"dependencies": {
|
|
18
|
-
"@claspo/common": "7.0.
|
|
18
|
+
"@claspo/common": "7.0.7",
|
|
19
19
|
"@testing-library/dom": "^10.4.0"
|
|
20
20
|
},
|
|
21
21
|
"devDependencies": {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{WidgetToEditorEventType}from"./WidgetToEditorEventType";import{applySysAttrPrefix}from"./RenderConstants";export default class DragEventListener{constructor(t,e){this.eventEmitter=t,this.documentModel=e,this.dragStartSubscription=this.eventEmitter.on(WidgetToEditorEventType.COMPONENT_DRAGSTART,()=>{this.updateHovered("add")}),this.dragEndSubscription=this.eventEmitter.on(WidgetToEditorEventType.COMPONENT_DRAGEND,()=>{this.updateHovered("remove")})}updateHovered(t){this.documentModel.getViews().forEach((e,o)=>{this.documentModel.iterateViewModelAndExecute(o,e=>{var o;const r=null===(o=e.componentRef)||void 0===o?void 0:o.getHostElement();r&&r.classList[t](applySysAttrPrefix("hovered"),applySysAttrPrefix("drag-over"))})})}destroy(){this.dragStartSubscription.off(),this.dragEndSubscription.off()}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export declare const
|
|
1
|
+
export declare const WidgetToEditorEventType: {
|
|
2
2
|
COMPONENT_FOCUSED: string;
|
|
3
3
|
REMOVE_FOCUS: string;
|
|
4
4
|
SET_FOCUS: string;
|
|
@@ -15,4 +15,5 @@ export declare const ViewRendererActionType: {
|
|
|
15
15
|
GAME_PHASE_READY_TO_PLAY: string;
|
|
16
16
|
GAME_PHASE_COMPLETED: string;
|
|
17
17
|
GAME_PHASE_IDLE: string;
|
|
18
|
+
COMPONENT_PROPS_UPDATE: string;
|
|
18
19
|
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const WidgetToEditorEventType={COMPONENT_FOCUSED:"COMPONENT_FOCUSED",REMOVE_FOCUS:"REMOVE_FOCUS",SET_FOCUS:"SET_FOCUS",COMPONENT_MOUSE_MOVE:"COMPONENT_MOUSE_MOVE",COMPONENT_CLICKED:"COMPONENT_CLICKED",COMPONENT_DOUBLE_CLICKED:"COMPONENT_DOUBLE_CLICKED",COMPONENT_DRAGSTART:"COMPONENT_DRAGSTART",COMPONENT_DRAGEND:"COMPONENT_DRAGEND",COMPONENT_DRAGOVER:"COMPONENT_DRAGOVER",DOCUMENT_DROP:"DOCUMENT_DROP",SHOW_INLINE_EDIT:"SHOW_INLINE_EDIT",VIEW_COMPONENT_RESOURCES_LOADED:"VIEW_COMPONENT_RESOURCES_LOADED",FAILED_TO_LOAD_COMPONENT_RESOURCE:"FAILED_TO_LOAD_COMPONENT_RESOURCE",GAME_PHASE_READY_TO_PLAY:"GAME_PHASE_READY_TO_PLAY",GAME_PHASE_COMPLETED:"GAME_PHASE_COMPLETED",GAME_PHASE_IDLE:"GAME_PHASE_IDLE",COMPONENT_PROPS_UPDATE:"COMPONENT_PROPS_UPDATE_FROM_WIDGET"};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{
|
|
1
|
+
import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{EditorToWidgetEventType}from"../../document-model/DocumentModelService";class ClDocumentResizeListener extends DefaultEventEmitter{constructor(e,t){super(),this.documentModel=e,this.containerElement=t,this.mobileBreakpointWidth=this.documentModel.getShared().mobileBreakpointWidth,this._isMobile=this._calculateMobileFlag(),this.documentModel.on(EditorToWidgetEventType.ENVIRONMENT_UPDATE,e=>{this._isMobile=e.isMobileEnv,this.emit(ClDocumentResizeListener.changeEventName,this._isMobile)})}isMobile(){return this._isMobile}destroy(){super.destroy()}_calculateMobileFlag(){return this._getElementsWidthPx(this.containerElement)<=this.mobileBreakpointWidth}_getElementsWidthPx(e){return parseInt(getComputedStyle(e).width)}}ClDocumentResizeListener.changeEventName="CHANGE";export default ClDocumentResizeListener;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{EditorToWidgetEventType}from"../../document-model/DocumentModelService";import ErrorLogger from"../../error/ErrorLogger";import{fromCssVarToSchemaToken,toCssVarToken}from"@claspo/common/theme/theme.utils";export default class ColorSchemaListener{constructor(e,t,o,s,n,r){this.hostElement=t,this.documentModel=e,this.getSharedCb=o,this.getPropsCb=s,this.getEnvCb=n,this.httpClient=r,this.schemaSubscription=null,this.themeSubscription=null,this.envUrlMaps={desktop:new Map,mobile:new Map}}parseBackground(e){const t=String(e||"");if(t.includes("url")){const[e,o]=t.split("(")[1].split(")");return{url:e.replace(/['"]+/g,""),positionOptions:o.replace(";","")}}return{url:null,positionOptions:null}}apply(e){const t=this.getPropsCb();return t.backgroundDynamicInlineSVGElements[e].forEach(o=>{var s,n,r,i,l;const a=null===(n=null===(s=t.adaptiveStyles)||void 0===s?void 0:s[e])||void 0===n?void 0:n.find(e=>e.element===o),c=(null===(r=t.styles)||void 0===r?void 0:r.find(e=>e.element===o))||{},h=(null===(i=null==c?void 0:c.styleAttributes)||void 0===i?void 0:i.background)||(null===(l=null==a?void 0:a.styleAttributes)||void 0===l?void 0:l.background),m=this.parseBackground(h);m.url&&this.envUrlMaps[e].set(o,{originalSVGResourceURL:m.url,inlineSvgString:null,positionOptions:m.positionOptions})}),Promise.all([...this.envUrlMaps[e].entries()].map(([t,o])=>this.httpClient.execute(o.originalSVGResourceURL).then(e=>e.text()).then(s=>{this.envUrlMaps[e].set(t,Object.assign(Object.assign({},o),{inlineSvgString:s}))}))).then(()=>{var t;const o=this.getSharedCb();return Object.keys((null===(t=o.theme)||void 0===t?void 0:t.schema)||{}).length>0?this._applyHostElementBackgroundFromTheme(this.envUrlMaps[e].get("host"),o.theme.schema):this._applyHostElementBackgroundFromCssVars(this.envUrlMaps[e].get("host"),o.cssVars)}).catch(e=>{console.error(e),ErrorLogger.log(`Failed to load/apply backgroundDynamicInlineSVGElements[${this.getPropsCb().backgroundDynamicInlineSVGElements}] ${e}`)})}on(){return this.schemaSubscription=this.documentModel.on(EditorToWidgetEventType.COLOR_SCHEMA_UPDATE,e=>{this._applyHostElementBackgroundFromCssVars(this.envUrlMaps[this.getEnvCb()].get("host"),e)}),this.themeSubscription=this.documentModel.on(EditorToWidgetEventType.THEME_UPDATE,e=>{this._applyHostElementBackgroundFromTheme(this.envUrlMaps[this.getEnvCb()].get("host"),e.schema)}),this}_applyHostElementBackgroundFromCssVars(e,t){e&&t&&(this.hostElement.style.background=this._buildBackgroundUrlFromCssVars(e,t))}_applyHostElementBackgroundFromTheme(e,t){e&&t&&(this.hostElement.style.background=this._buildBackgroundUrlFromTheme(e,t))}_buildBackgroundUrlFromCssVars(e,t){const o=e.inlineSvgString.trim().replace("var(--cl-schema-accent)",t["cl-schema-accent"]);return`url('data:image/svg+xml,${encodeURIComponent(o)}')${e.positionOptions}`}_buildBackgroundUrlFromTheme(e,t){const o=e.inlineSvgString.trim();let s=o;[...o.matchAll(/var\(--cl-schema-([^)]+)\)/g)].forEach(e=>{const o=fromCssVarToSchemaToken(e[1]);s=s.replace(`var(--${toCssVarToken(o)})`,t[o])});return`url('data:image/svg+xml,${encodeURIComponent(s)}')${e.positionOptions}`}off(){var e,t;null===(e=this.schemaSubscription)||void 0===e||e.off(),null===(t=this.themeSubscription)||void 0===t||t.off()}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{
|
|
1
|
+
import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{EditorToWidgetEventType}from"../../document-model/DocumentModelService";class DefaultMediaQueryListener extends DefaultEventEmitter{constructor(e,i){super(),this.config=i,this.handleMobileBreakpoint(e.getShared().mobileBreakpointWidth),e.on(EditorToWidgetEventType.ENVIRONMENT_UPDATE,({isMobileEnv:e})=>{this._isMobile=e,this.emit(DefaultMediaQueryListener.changeEventName,this._isMobile)})}handleMobileBreakpoint(e){this.mobileBreakpointWidth=e;const i=Number.isInteger(this.mobileBreakpointWidth)?`${this.mobileBreakpointWidth}px`:this.mobileBreakpointWidth;this.mediaQueryList=window.matchMedia(`(max-width: ${i})`),this.mediaQueryList.addListener(this.listener.bind(this)),this._isMobile=this.mediaQueryList.matches,this.emit(DefaultMediaQueryListener.changeEventName,this._isMobile)}isMobile(){return this.config.forceMobileEnv||this._isMobile}listener(e){this._isMobile=e.matches,this.emit(DefaultMediaQueryListener.changeEventName,this._isMobile)}destroy(){super.destroy(),this.mediaQueryList.removeListener(this.listener.bind(this))}}DefaultMediaQueryListener.changeEventName="CHANGE";export default DefaultMediaQueryListener;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{detectOrientation}from"@claspo/common/utils/orientationUtils";import{isIOS}from"@claspo/common/utils/deviceUtils";import{
|
|
1
|
+
import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{detectOrientation}from"@claspo/common/utils/orientationUtils";import{isIOS}from"@claspo/common/utils/deviceUtils";import{EditorToWidgetEventType}from"../../document-model/DocumentModelService";class MobileDeviceOrientationListener extends DefaultEventEmitter{constructor(e,t){var n;super(),this.documentModel=e,this._orientation=null!==(n=t.config.defaultOrientation)&&void 0!==n?n:detectOrientation(),this.documentModel.on(EditorToWidgetEventType.ENVIRONMENT_UPDATE,e=>{e.orientation&&(this._orientation=e.orientation,this.emit(MobileDeviceOrientationListener.changeEventName,this._orientation))}),this.handleOrientationChangeBound=this.handleOrientationChange.bind(this),this.addOrientationChangeListener()}isPortrait(){return"PORTRAIT"===this._orientation}handleOrientationChange(e){var t,n;this._orientation=null!==(n=null===(t=null==e?void 0:e.detail)||void 0===t?void 0:t.orientation)&&void 0!==n?n:detectOrientation(),this.emit(MobileDeviceOrientationListener.changeEventName,this._orientation)}addOrientationChangeListener(){!isIOS()&&window.screen.orientation?window.screen.orientation.addEventListener("change",this.handleOrientationChangeBound):"orientation"in window&&window.addEventListener("orientationchange",this.handleOrientationChangeBound)}removeOrientationChangeListener(){!isIOS()&&window.screen.orientation?window.screen.orientation.removeEventListener("change",this.handleOrientationChangeBound):"orientation"in window&&window.removeEventListener("orientationchange",this.handleOrientationChangeBound)}destroy(){super.destroy(),this.removeOrientationChangeListener()}}MobileDeviceOrientationListener.changeEventName="CHANGE";export default MobileDeviceOrientationListener;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import SysEventTypes from"../common/SysEventTypes";import{
|
|
1
|
+
import SysEventTypes from"../common/SysEventTypes";import{WidgetToEditorEventType}from"../renderer/WidgetToEditorEventType";export default class ViewResourcesManager{constructor(e){this._onComponentResourcesLoaded=e=>{this.componentResourcesMap.delete(e),this.viewHasPendingResources()||this.systemEventEmitter.emit(WidgetToEditorEventType.VIEW_COMPONENT_RESOURCES_LOADED)},this.systemEventEmitter=e,this.componentResourcesMap=new Map,this.systemEventEmitter.on(SysEventTypes.COMPONENT_RESOURCES_LOADED,this._onComponentResourcesLoaded)}registerComponent(e,t){this.componentResourcesMap.set(e,t)}viewHasPendingResources(){return[...this.componentResourcesMap.entries()].filter(([e,t])=>t.getPending().count()>0).length>0}}
|
package/sdk/WcElement.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import HandlerFactory from"../handler/HandlerFactory";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import addEventListenerToElement from"@claspo/common/utils/addEventListener";import DefaultState from"../common/DefaultState";import{DocumentModelUpdateType}from"../document-model/DocumentModelService";import DefaultMediaQueryListener from"../renderer/style/DefaultMediaQueryListener";import{applySysAttrPrefix,applySysClassPrefix,RenderConstants}from"../renderer/RenderConstants";import StyleAttributeAccessor from"./accessor/StyleAttributeAccessor";import CommonStylesService from"../renderer/style/CommonStylesService";import ColorSchemaListener from"../renderer/style/ColorSchemaListener";import HttpClient from"@claspo/common/network/HttpClient";import omitKeys from"@claspo/common/object/omitKeys";import{CaseTransformer}from"@claspo/common/utils/CaseTransformer";import ComponentResourceManager from"../resource-management/ComponentResourceManager";import createObservers from"../wc-renderer/observers/createObservers";import observerType from"../wc-renderer/observers/observerType";import createSubscriptions from"../wc-renderer/subscriptions/createSubscriptions";import recursiveFindParentNodeByAttribute from"@claspo/common/element/recursiveFindParentNodeByAttribute";import{getTranslationsMap,getWidgetLanguages}from"./TranslationUtils";import ActionCategory from"../action/actions/ActionCategory";import SysActionTypes from"../action/SysActionTypes";import mergeAdaptiveStylesWithEnvIndependentStyles from"../document-model/MergeAdaptiveStylesWithEnvIndependentStyles";import{applySharedClasses,getAdaptiveStylesForPlatform}from"./ModelStyleUtils";import insertHtmlIntoElement from"@claspo/common/dom/insertHtmlIntoElement";import{PayloadEvent}from"./PayloadEvent";import{RenderMode}from"@claspo/common/RenderMode";import{ViewRendererActionType}from"../renderer/ViewRendererActionType";class WcElement extends HTMLElement{constructor(){var e;super(),this.skipGameBlur=!0,this.construct=()=>{let e;const t=this.getAttribute(applySysAttrPrefix("id")),s=this.getWidgetContainerNode();if(!s)throw new Error("Widget container not found in construct");const o=s.closest(`[${applySysAttrPrefix("widget-id")}]`);let r;o&&(r=o.getAttribute(applySysAttrPrefix("widget-id")));let i=new PayloadEvent("cl-props-request",{nodeName:this.nodeName,path:this.getAttribute(applySysAttrPrefix("path")),id:t,widgetId:r},{bubbles:!0,composed:!0});this.dispatchEvent(i),e=i.detail.props,Object.assign(this,e),this.observers=createObservers(observerType.PROPS,observerType.SHARED,observerType.ENVIRONMENT),this.subscriptions=createSubscriptions(),this.state=new DefaultState({}),this.componentEventEmitter=new DefaultEventEmitter,this.componentResourceManager=new ComponentResourceManager(this.model.id,this.services.eventEmitter,this.isStaticRenderMode()),this.mergeTagsProcessor=this.services.mergeTagsProcessorFactory.create(),this._actionFactory=this.services.actionFactory,this._handlerFactory=new HandlerFactory(this._actionFactory,this.services.actionRegister),this.prevProps=this.model.props,this.prevEnvironment=this.getEnvironment(),this.documentModel.on(`${DocumentModelUpdateType.COMPONENT_PROPS_UPDATE}_${this.model.id}`,e=>{this.model.props=e,this.observers.get(observerType.PROPS).forEach(t=>t(this.prevProps,e)),this.prevProps=e;const t=this.getHostElement(),s=applySysAttrPrefix("floating");e.floating&&!t.getAttribute(s)?t.setAttribute(s,"true"):!e.floating&&t.getAttribute(s)&&t.removeAttribute(s)}),this.documentModel.on(`${DocumentModelUpdateType.COMPONENT_UPDATE}_${this.model.id}`,e=>{Object.assign(this.model,e)}),this.documentModel.on(DocumentModelUpdateType.SHARED_UPDATE_ALL,()=>{this.applyAutoAdaptiveStyles(this.prevProps.adaptiveStyles,this.prevProps.styles),this.observers.get(observerType.SHARED).forEach(e=>e(this.getShared()))}),this.model.props.backgroundDynamicInlineSVGElements&&(this.colorSchemaListener=new ColorSchemaListener(this.documentModel,this.getHostElement(),()=>this.getShared(),()=>this.model.props,()=>this.getEnvironment(),HttpClient),this.colorSchemaListener.apply(this.getEnvironment()).then(()=>{this.subscriptions.push(this.colorSchemaListener.on())})),this.prevProps.adaptiveStyles&&this.subscriptions.push(this.resizeListener.on(DefaultMediaQueryListener.changeEventName,()=>{this.applyAutoAdaptiveStyles(this.prevProps.adaptiveStyles,this.prevProps.styles);const e=this.getEnvironment();this.observers.get(observerType.ENVIRONMENT).forEach(t=>t(this.prevEnvironment,e)),this.prevEnvironment=e})),this.subscriptions.push(this.services.eventEmitter.on(ViewRendererActionType.GAME_PHASE_READY_TO_PLAY,()=>{this.skipGameBlur||this.getHostElement().classList.add("cl-game-spotlight-component")})),this.subscriptions.push(this.services.eventEmitter.on(ViewRendererActionType.GAME_PHASE_COMPLETED,()=>{this.skipGameBlur||this.getHostElement().classList.remove("cl-game-spotlight-component")}))},this.attachHandlers=()=>{this.getHandlers().map(e=>this._handlerFactory.get(e)).map(e=>()=>e.activate(this.state,this.componentEventEmitter,this.getHostElement.bind(this))).forEach(e=>e())},this.postponeHandlers=()=>{var e;null===(e=this.handlers)||void 0===e||e.forEach(e=>e.postpone())},this.releaseHandlers=()=>{var e;null===(e=this.handlers)||void 0===e||e.forEach(e=>e.release())},this.getProps=()=>{var e;return null===(e=this.getModel())||void 0===e?void 0:e.props},this.getShared=()=>this.documentModel.getShared(),this.getEnvironment=()=>this.resizeListener.isMobile()?"mobile":"desktop",this.isStaticRenderMode=()=>this.services.config.getConfig("renderMode")===RenderMode.STATIC,this.isUpdatingRenderMode=()=>this.services.config.getConfig("renderMode")===RenderMode.UPDATING,this.getRootElement=()=>this.shadowRoot?this.shadowRoot:this,this.getHostElement=()=>this,this.observeProps=e=>{this.observers.get(observerType.PROPS).push(e),e(null,this.prevProps)},this.observeShared=e=>{this.observers.get(observerType.SHARED).push(e),e(this.getShared())},this.observeEnvironment=e=>{this.observers.get(observerType.ENVIRONMENT).push(e),e(null,this.getEnvironment())},this.getElements=()=>[this.getHostElement(),...Array.from(this.getRootElement().querySelectorAll(`[${applySysAttrPrefix("element")}]`)).filter(e=>!e.hasAttribute(applySysAttrPrefix("component")))],this.getElement=(e,t)=>this.getElements().find(s=>t?s.getAttribute(applySysAttrPrefix("element"))===e&&s.id===t:s.getAttribute(applySysAttrPrefix("element"))===e),this.applyAutoAdaptiveStyles=(e,t)=>{if(!e&&!t)return;const s=this.getElements();if(!s.length)return;const o=mergeAdaptiveStylesWithEnvIndependentStyles(e,t),r=applySysAttrPrefix("type"),i="element-styles";let n=this.getRootElement().querySelector(`style[${r}="${i}"]`);n||(n=document.createElement("style"),n.setAttribute(r,i),this.getRootElement().appendChild(n)),insertHtmlIntoElement({element:n,html:""}),s.forEach(e=>{let t=e.getAttribute(applySysAttrPrefix("element"));const s=this.getEnvironment();let r=getAdaptiveStylesForPlatform(o,s,t);if(r){if(this.resizeListener.isMobile()){const e=getAdaptiveStylesForPlatform(o,"desktop",t);e&&(r=Object.assign(Object.assign({},r),{styleAttributes:Object.assign(Object.assign({},e.styleAttributes),r.styleAttributes)}))}this.applyStylesToElement(e,this.applySharedClassesToElementModel(r),n)}}),this._addLinkColor(n,this.getShared())},this.registerComponentResourceManagement=()=>{this.viewResourceManager.registerComponent(this.model.id,this.componentResourceManager)},this.applyStyles=(e,t={})=>{if(!e||!e.style)return!1;for(const[s,o]of Object.entries(t))e.style[s]=o;return!0},this.applyStylesToElement=(e,t,s)=>{var o,r;const i=[];if("host"===(t=WcElement._resolveTogglableStylesForElementModel(t)).element){CommonStylesService.applyHostStyles(this.model.type,e,null,this.layoutType);!!("desktop"===this.getEnvironment()&&(null===(o=this.model.props.backgroundDynamicInlineSVGElements)||void 0===o?void 0:o.desktop)||"mobile"===this.getEnvironment()&&(null===(r=this.model.props.backgroundDynamicInlineSVGElements)||void 0===r?void 0:r.mobile))&&(this.colorSchemaListener.apply(this.getEnvironment()),i.push("background"))}let n=t.styleAttributes.background,l=n&&n.match(/url\("([^"]*)"\)/);if(this.manifest.waitForResourcesLoad&&l){this.componentResourceManager.getPending().increment();const e=new Image;e.src=l[1],addEventListenerToElement(e,"load",()=>{this.componentResourceManager.getPending().decrement()}),addEventListenerToElement(e,"error",()=>{this.componentResourceManager.onResourceLoadFailure(e.src),this.isUpdatingRenderMode&&this.componentResourceManager.getPending().decrement()})}const a=Object.assign(Object.assign({},t),{styleAttributes:omitKeys(t.styleAttributes,i)});if(StyleAttributeAccessor.set(e,a),this._setClassAttributes(e,t),s){if(t.hoverStyleAttributes){let o=Object.assign({},t.hoverStyleAttributes);if("FILL_UP"===t.hoverAnimationType){e.style.boxShadow="inset 0px 0px 0px 0px rgb(0, 0, 0, 0)",e.style.overflow="hidden";const s=e.tagName.toLowerCase(),r=`flip-up-animation-${t.element}`;let i=this.getRootElement().querySelector(`#${r}`);i||(i=document.createElement("style"),i.id=r,e.appendChild(i)),insertHtmlIntoElement({element:i,html:`\n ${s}::before {\n content: '';\n background: ${o.background};\n position: absolute;\n left: 0;\n top: ${e.getBoundingClientRect().height}px;\n height: ${e.getBoundingClientRect().height}px;\n width: 100%;\n z-index: -10;\n }\n ${s}:hover::before {\n top: 0;\n transition: 0.3s;\n }\n `}),o=Object.assign(Object.assign({},t.hoverStyleAttributes),{background:"transparent",position:"relative"})}o.borderTopWidth&&"0px"!==o.borderTopWidth||delete o.borderTopColor;o.borderBottomWidth&&"0px"!==o.borderBottomWidth||delete o.borderBottomColor;o.borderLeftWidth&&"0px"!==o.borderLeftWidth||delete o.borderLeftColor;o.borderRightWidth&&"0px"!==o.borderRightWidth||delete o.borderRightColor,this._addStylesToStyleElement(s,t.element,o,`:not(.${applySysAttrPrefix("no-hover")}):hover`,!0)}t.placeholderStyleAttributes&&this._addStylesToStyleElement(s,t.element,t.placeholderStyleAttributes,"::placeholder"),this._addFontStylesToStyleElement(s,this.getShared()),this.stylesAppliedToElement(e,t,s)}},this.applySharedClassesToElementModel=e=>{const t=this.documentModel.getShared();return applySharedClasses(e,t)},this.getModel=()=>this.model,this._addStylesToStyleElement=(e,t,s,o="",r)=>{const i=Object.keys(s).reduce((e,t)=>e+` ${CaseTransformer.camelCaseToDashCase(t)}: ${s[t]}${r?" !important;":";"}`,"");insertHtmlIntoElement({element:e,html:`[${applySysAttrPrefix("element")}="${t}"]${o} { ${i} }`,appendHtml:!0})},this._addFontStylesToStyleElement=(e,t)=>{insertHtmlIntoElement({element:e,html:`[cl-type] {font-family:${t.textFontFamily||"inherit"}}`,appendHtml:!0})},this._addLinkColor=(e,t)=>{var s,o,r,i;t.linkColor&&insertHtmlIntoElement({element:e,html:`a {color: ${t.linkColor}}, a:visited {color: ${t.linkColor}}`,appendHtml:!0}),(null===(s=t.linkParams)||void 0===s?void 0:s.color)&&insertHtmlIntoElement({element:e,html:`a {color: ${null===(o=t.linkParams)||void 0===o?void 0:o.color}}, a:visited {color: ${null===(r=t.linkParams)||void 0===r?void 0:r.color}}`,appendHtml:!0}),(null===(i=t.linkParams)||void 0===i?void 0:i.removeUnderline)&&insertHtmlIntoElement({element:e,html:"a {text-decoration: none}, a:visited {text-decoration: none}",appendHtml:!0})},this._setClassAttributes=(e,t)=>{Array.from(e.classList).filter(e=>e!==applySysClassPrefix("hovered")&&e!==applySysClassPrefix("focused")).forEach(t=>{t.startsWith(RenderConstants.SYSTEM_CLASS_PREFIX)&&e.classList.remove(t)});const s=((e.getAttribute("class")||"")+" "+t.classes).trim();e.setAttribute("class",s)},this.getParentComponent=()=>recursiveFindParentNodeByAttribute(this.parentNode,applySysAttrPrefix("element"),"host"),this.getWidgetContainerNode=()=>{const e=null==this?void 0:this.getAttribute(applySysAttrPrefix("path"));return 1===(null==e?void 0:e.split(",").length)?this.parentNode:recursiveFindParentNodeByAttribute(this.parentNode,applySysAttrPrefix("path"),void 0,e=>1===(null==e?void 0:e.split(",").length))},this.getWidgetLanguages=()=>getWidgetLanguages(this.services.config),this.getPreferredWidgetLanguage=()=>this.getWidgetLanguages()[0],this.getTranslationsMap=e=>getTranslationsMap(e,this.getWidgetLanguages()),this.stylesAppliedToElement=(e,t,s)=>{},this.updateContext=()=>{var e;const t=this.getModel();this.services.context.updateRecord(t.id,{label:this.getContextRecordLabel(t.props),viewIndex:null===(e=t.path)||void 0===e?void 0:e[0]})},this.addContextRecord=()=>{var e;const t=this.getModel();this.services.context.addRecord(t.id,{recordKey:t.id,id:t.props.control.name,label:this.getContextRecordLabel(t.props),value:t.props.control.defaultValue||"",viewIndex:null===(e=t.path)||void 0===e?void 0:e[0],sourceId:"FORM",initialData:{fallbackValue:"",exampleValue:this.getContextRecordExampleValue(t.props)}})},this.getContextRecordLabel=e=>{var t,s,o,r,i,n;const l=e.control.name;if(["email","first_name","last_name"].includes(l))return l.toUpperCase();if((null===(t=e.content)||void 0===t?void 0:t.label)&&(null===(r=null===(o=null===(s=e.adaptiveStyles)||void 0===s?void 0:s.desktop.find(e=>"label"===e.element))||void 0===o?void 0:o.params)||void 0===r?void 0:r.enabled)){const t=(new DOMParser).parseFromString(e.content.label,"text/html");return this.capitalizeFirstLetter(t.body.textContent||"")}return(null===(i=e.content)||void 0===i?void 0:i.placeholder)?this.capitalizeFirstLetter(e.content.placeholder):(null===(n=e.control)||void 0===n?void 0:n.integrationName)?this.capitalizeFirstLetter(e.control.integrationName).replace(new RegExp("_","g")," "):void 0},this.capitalizeFirstLetter=e=>e.charAt(0).toUpperCase()+e.slice(1),this.getContextRecordExampleValue=e=>{var t;switch(null===(t=e.control)||void 0===t?void 0:t.name){case"email":return"myemail@example.com";case"first_name":return"Maria";case"last_name":return"Taylor";default:return this.getContextRecordLabel(e)}},this.completeSubmitAction=e=>{const t=e||{},s=this.services.actionRegister.getRegisteredActions().find(e=>e.category===ActionCategory.SUBMIT);s?null==s||s.execute(void 0,void 0,!0,t):this.services.actionFactory.get({type:SysActionTypes.REQUEST}).execute(void 0,void 0,!0,t)},this.getHandlers=()=>{var e;return(null===(e=this.getProps())||void 0===e?void 0:e.handlers)&&this.getProps().handlers.length?[...this.getProps().handlers]:[]},this.assets=(e="")=>`${this.services.config.getConfig("staticResourcesUrl").replace(/\/$/,"")}/${this.manifest.name}/assets${e?`/${e}`:""}`,this.attachShadow({mode:"open"}),this.manifest=this.manifest||(null===(e=this.constructor.define)||void 0===e?void 0:e.manifest)}connectedCallback(){this.construct(),this.registerComponentResourceManagement(),Promise.resolve().then(()=>{this.attachHandlers()});const e=document.createElement("style");e.textContent='\n :host(.cl-game-spotlight-component)::after {\n content: "";\n position: absolute;\n background-size: 100% 100%;\n background-repeat: no-repeat;\n overflow: visible;\n \n backdrop-filter: blur(4px);\n \n inset: -30px;\n mask-image: \n linear-gradient(to bottom, transparent, grey 30px, grey calc(100% - 30px), transparent),\n linear-gradient(to right, transparent, grey 30px, grey calc(100% - 30px), transparent);\n mask-composite: intersect;\n -webkit-mask-composite: source-in; /* for Chrome/Safari */\n \n transition: opacity 0.35s ease;\n pointer-events: auto;\n }\n ',this.getRootElement().prepend(e)}disconnectedCallback(){var e;this.observers.clear(),this.subscriptions.off(),this.state.destroy(),this.componentEventEmitter.destroy(),null===(e=this.mergeTagsProcessor)||void 0===e||e.destroy()}}WcElement._resolveTogglableStylesForElementModel=e=>{const t=Object.assign({},e);return Object.keys(t).forEach(e=>{e.toLowerCase().includes("styleattributes")&&(t[e]=WcElement._resolveTogglableStyles(t[e]))}),t},WcElement._resolveTogglableStyles=e=>{const t=Object.assign({},e),s=(e,s,o)=>{s in t&&(e.forEach(e=>{e in t&&(t[e]=t[s]?t[e]:o)}),delete t[s])};return s(["marginTop","marginBottom","marginLeft","marginRight"],"_marginEnabled","0px"),s(["paddingTop","paddingBottom","paddingLeft","paddingRight"],"_paddingEnabled","0px"),t};export default WcElement;
|
|
1
|
+
import HandlerFactory from"../handler/HandlerFactory";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import addEventListenerToElement from"@claspo/common/utils/addEventListener";import DefaultState from"../common/DefaultState";import{EditorToWidgetEventType}from"../document-model/DocumentModelService";import DefaultMediaQueryListener from"../renderer/style/DefaultMediaQueryListener";import{applySysAttrPrefix,applySysClassPrefix,RenderConstants}from"../renderer/RenderConstants";import StyleAttributeAccessor from"./accessor/StyleAttributeAccessor";import CommonStylesService from"../renderer/style/CommonStylesService";import ColorSchemaListener from"../renderer/style/ColorSchemaListener";import HttpClient from"@claspo/common/network/HttpClient";import omitKeys from"@claspo/common/object/omitKeys";import{CaseTransformer}from"@claspo/common/utils/CaseTransformer";import ComponentResourceManager from"../resource-management/ComponentResourceManager";import createObservers from"../wc-renderer/observers/createObservers";import observerType from"../wc-renderer/observers/observerType";import createSubscriptions from"../wc-renderer/subscriptions/createSubscriptions";import recursiveFindParentNodeByAttribute from"@claspo/common/element/recursiveFindParentNodeByAttribute";import{getTranslationsMap,getWidgetLanguages}from"./TranslationUtils";import ActionCategory from"../action/actions/ActionCategory";import SysActionTypes from"../action/SysActionTypes";import mergeAdaptiveStylesWithEnvIndependentStyles from"../document-model/MergeAdaptiveStylesWithEnvIndependentStyles";import{applySharedClasses,getAdaptiveStylesForPlatform}from"./ModelStyleUtils";import insertHtmlIntoElement from"@claspo/common/dom/insertHtmlIntoElement";import{PayloadEvent}from"./PayloadEvent";import{RenderMode}from"@claspo/common/RenderMode";import{WidgetToEditorEventType}from"../renderer/WidgetToEditorEventType";class WcElement extends HTMLElement{constructor(){var e;super(),this.skipGameBlur=!0,this.construct=()=>{let e;const t=this.getAttribute(applySysAttrPrefix("id")),s=this.getWidgetContainerNode();if(!s)throw new Error("Widget container not found in construct");const o=s.closest(`[${applySysAttrPrefix("widget-id")}]`);let r;o&&(r=o.getAttribute(applySysAttrPrefix("widget-id")));let i=new PayloadEvent("cl-props-request",{nodeName:this.nodeName,path:this.getAttribute(applySysAttrPrefix("path")),id:t,widgetId:r},{bubbles:!0,composed:!0});this.dispatchEvent(i),e=i.detail.props,Object.assign(this,e),this.observers=createObservers(observerType.PROPS,observerType.SHARED,observerType.ENVIRONMENT),this.subscriptions=createSubscriptions(),this.state=new DefaultState({}),this.componentEventEmitter=new DefaultEventEmitter,this.componentResourceManager=new ComponentResourceManager(this.model.id,this.services.eventEmitter,this.isStaticRenderMode()),this.mergeTagsProcessor=this.services.mergeTagsProcessorFactory.create(),this._actionFactory=this.services.actionFactory,this._handlerFactory=new HandlerFactory(this._actionFactory,this.services.actionRegister),this.prevProps=this.model.props,this.prevEnvironment=this.getEnvironment(),this.documentModel.on(`${EditorToWidgetEventType.COMPONENT_PROPS_UPDATE}_${this.model.id}`,e=>{this.model.props=e,this.observers.get(observerType.PROPS).forEach(t=>t(this.prevProps,e)),this.prevProps=e;const t=this.getHostElement(),s=applySysAttrPrefix("floating");e.floating&&!t.getAttribute(s)?t.setAttribute(s,"true"):!e.floating&&t.getAttribute(s)&&t.removeAttribute(s)}),this.documentModel.on(`${EditorToWidgetEventType.COMPONENT_UPDATE}_${this.model.id}`,e=>{Object.assign(this.model,e)}),this.documentModel.on(EditorToWidgetEventType.SHARED_UPDATE_ALL,()=>{this.applyAutoAdaptiveStyles(this.prevProps.adaptiveStyles,this.prevProps.styles),this.observers.get(observerType.SHARED).forEach(e=>e(this.getShared()))}),this.model.props.backgroundDynamicInlineSVGElements&&(this.colorSchemaListener=new ColorSchemaListener(this.documentModel,this.getHostElement(),()=>this.getShared(),()=>this.model.props,()=>this.getEnvironment(),HttpClient),this.colorSchemaListener.apply(this.getEnvironment()).then(()=>{this.subscriptions.push(this.colorSchemaListener.on())})),this.prevProps.adaptiveStyles&&this.subscriptions.push(this.resizeListener.on(DefaultMediaQueryListener.changeEventName,()=>{this.applyAutoAdaptiveStyles(this.prevProps.adaptiveStyles,this.prevProps.styles);const e=this.getEnvironment();this.observers.get(observerType.ENVIRONMENT).forEach(t=>t(this.prevEnvironment,e)),this.prevEnvironment=e})),this.subscriptions.push(this.services.eventEmitter.on(WidgetToEditorEventType.GAME_PHASE_READY_TO_PLAY,()=>{this.skipGameBlur||this.getHostElement().classList.add("cl-game-spotlight-component")})),this.subscriptions.push(this.services.eventEmitter.on(WidgetToEditorEventType.GAME_PHASE_COMPLETED,()=>{this.skipGameBlur||this.getHostElement().classList.remove("cl-game-spotlight-component")}))},this.attachHandlers=()=>{this.getHandlers().map(e=>this._handlerFactory.get(e)).map(e=>()=>e.activate(this.state,this.componentEventEmitter,this.getHostElement.bind(this))).forEach(e=>e())},this.postponeHandlers=()=>{var e;null===(e=this.handlers)||void 0===e||e.forEach(e=>e.postpone())},this.releaseHandlers=()=>{var e;null===(e=this.handlers)||void 0===e||e.forEach(e=>e.release())},this.getProps=()=>{var e;return null===(e=this.getModel())||void 0===e?void 0:e.props},this.getShared=()=>this.documentModel.getShared(),this.getEnvironment=()=>this.resizeListener.isMobile()?"mobile":"desktop",this.isStaticRenderMode=()=>this.services.config.getConfig("renderMode")===RenderMode.STATIC,this.isUpdatingRenderMode=()=>this.services.config.getConfig("renderMode")===RenderMode.UPDATING,this.getRootElement=()=>this.shadowRoot?this.shadowRoot:this,this.getHostElement=()=>this,this.observeProps=e=>{this.observers.get(observerType.PROPS).push(e),e(null,this.prevProps)},this.observeShared=e=>{this.observers.get(observerType.SHARED).push(e),e(this.getShared())},this.observeEnvironment=e=>{this.observers.get(observerType.ENVIRONMENT).push(e),e(null,this.getEnvironment())},this.getElements=()=>[this.getHostElement(),...Array.from(this.getRootElement().querySelectorAll(`[${applySysAttrPrefix("element")}]`)).filter(e=>!e.hasAttribute(applySysAttrPrefix("component")))],this.getElement=(e,t)=>this.getElements().find(s=>t?s.getAttribute(applySysAttrPrefix("element"))===e&&s.id===t:s.getAttribute(applySysAttrPrefix("element"))===e),this.applyAutoAdaptiveStyles=(e,t)=>{if(!e&&!t)return;const s=this.getElements();if(!s.length)return;const o=mergeAdaptiveStylesWithEnvIndependentStyles(e,t),r=applySysAttrPrefix("type"),i="element-styles";let n=this.getRootElement().querySelector(`style[${r}="${i}"]`);n||(n=document.createElement("style"),n.setAttribute(r,i),this.getRootElement().appendChild(n)),insertHtmlIntoElement({element:n,html:""}),s.forEach(e=>{let t=e.getAttribute(applySysAttrPrefix("element"));const s=this.getEnvironment();let r=getAdaptiveStylesForPlatform(o,s,t);if(r){if(this.resizeListener.isMobile()){const e=getAdaptiveStylesForPlatform(o,"desktop",t);e&&(r=Object.assign(Object.assign({},r),{styleAttributes:Object.assign(Object.assign({},e.styleAttributes),r.styleAttributes)}))}this.applyStylesToElement(e,this.applySharedClassesToElementModel(r),n)}}),this._addLinkColor(n,this.getShared())},this.registerComponentResourceManagement=()=>{this.viewResourceManager.registerComponent(this.model.id,this.componentResourceManager)},this.applyStyles=(e,t={})=>{if(!e||!e.style)return!1;for(const[s,o]of Object.entries(t))e.style[s]=o;return!0},this.applyStylesToElement=(e,t,s)=>{var o,r;const i=[];if("host"===(t=WcElement._resolveTogglableStylesForElementModel(t)).element){CommonStylesService.applyHostStyles(this.model.type,e,null,this.layoutType);!!("desktop"===this.getEnvironment()&&(null===(o=this.model.props.backgroundDynamicInlineSVGElements)||void 0===o?void 0:o.desktop)||"mobile"===this.getEnvironment()&&(null===(r=this.model.props.backgroundDynamicInlineSVGElements)||void 0===r?void 0:r.mobile))&&(this.colorSchemaListener.apply(this.getEnvironment()),i.push("background"))}let n=t.styleAttributes.background,l=n&&n.match(/url\("([^"]*)"\)/);if(this.manifest.waitForResourcesLoad&&l){this.componentResourceManager.getPending().increment();const e=new Image;e.src=l[1],addEventListenerToElement(e,"load",()=>{this.componentResourceManager.getPending().decrement()}),addEventListenerToElement(e,"error",()=>{this.componentResourceManager.onResourceLoadFailure(e.src),this.isUpdatingRenderMode&&this.componentResourceManager.getPending().decrement()})}const a=Object.assign(Object.assign({},t),{styleAttributes:omitKeys(t.styleAttributes,i)});if(StyleAttributeAccessor.set(e,a),this._setClassAttributes(e,t),s){if(t.hoverStyleAttributes){let o=Object.assign({},t.hoverStyleAttributes);if("FILL_UP"===t.hoverAnimationType){e.style.boxShadow="inset 0px 0px 0px 0px rgb(0, 0, 0, 0)",e.style.overflow="hidden";const s=e.tagName.toLowerCase(),r=`flip-up-animation-${t.element}`;let i=this.getRootElement().querySelector(`#${r}`);i||(i=document.createElement("style"),i.id=r,e.appendChild(i)),insertHtmlIntoElement({element:i,html:`\n ${s}::before {\n content: '';\n background: ${o.background};\n position: absolute;\n left: 0;\n top: ${e.getBoundingClientRect().height}px;\n height: ${e.getBoundingClientRect().height}px;\n width: 100%;\n z-index: -10;\n }\n ${s}:hover::before {\n top: 0;\n transition: 0.3s;\n }\n `}),o=Object.assign(Object.assign({},t.hoverStyleAttributes),{background:"transparent",position:"relative"})}o.borderTopWidth&&"0px"!==o.borderTopWidth||delete o.borderTopColor;o.borderBottomWidth&&"0px"!==o.borderBottomWidth||delete o.borderBottomColor;o.borderLeftWidth&&"0px"!==o.borderLeftWidth||delete o.borderLeftColor;o.borderRightWidth&&"0px"!==o.borderRightWidth||delete o.borderRightColor,this._addStylesToStyleElement(s,t.element,o,`:not(.${applySysAttrPrefix("no-hover")}):hover`,!0)}t.placeholderStyleAttributes&&this._addStylesToStyleElement(s,t.element,t.placeholderStyleAttributes,"::placeholder"),this._addFontStylesToStyleElement(s,this.getShared()),this.stylesAppliedToElement(e,t,s)}},this.applySharedClassesToElementModel=e=>{const t=this.documentModel.getShared();return applySharedClasses(e,t)},this.getModel=()=>this.model,this._addStylesToStyleElement=(e,t,s,o="",r)=>{const i=Object.keys(s).reduce((e,t)=>e+` ${CaseTransformer.camelCaseToDashCase(t)}: ${s[t]}${r?" !important;":";"}`,"");insertHtmlIntoElement({element:e,html:`[${applySysAttrPrefix("element")}="${t}"]${o} { ${i} }`,appendHtml:!0})},this._addFontStylesToStyleElement=(e,t)=>{insertHtmlIntoElement({element:e,html:`[cl-type] {font-family:${t.textFontFamily||"inherit"}}`,appendHtml:!0})},this._addLinkColor=(e,t)=>{var s,o,r,i;t.linkColor&&insertHtmlIntoElement({element:e,html:`a {color: ${t.linkColor}}, a:visited {color: ${t.linkColor}}`,appendHtml:!0}),(null===(s=t.linkParams)||void 0===s?void 0:s.color)&&insertHtmlIntoElement({element:e,html:`a {color: ${null===(o=t.linkParams)||void 0===o?void 0:o.color}}, a:visited {color: ${null===(r=t.linkParams)||void 0===r?void 0:r.color}}`,appendHtml:!0}),(null===(i=t.linkParams)||void 0===i?void 0:i.removeUnderline)&&insertHtmlIntoElement({element:e,html:"a {text-decoration: none}, a:visited {text-decoration: none}",appendHtml:!0})},this._setClassAttributes=(e,t)=>{Array.from(e.classList).filter(e=>e!==applySysClassPrefix("hovered")&&e!==applySysClassPrefix("focused")).forEach(t=>{t.startsWith(RenderConstants.SYSTEM_CLASS_PREFIX)&&e.classList.remove(t)});const s=((e.getAttribute("class")||"")+" "+t.classes).trim();e.setAttribute("class",s)},this.getParentComponent=()=>recursiveFindParentNodeByAttribute(this.parentNode,applySysAttrPrefix("element"),"host"),this.getWidgetContainerNode=()=>{const e=null==this?void 0:this.getAttribute(applySysAttrPrefix("path"));return 1===(null==e?void 0:e.split(",").length)?this.parentNode:recursiveFindParentNodeByAttribute(this.parentNode,applySysAttrPrefix("path"),void 0,e=>1===(null==e?void 0:e.split(",").length))},this.getWidgetLanguages=()=>getWidgetLanguages(this.services.config),this.getPreferredWidgetLanguage=()=>this.getWidgetLanguages()[0],this.getTranslationsMap=e=>getTranslationsMap(e,this.getWidgetLanguages()),this.stylesAppliedToElement=(e,t,s)=>{},this.updateContext=()=>{var e;const t=this.getModel();this.services.context.updateRecord(t.id,{label:this.getContextRecordLabel(t.props),viewIndex:null===(e=t.path)||void 0===e?void 0:e[0]})},this.addContextRecord=()=>{var e;const t=this.getModel();this.services.context.addRecord(t.id,{recordKey:t.id,id:t.props.control.name,label:this.getContextRecordLabel(t.props),value:t.props.control.defaultValue||"",viewIndex:null===(e=t.path)||void 0===e?void 0:e[0],sourceId:"FORM",initialData:{fallbackValue:"",exampleValue:this.getContextRecordExampleValue(t.props)}})},this.getContextRecordLabel=e=>{var t,s,o,r,i,n;const l=e.control.name;if(["email","first_name","last_name"].includes(l))return l.toUpperCase();if((null===(t=e.content)||void 0===t?void 0:t.label)&&(null===(r=null===(o=null===(s=e.adaptiveStyles)||void 0===s?void 0:s.desktop.find(e=>"label"===e.element))||void 0===o?void 0:o.params)||void 0===r?void 0:r.enabled)){const t=(new DOMParser).parseFromString(e.content.label,"text/html");return this.capitalizeFirstLetter(t.body.textContent||"")}return(null===(i=e.content)||void 0===i?void 0:i.placeholder)?this.capitalizeFirstLetter(e.content.placeholder):(null===(n=e.control)||void 0===n?void 0:n.integrationName)?this.capitalizeFirstLetter(e.control.integrationName).replace(new RegExp("_","g")," "):void 0},this.capitalizeFirstLetter=e=>e.charAt(0).toUpperCase()+e.slice(1),this.getContextRecordExampleValue=e=>{var t;switch(null===(t=e.control)||void 0===t?void 0:t.name){case"email":return"myemail@example.com";case"first_name":return"Maria";case"last_name":return"Taylor";default:return this.getContextRecordLabel(e)}},this.completeSubmitAction=e=>{const t=e||{},s=this.services.actionRegister.getRegisteredActions().find(e=>e.category===ActionCategory.SUBMIT);s?null==s||s.execute(void 0,void 0,!0,t):this.services.actionFactory.get({type:SysActionTypes.REQUEST}).execute(void 0,void 0,!0,t)},this.getHandlers=()=>{var e;return(null===(e=this.getProps())||void 0===e?void 0:e.handlers)&&this.getProps().handlers.length?[...this.getProps().handlers]:[]},this.assets=(e="")=>`${this.services.config.getConfig("staticResourcesUrl").replace(/\/$/,"")}/${this.manifest.name}/assets${e?`/${e}`:""}`,this.attachShadow({mode:"open"}),this.manifest=this.manifest||(null===(e=this.constructor.define)||void 0===e?void 0:e.manifest)}connectedCallback(){this.construct(),this.registerComponentResourceManagement(),Promise.resolve().then(()=>{this.attachHandlers()});const e=document.createElement("style");e.textContent='\n :host(.cl-game-spotlight-component)::after {\n content: "";\n position: absolute;\n background-size: 100% 100%;\n background-repeat: no-repeat;\n overflow: visible;\n \n backdrop-filter: blur(4px);\n \n inset: -30px;\n mask-image: \n linear-gradient(to bottom, transparent, grey 30px, grey calc(100% - 30px), transparent),\n linear-gradient(to right, transparent, grey 30px, grey calc(100% - 30px), transparent);\n mask-composite: intersect;\n -webkit-mask-composite: source-in; /* for Chrome/Safari */\n \n transition: opacity 0.35s ease;\n pointer-events: auto;\n }\n ',this.getRootElement().prepend(e)}disconnectedCallback(){var e;this.observers.clear(),this.subscriptions.off(),this.state.destroy(),this.componentEventEmitter.destroy(),null===(e=this.mergeTagsProcessor)||void 0===e||e.destroy()}}WcElement._resolveTogglableStylesForElementModel=e=>{const t=Object.assign({},e);return Object.keys(t).forEach(e=>{e.toLowerCase().includes("styleattributes")&&(t[e]=WcElement._resolveTogglableStyles(t[e]))}),t},WcElement._resolveTogglableStyles=e=>{const t=Object.assign({},e),s=(e,s,o)=>{s in t&&(e.forEach(e=>{e in t&&(t[e]=t[s]?t[e]:o)}),delete t[s])};return s(["marginTop","marginBottom","marginLeft","marginRight"],"_marginEnabled","0px"),s(["paddingTop","paddingBottom","paddingLeft","paddingRight"],"_paddingEnabled","0px"),t};export default WcElement;
|
|
@@ -20,6 +20,7 @@ export default class UrlQueryParamsSource extends DefaultEventEmitter {
|
|
|
20
20
|
config: UrlQueryParamsConfigI;
|
|
21
21
|
constructor(config?: UrlQueryParamsConfigI);
|
|
22
22
|
subscribe(cb: (data: SourceUpdateDataI) => void): void;
|
|
23
|
+
getSessionHistory(): string[];
|
|
23
24
|
getValue(key?: string): UrlQueryParamsProcessorResultI | Record<string, never>;
|
|
24
|
-
static processModel(model: UrlQueryParamsModelI, sessionUrlSearchParams
|
|
25
|
+
static processModel(model: UrlQueryParamsModelI, sessionUrlSearchParams: string[]): string;
|
|
25
26
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";class UrlQueryParamsSource extends DefaultEventEmitter{constructor(e={}){super(),this.config=e}subscribe(e){}getValue(e){return e?{processor:(e,r)=>UrlQueryParamsSource.processModel(r,this.
|
|
1
|
+
import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";class UrlQueryParamsSource extends DefaultEventEmitter{constructor(e={}){super(),this.config=e}subscribe(e){}getSessionHistory(){return this.config.sessionUrlSearchParams||[new URL(window.location.href).search]}getValue(e){return e?{processor:(e,r)=>UrlQueryParamsSource.processModel(r,this.getSessionHistory())}:{}}static processModel(e,r){if(!e.arguments)return"";const t=e.arguments.find(e=>"urlQueryParamName"===e.name);if(!t||!t.value)return"";let s;for(let e=r.length-1;e>=0;e--){const o=new URLSearchParams(r[e]).getAll(t.value).filter(Boolean);if(o.length){s=o;break}}return s?s.join(", "):""}}UrlQueryParamsSource.sourceId="URL_QUERY_PARAMS";export default UrlQueryParamsSource;
|
package/sdk.d.ts
CHANGED
|
@@ -4,8 +4,8 @@ import CompositionRoot from "./CompositionRoot";
|
|
|
4
4
|
import ViewRouter from "./ViewRouter";
|
|
5
5
|
import ViewEntryType from "./document-model/ViewEntryType";
|
|
6
6
|
import ComponentType from './sdk/ComponentType';
|
|
7
|
-
import {
|
|
7
|
+
import { EditorToWidgetEventType } from "./document-model/DocumentModelService";
|
|
8
8
|
import { RenderConstants } from "./renderer/RenderConstants";
|
|
9
|
-
import {
|
|
9
|
+
import { WidgetToEditorEventType } from "./renderer/WidgetToEditorEventType";
|
|
10
10
|
import { LoopAnimationStylesService } from "./renderer/style/LoopAnimationStylesService";
|
|
11
|
-
export { UpdatingEntryModule, StaticEntryModule, ViewRouter, CompositionRoot, ComponentType, ViewEntryType,
|
|
11
|
+
export { UpdatingEntryModule, StaticEntryModule, ViewRouter, CompositionRoot, ComponentType, ViewEntryType, EditorToWidgetEventType, RenderConstants, WidgetToEditorEventType, LoopAnimationStylesService };
|
package/sdk.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import UpdatingEntryModule from"./UpdatingEntryModule";import StaticEntryModule from"./StaticEntryModule";import CompositionRoot from"./CompositionRoot";import ViewRouter from"./ViewRouter";import ViewEntryType from"./document-model/ViewEntryType";import ComponentType from"./sdk/ComponentType";import{
|
|
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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ComponentInsertType}from"@claspo/common/document/ComponentInsertType";import ViewEntryType from"../document-model/ViewEntryType";import{
|
|
1
|
+
import{ComponentInsertType}from"@claspo/common/document/ComponentInsertType";import ViewEntryType from"../document-model/ViewEntryType";import{WidgetToEditorEventType}from"../renderer/WidgetToEditorEventType";import{applySysAttrPrefix}from"../renderer/RenderConstants";import ViewResourcesManager from"../resource-management/ViewResourcesManager";import{RenderMode}from"@claspo/common/RenderMode";export default class WcViewRenderer{constructor(e,t,n,o,r){this.isMobile=null,this.resizeListener=t,this.documentModel=e,this.factory=o,this.eventEmitter=r,this.viewResourceManager=new ViewResourcesManager(this.eventEmitter),this.destroy=this.destroy.bind(this)}render(e,t,n=RenderMode.STATIC){const o=this.factory.create(e,n,this.viewResourceManager);if(this.documentModel.setComponentRef(e.id,o),e.componentRef=o,e.type===ViewEntryType.VIEW&&"SysColumnsComponent"===e.name){const t=applySysAttrPrefix("content-container"),n=this.getRenderOutlet(e.componentRef.getRootElement());null==n||n.setAttribute(t,"")}return e.children.forEach(t=>{this.renderComponent(e,t,n)}),setTimeout(()=>{this.viewResourceManager.viewHasPendingResources()||this.eventEmitter.emit(WidgetToEditorEventType.VIEW_COMPONENT_RESOURCES_LOADED)},5),o}destroy(e){var t;if(!(null===(t=e.model)||void 0===t?void 0:t.path))return;const n=e.model.path[0];this.documentModel.destroyView(n)}renderComponent(e,t,n,o=ComponentInsertType.INSIDE){var r;const i=this.factory.create(t,n,this.viewResourceManager);this.documentModel.setComponentRef(t.id,i);const s=e.componentRef.getRootElement();let p=t.props.floating||"FLOATING_IMAGE"===t.type?s:this.selectElementToAppendTo(e.componentRef.contentContainer)||this.selectElementToAppendTo(s);if(o===ComponentInsertType.INSIDE)i.connect(o,p,i);else if(o===ComponentInsertType.INSTEAD){const n=(null===(r=t.prevPath)||void 0===r?void 0:r.at(-1))<t.path.at(-1)?ComponentInsertType.AFTER:ComponentInsertType.BEFORE;i.connect(n,e.componentRef,t.componentRef)}else i.connect(o,e.componentRef,t.componentRef);return t.children&&t.children.forEach(e=>this.renderComponent(t,e,n)),t}selectElementToAppendTo(e){return e?this.getRenderOutlet(e)||e:null}getRenderOutlet(e){return e.querySelector(`[${applySysAttrPrefix("render-outlet")}]`)}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import ViewEntryType from"../../document-model/ViewEntryType";import{ViewRendererActionType}from"../../renderer/ViewRendererActionType";import ComponentType from"../../sdk/ComponentType";import{applySysAttrPrefix,applySysClassPrefix}from"../../renderer/RenderConstants";import getParentHostElement from"../../sdk/getParentHostElement";import debounce from"@claspo/common/async/debounce";import wcStaticDecorator from"./wcStaticDecorator";export default function wcUpdatingDecorator(e){return class extends(wcStaticDecorator(e)){constructor(){super(),this.eventListeners=[],this.lastDragOverEvent=null,this.focusedElements=[],this.observer=null,this._observeChanges()}connectedCallback(){super.connectedCallback(),this._addAllListeners()}disconnectedCallback(){var e,t,s;super.disconnectedCallback(),this._deactivateEventListeners(),null===(e=this.removeFocusSubscription)||void 0===e||e.off(),null===(t=this.setFocusSubscription)||void 0===t||t.off(),null===(s=this.componentFocusedSubscription)||void 0===s||s.off(),this.observer.disconnect()}_addAllListeners(){this.observer.observe(this.getRootElement(),{childList:!0,subtree:!0}),this.model.type===ViewEntryType.VIEW&&(this.eventListeners.push({eventName:"mousemove",callback:this._mouseMoveEventListener.bind(this),element:this}),this.eventListeners.push({eventName:"mouseout",callback:this._mouseOutEventListener.bind(this),element:this})),this.removeFocusSubscription=this.services.eventEmitter.on(ViewRendererActionType.REMOVE_FOCUS,()=>{this._removeFocus()}),this.setFocusSubscription=this.services.eventEmitter.on(ViewRendererActionType.SET_FOCUS,e=>{this._removeFocus(),this.model.id===e&&this._setFocus("host")}),this.componentFocusedSubscription=this.services.eventEmitter.on(ViewRendererActionType.COMPONENT_FOCUSED,({id:e,targetElementName:t})=>{this._removeFocus(),this.model.id===e&&this._setFocus(t)}),this.manifest.preventDraggable||this.getHostElement().setAttribute("draggable","true"),this._setElementListeners(this.getHostElement()),this._setGlobalListeners(),this._setEventListeners(),this._activateEventListeners(),this._setFocusableElementsAttribute()}_observeChanges(){let e={addded:!1,removed:!1};const t=debounce(()=>{e.removed&&this._removeListenersForDisconnectedNodes(),e.addded&&(this._setEventListeners(),this._activateEventListeners(),this._setFocusableElementsAttribute(),this._updateFocusedElementClasses()),e={addded:!1,removed:!1}},500);this.observer=new MutationObserver(function(s){for(let i of s){for(let t of i.addedNodes)t instanceof HTMLElement&&"STYLE"!==t.nodeName&&!e.addded&&(e=Object.assign(Object.assign({},e),{addded:!0}));for(let t of i.removedNodes)t instanceof HTMLElement&&"STYLE"!==t.nodeName&&!e.removed&&(e=Object.assign(Object.assign({},e),{removed:!0}));t()}})}_setEventListeners(){this.getRootElement().querySelectorAll("[cl-inline-edit], [cl-inline-edit] *").forEach(e=>{this._isEventListenerPresent(e)||"STYLE"!==e.tagName&&(e.getAttribute("draggable")||e.setAttribute("draggable","true"),this._setElementListeners(e,!0))}),this.getRootElement().querySelectorAll(":not([cl-inline-edit]):not([cl-type]):not([cl-inline-edit] *)").forEach(e=>{if(!this._isEventListenerPresent(e)&&"STYLE"!==e.tagName){if(e.getAttribute("draggable")||e.setAttribute("draggable","true"),e instanceof HTMLElement){const t=e.tagName.toLowerCase();"input"!==t&&"textarea"!==t||"readonly"===!e.getAttribute("readonly")||e.setAttribute("readonly","readonly"),this.manifest.componentType===ComponentType.VIDEO&&e.classList.contains("video-overlay")&&(e.style.visibility="visible")}this._setElementListeners(e)}})}_removeListenersForDisconnectedNodes(){this.eventListeners=this.eventListeners.filter(e=>(e.element.isConnected||e.element.removeEventListener(e.eventName,e.callback),e.element.isConnected))}_setGlobalListeners(){this.eventListeners.push({eventName:"drop",callback:e=>this._documentDropListener(e),element:document})}_isEventListenerPresent(e){return!!this.eventListeners.find(t=>t.element===e)}_setElementListeners(e,t){[{eventName:"click",callback:e=>this._elementClickListener(e,t),element:e},{eventName:"dblclick",callback:this._elementDoubleClickListener.bind(this),element:e},{eventName:"dragstart",callback:this._elementDragStartListener.bind(this),element:e},{eventName:"dragend",callback:this._elementDragEndListener.bind(this),element:e},{eventName:"dragover",callback:this._elementDragOverListener.bind(this),element:e},{eventName:"blur",callback:this._blurEventListener.bind(this),element:e,useCapture:!0}].forEach(e=>this.eventListeners.push(e))}_elementClickListener(e,t){e.preventDefault(),e.stopImmediatePropagation();const s=e.composedPath()[0],i=this.getHostElement();if(t&&this.services.eventEmitter.emit(ViewRendererActionType.SHOW_INLINE_EDIT,{id:this.model.id,hostElement:i,targetElement:s}),this.model.focusParentOnClick){const e=getParentHostElement(i);this.services.eventEmitter.emit(ViewRendererActionType.COMPONENT_FOCUSED,{id:e.getAttribute(applySysAttrPrefix("id")),hostElement:e,targetElement:e,targetElementName:"host"})}else this.services.eventEmitter.emit(ViewRendererActionType.COMPONENT_FOCUSED,{id:this.model.id,hostElement:i,targetElement:s,targetElementName:this._getElementNameByNode(s)});this.services.eventEmitter.emit(ViewRendererActionType.COMPONENT_CLICKED,e)}_elementDoubleClickListener(e){e.preventDefault(),e.stopImmediatePropagation(),this.services.eventEmitter.emit(ViewRendererActionType.COMPONENT_DOUBLE_CLICKED,{id:this.model.id,hostElement:this.getHostElement(),targetElement:e.composedPath()[0]})}_elementDragStartListener(e){e.stopPropagation();const t=e.composedPath().find(e=>{var t;return null===(t=e.hasAttribute)||void 0===t?void 0:t.call(e,applySysAttrPrefix("type"))}),s=t.getAttribute(applySysAttrPrefix("type"));this.services.eventEmitter.emit(ViewRendererActionType.COMPONENT_DRAGSTART,{id:this.model.id,path:this.model.path,hostElement:this.getHostElement(),targetElement:e.composedPath()[0],event:e,checkIfAllowed:i=>{if(i){const i=t.getBoundingClientRect();if(this._isWidgetRotated(this.documentModel.getShared(),!this.resizeListener.isMobile())){const s=e.pageX-i.left-window.pageXOffset,n=e.pageY-i.top-window.pageYOffset;if(navigator.userAgent.match(/Firefox/i)){const i=t.style.transform,r=t.style.transformOrigin;t.style.transform="rotate(-90deg)",t.style.transformOrigin="left top",e.dataTransfer.setDragImage(t,s,n),requestAnimationFrame(()=>{t.style.transform=i,t.style.transformOrigin=r})}else{const t=this._createDragPreviewPlaceholder(i);document.body.appendChild(t),e.dataTransfer.setDragImage(t,s,n),setTimeout(()=>{t.remove()})}}else e.dataTransfer.setDragImage(t,e.pageX-i.left-window.pageXOffset,e.pageY-i.top-window.pageYOffset);if(s===ViewEntryType.SLIDER){const s=t.shadowRoot.querySelector(".slides-container"),n=new WebKitCSSMatrix(getComputedStyle(s).transform).m41;e.dataTransfer.setDragImage(t,e.pageX-i.left-n-window.pageXOffset,e.pageY-i.top-window.pageYOffset)}}else e.preventDefault(),this.services.eventEmitter.emit(ViewRendererActionType.COMPONENT_DRAGEND)}})}_createDragPreviewPlaceholder(e){const t=document.createElement("div");return t.style.width=`${e.width}px`,t.style.height=`${e.height}px`,t.style.background="rgba(159, 41, 176, 0.3)",t.style.display="flex",t.style.justifyContent="center",t.style.alignItems="center",t.innerHTML='<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">\n<g opacity="0.6" clip-path="url(#clip0_43446_120564)">\n<path d="M26.5566 11.7573L30.7993 16L26.5566 20.2426" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M20.2422 26.5564L15.9995 30.799L11.7569 26.5564" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M5.44336 20.2426L1.20072 16L5.44336 11.7573" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M11.7569 5.4436L15.9995 1.20096L20.2422 5.4436" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M30.7994 16H20.8999" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M15.9995 30.7989L15.9995 20.8994" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M1.20064 16H11.1001" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M15.9995 1.20113L15.9995 11.1006" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n</g>\n<defs>\n<clipPath id="clip0_43446_120564">\n<rect width="32" height="32" fill="white"/>\n</clipPath>\n</defs>\n</svg>',t.firstChild.style.width=.4*e.width+"px",t.firstChild.style.height=.4*e.height+"px",t}_isWidgetRotated(e,t){const s=this._getFloatingBoxParams(e,t);return!!s&&"CENTER"===s.verticalPosition}_getFloatingBoxParams(e,t){return e&&e.floatingBox?t?e.floatingBox:e.floatingBox.mobile:null}_elementDragEndListener(e){e.stopPropagation(),this.services.eventEmitter.emit(ViewRendererActionType.COMPONENT_DRAGEND,{id:this.model.id,path:this.model.path,hostElement:this.getHostElement(),targetElement:e.composedPath()[0],event:e})}_elementDragOverListener(e){e.preventDefault(),e.stopPropagation();const t=this.lastDragOverEvent;this.lastDragOverEvent=e,e.pageX&&e.pageY&&(t&&t.clientY===e.clientY&&t.clientX===e.clientX||this.services.eventEmitter.emit(ViewRendererActionType.COMPONENT_DRAGOVER,{id:this.model.id,hostElement:this.getHostElement(),targetElement:e.composedPath()[0],event:e}))}_documentDropListener(e){this.services.eventEmitter.emit(ViewRendererActionType.DOCUMENT_DROP,{id:this.model.id,hostElement:this.getHostElement(),targetElement:e.composedPath()[0],event:e})}_mouseMoveEventListener(e){const t=this._findClosestHostElement(e.composedPath());if(this.preHoveredElement&&this.preHoveredElement!==t&&this.preHoveredElement.classList.remove(applySysClassPrefix("hovered")),this.preHoveredElement=t,t){t.classList.add(applySysClassPrefix("hovered"));const s={id:t.getAttribute(applySysAttrPrefix("id")),hostElement:t,targetElement:e.composedPath()[0],event:e};this.services.eventEmitter.emit(ViewRendererActionType.COMPONENT_MOUSE_MOVE,s)}}_mouseOutEventListener(e){e.stopPropagation();const t=this._findClosestHostElement(e.composedPath());t&&t.classList.remove(applySysClassPrefix("hovered"))}_blurEventListener(e){e.stopImmediatePropagation()}_removeFocus(){this.focusedElements.length&&this.focusedElements.forEach(e=>{var t;return null===(t=e.classList)||void 0===t?void 0:t.remove(applySysClassPrefix("focused"))}),this.focusedElements=[]}_setFocus(e){const t=this.getHostElement();if(this.focusedElements=[t],t.classList.add(applySysClassPrefix("focused")),"host"!==e){const t=this.getElements().filter(t=>t.getAttribute(applySysAttrPrefix("element"))===e);t.forEach(e=>e.classList.add(applySysClassPrefix("focused"))),this.focusedElements=this.focusedElements.concat(t)}}_findClosestHostElement(e){const t=e.filter(e=>e instanceof HTMLElement).filter(e=>!!e.getAttribute(applySysAttrPrefix("component")));return t.length?t[0]:null}_activateEventListeners(){this.eventListeners.forEach(e=>{e.activated||(e.element.addEventListener(e.eventName,e.callback,e.useCapture),e.activated=!0)})}_deactivateEventListeners(){this.eventListeners.forEach(e=>{e.element.removeEventListener(e.eventName,e.callback)}),this.eventListeners=[]}_getElementNameByNode(e){var t;const s="host";if(!e)return s;const i=e.closest(`[${applySysAttrPrefix("element")}]`);if(!i)return s;const n=i.getAttribute(applySysAttrPrefix("element"));return"host"===n||(null===(t=this.manifest.focusableElements)||void 0===t?void 0:t.includes(n))?n:s}_setFocusableElementsAttribute(){this.getElements().forEach(e=>{var t;(null===(t=this.manifest.focusableElements)||void 0===t?void 0:t.includes(e.getAttribute(applySysAttrPrefix("element"))))&&e.setAttribute(applySysAttrPrefix("focusable-element"),"")})}_updateFocusedElementClasses(){if(this.focusedElements.length<2)return;const e=this.focusedElements.find(e=>e.hasAttribute(applySysAttrPrefix("focusable-element")));e&&this._setFocus(e.getAttribute(applySysAttrPrefix("element")))}}}
|
|
1
|
+
import ViewEntryType from"../../document-model/ViewEntryType";import{WidgetToEditorEventType}from"../../renderer/WidgetToEditorEventType";import ComponentType from"../../sdk/ComponentType";import{applySysAttrPrefix,applySysClassPrefix}from"../../renderer/RenderConstants";import getParentHostElement from"../../sdk/getParentHostElement";import debounce from"@claspo/common/async/debounce";import wcStaticDecorator from"./wcStaticDecorator";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(WidgetToEditorEventType.REMOVE_FOCUS,()=>{this._removeFocus()}),this.setFocusSubscription=this.services.eventEmitter.on(WidgetToEditorEventType.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 this.services.eventEmitter.emit(WidgetToEditorEventType.COMPONENT_FOCUSED,{id:this.model.id,hostElement:i,targetElement:s,targetElementName:this._getElementNameByNode(s)});this.services.eventEmitter.emit(WidgetToEditorEventType.COMPONENT_CLICKED,e)}_elementDoubleClickListener(e){e.preventDefault(),e.stopImmediatePropagation(),this.services.eventEmitter.emit(WidgetToEditorEventType.COMPONENT_DOUBLE_CLICKED,{id:this.model.id,hostElement:this.getHostElement(),targetElement:e.composedPath()[0]})}_elementDragStartListener(e){e.stopPropagation();const t=e.composedPath().find(e=>{var t;return null===(t=e.hasAttribute)||void 0===t?void 0:t.call(e,applySysAttrPrefix("type"))}),s=t.getAttribute(applySysAttrPrefix("type"));this.services.eventEmitter.emit(WidgetToEditorEventType.COMPONENT_DRAGSTART,{id:this.model.id,path:this.model.path,hostElement:this.getHostElement(),targetElement:e.composedPath()[0],event:e,checkIfAllowed:i=>{if(i){const i=t.getBoundingClientRect();if(this._isWidgetRotated(this.documentModel.getShared(),!this.resizeListener.isMobile())){const s=e.pageX-i.left-window.pageXOffset,n=e.pageY-i.top-window.pageYOffset;if(navigator.userAgent.match(/Firefox/i)){const i=t.style.transform,o=t.style.transformOrigin;t.style.transform="rotate(-90deg)",t.style.transformOrigin="left top",e.dataTransfer.setDragImage(t,s,n),requestAnimationFrame(()=>{t.style.transform=i,t.style.transformOrigin=o})}else{const t=this._createDragPreviewPlaceholder(i);document.body.appendChild(t),e.dataTransfer.setDragImage(t,s,n),setTimeout(()=>{t.remove()})}}else e.dataTransfer.setDragImage(t,e.pageX-i.left-window.pageXOffset,e.pageY-i.top-window.pageYOffset);if(s===ViewEntryType.SLIDER){const s=t.shadowRoot.querySelector(".slides-container"),n=new WebKitCSSMatrix(getComputedStyle(s).transform).m41;e.dataTransfer.setDragImage(t,e.pageX-i.left-n-window.pageXOffset,e.pageY-i.top-window.pageYOffset)}}else e.preventDefault(),this.services.eventEmitter.emit(WidgetToEditorEventType.COMPONENT_DRAGEND)}})}_createDragPreviewPlaceholder(e){const t=document.createElement("div");return t.style.width=`${e.width}px`,t.style.height=`${e.height}px`,t.style.background="rgba(159, 41, 176, 0.3)",t.style.display="flex",t.style.justifyContent="center",t.style.alignItems="center",t.innerHTML='<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">\n<g opacity="0.6" clip-path="url(#clip0_43446_120564)">\n<path d="M26.5566 11.7573L30.7993 16L26.5566 20.2426" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M20.2422 26.5564L15.9995 30.799L11.7569 26.5564" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M5.44336 20.2426L1.20072 16L5.44336 11.7573" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M11.7569 5.4436L15.9995 1.20096L20.2422 5.4436" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M30.7994 16H20.8999" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M15.9995 30.7989L15.9995 20.8994" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M1.20064 16H11.1001" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M15.9995 1.20113L15.9995 11.1006" stroke="#50005B" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>\n</g>\n<defs>\n<clipPath id="clip0_43446_120564">\n<rect width="32" height="32" fill="white"/>\n</clipPath>\n</defs>\n</svg>',t.firstChild.style.width=.4*e.width+"px",t.firstChild.style.height=.4*e.height+"px",t}_isWidgetRotated(e,t){const s=this._getFloatingBoxParams(e,t);return!!s&&"CENTER"===s.verticalPosition}_getFloatingBoxParams(e,t){return e&&e.floatingBox?t?e.floatingBox:e.floatingBox.mobile:null}_elementDragEndListener(e){e.stopPropagation(),this.services.eventEmitter.emit(WidgetToEditorEventType.COMPONENT_DRAGEND,{id:this.model.id,path:this.model.path,hostElement:this.getHostElement(),targetElement:e.composedPath()[0],event:e})}_elementDragOverListener(e){e.preventDefault(),e.stopPropagation();const t=this.lastDragOverEvent;this.lastDragOverEvent=e,e.pageX&&e.pageY&&(t&&t.clientY===e.clientY&&t.clientX===e.clientX||this.services.eventEmitter.emit(WidgetToEditorEventType.COMPONENT_DRAGOVER,{id:this.model.id,hostElement:this.getHostElement(),targetElement:e.composedPath()[0],event:e}))}_documentDropListener(e){this.services.eventEmitter.emit(WidgetToEditorEventType.DOCUMENT_DROP,{id:this.model.id,hostElement:this.getHostElement(),targetElement:e.composedPath()[0],event:e})}_mouseMoveEventListener(e){const t=this._findClosestHostElement(e.composedPath());if(this.preHoveredElement&&this.preHoveredElement!==t&&this.preHoveredElement.classList.remove(applySysClassPrefix("hovered")),this.preHoveredElement=t,t){t.classList.add(applySysClassPrefix("hovered"));const s={id:t.getAttribute(applySysAttrPrefix("id")),hostElement:t,targetElement:e.composedPath()[0],event:e};this.services.eventEmitter.emit(WidgetToEditorEventType.COMPONENT_MOUSE_MOVE,s)}}_mouseOutEventListener(e){e.stopPropagation();const t=this._findClosestHostElement(e.composedPath());t&&t.classList.remove(applySysClassPrefix("hovered"))}_blurEventListener(e){e.stopImmediatePropagation()}_removeFocus(){this.focusedElements.length&&this.focusedElements.forEach(e=>{var t;return null===(t=e.classList)||void 0===t?void 0:t.remove(applySysClassPrefix("focused"))}),this.focusedElements=[]}_setFocus(e){const t=this.getHostElement();if(this.focusedElements=[t],t.classList.add(applySysClassPrefix("focused")),"host"!==e){const t=this.getElements().filter(t=>t.getAttribute(applySysAttrPrefix("element"))===e);t.forEach(e=>e.classList.add(applySysClassPrefix("focused"))),this.focusedElements=this.focusedElements.concat(t)}}_findClosestHostElement(e){const t=e.filter(e=>e instanceof HTMLElement).filter(e=>!!e.getAttribute(applySysAttrPrefix("component")));return t.length?t[0]:null}_activateEventListeners(){this.eventListeners.forEach(e=>{e.activated||(e.element.addEventListener(e.eventName,e.callback,e.useCapture),e.activated=!0)})}_deactivateEventListeners(){this.eventListeners.forEach(e=>{e.element.removeEventListener(e.eventName,e.callback)}),this.eventListeners=[]}_getElementNameByNode(e){var t;const s="host";if(!e)return s;const i=e.closest(`[${applySysAttrPrefix("element")}]`);if(!i)return s;const n=i.getAttribute(applySysAttrPrefix("element"));return"host"===n||(null===(t=this.manifest.focusableElements)||void 0===t?void 0:t.includes(n))?n:s}_setFocusableElementsAttribute(){this.getElements().forEach(e=>{var t;(null===(t=this.manifest.focusableElements)||void 0===t?void 0:t.includes(e.getAttribute(applySysAttrPrefix("element"))))&&e.setAttribute(applySysAttrPrefix("focusable-element"),"")})}_updateFocusedElementClasses(){if(this.focusedElements.length<2)return;const e=this.focusedElements.find(e=>e.hasAttribute(applySysAttrPrefix("focusable-element")));e&&this._setFocus(e.getAttribute(applySysAttrPrefix("element")))}}}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export const ViewRendererActionType={COMPONENT_FOCUSED:"COMPONENT_FOCUSED",REMOVE_FOCUS:"REMOVE_FOCUS",SET_FOCUS:"SET_FOCUS",COMPONENT_MOUSE_MOVE:"COMPONENT_MOUSE_MOVE",COMPONENT_CLICKED:"COMPONENT_CLICKED",COMPONENT_DOUBLE_CLICKED:"COMPONENT_DOUBLE_CLICKED",COMPONENT_DRAGSTART:"COMPONENT_DRAGSTART",COMPONENT_DRAGEND:"COMPONENT_DRAGEND",COMPONENT_DRAGOVER:"COMPONENT_DRAGOVER",DOCUMENT_DROP:"DOCUMENT_DROP",SHOW_INLINE_EDIT:"SHOW_INLINE_EDIT",VIEW_COMPONENT_RESOURCES_LOADED:"VIEW_COMPONENT_RESOURCES_LOADED",FAILED_TO_LOAD_COMPONENT_RESOURCE:"FAILED_TO_LOAD_COMPONENT_RESOURCE",GAME_PHASE_READY_TO_PLAY:"GAME_PHASE_READY_TO_PLAY",GAME_PHASE_COMPLETED:"GAME_PHASE_COMPLETED",GAME_PHASE_IDLE:"GAME_PHASE_IDLE"};
|