summaryrefslogtreecommitdiffstats
path: root/ecomp-portal-FE-common/client/app/views/tabs/tabs.controller.js
blob: 3e15144af11b8d287b739016690b112a4b40340e (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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
/*-
 * ============LICENSE_START==========================================
 * ONAP Portal
 * ===================================================================
 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
 * ===================================================================
 *
 * Unless otherwise specified, all software contained herein is licensed
 * under the Apache License, Version 2.0 (the "License");
 * you may not use this software except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Unless otherwise specified, all documentation contained herein is licensed
 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
 * you may not use this documentation except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             https://creativecommons.org/licenses/by/4.0/
 *
 * Unless required by applicable law or agreed to in writing, documentation
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * ============LICENSE_END============================================
 *
 * 
 */
'use strict';
(function () {
    const HTTP_PROTOCOL_RGX = /https?:\/\//;
    class  TabsCtrl {
        constructor(applicationsService, $log, $window, conf, userProfileService, userbarUpdateService, $scope,$cookies,$rootScope,confirmBoxService,auditLogService,schedulerService) {        	
        	// Tab counter
            var counter = 1;
            var tabLimit = 6;
            this.conf = conf;
            var cookieDomain = this.conf.cookieDomain;
            // Array to store the tabs
            $scope.tabs = [];
            $scope.notificationShow=true;
            $rootScope.showFooter = "";
            $cookies.putObject('show_app_header', false,{domain: cookieDomain, path : '/'});

            let  getCookieDomain = function() {
         	   return window.location.hostname;
         	}
          let getContextPath=function() {
         	   return  window.location.pathname.substring( 0, window.location.pathname.lastIndexOf( '/' ) + 1 );
         	}

            let noRefresh = function () {
                    window.onbeforeunload = function(e) {

                    	var isQtoHref = false;
                    	try{
                    		isQtoHref = e.srcElement.activeElement.href.includes("to");
                    	} catch(err) {

                    	}

                        if ($scope.tabs.length > 1 && isQtoHref == false) {
                            return "Changes you made may not be saved. Are you sure you want to refresh?";
                        } else {
                            return null;
                        }
                    }
            }
            // Add tab to the end of the array
            var addTab = function (title, content) {
            	
            	if($scope.tabs.length===tabLimit){
            		//alert
            		confirmBoxService.showInformation('You have reached your maximum limit of tabs allowed.').then(isConfirmed => {});
            	} else {
            		// console.log(window.performance.memory);
            		// var usedperc = (window.performance.memory.usedJSHeapSize/window.performance.memory.jsHeapSizeLimit)*100;
            		// console.log('Current memory usage: '+usedperc+'%');
            		if(title!=='Home' && content.indexOf('https') == -1){
            			console.log('App URL: '+content+'. The application URL you are trying to open is not HTTPS. We recommend to use secured HTTPS URL while on-boarding the application.');
            			//confirmBoxService.showInformation('The application URL you are trying to open is not HTTPS. We recommend to use secured HTTPS URL while on-boarding the application.').then(isConfirmed => {});
            		}
            		
                    $scope.tabs.push({ title: title, content: content });
                    counter++;
                    //$scope.tabs[$scope.tabs.length - 1].disabled = false;
                    $scope.selectedIndex = $scope.tabs.length - 1;
                    if ($scope.tabs.length > 1) {
                        noRefresh();
                    }
                    $cookies.putObject('cookieTabs', $scope.tabs,{domain: getCookieDomain(), path : getContextPath()});
                    $cookies.putObject('visInVisCookieTabs', $scope.tabs,{domain: getCookieDomain(), path : getContextPath()});
                   
            	}
            };
            
            //with APP ID
            var addTab = function (title, content, appId) {
            	if($scope.tabs.length===tabLimit){
            		//alert
            		confirmBoxService.showInformation('You have reached your maximum limit of tabs allowed.').then(isConfirmed => {});
            	} else {     		
            		if(title!=='Home' && content.indexOf('https') === -1){
            			console.log('App URL: '+content+'. The application URL you are trying to open is not HTTPS. We recommend to use secured HTTPS URL while on-boarding the application.');
            		}
                    $scope.tabs.push({ title: title, content: content, appId:appId });
                    counter++;
                    $scope.selectedIndex = $scope.tabs.length - 1;
                    if ($scope.tabs.length > 1) {
                        noRefresh();
                    }
                    $cookies.putObject('cookieTabs', $scope.tabs,{domain: getCookieDomain(), path : getContextPath()});
                    $cookies.putObject('visInVisCookieTabs', $scope.tabs,{domain: getCookieDomain(), path : getContextPath()});
            	}
            };
            
            // adjust title - trim the title and append ...
            var adjustTitle = function (title) {
            	var index = 15;
            	var nonEmptyCharPattern = /(\s|\w)/;
            	var adjustedTitle = title.substring(0,index);
            	var ext = title.charAt(index).replace(nonEmptyCharPattern,'...');
            	return adjustedTitle.concat(ext);
            	
            	
            };
            
            //store audit log
            $scope.auditLog = function(app) {
                $log.debug('auditLog::auditLog: auditLog.ping() = ' + app);
                var comment = '';
                if(app.content==null || app.content=='')
                	comment= app.title;
                else
                	comment = app.content;
                auditLogService.storeAudit(app.appId, 'tab', comment);
        	};
            
            // Remove tab by index
            var removeTab = function (event, index) {
              event.preventDefault();
              event.stopPropagation();
              $scope.tabs.splice(index, 1);
              $cookies.putObject('cookieTabs', $scope.tabs,{domain: getCookieDomain(), path : getContextPath()});
            };
            
          //adjust height of the tab due to the search popup being hidden 
        	$scope.adjustTabStyle = function(title){
        		if(title=='Home'){
        			$(".w-ecomp-tabs").css('height',"50px");
        		}else{
        			$(".w-ecomp-tabs").css('height',"100%");
        		}
        	}
        	
           // select tab 
            var selectTab = function (title) {
            	$scope.adjustTabStyle(title);
                if(title==='Home') {
                    $rootScope.ContentModel.IsVisible=true;
                    $rootScope.showFooter = true;
                    $rootScope.tabBottom = 75;
                    userbarUpdateService.setRefreshCount(userbarUpdateService.maxCount);
                }
                else {
                    $rootScope.ContentModel.IsVisible=false;
                    $rootScope.showFooter = false;
                    $rootScope.tabBottom = 0;
                }
            };

            // Initialize the scope functions
            $scope.addTab    = addTab;
            $scope.removeTab = removeTab;
            $scope.selectTab = selectTab;
            $scope.adjustTitle = adjustTitle;
            

            $rootScope.ContentModel = {
            	    IsVisible : false,
            	    ViewUrl : null,
            	};
            
            
        	var sessionActive = applicationsService.ping()
        	.then(sessionActive => {
            // $log.debug('TabsCtrl::addTab: applicationsService.ping() = ' + JSON.stringify(sessionActive));
        	// For demonstration add 5 tabs
               
            var cookieTabs = $cookies.getObject('cookieTabs');
        	if(cookieTabs!=null){
        		for(var t in cookieTabs){
        			// console.log('TabsCtrl::addTab: cookieTabs title: '+cookieTabs[t].title);
        			if(cookieTabs[t].title!=null && cookieTabs[t].title==='Home'){
        				cookieTabs[t].content = "";
        				$rootScope.ContentModel.IsVisible=true;
            			addTab( cookieTabs[t].title, cookieTabs[t].content,1) ;
        			}else{
            			addTab( cookieTabs[t].title, cookieTabs[t].content,cookieTabs[t].appId) ;
        			}
        				
        		}
        	} else {
            for (var i = 0; i < 1; i++) {
            	var content="";
            	var title="";
            	var appId=""
            	if(i===0){
            		title="Home";
            		$rootScope.ContentModel.IsVisible=true;
                    addTab(title, content,1);
            	}else{
                    addTab(title, content,appId);
            	} 
            }
        	}
            

            
            //$scope.tabs[$scope.tabs.length - 1].active = false;
            //$scope.tabs[0].disabled = false;
            $scope.selectedIndex = 0;
        	});
        	
            $scope.$watchCollection(function() { return $cookies.getObject('addTab'); }, function(newValue) {
            	// $log.log('Cookie string: ' + $cookies.get('test'))
            	var tabContent = $cookies.getObject('addTab');
            	if(tabContent!=null && tabContent.url!=null){
            		var tabExists = false;
            		for(var x in $scope.tabs){
            			// console.log($scope.tabs[x].content);
            			if($scope.tabs[x].title==tabContent.title){
            				tabExists = true;
            				//$scope.tabs[x].disabled = false;
            				$scope.selectedIndex = x;
                            // added dummy variable to get iframe reloded if tab is already opened.
                            if(tabContent.url.indexOf('?')===-1){
                                $scope.tabs[x].content=tabContent.url+'?dummyVar='+(new Date()).getTime();
                            }
                            else{
                                $scope.tabs[x].content=tabContent.url+'&dummyVar='+(new Date()).getTime();
                            }
            			}
            		}
            		if(!tabExists){
            	         addTab( tabContent.title, tabContent.url,tabContent.appId) ;
            		}
            		$cookies.remove('addTab');
            	}
            });
            
            /*Listening on partner applications */
            var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
    	    var eventer = window[eventMethod];
    	    var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
    	    eventer(messageEvent,function(e) {
	    	  $scope.openModal(e.data);
	    	},false);
    	    
    	    $scope.openModal = function(data){
    	    	if(data!=null && data!='' && data.widgetData!=null)
    	    		schedulerService.showWidget(data.widgetName,data.widgetData,data.widgetParameter).then(isConfirmed => {});
    	    }
        }
    }
    TabsCtrl.$inject = ['applicationsService', '$log', '$window', 'conf', 'userProfileService', 'userbarUpdateService', '$scope','$cookies','$rootScope','confirmBoxService','auditLogService','schedulerService'];
    angular.module('ecompApp').controller('TabsCtrl', TabsCtrl);
    
    angular.module('ecompApp').directive('mainArea', function() {
        return {
            restrict: "E",
            templateUrl: 'app/views/tabs/tabframe.html',
            link: function(scope, element) {
  	
            	var iframeId = "tabframe-" + scope.$parent.tab.title.split(' ').join('-');
            	var iframeVal = scope.$parent.tab.content;// +  "| trusted";
            	if(iframeId != 'tabframe-Home') {
            		sessionStorage.setItem("currentTabFrameId",iframeId);
            		sessionStorage.setItem("currentTabFrameVal",iframeVal);
            	}
            	//console.log(document.getElementById(sessionStorage.getItem("currentTabFrameId")));
            	
            	// jQuery(iframeId).load(function() {
            	  //      alert("hello");
            	//   }); //.attr("src",'{{tab.content | trusted}}' ); //src='{{tab.content | trusted}}'
            	// jQuery(iframeId).attr('src', '{{tab.content | trusted}}');
            	 
            	//element.childNodes[0].on('load', function() {
            	//	alert('hello');
            	//});
            }
        }
    });
    
   
    
    angular.module('ecompApp').directive('tabHighlight', [function () {
        return {
          restrict: 'A',
          link: function (scope, element) {
            // Here is the major jQuery usage where we add the event
            // listeners mousemove and mouseout on the tabs to initalize
            // the moving highlight for the inactive tabs
            var x, y, initial_background = '#c3d5e6';

            element
              .removeAttr('style')
              .mousemove(function (e) {
                // Add highlight effect on inactive tabs
                if(!element.hasClass('md-active'))
                {
                  x = e.pageX - this.offsetLeft;
                  y = e.pageY - this.offsetTop;

                  // Set the background when mouse moves over inactive tabs
                  element
                    .css({ background: '-moz-radial-gradient(circle at ' + x + 'px ' + y + 'px, rgba(255,255,255,0.4) 0px, rgba(255,255,255,0.0) 45px), ' + initial_background })
                    .css({ background: '-webkit-radial-gradient(circle at ' + x + 'px ' + y + 'px, rgba(255,255,255,0.4) 0px, rgba(255,255,255,0.0) 45px), ' + initial_background })
                    .css({ background: 'radial-gradient(circle at ' + x + 'px ' + y + 'px, rgba(255,255,255,0.4) 0px, rgba(255,255,255,0.0) 45px), ' + initial_background });
                }
              })
              .mouseout(function () {
                // Return the inital background color of the tab
                element.removeAttr('style');
              });
          }
        };
      }]);


    
})();

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return '';
    if (!results[2]) return '';
    return (results[2].replace(/\+/g, " "));
}

function isCascadeFrame(ref) {
	  // alert(ref.id);
	   if (self != top) {
		   var e = document.body;
		   e.parentNode.removeChild(e);
		   window.location = "unKnownError";
		   }
}

function loadFrame() {
	
		var interval = setInterval(function() {
			
			if(sessionStorage.getItem("currentTabFrameId") == null && sessionStorage.getItem("currentTabFrameVal") == null)
				clearInterval(interval);
			else if(document.getElementById(sessionStorage.getItem("currentTabFrameId")).src != sessionStorage.getItem("currentTabFrameVal")) {
            	document.getElementById(sessionStorage.getItem("currentTabFrameId")).src = sessionStorage.getItem("currentTabFrameVal");
				sessionStorage.removeItem("currentTabFrameId");
            	sessionStorage.removeItem("currentTabFrameVal");
            	clearInterval(interval);
			}
			},1000);

	
	}