aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-ui/src/app/directives/graphs-v2/palette/palette.directive.ts
blob: 0158a38253b4808ba323f2a13f44bf94de6c1d06 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import {
    Component,
    IAppMenu,
    LeftPanelModel,
    NodesFactory,
    LeftPaletteComponent,
    CompositionCiNodeBase,
    ComponentInstance
} from "app/models";
import {CompositionGraphGeneralUtils} from "../composition-graph/utils/composition-graph-general-utils";
import {EventListenerService} from "app/services";
import {ResourceType, GRAPH_EVENTS, EVENTS, ComponentInstanceFactory, ModalsHandler} from "app/utils";
import 'sdc-angular-dragdrop';
import {LeftPaletteLoaderService} from "../../../services/components/utils/composition-left-palette-service";

interface IPaletteScope {
    components:Array<LeftPaletteComponent>;
    currentComponent:Component;
    model:any;
    displaySortedCategories:any;
    expandedSection:string;
    dragElement:JQuery;
    dragbleNode:{
        event:JQueryEventObject,
        components:LeftPaletteComponent,
        ui:any
    }

    sectionClick:(section:string)=>void;
    searchComponents:(searchText:string)=>void;
    onMouseOver:(displayComponent:LeftPaletteComponent)=>void;
    onMouseOut:(displayComponent:LeftPaletteComponent)=>void;
    dragStartCallback:(event:JQueryEventObject, ui, displayComponent:LeftPaletteComponent)=>void;
    dragStopCallback:()=>void;
    onDragCallback:(event:JQueryEventObject) => void;

    setElementTemplate:(e:JQueryEventObject)=>void;

    isOnDrag:boolean;
    isDragable:boolean;
    isLoading:boolean;
    isViewOnly:boolean;
}

export class Palette implements ng.IDirective {
    constructor(private $log:ng.ILogService,
                private LeftPaletteLoaderService: LeftPaletteLoaderService,
                private sdcConfig,
                private ComponentFactory,
                private ComponentInstanceFactory:ComponentInstanceFactory,
                private NodesFactory:NodesFactory,
                private CompositionGraphGeneralUtils:CompositionGraphGeneralUtils,
                private EventListenerService:EventListenerService,
                private sdcMenu:IAppMenu,
                private ModalsHandler:ModalsHandler) {

    }

    private fetchingComponentFromServer:boolean = false;
    private nodeHtmlSubstitute:JQuery;

    scope = {
        currentComponent: '=',
        isViewOnly: '=',
        isLoading: '='
    };
    restrict = 'E';
    template = require('./palette.html');

    link = (scope:IPaletteScope, el:JQuery) => {
        this.nodeHtmlSubstitute = $('<div class="node-substitute"><span></span><img /></div>');
        el.append(this.nodeHtmlSubstitute);
        this.registerEventListenerForLeftPalette(scope);
        // this.LeftPaletteLoaderService.loadLeftPanel(scope.currentComponent.componentType);
                   
        this.initComponents(scope);
        this.initEvents(scope);
        this.initDragEvents(scope);
        this._initExpandedSection(scope, '');
        el.on('$destroy', ()=> {
            //remove listener of download event
            this.unRegisterEventListenerForLeftPalette(scope);
        });
    };

    private registerEventListenerForLeftPalette = (scope:IPaletteScope):void => {
        if (scope.currentComponent.isResource()) {
            this.EventListenerService.registerObserverCallback(EVENTS.RESOURCE_LEFT_PALETTE_UPDATE_EVENT, () => {
                this.updateLeftPanelDisplay(scope);
            });
        }
        if (scope.currentComponent.isService()) {
            this.EventListenerService.registerObserverCallback(EVENTS.SERVICE_LEFT_PALETTE_UPDATE_EVENT, () => {
                this.updateLeftPanelDisplay(scope);
            });
        }
        if (scope.currentComponent.isProduct()) {
            this.EventListenerService.registerObserverCallback(EVENTS.PRODUCT_LEFT_PALETTE_UPDATE_EVENT, () => {
                this.updateLeftPanelDisplay(scope);
            });
        }
    };

    private unRegisterEventListenerForLeftPalette = (scope:IPaletteScope):void => {
        if (scope.currentComponent.isResource()) {
            this.EventListenerService.unRegisterObserver(EVENTS.RESOURCE_LEFT_PALETTE_UPDATE_EVENT);
        }
        if (scope.currentComponent.isService()) {
            this.EventListenerService.unRegisterObserver(EVENTS.SERVICE_LEFT_PALETTE_UPDATE_EVENT);
        }
        if (scope.currentComponent.isProduct()) {
            this.EventListenerService.unRegisterObserver(EVENTS.PRODUCT_LEFT_PALETTE_UPDATE_EVENT);
        }
    };

