re base code
[sdc.git] / catalog-ui / src / app / ng2 / components / layout / top-nav / top-nav.component.ts
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 import * as _ from "lodash";
22 import {Component, Inject, Input, Output, EventEmitter} from "@angular/core";
23 import {IHostedApplication, IUserProperties} from "app/models";
24 import {MenuItemGroup, MenuItem} from "app/utils";
25 import {UserService} from "../../../services/user.service";
26 import {SdcConfigToken, ISdcConfig} from "../../../config/sdc-config.config";
27 import {TranslateService} from "../../../shared/translator/translate.service";
28 import {PluginsConfiguration, Plugin} from "app/models";
29
30
31 declare const window:any;
32 @Component({
33     selector: 'top-nav',
34     templateUrl: './top-nav.component.html',
35     styleUrls:['./top-nav.component.less']
36 })
37 export class TopNavComponent {
38     @Input() public version:string;
39     @Input() public menuModel:Array<MenuItemGroup>;
40     @Input() public topLvlSelectedIndex:number;
41     @Input() public hideSearch:boolean;
42     @Input() public searchTerm:string;
43     @Input() public notificationIconCallback:Function;
44     @Input() public unsavedChanges: boolean;
45     @Input() public unsavedChangesCallback: (completeCallback:Function)=> Promise<any>;
46     @Output() public searchTermChange:EventEmitter<string> = new EventEmitter<string>();
47     emitSearchTerm(event:string) {
48         this.searchTermChange.emit(event);
49     }
50
51     public topLvlMenu:MenuItemGroup;
52     public user:IUserProperties;
53
54     constructor(private translateService:TranslateService,
55                 @Inject('$state') private $state:ng.ui.IStateService,
56                 private userService:UserService,
57                 @Inject(SdcConfigToken) private sdcConfig:ISdcConfig) {
58         window.nav = this;
59     }
60
61     private _getTopLvlSelectedIndexByState = ():number => {
62         if (!this.topLvlMenu.menuItems) {
63             return 0;
64         }
65
66         let result = -1;
67
68         //set result to current state
69         this.topLvlMenu.menuItems.every((item:MenuItem, index:number)=> {
70             if (item.state === this.$state.current.name) {
71                 if (this.$state.current.name === 'plugins') {
72                     const pluginIdx = _.findIndex(PluginsConfiguration.plugins, (plugin: Plugin) => plugin.pluginStateUrl === this.$state.params.path);
73                     if (pluginIdx !== -1) {
74                         result = index + pluginIdx;
75                         return false;
76                     }
77                 } else {
78                     result = index;
79                     return false;
80                 }
81             }
82             return true;
83         });
84
85         //if it's a different state
86         if (result === -1) {
87             //if in 'workspace' -  checking previous state param
88             if (this.$state.includes('workspace')) {
89                 // if previous state is 'dashboard' or 'catalog', then select it - otherwise, use 'catalog' as default for 'workspace'
90                 const selectedStateName = (['dashboard', 'catalog'].indexOf(this.$state.params['previousState']) !== -1)
91                     ? this.$state.params['previousState']
92                     : 'catalog';
93                 result = this.topLvlMenu.menuItems.findIndex((item:MenuItem) => item.state === selectedStateName);
94             }
95
96             //if yet, none is selected, then select the first as default
97             if (result === -1) {
98                 result = 0;
99             }
100         }
101
102         return result;
103     };
104
105     ngOnChanges(changes) {
106         if (changes['menuModel']) {
107             console.log('menuModel was changed!');
108             this.generateMenu();
109         }
110     }
111
112     ngOnInit() {
113         console.log('Nav is init!', this.menuModel);
114         this.user = this.userService.getLoggedinUser();
115
116         this.translateService.languageChangedObservable.subscribe((lang) => {
117             let tmpArray: Array<MenuItem> = [
118                 new MenuItem(this.translateService.translate("TOP_MENU_HOME_BUTTON"), null, "dashboard", "goToState", null, null),
119                 new MenuItem(this.translateService.translate("TOP_MENU_CATALOG_BUTTON"), null, "catalog", "goToState", null, null)
120             ];
121
122             // Only designer can perform onboarding
123             if (this.user && this.user.role === 'DESIGNER') {
124                 tmpArray.push(new MenuItem(this.translateService.translate("TOP_MENU_ON_BOARD_BUTTON"), null, "onboardVendor", "goToState", null, null));
125                 _.each(this.sdcConfig.hostedApplications, (hostedApp: IHostedApplication) => {
126                     if (hostedApp.exists) {
127                         tmpArray.push(new MenuItem(hostedApp.navTitle, null, hostedApp.defaultState, "goToState", null, null));
128                     }
129                 });
130             }
131
132             // Adding plugins to top-nav only if they can be displayed for the current connected user role
133             _.each(PluginsConfiguration.plugins, (plugin: Plugin) => {
134                 if (plugin.pluginDisplayOptions["tab"] && (this.user && plugin.pluginDisplayOptions["tab"].displayRoles.includes(this.user.role))) {
135                     tmpArray.push(new MenuItem(plugin.pluginDisplayOptions["tab"].displayName, null, "plugins", "goToState", {path: plugin.pluginStateUrl}, null));
136                 }
137             });
138
139             this.topLvlMenu = new MenuItemGroup(0, tmpArray, true);
140             this.topLvlMenu.selectedIndex = isNaN(this.topLvlSelectedIndex) ? this._getTopLvlSelectedIndexByState() : this.topLvlSelectedIndex;
141
142             this.generateMenu();
143         });
144     }
145
146     generateMenu() {
147         if (this.menuModel && this.topLvlMenu && this.menuModel[0] !== this.topLvlMenu) {
148             this.menuModel.unshift(this.topLvlMenu);
149         }
150     }
151
152     goToState(state:string, params:any):Promise<boolean> {
153         return new Promise((resolve, reject) => {
154             this.$state.go(state, params || undefined);
155             resolve(true);
156         });
157     }
158
159     menuItemClick(itemGroup:MenuItemGroup, item:MenuItem) {
160
161         let onSuccessFunction = () => {
162             this.navigate(itemGroup, item);
163         }
164         if (this.unsavedChanges && this.unsavedChangesCallback){
165             this.unsavedChangesCallback(onSuccessFunction).then((onSuccess)=> {
166                 this.navigate(itemGroup, item);
167             }, (onReject) => {});
168         } else {
169             this.navigate(itemGroup, item);
170         }
171     }
172
173     navigate(itemGroup:MenuItemGroup, item:MenuItem) {
174         itemGroup.itemClick = false;
175         let onSuccess = ():void => {
176             itemGroup.selectedIndex = itemGroup.menuItems.indexOf(item);
177         };
178         let onFailed = ():void => {
179         };
180
181         if (item.callback) {
182             (item.callback.apply(undefined, item.params)).then(onSuccess, onFailed);
183         } else {
184             this[item.action](item.state, item.params).then(onSuccess, onFailed);
185         }
186     }
187
188 }