]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/ui.js
LP#1464767 Browser client scrollable selectors
[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 .directive('aDisabled', function() {
188     return {
189         restrict : 'A',
190         compile: function(tElement, tAttrs, transclude) {
191             //Disable ngClick
192             tAttrs["ngClick"] = ("ng-click", "!("+tAttrs["aDisabled"]+") && ("+tAttrs["ngClick"]+")");
193
194             //Toggle "disabled" to class when aDisabled becomes true
195             return function (scope, iElement, iAttrs) {
196                 scope.$watch(iAttrs["aDisabled"], function(newValue) {
197                     if (newValue !== undefined) {
198                         iElement.toggleClass("disabled", newValue);
199                     }
200                 });
201
202                 //Disable href on click
203                 iElement.on("click", function(e) {
204                     if (scope.$eval(iAttrs["aDisabled"])) {
205                         e.preventDefault();
206                     }
207                 });
208             };
209         }
210     };
211 })
212
213 .directive('egBasicComboBox', function() {
214     return {
215         restrict: 'E',
216         replace: true,
217         scope: {
218             list: "=", // list of strings
219             selected: "="
220         },
221         template:
222             '<div class="input-group">'+
223                 '<input type="text" class="form-control" ng-model="selected" ng-change="makeOpen()">'+
224                 '<div class="input-group-btn" dropdown ng-class="{open:isopen}">'+
225                     '<button type="button" ng-click="showAll()" class="btn btn-default dropdown-toggle"><span class="caret"></span></button>'+
226                     '<ul class="dropdown-menu dropdown-menu-right">'+
227                         '<li ng-repeat="item in list|filter:selected"><a href ng-click="changeValue(item)">{{item}}</a></li>'+
228                         '<li ng-if="all" class="divider"><span></span></li>'+
229                         '<li ng-if="all" ng-repeat="item in list"><a href ng-click="changeValue(item)">{{item}}</a></li>'+
230                     '</ul>'+
231                 '</div>'+
232             '</div>',
233         controller: ['$scope','$filter',
234             function( $scope , $filter) {
235
236                 $scope.all = false;
237                 $scope.isopen = false;
238
239                 $scope.showAll = function () {
240                     if ($scope.selected.length > 0)
241                         $scope.all = true;
242                 }
243
244                 $scope.makeOpen = function () {
245                     $scope.isopen = $filter('filter')(
246                         $scope.list,
247                         $scope.selected
248                     ).length > 0 && $scope.selected.length > 0;
249                     $scope.all = false;
250                 }
251
252                 $scope.changeValue = function (newVal) {
253                     $scope.selected = newVal;
254                     $scope.isopen = false;
255                 }
256
257             }
258         ]
259     };
260 })
261
262 /**
263  * Nested org unit selector modeled as a Bootstrap dropdown button.
264  */
265 .directive('egOrgSelector', function() {
266     return {
267         restrict : 'AE',
268         transclude : true,
269         replace : true, // makes styling easier
270         scope : {
271             selected : '=', // defaults to workstation or root org,
272                             // unless the nodefault attibute exists
273
274             // Each org unit is passed into this function and, for
275             // any org units where the response value is true, the
276             // org unit will not be added to the selector.
277             hiddenTest : '=',
278
279             // Each org unit is passed into this function and, for
280             // any org units where the response value is true, the
281             // org unit will not be available for selection.
282             disableTest : '=',
283
284             // if set to true, disable the UI element altogether
285             alldisabled : '@',
286
287             // Caller can either $watch(selected, ..) or register an
288             // onchange handler.
289             onchange : '=',
290
291             // optional primary drop-down button label
292             label : '@'
293         },
294
295         // any reason to move this into a TT2 template?
296         template : 
297             '<div class="btn-group eg-org-selector" dropdown>'
298             + '<button type="button" class="btn btn-default dropdown-toggle" ng-disabled="disable_button">'
299              + '<span style="padding-right: 5px;">{{getSelectedName()}}</span>'
300              + '<span class="caret"></span>'
301            + '</button>'
302            + '<ul class="dropdown-menu scrollable-menu">'
303              + '<li ng-repeat="org in orgList" ng-hide="hiddenTest(org.id)">'
304                + '<a href ng-click="orgChanged(org)" a-disabled="disableTest(org.id)" '
305                  + 'style="padding-left: {{org.depth * 10 + 5}}px">'
306                  + '{{org.shortname}}'
307                + '</a>'
308              + '</li>'
309            + '</ul>'
310           + '</div>',
311
312         controller : ['$scope','$timeout','egOrg','egAuth',
313               function($scope , $timeout , egOrg , egAuth) {
314
315             if ($scope.alldisabled) {
316                 $scope.disable_button = $scope.alldisabled == 'true' ? true : false;
317             } else {
318                 $scope.disable_button = false;
319             }
320
321             $scope.egOrg = egOrg; // for use in the link function
322             $scope.egAuth = egAuth; // for use in the link function
323
324             // avoid linking the full fleshed tree to the scope by 
325             // tossing in a flattened list.
326             $scope.orgList = egOrg.list().map(function(org) {
327                 return {
328                     id : org.id(),
329                     shortname : org.shortname(), 
330                     depth : org.ou_type().depth()
331                 }
332             });
333
334             $scope.getSelectedName = function() {
335                 if ($scope.selected)
336                     return $scope.selected.shortname();
337                 return $scope.label;
338             }
339
340             $scope.orgChanged = function(org) {
341                 $scope.selected = egOrg.get(org.id);
342                 if ($scope.onchange) $scope.onchange($scope.selected);
343             }
344
345         }],
346         link : function(scope, element, attrs, egGridCtrl) {
347
348             // boolean fields are presented as value-less attributes
349             angular.forEach(
350                 ['nodefault'],
351                 function(field) {
352                     if (angular.isDefined(attrs[field]))
353                         scope[field] = true;
354                     else
355                         scope[field] = false;
356                 }
357             );
358
359             if (!scope.selected && !scope.nodefault)
360                 scope.selected = scope.egOrg.get(scope.egAuth.user().ws_ou());
361         }
362
363     }
364 })
365
366 /* http://eric.sau.pe/angularjs-detect-enter-key-ngenter/ */
367 .directive('egEnter', function () {
368     return function (scope, element, attrs) {
369         element.bind("keydown keypress", function (event) {
370             if(event.which === 13) {
371                 scope.$apply(function (){
372                     scope.$eval(attrs.egEnter);
373                 });
374  
375                 event.preventDefault();
376             }
377         });
378     };
379 })
380
381 /*
382 http://stackoverflow.com/questions/18061757/angular-js-and-html5-date-input-value-how-to-get-firefox-to-show-a-readable-d
383
384 This directive allows us to use html5 input type="date" (for Chrome) and 
385 gracefully fall back to a regular ISO text input for Firefox.
386 It also allows us to abstract away some browser finickiness.
387 */
388 .directive(
389     'egDateInput',
390     function(dateFilter) {
391         return {
392             require: 'ngModel',
393             template: '<input type="date"></input>',
394             replace: true,
395             link: function(scope, elm, attrs, ngModelCtrl) {
396
397                 // since this is a date-only selector, set the time
398                 // portion to 00:00:00, which should better match the
399                 // user's expectations.  Note this allows us to retain
400                 // the timezone.
401                 function strip_time(date) {
402                     if (!date) date = new Date();
403                     date.setHours(0);
404                     date.setMinutes(0);
405                     date.setSeconds(0);
406                     date.setMilliseconds(0);
407                     return date;
408                 }
409
410                 ngModelCtrl.$formatters.unshift(function (modelValue) {
411                     // apply strip_time here in case the user never 
412                     // modifies the date value.
413                     return dateFilter(strip_time(modelValue), 'yyyy-MM-dd');
414                 });
415                 
416                 ngModelCtrl.$parsers.unshift(function(viewValue) {
417                     return strip_time(new Date(viewValue));
418                 });
419             },
420         };
421 })