    private leftPanelResourceFilter(resourcesNotAbstract:Array<LeftPaletteComponent>, resourceFilterTypes:Array<string>):Array<LeftPaletteComponent> {
        let filterResources = _.filter(resourcesNotAbstract, (component) => {
            return resourceFilterTypes.indexOf(component.getComponentSubType()) > -1;
        });
        return filterResources;
    }

    private initLeftPanel(leftPanelComponents:Array<LeftPaletteComponent>, resourceFilterTypes:Array<string>):LeftPanelModel {
        let leftPanelModel = new LeftPanelModel();

        if (resourceFilterTypes && resourceFilterTypes.length) {
            leftPanelComponents = this.leftPanelResourceFilter(leftPanelComponents, resourceFilterTypes);
        }
        leftPanelModel.numberOfElements = leftPanelComponents && leftPanelComponents.length || 0;

        if (leftPanelComponents && leftPanelComponents.length) {

            let categories:any = _.groupBy(leftPanelComponents, 'mainCategory');
            for (let category in categories)
                categories[category] = _.groupBy(categories[category], 'subCategory');

            leftPanelModel.sortedCategories = categories;
        }
        return leftPanelModel;
    }


    private initEvents(scope:IPaletteScope) {
        /**
         *
         * @param section
         */
        scope.sectionClick = (section:string) => {
            if (section === scope.expandedSection) {
                scope.expandedSection = '';
                return;
            }
            scope.expandedSection = section;
        };

        scope.onMouseOver = (displayComponent:LeftPaletteComponent) => {
            if (scope.isOnDrag) {
                return;
            }
            scope.isOnDrag = true;

            this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_HOVER_IN, displayComponent);
            this.$log.debug('palette::onMouseOver:: fired');
            //
            // if (this.CompositionGraphGeneralUtils.componentRequirementsAndCapabilitiesCaching.containsKey(displayComponent.uniqueId)) {
            //     this.$log.debug(`palette::onMouseOver:: component id ${displayComponent.uniqueId} found in cache`);
            //     let cacheComponent:Component = this.CompositionGraphGeneralUtils.componentRequirementsAndCapabilitiesCaching.getValue(displayComponent.uniqueId);
            //
            //     //TODO: Danny: fire event to highlight matching nodes
            //     //showMatchingNodes(cacheComponent);
            //     return;
            // }
            //
            // this.$log.debug(`palette::onMouseOver:: component id ${displayComponent.uniqueId} not found in cache, initiating server get`);
            // // This will bring the component from the server including requirements and capabilities
            // // Check that we do not fetch many times, because only in the success we add the component to componentRequirementsAndCapabilitiesCaching
            // if (this.fetchingComponentFromServer) {
            //     return;
            // }
            //
            // this.fetchingComponentFromServer = true;
            // this.ComponentFactory.getComponentFromServer(displayComponent.componentSubType, displayComponent.uniqueId)
            //     .then((component:Component) => {
            //         this.$log.debug(`palette::onMouseOver:: component id ${displayComponent.uniqueId} fetch success`);
            //         // this.LeftPaletteLoaderService.updateSpecificComponentLeftPalette(component, scope.currentComponent.componentType);
            //         this.CompositionGraphGeneralUtils.componentRequirementsAndCapabilitiesCaching.setValue(component.uniqueId, component);
            //         this.fetchingComponentFromServer = false;
            //
            //         //TODO: Danny: fire event to highlight matching nodes
            //         //showMatchingNodes(component);
            //     })
            //     .catch(() => {
            //         this.$log.debug('palette::onMouseOver:: component id fetch error');
            //         this.fetchingComponentFromServer = false;
            //     });


        };

