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