69ca3faaf5ecf52924fe19ba6d61c63f095b2acc
[sdc.git] / catalog-ui / src / app / ng2 / pages / composition / graph / composition-graph.component.ts
1 /**
2  * Created by ob0695 on 4/24/2018.
3  */
4 import { AfterViewInit, Component, ElementRef, HostBinding, Input } from '@angular/core';
5 import { Select, Store } from '@ngxs/store';
6 import {
7     ButtonModel,
8     Component as TopologyTemplate,
9     ComponentInstance,
10     CompositionCiNodeBase,
11     ConnectRelationModel,
12     GroupInstance,
13     LeftPaletteComponent,
14     LinkMenu,
15     Match,
16     ModalModel,
17     NodesFactory,
18     Point,
19     PolicyInstance,
20     PropertyBEModel,
21     Relationship,
22     StepModel,
23     Zone,
24     ZoneInstance,
25     ZoneInstanceAssignmentType,
26     ZoneInstanceMode,
27     ZoneInstanceType
28 } from 'app/models';
29 import { ForwardingPath } from 'app/models/forwarding-path';
30 import { CompositionCiServicePathLink } from 'app/models/graph/graph-links/composition-graph-links/composition-ci-service-path-link';
31 import { UIZoneInstanceObject } from 'app/models/ui-models/ui-zone-instance-object';
32 import { CompositionService } from 'app/ng2/pages/composition/composition.service';
33 import { CommonGraphUtils } from 'app/ng2/pages/composition/graph/common/common-graph-utils';
34 import { ComponentInstanceNodesStyle } from 'app/ng2/pages/composition/graph/common/style/component-instances-nodes-style';
35 import { ConnectionPropertiesViewComponent } from 'app/ng2/pages/composition/graph/connection-wizard/connection-properties-view/connection-properties-view.component';
36 import { ConnectionWizardHeaderComponent } from 'app/ng2/pages/composition/graph/connection-wizard/connection-wizard-header/connection-wizard-header.component';
37 import { ConnectionWizardService } from 'app/ng2/pages/composition/graph/connection-wizard/connection-wizard.service';
38 import { FromNodeStepComponent } from 'app/ng2/pages/composition/graph/connection-wizard/from-node-step/from-node-step.component';
39 import { PropertiesStepComponent } from 'app/ng2/pages/composition/graph/connection-wizard/properties-step/properties-step.component';
40 import { ToNodeStepComponent } from 'app/ng2/pages/composition/graph/connection-wizard/to-node-step/to-node-step.component';
41 import { WorkspaceService } from 'app/ng2/pages/workspace/workspace.service';
42 import { ComponentInstanceServiceNg2 } from 'app/ng2/services/component-instance-services/component-instance.service';
43 import { TopologyTemplateService } from 'app/ng2/services/component-services/topology-template.service';
44 import { ModalService } from 'app/ng2/services/modal.service';
45 import { ComponentGenericResponse } from 'app/ng2/services/responses/component-generic-response';
46 import { ServiceGenericResponse } from 'app/ng2/services/responses/service-generic-response';
47 import { WorkspaceState } from 'app/ng2/store/states/workspace.state';
48 import { EventListenerService } from 'app/services';
49 import { ComponentInstanceFactory, EVENTS, SdcElementType } from 'app/utils';
50 import { ComponentType, GRAPH_EVENTS, GraphColors, DEPENDENCY_EVENTS } from 'app/utils/constants';
51 import * as _ from 'lodash';
52 import { DndDropEvent } from 'ngx-drag-drop/ngx-drag-drop';
53 import { SdcUiServices } from 'onap-ui-angular';
54 import { NotificationSettings } from 'onap-ui-angular/dist/notifications/utilities/notification.config';
55 import { menuItem } from 'onap-ui-angular/dist/simple-popup-menu/menu-data.interface';
56 import { CytoscapeEdgeEditation } from '../../../../../third-party/cytoscape.js-edge-editation/CytoscapeEdgeEditation.js';
57 import { SelectedComponentType, SetSelectedComponentAction } from '../common/store/graph.actions';
58 import { GraphState } from '../common/store/graph.state';
59 import {
60     CompositionGraphGeneralUtils,
61     CompositionGraphNodesUtils,
62     CompositionGraphZoneUtils,
63     MatchCapabilitiesRequirementsUtils
64 } from './utils';
65 import { CompositionGraphLinkUtils } from './utils/composition-graph-links-utils';
66 import { CompositionGraphPaletteUtils } from './utils/composition-graph-palette-utils';
67 import { ServicePathGraphUtils } from './utils/composition-graph-service-path-utils';
68
69 declare const window: any;
70
71 @Component({
72     selector: 'composition-graph',
73     templateUrl: './composition-graph.component.html',
74     styleUrls: ['./composition-graph.component.less']
75 })
76
77 export class CompositionGraphComponent implements AfterViewInit {
78
79     @Select(WorkspaceState.isViewOnly) isViewOnly$: boolean;
80     @Select(GraphState.withSidebar) withSidebar$: boolean;
81     @Input() topologyTemplate: TopologyTemplate;
82     @HostBinding('attr.data-tests-id') dataTestId: string;
83     @Input() testId: string;
84
85     // tslint:disable:variable-name
86     private _cy: Cy.Instance;
87     private zoneTagMode: string;
88     private activeZoneInstance: ZoneInstance;
89     private zones: Zone[];
90     private currentlyClickedNodePosition: Cy.Position;
91     private dragElement: JQuery;
92     private dragComponent: ComponentInstance;
93     private componentInstanceNames: string[];
94     private topologyTemplateId: string;
95     private topologyTemplateType: string;
96
97     constructor(private elRef: ElementRef,
98                 private nodesFactory: NodesFactory,
99                 private eventListenerService: EventListenerService,
100                 private compositionGraphZoneUtils: CompositionGraphZoneUtils,
101                 private generalGraphUtils: CompositionGraphGeneralUtils,
102                 private compositionGraphLinkUtils: CompositionGraphLinkUtils,
103                 private nodesGraphUtils: CompositionGraphNodesUtils,
104                 private connectionWizardService: ConnectionWizardService,
105                 private commonGraphUtils: CommonGraphUtils,
106                 private modalService: ModalService,
107                 private compositionGraphPaletteUtils: CompositionGraphPaletteUtils,
108                 private topologyTemplateService: TopologyTemplateService,
109                 private componentInstanceService: ComponentInstanceServiceNg2,
110                 private matchCapabilitiesRequirementsUtils: MatchCapabilitiesRequirementsUtils,
111                 private store: Store,
112                 private compositionService: CompositionService,
113                 private loaderService: SdcUiServices.LoaderService,
114                 private workspaceService: WorkspaceService,
115                 private notificationService: SdcUiServices.NotificationsService,
116                 private simplePopupMenuService: SdcUiServices.simplePopupMenuService,
117                 private servicePathGraphUtils: ServicePathGraphUtils) {
118     }
119
120     ngOnInit() {
121         this.dataTestId = this.testId;
122         this.topologyTemplateId = this.workspaceService.metadata.uniqueId;
123         this.topologyTemplateType = this.workspaceService.metadata.componentType;
124
125         this.store.dispatch(new SetSelectedComponentAction({
126             component: this.topologyTemplate,
127             type: SelectedComponentType.TOPOLOGY_TEMPLATE
128         }));
129         this.eventListenerService.registerObserverCallback(EVENTS.ON_CHECKOUT, () => {
130             this.loadGraphData();
131         });
132         this.loadCompositionData();
133     }
134
135     ngAfterViewInit() {
136         this.loadGraph();
137     }
138
139     ngOnDestroy() {
140         this._cy.destroy();
141         _.forEach(GRAPH_EVENTS, (event) => {
142             this.eventListenerService.unRegisterObserver(event);
143         });
144         this.eventListenerService.unRegisterObserver(EVENTS.ON_CHECKOUT);
145         this.eventListenerService.unRegisterObserver(DEPENDENCY_EVENTS.ON_DEPENDENCY_CHANGE);
146     }
147
148     public isViewOnly = (): boolean => {
149         return this.store.selectSnapshot((state) => state.workspace.isViewOnly);
150     }
151
152     public zoom = (zoomIn: boolean): void => {
153         const currentZoom: number = this._cy.zoom();
154         if (zoomIn) {
155             this.generalGraphUtils.zoomGraphTo(this._cy, currentZoom + .1);
156         } else {
157             this.generalGraphUtils.zoomGraphTo(this._cy, currentZoom - .1);
158         }
159     }
160
161     public zoomAllWithoutSidebar = () => {
162         setTimeout(() => { // wait for sidebar changes to take effect before zooming
163             this.generalGraphUtils.zoomAll(this._cy);
164         });
165     }
166
167     public getAutoCompleteValues = (searchTerm: string) => {
168         if (searchTerm.length > 1) { // US requirement: only display search results after 2nd letter typed.
169             const nodes: Cy.CollectionNodes = this.nodesGraphUtils.getMatchingNodesByName(this._cy, searchTerm);
170             this.componentInstanceNames = _.map(nodes, (node) => node.data('name'));
171         } else {
172             this.componentInstanceNames = [];
173         }
174     }
175
176     public highlightSearchMatches = (searchTerm: string) => {
177         this.nodesGraphUtils.highlightMatchingNodesByName(this._cy, searchTerm);
178         const matchingNodes: Cy.CollectionNodes = this.nodesGraphUtils.getMatchingNodesByName(this._cy, searchTerm);
179         this.generalGraphUtils.zoomAll(this._cy, matchingNodes);
180     }
181
182     public onDrop = (dndEvent: DndDropEvent) => {
183         this.compositionGraphPaletteUtils.addNodeFromPalette(this._cy, dndEvent);
184     }
185
186     public openServicePathMenu = ($event): void => {
187
188         const menuConfig: menuItem[] = [];
189         if (!this.isViewOnly()) {
190             menuConfig.push({
191                 text: 'Create Service Flow',
192                 action: () => this.servicePathGraphUtils.onCreateServicePath()
193             });
194         }
195         menuConfig.push({
196             text: 'Service Flows List',
197             type: '',
198             action: () => this.servicePathGraphUtils.onListServicePath()
199         });
200         const popup = this.simplePopupMenuService.openBaseMenu(menuConfig, {
201             x: $event.x,
202             y: $event.y
203         });
204
205     }
206
207     public deletePathsOnCy = () => {
208         this.servicePathGraphUtils.deletePathsFromGraph(this._cy);
209     }
210
211     public drawPathOnCy = (data: ForwardingPath) => {
212         this.servicePathGraphUtils.drawPath(this._cy, data);
213     }
214
215     public onTapEnd = (event: Cy.EventObject) => {
216         if (this.zoneTagMode) {
217             return;
218         }
219         if (event.cyTarget === this._cy) { // On Background clicked
220             if (this._cy.$('node:selected').length === 0) { // if the background click but not dragged
221                 if (this.activeZoneInstance) {
222                     this.unsetActiveZoneInstance();
223                     this.selectTopologyTemplate();
224                 } else {
225                     this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_GRAPH_BACKGROUND_CLICKED);
226                     this.selectTopologyTemplate();
227                 }
228
229             }
230         } else if (event.cyTarget[0].isEdge()) { // and Edge clicked
231             this.compositionGraphLinkUtils.handleLinkClick(this._cy, event);
232             if (event.cyTarget[0].data().type === CompositionCiServicePathLink.LINK_TYPE) {
233                 return;
234             }
235             this.openModifyLinkMenu(this.compositionGraphLinkUtils.getModifyLinkMenu(event.cyTarget[0], event), event);
236         } else { // On Node clicked
237
238             this._cy.nodes(':grabbed').style({'overlay-opacity': 0});
239
240             const newPosition = event.cyTarget[0].position();
241             // node position changed (drop after drag event) - we need to update position
242             if (this.currentlyClickedNodePosition.x !== newPosition.x || this.currentlyClickedNodePosition.y !== newPosition.y) {
243                 const nodesMoved: Cy.CollectionNodes = this._cy.$(':grabbed');
244                 this.nodesGraphUtils.onNodesPositionChanged(this._cy, this.topologyTemplate, nodesMoved);
245             } else {
246                 if (this.activeZoneInstance) {
247                     this.unsetActiveZoneInstance();
248                 }
249                 this.selectComponentInstance(event.cyTarget[0].data().componentInstance);
250             }
251         }
252     }
253
254     private registerCytoscapeGraphEvents() {
255
256         this._cy.on('addedgemouseup', (event, data) => {
257             const connectRelationModel: ConnectRelationModel = this.compositionGraphLinkUtils.onLinkDrawn(this._cy, data.source, data.target);
258             if (connectRelationModel != null) {
259                 this.connectionWizardService.setRelationMenuDirectiveObj(connectRelationModel);
260                 this.connectionWizardService.selectedMatch = null;
261
262                 const steps: StepModel[] = [];
263                 const fromNodeName: string = connectRelationModel.fromNode.componentInstance.name;
264                 const toNodeName: string = connectRelationModel.toNode.componentInstance.name;
265                 steps.push(new StepModel(fromNodeName, FromNodeStepComponent));
266                 steps.push(new StepModel(toNodeName, ToNodeStepComponent));
267                 steps.push(new StepModel('Properties', PropertiesStepComponent));
268                 const wizardTitle = 'Connect: ' + fromNodeName + ' to ' + toNodeName;
269                 const modalInstance = this.modalService.createMultiStepsWizard(wizardTitle, steps, this.createLinkFromMenu, ConnectionWizardHeaderComponent);
270                 modalInstance.instance.open();
271             }
272         });
273
274         this._cy.on('tapstart', 'node', (event: Cy.EventObject) => {
275             this.currentlyClickedNodePosition = angular.copy(event.cyTarget[0].position()); // update node position on drag
276         });
277
278         this._cy.on('drag', 'node', (event: Cy.EventObject) => {
279             if (event.cyTarget.data().componentSubType !== SdcElementType.POLICY && event.cyTarget.data().componentSubType !== SdcElementType.GROUP) {
280                 event.cyTarget.style({'overlay-opacity': 0.24});
281                 if (this.generalGraphUtils.isValidDrop(this._cy, event.cyTarget)) {
282                     event.cyTarget.style({'overlay-color': GraphColors.NODE_BACKGROUND_COLOR});
283                 } else {
284                     event.cyTarget.style({'overlay-color': GraphColors.NODE_OVERLAPPING_BACKGROUND_COLOR});
285                 }
286             }
287         });
288
289         this._cy.on('handlemouseover', (event, payload) => {
290             // no need to add opacity while we are dragging and hovering othe nodes- or if opacity was already calculated for these nodes
291             if (payload.node.grabbed() || this._cy.scratch('_edge_editation_highlights') === true) {
292                 return;
293             }
294
295             if (this.zoneTagMode) {
296                 this.zoneTagMode = this.zones[this.activeZoneInstance.type].getHoverTagModeId();
297                 return;
298             }
299
300             const nodesData = this.nodesGraphUtils.getAllNodesData(this._cy.nodes());
301             const nodesLinks = this.generalGraphUtils.getAllCompositionCiLinks(this._cy);
302             const instance = payload.node.data().componentInstance;
303             const filteredNodesData = this.matchCapabilitiesRequirementsUtils.findMatchingNodesToComponentInstance(instance, nodesData, nodesLinks);
304             this.matchCapabilitiesRequirementsUtils.highlightMatchingComponents(filteredNodesData, this._cy);
305             this.matchCapabilitiesRequirementsUtils.fadeNonMachingComponents(filteredNodesData, nodesData, this._cy, payload.node.data());
306
307             this._cy.scratch()._edge_editation_highlights = true;
308         });
309
310         this._cy.on('handlemouseout', () => {
311             if (this.zoneTagMode) {
312                 this.zoneTagMode = this.zones[this.activeZoneInstance.type].getTagModeId();
313                 return;
314             }
315             if (this._cy.scratch('_edge_editation_highlights') === true) {
316                 this._cy.removeScratch('_edge_editation_highlights');
317                 this._cy.emit('hidehandles');
318                 this.matchCapabilitiesRequirementsUtils.resetFadedNodes(this._cy);
319             }
320         });
321
322         this._cy.on('tapend', (event: Cy.EventObject) => {
323             this.onTapEnd(event);
324         });
325
326         this._cy.on('boxselect', 'node', (event: Cy.EventObject) => {
327             this.unsetActiveZoneInstance();
328             this.selectComponentInstance(event.cyTarget.data().componentInstance);
329         });
330
331         this._cy.on('canvasredraw', (event: Cy.EventObject) => {
332             if (this.zoneTagMode) {
333                 this.compositionGraphZoneUtils.showZoneTagIndications(this._cy, this.activeZoneInstance);
334             }
335         });
336
337         this._cy.on('handletagclick', (event: Cy.EventObject, eventData: any) => {
338             this.compositionGraphZoneUtils.handleTagClick(this._cy, this.activeZoneInstance, eventData.nodeId);
339         });
340     }
341
342     private initViewMode() {
343
344         if (this.isViewOnly()) {
345             // remove event listeners
346             this._cy.off('drag');
347             this._cy.off('handlemouseout');
348             this._cy.off('handlemouseover');
349             this._cy.off('canvasredraw');
350             this._cy.off('handletagclick');
351             this._cy.edges().unselectify();
352         }
353     }
354
355     private saveChangedCapabilityProperties = (): Promise<PropertyBEModel[]> => {
356         return new Promise<PropertyBEModel[]>((resolve) => {
357             const capabilityPropertiesBE: PropertyBEModel[] = this.connectionWizardService.changedCapabilityProperties.map((prop) => {
358                 prop.value = prop.getJSONValue();
359                 const propBE = new PropertyBEModel(prop);
360                 propBE.parentUniqueId = this.connectionWizardService.selectedMatch.relationship.relation.capabilityOwnerId;
361                 return propBE;
362             });
363             if (capabilityPropertiesBE.length > 0) {
364                 // if there are capability properties to update, then first update capability properties and then resolve promise
365                 this.componentInstanceService
366                     .updateInstanceCapabilityProperties(
367                         this.topologyTemplate,
368                         this.connectionWizardService.selectedMatch.toNode,
369                         this.connectionWizardService.selectedMatch.capability,
370                         capabilityPropertiesBE
371                     )
372                     .subscribe((response) => {
373                         console.log('Update resource instance capability properties response: ', response);
374                         this.connectionWizardService.changedCapabilityProperties = [];
375                         resolve(capabilityPropertiesBE);
376                     });
377             } else {
378                 // no capability properties to update, immediately resolve promise
379                 resolve(capabilityPropertiesBE);
380             }
381         });
382     }
383
384     private loadCompositionData = () => {
385         this.loaderService.activate();
386         this.topologyTemplateService.getComponentCompositionData(this.topologyTemplateId, this.topologyTemplateType).subscribe((response: ComponentGenericResponse) => {
387             if (this.topologyTemplateType === ComponentType.SERVICE) {
388                 this.compositionService.forwardingPaths = (response as ServiceGenericResponse).forwardingPaths;
389             }
390             this.compositionService.componentInstances = response.componentInstances;
391             this.compositionService.componentInstancesRelations = response.componentInstancesRelations;
392             this.compositionService.groupInstances = response.groupInstances;
393             this.compositionService.policies = response.policies;
394             this.loadGraphData();
395             this.loaderService.deactivate();
396         }, (error) => { this.loaderService.deactivate(); });
397     }
398
399     private loadGraph = () => {
400         const graphEl = this.elRef.nativeElement.querySelector('.sdc-composition-graph-wrapper');
401         this.initGraph(graphEl);
402         this.zones = this.compositionGraphZoneUtils.createCompositionZones();
403         this.registerCytoscapeGraphEvents();
404         this.registerCustomEvents();
405         this.initViewMode();
406     }
407
408     private initGraphNodes() {
409
410         setTimeout(() => {
411             const handles = new CytoscapeEdgeEditation();
412             handles.init(this._cy);
413             if (!this.isViewOnly()) { // Init nodes handle extension - enable dynamic links
414                 handles.initNodeEvents();
415                 handles.registerHandle(ComponentInstanceNodesStyle.getAddEdgeHandle());
416             }
417             handles.registerHandle(ComponentInstanceNodesStyle.getTagHandle());
418             handles.registerHandle(ComponentInstanceNodesStyle.getTaggedPolicyHandle());
419             handles.registerHandle(ComponentInstanceNodesStyle.getTaggedGroupHandle());
420         }, 0);
421
422         _.each(this.compositionService.componentInstances, (instance) => {
423             const compositionGraphNode: CompositionCiNodeBase = this.nodesFactory.createNode(instance);
424             this.commonGraphUtils.addComponentInstanceNodeToGraph(this._cy, compositionGraphNode);
425         });
426
427     }
428
429     private loadGraphData = () => {
430         this.initGraphNodes();
431         this.compositionGraphLinkUtils.initGraphLinks(this._cy, this.compositionService.componentInstancesRelations);
432         this.compositionGraphZoneUtils.initZoneInstances(this.zones);
433         setTimeout(() => { // Need setTimeout so that angular canvas changes will take effect before resize & center
434             this.generalGraphUtils.zoomAllWithMax(this._cy, 1);
435         });
436         this.componentInstanceNames = _.map(this._cy.nodes(), (node) => node.data('name'));
437     }
438
439     private initGraph(graphEl: JQuery) {
440
441         this._cy = cytoscape({
442             container: graphEl,
443             style: ComponentInstanceNodesStyle.getCompositionGraphStyle(),
444             zoomingEnabled: true,
445             maxZoom: 1.2,
446             minZoom: .1,
447             userZoomingEnabled: false,
448             userPanningEnabled: true,
449             selectionType: 'single',
450             boxSelectionEnabled: true,
451             autolock: this.isViewOnly(),
452             autoungrabify: this.isViewOnly()
453         });
454
455         // Testing Bridge that allows Cypress tests to select a component on canvas not via DOM
456         if (window.Cypress) {
457             window.testBridge = this.createCanvasTestBridge();
458         }
459     }
460
461     private createCanvasTestBridge(): any {
462         return {
463             selectComponentInstance: (componentName: string) => {
464                 const matchingNodesByName = this.nodesGraphUtils.getMatchingNodesByName(this._cy, componentName);
465                 const component = new ComponentInstance(matchingNodesByName.first().data().componentInstance);
466                 this.selectComponentInstance(component);
467             }
468         };
469     }
470
471     // -------------------------------------------- ZONES---------------------------------------------------------//
472     private zoneMinimizeToggle = (zoneType: ZoneInstanceType): void => {
473         this.zones[zoneType].minimized = !this.zones[zoneType].minimized;
474     }
475
476     private zoneInstanceModeChanged = (newMode: ZoneInstanceMode, instance: ZoneInstance, zoneId: ZoneInstanceType): void => {
477         if (this.zoneTagMode) { // we're in tag mode.
478             if (instance === this.activeZoneInstance && newMode === ZoneInstanceMode.NONE) { // we want to turn tag mode off.
479                 this.zoneTagMode = null;
480                 this.activeZoneInstance.mode = ZoneInstanceMode.SELECTED;
481                 this.compositionGraphZoneUtils.endCyTagMode(this._cy);
482                 this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_CANVAS_TAG_END, instance);
483
484             }
485         } else {
486             // when active zone instance gets hover/none, don't actually change mode, just show/hide indications
487             if (instance !== this.activeZoneInstance || (instance === this.activeZoneInstance && newMode > ZoneInstanceMode.HOVER)) {
488                 instance.mode = newMode;
489             }
490
491             if (newMode === ZoneInstanceMode.NONE) {
492                 this.compositionGraphZoneUtils.hideZoneTagIndications(this._cy);
493                 if (this.zones[ZoneInstanceType.GROUP]) {
494                     this.compositionGraphZoneUtils.hideGroupZoneIndications(this.zones[ZoneInstanceType.GROUP].instances);
495                 }
496             }
497             if (newMode >= ZoneInstanceMode.HOVER) {
498                 this.compositionGraphZoneUtils.showZoneTagIndications(this._cy, instance);
499                 if (instance.type === ZoneInstanceType.POLICY && this.zones[ZoneInstanceType.GROUP]) {
500                     this.compositionGraphZoneUtils.showGroupZoneIndications(this.zones[ZoneInstanceType.GROUP].instances, instance);
501                 }
502             }
503             if (newMode >= ZoneInstanceMode.SELECTED) {
504                 this._cy.$('node:selected').unselect();
505                 if (this.activeZoneInstance && this.activeZoneInstance !== instance && newMode >= ZoneInstanceMode.SELECTED) {
506                     this.activeZoneInstance.mode = ZoneInstanceMode.NONE;
507                 }
508                 this.activeZoneInstance = instance;
509                 this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_ZONE_INSTANCE_SELECTED, instance);
510                 this.store.dispatch(new SetSelectedComponentAction({
511                     component: instance.instanceData,
512                     type: SelectedComponentType[ZoneInstanceType[instance.type]]
513                 }));
514             }
515             if (newMode === ZoneInstanceMode.TAG) {
516                 this.compositionGraphZoneUtils.startCyTagMode(this._cy);
517                 this.zoneTagMode = this.zones[zoneId].getTagModeId();
518                 this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_CANVAS_TAG_START, zoneId);
519             }
520         }
521     }
522
523     private zoneInstanceTagged = (taggedInstance: ZoneInstance) => {
524         this.activeZoneInstance.addOrRemoveAssignment(taggedInstance.instanceData.uniqueId, ZoneInstanceAssignmentType.GROUPS);
525         const newHandle: string = this.compositionGraphZoneUtils.getCorrectHandleForNode(taggedInstance.instanceData.uniqueId, this.activeZoneInstance);
526         taggedInstance.showHandle(newHandle);
527     }
528
529     private unsetActiveZoneInstance = (): void => {
530         if (this.activeZoneInstance) {
531             this.activeZoneInstance.mode = ZoneInstanceMode.NONE;
532             this.activeZoneInstance = null;
533             this.zoneTagMode = null;
534         }
535     }
536
537     private selectComponentInstance = (componentInstance: ComponentInstance) => {
538         this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_NODE_SELECTED, componentInstance);
539         this.store.dispatch(new SetSelectedComponentAction({
540             component: componentInstance,
541             type: SelectedComponentType.COMPONENT_INSTANCE
542         }));
543     }
544
545     private selectTopologyTemplate = () => {
546         this.store.dispatch(new SetSelectedComponentAction({
547             component: this.topologyTemplate,
548             type: SelectedComponentType.TOPOLOGY_TEMPLATE
549         }));
550     }
551
552     private zoneBackgroundClicked = (): void => {
553         if (!this.zoneTagMode && this.activeZoneInstance) {
554             this.unsetActiveZoneInstance();
555             this.selectTopologyTemplate();
556         }
557     }
558
559     private zoneAssignmentSaveStart = () => {
560         this.loaderService.activate();
561     }
562
563     private zoneAssignmentSaveComplete = (success: boolean) => {
564         this.loaderService.deactivate();
565         if (!success) {
566             this.notificationService.push(new NotificationSettings('error', 'Update Failed', 'Error'));
567         }
568     }
569
570     private deleteZoneInstance = (deletedInstance: UIZoneInstanceObject) => {
571         if (deletedInstance.type === ZoneInstanceType.POLICY) {
572             this.compositionService.policies = this.compositionService.policies.filter((policy) => policy.uniqueId !== deletedInstance.uniqueId);
573         } else if (deletedInstance.type === ZoneInstanceType.GROUP) {
574             this.compositionService.groupInstances = this.compositionService.groupInstances.filter((group) => group.uniqueId !== deletedInstance.uniqueId);
575         }
576         // remove it from zones
577         this.zones[deletedInstance.type].removeInstance(deletedInstance.uniqueId);
578         if (deletedInstance.type === ZoneInstanceType.GROUP && !_.isEmpty(this.zones[ZoneInstanceType.POLICY])) {
579             this.compositionGraphZoneUtils.updateTargetsOrMembersOnCanvasDelete(deletedInstance.uniqueId, [this.zones[ZoneInstanceType.POLICY]], ZoneInstanceAssignmentType.GROUPS);
580         }
581         this.selectTopologyTemplate();
582     }
583     // -------------------------------------------------------------------------------------------------------------//
584
585     private registerCustomEvents() {
586
587         this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_GROUP_INSTANCE_UPDATE, (groupInstance: GroupInstance) => {
588             this.compositionGraphZoneUtils.findAndUpdateZoneInstanceData(this.zones, groupInstance);
589             this.notificationService.push(new NotificationSettings('success', 'Group Updated', 'Success'));
590         });
591
592         this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_POLICY_INSTANCE_UPDATE, (policyInstance: PolicyInstance) => {
593             this.compositionGraphZoneUtils.findAndUpdateZoneInstanceData(this.zones, policyInstance);
594             this.notificationService.push(new NotificationSettings('success', 'Policy Updated', 'Success'));
595         });
596
597         this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_PALETTE_COMPONENT_HOVER_IN, (leftPaletteComponent: LeftPaletteComponent) => {
598             this.compositionGraphPaletteUtils.onComponentHoverIn(leftPaletteComponent, this._cy);
599         });
600
601         this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_ADD_ZONE_INSTANCE_FROM_PALETTE,
602             (component: TopologyTemplate, paletteComponent: LeftPaletteComponent, startPosition: Point) => {
603
604                 const zoneType: ZoneInstanceType = this.compositionGraphZoneUtils.getZoneTypeForPaletteComponent(paletteComponent.categoryType);
605                 this.compositionGraphZoneUtils.showZone(this.zones[zoneType]);
606
607                 this.loaderService.activate();
608                 this.compositionGraphZoneUtils.createZoneInstanceFromLeftPalette(zoneType, paletteComponent.type).subscribe((zoneInstance: ZoneInstance) => {
609                     this.loaderService.deactivate();
610                     this.compositionGraphZoneUtils.addInstanceToZone(this.zones[zoneInstance.type], zoneInstance, true);
611                     this.compositionGraphZoneUtils.createPaletteToZoneAnimation(startPosition, zoneType, zoneInstance);
612                 }, (error) => {
613                     this.loaderService.deactivate();
614                 });
615             });
616
617         this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_PALETTE_COMPONENT_HOVER_OUT, () => {
618             this._cy.emit('hidehandles');
619             this.matchCapabilitiesRequirementsUtils.resetFadedNodes(this._cy);
620         });
621
622         this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_PALETTE_COMPONENT_DRAG_START, (dragElement, dragComponent) => {
623             this.dragElement = dragElement;
624             this.dragComponent = ComponentInstanceFactory.createComponentInstanceFromComponent(dragComponent);
625         });
626
627         this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_PALETTE_COMPONENT_DRAG_ACTION, (position: Point) => {
628             const draggedElement = document.getElementById('draggable_element');
629             draggedElement.className = this.compositionGraphPaletteUtils.isDragValid(this._cy, position) ? 'valid-drag' : 'invalid-drag';
630         });
631
632         this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_PALETTE_COMPONENT_DROP, (event: DndDropEvent) => {
633             this.onDrop(event);
634         });
635
636         this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_COMPONENT_INSTANCE_NAME_CHANGED, (component: ComponentInstance) => {
637             const selectedNode = this._cy.getElementById(component.uniqueId);
638             selectedNode.data().componentInstance.name = component.name;
639             selectedNode.data('name', component.name); // used for tooltip
640             selectedNode.data('displayName', selectedNode.data().getDisplayName()); // abbreviated
641         });
642
643         this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_DELETE_COMPONENT_INSTANCE, (componentInstanceId: string) => {
644             const nodeToDelete = this._cy.getElementById(componentInstanceId);
645             this.nodesGraphUtils.deleteNode(this._cy, this.topologyTemplate, nodeToDelete);
646             this.selectTopologyTemplate();
647         });
648
649         this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_DELETE_ZONE_INSTANCE, (deletedInstance: UIZoneInstanceObject) => {
650             this.deleteZoneInstance(deletedInstance);
651         });
652
653         this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_DELETE_COMPONENT_INSTANCE_SUCCESS, (componentInstanceId: string) => {
654             if (!_.isEmpty(this.zones)) {
655                 this.compositionGraphZoneUtils.updateTargetsOrMembersOnCanvasDelete(componentInstanceId, this.zones, ZoneInstanceAssignmentType.COMPONENT_INSTANCES);
656             }
657         });
658
659         this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_DELETE_EDGE, (releaseLoading: boolean, linksToDelete: Cy.CollectionEdges) => {
660             this.compositionGraphLinkUtils.deleteLink(this._cy, this.topologyTemplate, releaseLoading, linksToDelete);
661         });
662
663         this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_VERSION_CHANGED, (component: ComponentInstance) => {
664             // Remove everything from graph and reload it all
665             this._cy.elements().remove();
666             this.loadCompositionData();
667             setTimeout(() => { this._cy.getElementById(component.uniqueId).select(); }, 1000);
668             this.selectComponentInstance(component);
669         });
670         this.eventListenerService.registerObserverCallback(DEPENDENCY_EVENTS.ON_DEPENDENCY_CHANGE, (ischecked: boolean) => {
671             if (ischecked) {
672                 this._cy.$('node:selected').addClass('dependent');
673             } else {
674                 // due to defect in cytoscape, just changing the class does not replace the icon, and i need to revert to original icon with no markings.
675                 this._cy.$('node:selected').removeClass('dependent');
676                 this._cy.$('node:selected').style({'background-image': this._cy.$('node:selected').data('originalImg')});
677             }
678         });
679     }
680     private createLinkFromMenu = (): void => {
681         this.saveChangedCapabilityProperties().then(() => {
682             this.compositionGraphLinkUtils.createLinkFromMenu(this._cy, this.connectionWizardService.selectedMatch);
683         });
684     }
685
686     private deleteRelation = (link: Cy.CollectionEdges) => {
687         // if multiple edges selected, delete the VL itself so edges get deleted automatically
688         if (this._cy.$('edge:selected').length > 1) {
689             this.nodesGraphUtils.deleteNode(this._cy, this.topologyTemplate, this._cy.$('node:selected'));
690         } else {
691             this.compositionGraphLinkUtils.deleteLink(this._cy, this.topologyTemplate, true, link);
692         }
693     }
694
695     private viewRelation = (link: Cy.CollectionEdges) => {
696
697         const linkData = link.data();
698         const sourceNode: CompositionCiNodeBase = link.source().data();
699         const targetNode: CompositionCiNodeBase = link.target().data();
700         const relationship: Relationship = linkData.relation.relationships[0];
701
702         this.compositionGraphLinkUtils.getRelationRequirementCapability(relationship, sourceNode.componentInstance, targetNode.componentInstance).then((objReqCap) => {
703             const capability = objReqCap.capability;
704             const requirement = objReqCap.requirement;
705
706             this.connectionWizardService.connectRelationModel = new ConnectRelationModel(sourceNode, targetNode, []);
707             this.connectionWizardService.selectedMatch = new Match(requirement, capability, true, linkData.source, linkData.target);
708             this.connectionWizardService.selectedMatch.relationship = relationship;
709
710             const title = `Connection Properties`;
711             const saveButton: ButtonModel = new ButtonModel('Save', 'blue', () => {
712                 this.saveChangedCapabilityProperties().then(() => {
713                     this.modalService.closeCurrentModal();
714                 });
715             });
716             const cancelButton: ButtonModel = new ButtonModel('Cancel', 'white', () => {
717                 this.modalService.closeCurrentModal();
718             });
719             const modal = new ModalModel('xl', title, '', [saveButton, cancelButton]);
720             const modalInstance = this.modalService.createCustomModal(modal);
721             this.modalService.addDynamicContentToModal(modalInstance, ConnectionPropertiesViewComponent);
722             modalInstance.instance.open();
723
724             new Promise((resolve) => {
725                 if (!this.connectionWizardService.selectedMatch.capability.properties) {
726                     this.componentInstanceService.getInstanceCapabilityProperties(this.topologyTemplateType, this.topologyTemplateId, linkData.target, capability)
727                         .subscribe(() => {
728                             resolve();
729                         }, () => { /* do nothing */ });
730                 } else {
731                     resolve();
732                 }
733             }).then(() => {
734                 this.modalService.addDynamicContentToModal(modalInstance, ConnectionPropertiesViewComponent);
735             });
736         }, () => { /* do nothing */ });
737     }
738
739     private openModifyLinkMenu = (linkMenuObject: LinkMenu, $event) => {
740
741         const menuConfig: menuItem[] = [{
742             text: 'View',
743             iconName: 'eye-o',
744             iconType: 'common',
745             iconMode: 'secondary',
746             iconSize: 'small',
747             type: '',
748             action: () => this.viewRelation(linkMenuObject.link as Cy.CollectionEdges)
749         }];
750
751         if (!this.isViewOnly()) {
752             menuConfig.push({
753                 text: 'Delete',
754                 iconName: 'trash-o',
755                 iconType: 'common',
756                 iconMode: 'secondary',
757                 iconSize: 'small',
758                 type: '',
759                 action: () => this.deleteRelation(linkMenuObject.link as Cy.CollectionEdges)
760             });
761         }
762         this.simplePopupMenuService.openBaseMenu(menuConfig, {
763             x: $event.originalEvent.x,
764             y: $event.originalEvent.y
765         });
766     }
767
768 }