]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/ui.js
LP#1452950 Unload prompts more handlers / dupe styling
[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  * Only one handler is supported per page.
191  * NOTE: we can't use an egUnloadDialog as the dialog builder, because
192  * it renders asynchronously, which allows the page to redirect before
193  * the dialog appears.
194  */
195 .factory('egUnloadPrompt', [
196         '$window','egStrings', 
197 function($window , egStrings) {
198     var service = {};
199
200     // attach a page/scope unload prompt
201     service.attach = function($scope, msg) {
202
203         // handle page change
204         $($window).on('beforeunload', function() { 
205             return msg || egStrings.EG_UNLOAD_PAGE_PROMPT_MSG;
206         });
207
208         if (!$scope) return;
209
210         // If a scope was provided, attach a scope-change handler,
211         // similar to the page-page prompt.
212         service.locChangeCancel = 
213             $scope.$on('$locationChangeStart', function(evt, next, current) {
214             if (!confirm(msg || egStrings.EG_UNLOAD_CTRL_PROMPT_MSG)) 
215                 evt.preventDefault();
216         });
217     };
218
219     // remove the page unload prompt
220     service.clear = function() {
221         $($window).off('beforeunload');
222         if (service.locChangeCancel)
223             service.locChangeCancel();
224     }
225
226     return service;
227 }])
228
229 .directive('aDisabled', function() {
230     return {
231         restrict : 'A',
232         compile: function(tElement, tAttrs, transclude) {
233             //Disable ngClick
234             tAttrs["ngClick"] = ("ng-click", "!("+tAttrs["aDisabled"]+") && ("+tAttrs["ngClick"]+")");
235
236             //Toggle "disabled" to class when aDisabled becomes true
237             return function (scope, iElement, iAttrs) {
238                 scope.$watch(iAttrs["aDisabled"], function(newValue) {
239                     if (newValue !== undefined) {
240                         iElement.toggleClass("disabled", newValue);
241                     }
242                 });
243
244                 //Disable href on click
245                 iElement.on("click", function(e) {
246                     if (scope.$eval(iAttrs["aDisabled"])) {
247                         e.preventDefault();
248                     }
249                 });
250             };
251         }
252     };
253 })
254
255 .directive('egBasicComboBox', function() {
256     return {
257         restrict: 'E',
258         replace: true,
259         scope: {
260             list: "=", // list of strings
261             selected: "=",
262             egDisabled: "="
263         },
264         template:
265             '<div class="input-group">'+
266                 '<input type="text" ng-disabled="egDisabled" class="form-control" ng-model="selected" ng-change="makeOpen()">'+
267                 '<div class="input-group-btn" dropdown ng-class="{open:isopen}">'+
268                     '<button type="button" ng-click="showAll()" class="btn btn-default dropdown-toggle"><span class="caret"></span></button>'+
269                     '<ul class="dropdown-menu dropdown-menu-right">'+
270                         '<li ng-repeat="item in list|filter:selected"><a href ng-click="changeValue(item)">{{item}}</a></li>'+
271                         '<li ng-if="all" class="divider"><span></span></li>'+
272                         '<li ng-if="all" ng-repeat="item in list"><a href ng-click="changeValue(item)">{{item}}</a></li>'+
273                     '</ul>'+
274                 '</div>'+
275             '</div>',
276         controller: ['$scope','$filter',
277             function( $scope , $filter) {
278
279                 $scope.all = false;
280                 $scope.isopen = false;
281
282                 $scope.showAll = function () {
283                     if ($scope.selected.length > 0)
284                         $scope.all = true;
285                 }
286
287                 $scope.makeOpen = function () {
288                     $scope.isopen = $filter('filter')(
289                         $scope.list,
290                         $scope.selected
291                     ).length > 0 && $scope.selected.length > 0;
292                     $scope.all = false;
293                 }
294
295                 $scope.changeValue = function (newVal) {
296                     $scope.selected = newVal;
297                     $scope.isopen = false;
298                 }
299
300             }
301         ]
302     };
303 })
304
305 /**
306  * Nested org unit selector modeled as a Bootstrap dropdown button.
307  */
308 .directive('egOrgSelector', function() {
309     return {
310         restrict : 'AE',
311         transclude : true,
312         replace : true, // makes styling easier
313         scope : {
314             selected : '=', // defaults to workstation or root org,
315                             // unless the nodefault attibute exists
316
317             // Each org unit is passed into this function and, for
318             // any org units where the response value is true, the
319             // org unit will not be added to the selector.
320             hiddenTest : '=',
321
322             // Each org unit is passed into this function and, for
323             // any org units where the response value is true, the
324             // org unit will not be available for selection.
325             disableTest : '=',
326
327             // if set to true, disable the UI element altogether
328             alldisabled : '@',
329
330             // Caller can either $watch(selected, ..) or register an
331             // onchange handler.
332             onchange : '=',
333
334             // optional primary drop-down button label
335             label : '@',
336
337             // optional name of settings key for persisting
338             // the last selected org unit
339             stickySetting : '@'
340         },
341
342         // any reason to move this into a TT2 template?
343         template : 
344             '<div class="btn-group eg-org-selector" dropdown>'
345             + '<button type="button" class="btn btn-default dropdown-toggle" ng-disabled="disable_button">'
346              + '<span style="padding-right: 5px;">{{getSelectedName()}}</span>'
347              + '<span class="caret"></span>'
348            + '</button>'
349            + '<ul class="dropdown-menu scrollable-menu">'
350              + '<li ng-repeat="org in orgList" ng-hide="hiddenTest(org.id)">'
351                + '<a href ng-click="orgChanged(org)" a-disabled="disableTest(org.id)" '
352                  + 'style="padding-left: {{org.depth * 10 + 5}}px">'
353                  + '{{org.shortname}}'
354                + '</a>'
355              + '</li>'
356            + '</ul>'
357           + '</div>',
358
359         controller : ['$scope','$timeout','egOrg','egAuth','egCore','egStartup',
360               function($scope , $timeout , egOrg , egAuth , egCore , egStartup) {
361
362             if ($scope.alldisabled) {
363                 $scope.disable_button = $scope.alldisabled == 'true' ? true : false;
364             } else {
365                 $scope.disable_button = false;
366             }
367
368             $scope.egOrg = egOrg; // for use in the link function
369             $scope.egAuth = egAuth; // for use in the link function
370             $scope.hatch = egCore.hatch // for use in the link function
371
372             // avoid linking the full fleshed tree to the scope by 
373             // tossing in a flattened list.
374             // --
375             // Run-time code referencing post-start data should be run
376             // from within a startup block, otherwise accessing this
377             // module before startup completes will lead to failure.
378             egStartup.go().then(function() {
379
380                 $scope.orgList = egOrg.list().map(function(org) {
381                     return {
382                         id : org.id(),
383                         shortname : org.shortname(), 
384                         depth : org.ou_type().depth()
385                     }
386                 });
387
388                 if (!$scope.selected)
389                     $scope.selected = egOrg.get(egAuth.user().ws_ou());
390             });
391
392             $scope.getSelectedName = function() {
393                 if ($scope.selected && $scope.selected.shortname)
394                     return $scope.selected.shortname();
395                 return $scope.label;
396             }
397
398             $scope.orgChanged = function(org) {
399                 $scope.selected = egOrg.get(org.id);
400                 if ($scope.stickySetting) {
401                     egCore.hatch.setLocalItem($scope.stickySetting, org.id);
402                 }
403                 if ($scope.onchange) $scope.onchange($scope.selected);
404             }
405
406         }],
407         link : function(scope, element, attrs, egGridCtrl) {
408
409             // boolean fields are presented as value-less attributes
410             angular.forEach(
411                 ['nodefault'],
412                 function(field) {
413                     if (angular.isDefined(attrs[field]))
414                         scope[field] = true;
415                     else
416                         scope[field] = false;
417                 }
418             );
419
420             if (scope.stickySetting) {
421                 var orgId = scope.hatch.getLocalItem(scope.stickySetting);
422                 if (orgId) {
423                     scope.selected = scope.egOrg.get(orgId);
424                 }
425             }
426
427             if (!scope.selected && !scope.nodefault)
428                 scope.selected = scope.egOrg.get(scope.egAuth.user().ws_ou());
429         }
430
431     }
432 })
433
434 /* http://eric.sau.pe/angularjs-detect-enter-key-ngenter/ */
435 .directive('egEnter', function () {
436     return function (scope, element, attrs) {
437         element.bind("keydown keypress", function (event) {
438             if(event.which === 13) {
439                 scope.$apply(function (){
440                     scope.$eval(attrs.egEnter);
441                 });
442  
443                 event.preventDefault();
444             }
445         });
446     };
447 })
448
449 /*
450 http://stackoverflow.com/questions/18061757/angular-js-and-html5-date-input-value-how-to-get-firefox-to-show-a-readable-d
451
452 This directive allows us to use html5 input type="date" (for Chrome) and 
453 gracefully fall back to a regular ISO text input for Firefox.
454 It also allows us to abstract away some browser finickiness.
455 */
456 .directive(
457     'egDateInput',
458     function(dateFilter) {
459         return {
460             require: 'ngModel',
461             template: '<input type="date"></input>',
462             replace: true,
463             link: function(scope, elm, attrs, ngModelCtrl) {
464
465                 // since this is a date-only selector, set the time
466                 // portion to 00:00:00, which should better match the
467                 // user's expectations.  Note this allows us to retain
468                 // the timezone.
469                 function strip_time(date) {
470                     if (!date) date = new Date();
471                     date.setHours(0);
472                     date.setMinutes(0);
473                     date.setSeconds(0);
474                     date.setMilliseconds(0);
475                     return date;
476                 }
477
478                 ngModelCtrl.$formatters.unshift(function (modelValue) {
479                     // apply strip_time here in case the user never 
480                     // modifies the date value.
481                     return dateFilter(strip_time(modelValue), 'yyyy-MM-dd');
482                 });
483                 
484                 ngModelCtrl.$parsers.unshift(function(viewValue) {
485                     return strip_time(new Date(viewValue));
486                 });
487             },
488         };
489 })