import clone from 'clone' ; import EventType from './EventType' ; import { ModelManager } from './ModelManager' ; import { PathUtils } from './PathUtils' ; param model fires private export function triggerPageModelLoaded ( model ) { PathUtils . dispatchGlobalCustomEvent ( EventType . PAGE_MODEL_LOADED , { detail : { model : clone ( model ) } } ) ; } private export class EditorClient { public _modelManager : ModelManager ; public _windowListener : any ; constructor ( modelManager ) { this . _modelManager = modelManager ; this . _windowListener = ( event ) => { if ( ! event || ! event . detail || ! event . detail . msg ) { console . error ( 'EditorService.js' , 'No message passed to cq-pagemodel-update' , event ) ; return ; } this . _updateModel ( event . detail . msg ) ; } ; if ( PathUtils . isBrowser ( ) ) { window . addEventListener ( EventType . PAGE_MODEL_UPDATE , this . _windowListener ) ; } } param { Object } msg property property param { String } msg . cmd param { Object } msg . data fires private public _updateModel ( msg ) { if ( ! msg || ! msg . cmd || ! msg . path ) { console . error ( 'PageModelManager.js' , 'Not enough data received to update the page model' ) ; return ; } const path = msg . path ; const cmd = msg . cmd ; const data = clone ( msg . data ) ; let siblingName ; let itemPath ; let insertBefore ; const parentNodePath = PathUtils . getParentNodePath ( path ) ; switch ( cmd ) { case 'replace' : this . _modelManager . modelStore . setData ( path , data ) ; this . _modelManager . _notifyListeners ( path ) ; break ; case 'delete' : this . _modelManager . modelStore . removeData ( path ) ; if ( parentNodePath ) { this . _modelManager . _notifyListeners ( parentNodePath ) ; } break ; case 'insertBefore' : insertBefore = true ; case 'insertAfter' : siblingName = PathUtils . getNodeName ( path ) ; if ( parentNodePath ) { itemPath = parentNodePath + '/' + data . key ; this . _modelManager . modelStore . insertData ( itemPath , data . value , siblingName , insertBefore ) ; this . _modelManager . _notifyListeners ( parentNodePath ) ; } break ; default : console . log ( 'EditorClient' , 'unsupported command:' , cmd ) ; } triggerPageModelLoaded ( this . _modelManager . modelStore . dataMap ) ; } private public destroy ( ) { if ( PathUtils . isBrowser ( ) ) { window . removeEventListener ( EventType . PAGE_MODEL_UPDATE , this . _windowListener ) ; } } }