]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/ui.js
LP#1452950 page unload warning prompt service
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / services / ui.js
1 /**
2   * UI tools and directives.
3   */
4 angular.module('egUiMod', ['egCoreMod', 'ui.bootstrap'])
5
6
7 /**
8  * <input focus-me="iAmOpen"/>
9  * $scope.iAmOpen = true;
10  */
11 .directive('focusMe', 
12        ['$timeout','$parse', 
13 function($timeout , $parse) {
14     return {
15         link: function(scope, element, attrs) {
16             var model = $parse(attrs.focusMe);
17             scope.$watch(model, function(value) {
18                 if(value === true) 
19                     $timeout(function() {element[0].focus()});
20             });
21             element.bind('blur', function() {
22                 scope.$apply(model.assign(scope, false));
23             })
24         }
25     };
26 }])
27
28 /**
29  * <input blur-me="pleaseBlurMe"/>
30  * $scope.pleaseBlurMe = true
31  * Useful for de-focusing when no other obvious focus target exists
32  */
33 .directive('blurMe', 
34        ['$timeout','$parse', 
35 function($timeout , $parse) {
36     return {
37         link: function(scope, element, attrs) {
38             var model = $parse(attrs.blurMe);
39             scope.$watch(model, function(value) {
40                 if(value === true) 
41                     $timeout(function() {element[0].blur()});
42             });
43             element.bind('focus', function() {
44                 scope.$apply(model.assign(scope, false));
45             })
46         }
47     };
48 }])
49
50
51 // <input select-me="iWantToBeSelected"/>
52 // $scope.iWantToBeSelected = true;
53 .directive('selectMe', 
54        ['$timeout','$parse', 
55 function($timeout , $parse) {
56     return {
57         link: function(scope, element, attrs) {
58             var model = $parse(attrs.selectMe);
59             scope.$watch(model, function(value) {
60                 if(value === true) 
61                     $timeout(function() {element[0].select()});
62             });
63             element.bind('blur', function() {
64                 scope.$apply(model.assign(scope, false));
65             })
66         }
67     };
68 }])
69
70
71 // 'reverse' filter 
72 // <div ng-repeat="item in items | reverse">{{item.name}}</div>
73 // http://stackoverflow.com/questions/15266671/angular-ng-repeat-in-reverse
74 // TODO: perhaps this should live elsewhere
75 .filter('reverse', function() {
76     return function(items) {
77         return items.slice().reverse();
78     };
79 })
80
81
82 /**
83  * egAlertDialog.open({message : 'hello {{name}}'}).result.then(
84  *     function() { console.log('alert closed') });
85  */
86 .factory('egAlertDialog', 
87
88         ['$modal','$interpolate',
89 function($modal , $interpolate) {
90     var service = {};
91
92     service.open = function(message, msg_scope) {
93         return $modal.open({
94             templateUrl: './share/t_alert_dialog',
95             controller: ['$scope', '$modalInstance',
96                 function($scope, $modalInstance) {
97                     $scope.message = $interpolate(message)(msg_scope);
98                     $scope.ok = function() {
99                         if (msg_scope && msg_scope.ok) msg_scope.ok();
100                         $modalInstance.close()
101                     }
102                 }
103             ]
104         });
105     }
106
107     return service;
108 }])
109
110 /**
111  * egConfirmDialog.open("some message goes {{here}}", {
112  *  here : 'foo', ok : function() {}, cancel : function() {}},
113  *  'OK', 'Cancel');
114  */
115 .factory('egConfirmDialog', 
116     
117        ['$modal','$interpolate',
118 function($modal, $interpolate) {
119     var service = {};
120
121     service.open = function(title, message, msg_scope, ok_button_label, cancel_button_label) {
122         return $modal.open({
123             templateUrl: './share/t_confirm_dialog',
124             controller: ['$scope', '$modalInstance',
125                 function($scope, $modalInstance) {
126                     $scope.title = $interpolate(title)(msg_scope);
127                     $scope.message = $interpolate(message)(msg_scope);
128                     $scope.ok_button_label = $interpolate(ok_button_label || '')(msg_scope);
129                     $scope.cancel_button_label = $interpolate(cancel_button_label || '')(msg_scope);
130                     $scope.ok = function() {
131                         if (msg_scope.ok) msg_scope.ok();
132                         $modalInstance.close()
133                     }
134                     $scope.cancel = function() {
135                         if (msg_scope.cancel) msg_scope.cancel();
136                         $modalInstance.dismiss();
137                     }
138                 }
139             ]
140         })
141     }
142
143     return service;
144 }])
145
146 /**
147  * egPromptDialog.open(
148  *    "prompt message goes {{here}}", 
149  *    promptValue,  // optional
150  *    {
151  *      here : 'foo',  
152  *      ok : function(value) {console.log(value)}, 
153  *      cancel : function() {console.log('prompt denied')}
154  *    }
155  *  );
156  */
157 .factory('egPromptDialog', 
158     
159        ['$modal','$interpolate',
160 function($modal, $interpolate) {
161     var service = {};
162
163     service.open = function(message, promptValue, msg_scope) {
164         return $modal.open({
165             templateUrl: './share/t_prompt_dialog',
166             controller: ['$scope', '$modalInstance',
167                 function($scope, $modalInstance) {
168                     $scope.message = $interpolate(message)(msg_scope);
169                     $scope.args = {value : promptValue || ''};
170                     $scope.focus = true;
171                     $scope.ok = function() {
172                         if (msg_scope.ok) msg_scope.ok($scope.args.value);
173                         $modalInstance.close()
174                     }
175                     $scope.cancel = function() {
176                         if (msg_scope.cancel) msg_scope.cancel();
177                         $modalInstance.dismiss();
178                     }
179                 }
180             ]
181         })
182     }
183
184     return service;
185 }])
186
187 /**
188  * Warn on page unload and give the user a chance to avoid navigating
189  * away from the current page.
190  * NOTE: we can't use an egUnloadDialog as the dialog builder, because
191  * it renders asynchronously, which allows the page to redirect before
192  * the dialog appears.
193  */
194 .factory('egUnloadPrompt', [
195         '$window','egStrings', 
196 function($window , egStrings) {
197     var service = {};
198
199     service.attach = function($scope, msg) {
200
201         // handle page change
202         $($window).on('beforeunload', function() { 
203             return msg || egStrings.EG_UNLOAD_PAGE_PROMPT_MSG;
204         });
205
206         // handle controller change (e.g. tabbed navigation)
207         $scope.$on('$locationChangeStart', function(evt, next, current) {
208             if (!confirm(msg || egStrings.EG_UNLOAD_CTRL_PROMPT_MSG)) 
209                 evt.preventDefault();
210         });
211     };
212     return service;
213 }])
214
215 .directive('aDisabled', function() {
216     return {
217         restrict : 'A',
218         compile: function(tElement, tAttrs, transclude) {
219             //Disable ngClick
220             tAttrs["ngClick"] = ("ng-click", "!("+tAttrs["aDisabled"]+") && ("+tAttrs["ngClick"]+")");
221
222             //Toggle "disabled" to class when aDisabled becomes true
223             return function (scope, iElement, iAttrs) {
224                 scope.$watch(iAttrs["aDisabled"], function(newValue) {
225                     if (newValue !== undefined) {
226                         iElement.toggleClass("disabled", newValue);
227                     }
228                 });
229
230                 //Disable href on click
231                 iElement.on("click", function(e) {
232                     if (scope.$eval(iAttrs["aDisabled"])) {
233                         e.preventDefault();
234                     }
235                 });
236             };
237         }
238     };
239 })
240
241 .directive('egBasicComboBox', function() {
242     return {
243         restrict: 'E',
244         replace: true,
245         scope: {
246             list: "=", // list of strings
247             selected: "=",
248             egDisabled: "="
249         },
250         template:
251             '<div class="input-group">'+
252                 '<input type="text" ng-disabled="egDisabled" class="form-control" ng-model="selected" ng-change="makeOpen()">'+
253                 '<div class="input-group-btn" dropdown ng-class="{open:isopen}">'+
254                     '<button type="button" ng-click="showAll()" class="btn btn-default dropdown-toggle"><span class="caret"></span></button>'+
255                     '<ul class="dropdown-menu dropdown-menu-right">'+
256                         '<li ng-repeat="item in list|filter:selected"><a href ng-click="changeValue(item)">{{item}}</a></li>'+
257                         '<li ng-if="all" class="divider"><span></span></li>'+
258                         '<li ng-if="all" ng-repeat="item in list"><a href ng-click="changeValue(item)">{{item}}</a></li>'+
259                     '</ul>'+
260                 '</div>'+
261             '</div>',
262         controller: ['$scope','$filter',
263             function( $scope , $filter) {
264
265                 $scope.all = false;
266                 $scope.isopen = false;
267
268                 $scope.showAll = function () {
269                     if ($scope.selected.length > 0)
270                         $scope.all = true;
271                 }
272
273                 $scope.makeOpen = function () {
274                     $scope.isopen = $filter('filter')(
275                         $scope.list,
276                         $scope.selected
277                     ).length > 0 && $scope.selected.length > 0;
278                     $scope.all = false;
279                 }
280
281                 $scope.changeValue = function (newVal) {
282                     $scope.selected = newVal;
283                     $scope.isopen = false;
284                 }
285
286             }
287         ]
288     };
289 })
290
291 /**
292  * Nested org unit selector modeled as a Bootstrap dropdown button.
293  */
294 .directive('egOrgSelector', function() {
295     return {
296         restrict : 'AE',
297         transclude : true,
298         replace : true, // makes styling easier
299         scope : {
300             selected : '=', // defaults to workstation or root org,
301                             // unless the nodefault attibute exists
302
303             // Each org unit is passed into this function and, for
304             // any org units where the response value is true, the
305             // org unit will not be added to the selector.
306             hiddenTest : '=',
307
308             // Each org unit is passed into this function and, for
309             // any org units where the response value is true, the
310             // org unit will not be available for selection.
311             disableTest : '=',
312
313             // if set to true, disable the UI element altogether
314             alldisabled : '@',
315
316             // Caller can either $watch(selected, ..) or register an
317             // onchange handler.
318             onchange : '=',
319
320             // optional primary drop-down button label
321             label : '@',
322
323             // optional name of settings key for persisting
324             // the last selected org unit
325             stickySetting : '@'
326         },
327
328         // any reason to move this into a TT2 template?
329         template : 
330             '<div class="btn-group eg-org-selector" dropdown>'
331             + '<button type="button" class="btn btn-default dropdown-toggle" ng-disabled="disable_button">'
332              + '<span style="padding-right: 5px;">{{getSelectedName()}}</span>'
333              + '<span class="caret"></span>'
334            + '</button>'
335            + '<ul class="dropdown-menu scrollable-menu">'
336              + '<li ng-repeat="org in orgList" ng-hide="hiddenTest(org.id)">'
337                + '<a href ng-click="orgChanged(org)" a-disabled="disableTest(org.id)" '
338                  + 'style="padding-left: {{org.depth * 10 + 5}}px">'
339                  + '{{org.shortname}}'
340                + '</a>'
341              + '</li>'
342            + '</ul>'
343           + '</div>',
344
345         controller : ['$scope','$timeout','egOrg','egAuth','egCore','egStartup',
346               function($scope , $timeout , egOrg , egAuth , egCore , egStartup) {
347
348             if ($scope.alldisabled) {
349                 $scope.disable_button = $scope.alldisabled == 'true' ? true : false;
350             } else {
351                 $scope.disable_button = false;
352             }
353
354             $scope.egOrg = egOrg; // for use in the link function
355             $scope.egAuth = egAuth; // for use in the link function
356             $scope.hatch = egCore.hatch // for use in the link function
357
358             // avoid linking the full fleshed tree to the scope by 
359             // tossing in a flattened list.
360             // --
361             // Run-time code referencing post-start data should be run
362             // from within a startup block, otherwise accessing this
363             // module before startup completes will lead to failure.
364             egStartup.go().then(function() {
365
366                 $scope.orgList = egOrg.list().map(function(org) {
367                     return {
368                         id : org.id(),
369                         shortname : org.shortname(), 
370                         depth : org.ou_type().depth()
371                     }
372                 });
373
374                 if (!$scope.selected)
375                     $scope.selected = egOrg.get(egAuth.user().ws_ou());
376             });
377
378             $scope.getSelectedName = function() {
379                 if ($scope.selected && $scope.selected.shortname)
380                     return $scope.selected.shortname();
381                 return $scope.label;
382             }
383
384             $scope.orgChanged = function(org) {
385                 $scope.selected = egOrg.get(org.id);
386                 if ($scope.stickySetting) {
387                     egCore.hatch.setLocalItem($scope.stickySetting, org.id);
388                 }
389                 if ($scope.onchange) $scope.onchange($scope.selected);
390             }
391
392         }],
393         link : function(scope, element, attrs, egGridCtrl) {
394
395             // boolean fields are presented as value-less attributes
396             angular.forEach(
397                 ['nodefault'],
398                 function(field) {
399                     if (angular.isDefined(attrs[field]))
400                         scope[field] = true;
401                     else
402                         scope[field] = false;
403                 }
404             );
405
406             if (scope.stickySetting) {
407                 var orgId = scope.hatch.getLocalItem(scope.stickySetting);
408                 if (orgId) {
409                     scope.selected = scope.egOrg.get(orgId);
410                 }
411             }
412
413             if (!scope.selected && !scope.nodefault)
414                 scope.selected = scope.egOrg.get(scope.egAuth.user().ws_ou());
415         }
416
417     }
418 })
419
420 /* http://eric.sau.pe/angularjs-detect-enter-key-ngenter/ */
421 .directive('egEnter', function () {
422     return function (scope, element, attrs) {
423         element.bind("keydown keypress", function (event) {
424             if(event.which === 13) {
425                 scope.$apply(function (){
426                     scope.$eval(attrs.egEnter);
427                 });
428  
429                 event.preventDefault();
430             }
431         });
432     };
433 })
434
435 /*
436 http://stackoverflow.com/questions/18061757/angular-js-and-html5-date-input-value-how-to-get-firefox-to-show-a-readable-d
437
438 This directive allows us to use html5 input type="date" (for Chrome) and 
439 gracefully fall back to a regular ISO text input for Firefox.
440 It also allows us to abstract away some browser finickiness.
441 */
442 .directive(
443     'egDateInput',
444     function(dateFilter) {
445         return {
446             require: 'ngModel',
447             template: '<input type="date"></input>',
448             replace: true,
449             link: function(scope, elm, attrs, ngModelCtrl) {
450
451                 // since this is a date-only selector, set the time
452                 // portion to 00:00:00, which should better match the
453                 // user's expectations.  Note this allows us to retain
454                 // the timezone.
455                 function strip_time(date) {
456                     if (!date) date = new Date();
457                     date.setHours(0);
458                     date.setMinutes(0);
459                     date.setSeconds(0);
460                     date.setMilliseconds(0);
461                     return date;
462                 }
463
464                 ngModelCtrl.$formatters.unshift(function (modelValue) {
465                     // apply strip_time here in case the user never 
466                     // modifies the date value.
467                     return dateFilter(strip_time(modelValue), 'yyyy-MM-dd');
468                 });
469                 
470                 ngModelCtrl.$parsers.unshift(function(viewValue) {
471                     return strip_time(new Date(viewValue));
472                 });
473             },
474         };
475 })