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