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