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