c4b31ef29b8ade906d6edd12f71d7ba47789e6b8
[portal.git] / ecomp-portal-FE-common / client / app / views / tabs / tabs.controller.js
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38 'use strict';
39 (function () {
40     const HTTP_PROTOCOL_RGX = /https?:\/\//;
41     class  TabsCtrl {
42         constructor(applicationsService, $log, $window, conf, userProfileService, userbarUpdateService, $scope,$cookies,$rootScope,confirmBoxService,auditLogService,schedulerService) {                
43                 // Tab counter
44             var counter = 1;
45             var tabLimit = 6;
46             this.conf = conf;
47             var cookieDomain = this.conf.cookieDomain;
48             // Array to store the tabs
49             $scope.tabs = [];
50             $scope.notificationShow=true;
51             $rootScope.showFooter = "";
52             $cookies.putObject('show_app_header', false,{domain: cookieDomain, path : '/'});
53
54             let  getCookieDomain = function() {
55                    return window.location.hostname;
56                 }
57           let getContextPath=function() {
58                    return  window.location.pathname.substring( 0, window.location.pathname.lastIndexOf( '/' ) + 1 );
59                 }
60
61             let noRefresh = function () {
62                     window.onbeforeunload = function(e) {
63
64                         var isQtoHref = false;
65                         try{
66                                 isQtoHref = e.srcElement.activeElement.href.includes("to");
67                         } catch(err) {
68
69                         }
70
71                         if ($scope.tabs.length > 1 && isQtoHref == false) {
72                             return "Changes you made may not be saved. Are you sure you want to refresh?";
73                         } else {
74                             return null;
75                         }
76                     }
77             }
78             // Add tab to the end of the array
79             var addTab = function (title, content) {
80                 if($scope.tabs.length===tabLimit){
81                         //alert
82                         confirmBoxService.showInformation('You have reached your maximum limit of tabs allowed.').then(isConfirmed => {});
83                 } else {
84                         // console.log(window.performance.memory);
85                         // var usedperc = (window.performance.memory.usedJSHeapSize/window.performance.memory.jsHeapSizeLimit)*100;
86                         // console.log('Current memory usage: '+usedperc+'%');
87                         if(title!=='Home' && content.indexOf('https') == -1){
88                                 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.');
89                                 //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 => {});
90                         }
91                         
92                     $scope.tabs.push({ title: title, content: content });
93                     counter++;
94                     //$scope.tabs[$scope.tabs.length - 1].disabled = false;
95                     $scope.selectedIndex = $scope.tabs.length - 1;
96                     if ($scope.tabs.length > 1) {
97                         noRefresh();
98                     }
99                     $cookies.putObject('cookieTabs', $scope.tabs,{domain: getCookieDomain(), path : getContextPath()});
100                     $cookies.putObject('visInVisCookieTabs', $scope.tabs,{domain: getCookieDomain(), path : getContextPath()});
101                    
102                 }
103             };
104             
105             //with APP ID
106             var addTab = function (title, content, appId) {
107                 if($scope.tabs.length===tabLimit){
108                         //alert
109                         confirmBoxService.showInformation('You have reached your maximum limit of tabs allowed.').then(isConfirmed => {});
110                 } else {                
111                         if(title!=='Home' && content.indexOf('https') === -1){
112                                 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.');
113                         }
114                     $scope.tabs.push({ title: title, content: content, appId:appId });
115                     counter++;
116                     $scope.selectedIndex = $scope.tabs.length - 1;
117                     if ($scope.tabs.length > 1) {
118                         noRefresh();
119                     }
120                     $cookies.putObject('cookieTabs', $scope.tabs,{domain: getCookieDomain(), path : getContextPath()});
121                     $cookies.putObject('visInVisCookieTabs', $scope.tabs,{domain: getCookieDomain(), path : getContextPath()});
122                 }
123             };
124             
125             // adjust title - trim the title and append ...
126             var adjustTitle = function (title) {
127                 var index = 15;
128                 var nonEmptyCharPattern = /(\s|\w)/;
129                 var adjustedTitle = title.substring(0,index);
130                 var ext = title.charAt(index).replace(nonEmptyCharPattern,'...');
131                 return adjustedTitle.concat(ext);
132                 
133                 
134             };
135             
136             //store audit log
137             $scope.auditLog = function(app) {
138                 $log.debug('auditLog::auditLog: auditLog.ping() = ' + app);
139                 var comment = '';
140                 if(app.content==null || app.content=='')
141                         comment= app.title;
142                 else
143                         comment = app.content;
144                 auditLogService.storeAudit(app.appId, 'tab', comment);
145                 };
146             
147             // Remove tab by index
148             var removeTab = function (event, index) {
149               event.preventDefault();
150               event.stopPropagation();
151               $scope.tabs.splice(index, 1);
152               $cookies.putObject('cookieTabs', $scope.tabs,{domain: getCookieDomain(), path : getContextPath()});
153             };
154             
155           //adjust height of the tab due to the search popup being hidden 
156                 $scope.adjustTabStyle = function(title){
157                         if(title=='Home'){
158                                 $(".w-ecomp-tabs").css('height',"50px");
159                         }else{
160                                 $(".w-ecomp-tabs").css('height',"100%");
161                         }
162                 }
163                 
164            // select tab 
165             var selectTab = function (title) {
166                 $scope.adjustTabStyle(title);
167                 if(title==='Home') {
168                     $rootScope.ContentModel.IsVisible=true;
169                     $rootScope.showFooter = true;
170                     $rootScope.tabBottom = 75;
171                     userbarUpdateService.setRefreshCount(userbarUpdateService.maxCount);
172                 }
173                 else {
174                     $rootScope.ContentModel.IsVisible=false;
175                     $rootScope.showFooter = false;
176                     $rootScope.tabBottom = 0;
177                 }
178             };
179
180             // Initialize the scope functions
181             $scope.addTab    = addTab;
182             $scope.removeTab = removeTab;
183             $scope.selectTab = selectTab;
184             $scope.adjustTitle = adjustTitle;
185             
186
187             $rootScope.ContentModel = {
188                     IsVisible : false,
189                     ViewUrl : null,
190                 };
191             
192             
193                 var sessionActive = applicationsService.ping()
194                 .then(sessionActive => {
195             // $log.debug('TabsCtrl::addTab: applicationsService.ping() = ' + JSON.stringify(sessionActive));
196                 // For demonstration add 5 tabs
197                
198             var cookieTabs = $cookies.getObject('cookieTabs');
199                 if(cookieTabs!=null){
200                         for(var t in cookieTabs){
201                                 // console.log('TabsCtrl::addTab: cookieTabs title: '+cookieTabs[t].title);
202                                 if(cookieTabs[t].title!=null && cookieTabs[t].title==='Home'){
203                                         cookieTabs[t].content = "";
204                                         $rootScope.ContentModel.IsVisible=true;
205                                 addTab( cookieTabs[t].title, cookieTabs[t].content,1) ;
206                                 }else{
207                                 addTab( cookieTabs[t].title, cookieTabs[t].content,cookieTabs[t].appId) ;
208                                 }
209                                         
210                         }
211                 } else {
212             for (var i = 0; i < 1; i++) {
213                 var content="";
214                 var title="";
215                 var appId=""
216                 if(i===0){
217                         title="Home";
218                         $rootScope.ContentModel.IsVisible=true;
219                     addTab(title, content,1);
220                 }else{
221                     addTab(title, content,appId);
222                 } 
223             }
224                 }
225             
226
227             
228             //$scope.tabs[$scope.tabs.length - 1].active = false;
229             //$scope.tabs[0].disabled = false;
230             $scope.selectedIndex = 0;
231                 });
232                 
233             $scope.$watchCollection(function() { return $cookies.getObject('addTab'); }, function(newValue) {
234                 // $log.log('Cookie string: ' + $cookies.get('test'))
235                 var tabContent = $cookies.getObject('addTab');
236                 if(tabContent!=null && tabContent.url!=null){
237                         var tabExists = false;
238                         for(var x in $scope.tabs){
239                                 // console.log($scope.tabs[x].content);
240                                 if($scope.tabs[x].title==tabContent.title){
241                                         tabExists = true;
242                                         //$scope.tabs[x].disabled = false;
243                                         $scope.selectedIndex = x;
244                             // added dummy variable to get iframe reloded if tab is already opened.
245                             if(tabContent.url.indexOf('?')===-1){
246                                 $scope.tabs[x].content=tabContent.url+'?dummyVar='+(new Date()).getTime();
247                             }
248                             else{
249                                 $scope.tabs[x].content=tabContent.url+'&dummyVar='+(new Date()).getTime();
250                             }
251                                 }
252                         }
253                         if(!tabExists){
254                          addTab( tabContent.title, tabContent.url,tabContent.appId) ;
255                         }
256                         $cookies.remove('addTab');
257                 }
258             });
259             
260             /*Listening on partner applications */
261             var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
262             var eventer = window[eventMethod];
263             var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
264             eventer(messageEvent,function(e) {
265                   $scope.openModal(e.data);
266                 },false);
267             
268             $scope.openModal = function(data){
269                 if(data!=null && data!='' && data.widgetData!=null)
270                         schedulerService.showWidget(data.widgetName,data.widgetData,data.widgetParameter).then(isConfirmed => {});
271             }
272         }
273     }
274     TabsCtrl.$inject = ['applicationsService', '$log', '$window', 'conf', 'userProfileService', 'userbarUpdateService', '$scope','$cookies','$rootScope','confirmBoxService','auditLogService','schedulerService'];
275     angular.module('ecompApp').controller('TabsCtrl', TabsCtrl);
276     
277     angular.module('ecompApp').directive('mainArea', function() {
278         return {
279             restrict: "E",
280             templateUrl: 'app/views/tabs/tabframe.html',
281             link: function(scope, element) {
282                                 
283                 //var iframeId = "#tabframe-" + scope.$parent.tab.title.split(' ').join('-');
284                 // jQuery(iframeId).load(function() {
285                 //        alert("hello");
286                 //    }); //.attr("src",'{{tab.content | trusted}}' ); //src='{{tab.content | trusted}}'
287                 // jQuery(iframeId).attr('src', '{{tab.content | trusted}}');
288                  
289                 //element.childNodes[0].on('load', function() {
290                 //      alert('hello');
291                 //});
292             }
293         }
294     });
295     
296    
297     
298     angular.module('ecompApp').directive('tabHighlight', [function () {
299         return {
300           restrict: 'A',
301           link: function (scope, element) {
302             // Here is the major jQuery usage where we add the event
303             // listeners mousemove and mouseout on the tabs to initalize
304             // the moving highlight for the inactive tabs
305             var x, y, initial_background = '#c3d5e6';
306
307             element
308               .removeAttr('style')
309               .mousemove(function (e) {
310                 // Add highlight effect on inactive tabs
311                 if(!element.hasClass('md-active'))
312                 {
313                   x = e.pageX - this.offsetLeft;
314                   y = e.pageY - this.offsetTop;
315
316                   // Set the background when mouse moves over inactive tabs
317                   element
318                     .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 })
319                     .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 })
320                     .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 });
321                 }
322               })
323               .mouseout(function () {
324                 // Return the inital background color of the tab
325                 element.removeAttr('style');
326               });
327           }
328         };
329       }]);
330
331
332     
333 })();
334
335 function getParameterByName(name, url) {
336     if (!url) url = window.location.href;
337     name = name.replace(/[\[\]]/g, "\\$&");
338     var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
339         results = regex.exec(url);
340     if (!results) return '';
341     if (!results[2]) return '';
342     return (results[2].replace(/\+/g, " "));
343 }
344
345 function isCascadeFrame(ref) {
346           // alert(ref.id);
347            if (self != top) {
348                    var e = document.body;
349                    e.parentNode.removeChild(e);
350                    window.location = "unKnownError";
351                    }
352 }