        scope.onMouseOut = () => {
            scope.isOnDrag = false;
            this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_HOVER_OUT);
        }
    }

    private initComponents(scope:IPaletteScope) {
        scope.searchComponents = (searchText:any):void => {
            scope.displaySortedCategories = this._searchComponents(searchText, scope.model.sortedCategories);
            this._initExpandedSection(scope, searchText);
        };

        scope.isDragable = scope.currentComponent.isComplex();
        this.updateLeftPanelDisplay(scope);
    }

    private updateLeftPanelDisplay(scope:IPaletteScope) {
        let entityType:string = scope.currentComponent.componentType.toLowerCase();
        let resourceFilterTypes:Array<string> = this.sdcConfig.resourceTypesFilter[entityType];
        scope.components = this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(scope.currentComponent.componentType);
        scope.model = this.initLeftPanel(scope.components, resourceFilterTypes);
        scope.displaySortedCategories = angular.copy(scope.model.sortedCategories);
    };

    private _initExpandedSection(scope:IPaletteScope, searchText:string):void {
        if (searchText == '') {
            let isContainingCategory:boolean = false;
            let categoryToExpand:string;
            if (scope.currentComponent && scope.currentComponent.categories && scope.currentComponent.categories[0]) {
                categoryToExpand = this.sdcMenu.categoriesDictionary[scope.currentComponent.categories[0].name];
                for (let category in scope.model.sortedCategories) {
                    if (categoryToExpand == category) {
                        isContainingCategory = true;
                        break;
                    }
                }
            }
            isContainingCategory ? scope.expandedSection = categoryToExpand : scope.expandedSection = 'Generic';
        }
        else {
            scope.expandedSection = Object.keys(scope.displaySortedCategories).sort()[0];
        }
    };

    private initDragEvents(scope:IPaletteScope) {
        scope.dragStartCallback = (event:IDragDropEvent, ui, displayComponent:LeftPaletteComponent):void => {
            if (scope.isLoading || !scope.isDragable || scope.isViewOnly) {
                return;
            }

            let component = _.find(this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(scope.currentComponent.componentType), (componentFullData:LeftPaletteComponent) => {
                return displayComponent.uniqueId === componentFullData.uniqueId;
            });
            this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_DRAG_START, scope.dragElement, component);

            scope.isOnDrag = true;

            // this.graphUtils.showMatchingNodes(component, myDiagram, scope.sdcConfig.imagesPath);
            // document.addEventListener('mousemove', moveOnDocument);
            event.dataTransfer.component = component;
        };

        scope.dragStopCallback = () => {
            scope.isOnDrag = false;
        };

        scope.onDragCallback = (event:IDragDropEvent):void => {
            this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_DRAG_ACTION, event);
        };
        scope.setElementTemplate = (e) => {
            let dragComponent:LeftPaletteComponent = _.find(this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(scope.currentComponent.componentType),
                (fullComponent:LeftPaletteComponent) => {
                    return (<any>angular.element(e.currentTarget).scope()).component.uniqueId === fullComponent.uniqueId;
                });
            let componentInstance:ComponentInstance = this.ComponentInstanceFactory.createComponentInstanceFromComponent(dragComponent);
            let node:CompositionCiNodeBase = this.NodesFactory.createNode(componentInstance);

            // myDiagram.dragFromPalette = node;
            this.nodeHtmlSubstitute.find("img").attr('src', node.img);
            scope.dragElement = this.nodeHtmlSubstitute.clone().show();

            return scope.dragElement;
        };
    }

    private _searchComponents = (searchText:string, categories:any):void => {
        let displaySortedCategories = angular.copy(categories);
        if (searchText != '') {
            angular.forEach(categories, function (category:any, categoryKey) {

                angular.forEach(category, function (subcategory:Array<LeftPaletteComponent>, subcategoryKey) {
                    let filteredResources = [];
                    angular.forEach(subcategory, function (component:LeftPaletteComponent) {

                        let resourceFilterTerm:string = component.searchFilterTerms;
                        if (resourceFilterTerm.indexOf(searchText.toLowerCase()) >= 0) {
                            filteredResources.push(component);
                        }
                    });
                    if (filteredResources.length > 0) {
                        displaySortedCategories[categoryKey][subcategoryKey] = filteredResources;
                    }
                    else {
                        delete  displaySortedCategories[categoryKey][subcategoryKey];
                    }
                });
                if (!(Object.keys(displaySortedCategories[categoryKey]).length > 0)) {
                    delete  displaySortedCategories[categoryKey];
                }

            });
        }
        return displaySortedCategories;
    };

    public static factory = ($log,
                             LeftPaletteLoaderService,
                             sdcConfig,
                             ComponentFactory,
                             ComponentInstanceFactory,
                             NodesFactory,
                             CompositionGraphGeneralUtils,
                             EventListenerService,
                             sdcMenu,
                             ModalsHandler) => {
        return new Palette($log,
            LeftPaletteLoaderService,
            sdcConfig,
            ComponentFactory,
            ComponentInstanceFactory,
            NodesFactory,
            CompositionGraphGeneralUtils,
            EventListenerService,
            sdcMenu,
            ModalsHandler);
    };
}

Palette.factory.$inject = [
    '$log',
    'LeftPaletteLoaderService',
    'sdcConfig',
    'ComponentFactory',
    'ComponentInstanceFactory',
    'NodesFactory',
    'CompositionGraphGeneralUtils',
    'EventListenerService',
    'sdcMenu',
    'ModalsHandler'
];