]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/grid.js
lp1691237 webstaff: fix Format Dates and Format Times
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / services / grid.js
1 angular.module('egGridMod', 
2     ['egCoreMod', 'egUiMod', 'ui.bootstrap'])
3
4 .directive('egGrid', function() {
5     return {
6         restrict : 'AE',
7         transclude : true,
8         scope : {
9
10             // IDL class hint (e.g. "aou")
11             idlClass : '@',
12
13             // default page size
14             pageSize : '@',
15
16             // if true, grid columns are derived from all non-virtual
17             // fields on the base idlClass
18             autoFields : '@',
19
20             // grid preferences will be stored / retrieved with this key
21             persistKey : '@',
22
23             // field whose value is unique and may be used for item
24             // reference / lookup.  This will usually be someting like
25             // "id".  This is not needed when using autoFields, since we
26             // can determine the primary key directly from the IDL.
27             idField : '@',
28
29             // Reference to externally provided egGridDataProvider
30             itemsProvider : '=',
31
32             // Reference to externally provided item-selection handler
33             onSelect : '=',
34
35             // Reference to externally provided after-item-selection handler
36             afterSelect : '=',
37
38             // comma-separated list of supported or disabled grid features
39             // supported features:
40             //  startSelected : init the grid with all rows selected by default
41             //  allowAll : add an "All" option to row count (really 10000)
42             //  -menu : don't show any menu buttons (or use space for them)
43             //  -picker : don't show the column picker
44             //  -pagination : don't show any pagination elements, and set
45             //                the limit to 10000
46             //  -actions : don't show the actions dropdown
47             //  -index : don't show the row index column (can't use "index"
48             //           as the idField in this case)
49             //  -display : columns are hidden by default
50             //  -sort    : columns are unsortable by default 
51             //  -multisort : sort priorities config disabled by default
52             //  -multiselect : only one row at a time can be selected;
53             //                 choosing this also disables the checkbox
54             //                 column
55             features : '@',
56
57             // optional primary grid label
58             mainLabel : '@',
59
60             // if true, use the IDL class label as the mainLabel
61             autoLabel : '=', 
62
63             // optional context menu label
64             menuLabel : '@',
65
66             dateformat : '@', // optional: passed down to egGridValueFilter
67
68             // Hash of control functions.
69             //
70             //  These functions are defined by the calling scope and 
71             //  invoked as-is by the grid w/ the specified parameters.
72             //
73             //  collectStarted    : function() {}
74             //  itemRetrieved     : function(item) {}
75             //  allItemsRetrieved : function() {}
76             //
77             //  ---
78             //  If defined, the grid will watch the return value from
79             //  the function defined at watchQuery on each digest and 
80             //  re-draw the grid when query changes occur.
81             //
82             //  watchQuery : function() { /* return grid query */ }
83             //
84             //  ---------------
85             //  These functions are defined by the grid and thus
86             //  replace any values defined for these attributes from the
87             //  calling scope.
88             //
89             //  activateItem  : function(item) {}
90             //  allItems      : function(allItems) {}
91             //  selectedItems : function(selected) {}
92             //  selectItems   : function(ids) {}
93             //  setQuery      : function(queryStruct) {} // causes reload
94             //  setSort       : function(sortSturct) {} // causes reload
95             gridControls : '=',
96         },
97
98         // TODO: avoid hard-coded url
99         templateUrl : '/eg/staff/share/t_autogrid', 
100
101         link : function(scope, element, attrs) {     
102             // link() is called after page compilation, which means our
103             // eg-grid-field's have been parsed and loaded.  Now it's 
104             // safe to perform our initial page load.
105
106             // load auto fields after eg-grid-field's so they are not clobbered
107             scope.handleAutoFields();
108             scope.collect();
109
110             scope.grid_element = element;
111             $(element)
112                 .find('.eg-grid-content-body')
113                 .bind('contextmenu', scope.showActionContextMenu);
114         },
115
116         controller : [
117                     '$scope','$q','egCore','egGridFlatDataProvider','$location',
118                     'egGridColumnsProvider','$filter','$window','$sce','$timeout',
119             function($scope,  $q , egCore,  egGridFlatDataProvider , $location,
120                      egGridColumnsProvider , $filter , $window , $sce , $timeout) {
121
122             var grid = this;
123
124             grid.init = function() {
125                 grid.offset = 0;
126                 $scope.items = [];
127                 $scope.showGridConf = false;
128                 grid.totalCount = -1;
129                 $scope.selected = {};
130                 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
131                 $scope.menuItems = []; // global actions
132
133                 // returns true if any rows are selected.
134                 $scope.hasSelected = function() {
135                     return grid.getSelectedItems().length > 0 };
136
137                 var features = ($scope.features) ? 
138                     $scope.features.split(',') : [];
139                 delete $scope.features;
140
141                 $scope.showIndex = (features.indexOf('-index') == -1);
142
143                 $scope.allowAll = (features.indexOf('allowAll') > -1);
144                 $scope.startSelected = $scope.selectAll = (features.indexOf('startSelected') > -1);
145                 $scope.showActions = (features.indexOf('-actions') == -1);
146                 $scope.showPagination = (features.indexOf('-pagination') == -1);
147                 $scope.showPicker = (features.indexOf('-picker') == -1);
148
149                 $scope.showMenu = (features.indexOf('-menu') == -1);
150
151                 // remove some unneeded values from the scope to reduce bloat
152
153                 grid.idlClass = $scope.idlClass;
154                 delete $scope.idlClass;
155
156                 grid.persistKey = $scope.persistKey;
157                 delete $scope.persistKey;
158
159                 var stored_limit = 0;
160                 if ($scope.showPagination) {
161                     if (grid.persistKey) {
162                         var stored_limit = Number(
163                             egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
164                         );
165                     }
166                 } else {
167                     stored_limit = 10000; // maybe support "Inf"?
168                 }
169
170                 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
171
172                 grid.indexField = $scope.idField;
173                 delete $scope.idField;
174
175                 grid.dataProvider = $scope.itemsProvider;
176
177                 if (!grid.indexField && grid.idlClass)
178                     grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
179
180                 grid.columnsProvider = egGridColumnsProvider.instance({
181                     idlClass : grid.idlClass,
182                     defaultToHidden : (features.indexOf('-display') > -1),
183                     defaultToNoSort : (features.indexOf('-sort') > -1),
184                     defaultToNoMultiSort : (features.indexOf('-multisort') > -1),
185                     defaultDateFormat : $scope.dateformat
186                 });
187                 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
188
189                 $scope.handleAutoFields = function() {
190                     if ($scope.autoFields) {
191                         if (grid.autoLabel) {
192                             $scope.mainLabel = 
193                                 egCore.idl.classes[grid.idlClass].label;
194                         }
195                         grid.columnsProvider.compileAutoColumns();
196                         delete $scope.autoFields;
197                     }
198                 }
199    
200                 if (!grid.dataProvider) {
201                     // no provider, um, provided.
202                     // Use a flat data provider
203
204                     grid.selfManagedData = true;
205                     grid.dataProvider = egGridFlatDataProvider.instance({
206                         indexField : grid.indexField,
207                         idlClass : grid.idlClass,
208                         columnsProvider : grid.columnsProvider,
209                         query : $scope.query
210                     });
211                 }
212
213                 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
214                 $scope.indexValue = function(item) {
215                     return grid.indexValue(item)
216                 };
217
218                 grid.applyControlFunctions();
219
220                 grid.loadConfig().then(function() { 
221                     // link columns to scope after loadConfig(), since it
222                     // replaces the columns array.
223                     $scope.columns = grid.columnsProvider.columns;
224                 });
225
226                 // NOTE: grid.collect() is first called from link(), not here.
227             }
228
229             // link our control functions into the gridControls 
230             // scope object so the caller can access them.
231             grid.applyControlFunctions = function() {
232
233                 // we use some of these controls internally, so sett
234                 // them up even if the caller doesn't request them.
235                 var controls = $scope.gridControls || {};
236
237                 controls.columnMap = function() {
238                     var m = {};
239                     angular.forEach(grid.columnsProvider.columns, function (c) {
240                         m[c.name] = c;
241                     });
242                     return m;
243                 }
244
245                 controls.columnsProvider = function() {
246                     return grid.columnsProvider;
247                 }
248
249                 // link in the control functions
250                 controls.selectedItems = function() {
251                     return grid.getSelectedItems()
252                 }
253
254                 controls.allItems = function() {
255                     return $scope.items;
256                 }
257
258                 controls.selectItems = function(ids) {
259                     if (!ids) return;
260                     $scope.selected = {};
261                     angular.forEach(ids, function(i) {
262                         $scope.selected[''+i] = true;
263                     });
264                 }
265
266                 // if the caller provided a functional setQuery,
267                 // extract the value before replacing it
268                 if (controls.setQuery) {
269                     grid.dataProvider.query = 
270                         controls.setQuery();
271                 }
272
273                 controls.setQuery = function(query) {
274                     grid.dataProvider.query = query;
275                     controls.refresh();
276                 }
277
278                 if (controls.watchQuery) {
279                     // capture the initial query value
280                     grid.dataProvider.query = controls.watchQuery();
281
282                     // watch for changes
283                     $scope.gridWatchQuery = controls.watchQuery;
284                     $scope.$watch('gridWatchQuery()', function(newv) {
285                         controls.setQuery(newv);
286                     }, true);
287                 }
288
289                 // if the caller provided a functional setSort
290                 // extract the value before replacing it
291                 grid.dataProvider.sort = 
292                     controls.setSort ?  controls.setSort() : [];
293
294                 controls.setSort = function(sort) {
295                     controls.refresh();
296                 }
297
298                 controls.refresh = function(noReset) {
299                     if (!noReset) grid.offset = 0;
300                     grid.collect();
301                 }
302
303                 controls.setLimit = function(limit,forget) {
304                     if (!forget && grid.persistKey)
305                         egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
306                     grid.limit = limit;
307                 }
308                 controls.getLimit = function() {
309                     return grid.limit;
310                 }
311                 controls.setOffset = function(offset) {
312                     grid.offset = offset;
313                 }
314                 controls.getOffset = function() {
315                     return grid.offset;
316                 }
317
318                 controls.saveConfig = function () {
319                     return $scope.saveConfig();
320                 }
321
322                 grid.dataProvider.refresh = controls.refresh;
323                 grid.controls = controls;
324             }
325
326             // If a menu item provides its own HTML template, translate it,
327             // using the menu item for the template scope.
328             // note: $sce is required to avoid security restrictions and
329             // is OK here, since the template comes directly from a
330             // local HTML template (not user input).
331             $scope.translateMenuItemTemplate = function(item) {
332                 var html = egCore.strings.$replace(item.template, {item : item});
333                 return $sce.trustAsHtml(html);
334             }
335
336             // add a new (global) grid menu item
337             grid.addMenuItem = function(item) {
338                 $scope.menuItems.push(item);
339                 var handler = item.handler;
340                 item.handler = function() {
341                     $scope.gridMenuIsOpen = false; // close menu
342                     if (handler) {
343                         handler(item, 
344                             item.handlerData, grid.getSelectedItems());
345                     }
346                 }
347             }
348
349             // add a selected-items action
350             grid.addAction = function(act) {
351                 var done = false;
352                 $scope.actionGroups.forEach(function(g){
353                     if (g.label === act.group) {
354                         g.actions.push(act);
355                         done = true;
356                     }
357                 });
358                 if (!done) {
359                     $scope.actionGroups.push({
360                         label : act.group,
361                         actions : [ act ]
362                     });
363                 }
364             }
365
366             // remove the stored column configuration preferenc, then recover 
367             // the column visibility information from the initial page load.
368             $scope.resetColumns = function() {
369                 $scope.gridColumnPickerIsOpen = false;
370                 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
371                 .then(function() {
372                     grid.columnsProvider.reset(); 
373                     if (grid.selfManagedData) grid.collect();
374                 });
375             }
376
377             $scope.showAllColumns = function() {
378                 $scope.gridColumnPickerIsOpen = false;
379                 grid.columnsProvider.showAllColumns();
380                 if (grid.selfManagedData) grid.collect();
381             }
382
383             $scope.hideAllColumns = function() {
384                 $scope.gridColumnPickerIsOpen = false;
385                 grid.columnsProvider.hideAllColumns();
386                 // note: no need to fetch new data if no columns are visible
387             }
388
389             $scope.toggleColumnVisibility = function(col) {
390                 $scope.gridColumnPickerIsOpen = false;
391                 col.visible = !col.visible;
392
393                 // egGridFlatDataProvider only retrieves data to be
394                 // displayed.  When column visibility changes, it's
395                 // necessary to fetch the newly visible column data.
396                 if (grid.selfManagedData) grid.collect();
397             }
398
399             // save the columns configuration (position, sort, width) to
400             // eg.grid.<persist-key>
401             $scope.saveConfig = function() {
402                 $scope.gridColumnPickerIsOpen = false;
403
404                 if (!grid.persistKey) {
405                     console.warn(
406                         "Cannot save settings without a grid persist-key");
407                     return;
408                 }
409
410                 // only store information about visible columns.
411                 var conf = grid.columnsProvider.columns.filter(
412                     function(col) {return Boolean(col.visible) });
413
414                 // now scrunch the data down to just the needed info
415                 conf = conf.map(function(col) {
416                     var c = {name : col.name}
417                     // Apart from the name, only store non-default values.
418                     // No need to store col.visible, since that's implicit
419                     if (col.align != 'left') c.align = col.align;
420                     if (col.flex != 2) c.flex = col.flex;
421                     if (Number(col.sort)) c.sort = Number(c.sort);
422                     return c;
423                 });
424
425                 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
426                 .then(function() { 
427                     // Save operation performed from the grid configuration UI.
428                     // Hide the configuration UI and re-draw w/ sort applied
429                     if ($scope.showGridConf) 
430                         $scope.toggleConfDisplay();
431                 });
432             }
433
434
435             // load the columns configuration (position, sort, width) from
436             // eg.grid.<persist-key> and apply the loaded settings to the
437             // columns on our columnsProvider
438             grid.loadConfig = function() {
439                 if (!grid.persistKey) return $q.when();
440
441                 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
442                 .then(function(conf) {
443                     if (!conf) return;
444
445                     var columns = grid.columnsProvider.columns;
446                     var new_cols = [];
447
448                     angular.forEach(conf, function(col) {
449                         var grid_col = columns.filter(
450                             function(c) {return c.name == col.name})[0];
451
452                         if (!grid_col) {
453                             // saved column does not match a column in the 
454                             // current grid.  skip it.
455                             return;
456                         }
457
458                         grid_col.align = col.align || 'left';
459                         grid_col.flex = col.flex || 2;
460                         grid_col.sort = col.sort || 0;
461                         // all saved columns are assumed to be true
462                         grid_col.visible = true;
463                         if (new_cols
464                                 .filter(function (c) {
465                                     return c.name == grid_col.name;
466                                 }).length == 0
467                         )
468                             new_cols.push(grid_col);
469                     });
470
471                     // columns which are not expressed within the saved 
472                     // configuration are marked as non-visible and 
473                     // appended to the end of the new list of columns.
474                     angular.forEach(columns, function(col) {
475                         var found = conf.filter(
476                             function(c) {return (c.name == col.name)})[0];
477                         if (!found) {
478                             col.visible = false;
479                             new_cols.push(col);
480                         }
481                     });
482
483                     grid.columnsProvider.columns = new_cols;
484                     grid.compileSort();
485
486                 });
487             }
488
489             $scope.onContextMenu = function($event) {
490                 var col = angular.element($event.target).attr('column');
491                 console.log('selected column ' + col);
492             }
493
494             $scope.page = function() {
495                 return (grid.offset / grid.limit) + 1;
496             }
497
498             $scope.goToPage = function(page) {
499                 page = Number(page);
500                 if (angular.isNumber(page) && page > 0) {
501                     grid.offset = (page - 1) * grid.limit;
502                     grid.collect();
503                 }
504             }
505
506             $scope.offset = function(o) {
507                 if (angular.isNumber(o))
508                     grid.offset = o;
509                 return grid.offset 
510             }
511
512             $scope.limit = function(l) { 
513                 if (angular.isNumber(l)) {
514                     if (grid.persistKey)
515                         egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
516                     grid.limit = l;
517                 }
518                 return grid.limit 
519             }
520
521             $scope.onFirstPage = function() {
522                 return grid.offset == 0;
523             }
524
525             $scope.hasNextPage = function() {
526                 // we have less data than requested, there must
527                 // not be any more pages
528                 if (grid.count() < grid.limit) return false;
529
530                 // if the total count is not known, assume that a full
531                 // page of data implies more pages are available.
532                 if (grid.totalCount == -1) return true;
533
534                 // we have a full page of data, but is there more?
535                 return grid.totalCount > (grid.offset + grid.count());
536             }
537
538             $scope.incrementPage = function() {
539                 grid.offset += grid.limit;
540                 grid.collect();
541             }
542
543             $scope.decrementPage = function() {
544                 if (grid.offset < grid.limit) {
545                     grid.offset = 0;
546                 } else {
547                     grid.offset -= grid.limit;
548                 }
549                 grid.collect();
550             }
551
552             // number of items loaded for the current page of results
553             grid.count = function() {
554                 return $scope.items.length;
555             }
556
557             // returns the unique identifier value for the provided item
558             // for internal consistency, indexValue is always coerced 
559             // into a string.
560             grid.indexValue = function(item) {
561                 if (angular.isObject(item)) {
562                     if (item !== null) {
563                         if (angular.isFunction(item[grid.indexField]))
564                             return ''+item[grid.indexField]();
565                         return ''+item[grid.indexField]; // flat data
566                     }
567                 }
568                 // passed a non-object; assume it's an index
569                 return ''+item; 
570             }
571
572             // fires the hide handler function for a context action
573             $scope.actionHide = function(action) {
574                 if (typeof action.hide == 'undefined') {
575                     return false;
576                 }
577                 if (angular.isFunction(action.hide))
578                     return action.hide(action);
579                 return action.hide;
580             }
581
582             // fires the disable handler function for a context action
583             $scope.actionDisable = function(action) {
584                 if (typeof action.disabled == 'undefined') {
585                     return false;
586                 }
587                 if (angular.isFunction(action.disabled))
588                     return action.disabled(action);
589                 return action.disabled;
590             }
591
592             // fires the action handler function for a context action
593             $scope.actionLauncher = function(action) {
594                 if (!action.handler) {
595                     console.error(
596                         'No handler specified for "' + action.label + '"');
597                 } else {
598
599                     try {
600                         action.handler(grid.getSelectedItems());
601                     } catch(E) {
602                         console.error('Error executing handler for "' 
603                             + action.label + '" => ' + E + "\n" + E.stack);
604                     }
605
606                     if ($scope.action_context_showing) $scope.hideActionContextMenu();
607                 }
608
609             }
610
611             $scope.hideActionContextMenu = function () {
612                 $($scope.menu_dom).css({
613                     display: '',
614                     width: $scope.action_context_width,
615                     top: $scope.action_context_y,
616                     left: $scope.action_context_x
617                 });
618                 $($scope.action_context_parent).append($scope.menu_dom);
619                 $scope.action_context_oldy = $scope.action_context_oldx = 0;
620                 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
621                 $scope.action_context_showing = false;
622             }
623
624             $scope.action_context_showing = false;
625             $scope.showActionContextMenu = function ($event) {
626
627                 // Have to gather these here, instead of inside link()
628                 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
629                 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
630
631                 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
632                     $event.target.click();
633
634                 if (!$scope.action_context_showing) {
635                     $scope.action_context_width = $($scope.menu_dom).css('width');
636                     $scope.action_context_y = $($scope.menu_dom).css('top');
637                     $scope.action_context_x = $($scope.menu_dom).css('left');
638                     $scope.action_context_showing = true;
639                     $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
640
641                     $('body').append($($scope.menu_dom));
642                     $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
643                 }
644
645                 $($scope.menu_dom).css({
646                     display: 'block',
647                     width: $scope.action_context_width,
648                     top: $event.pageY,
649                     left: $event.pageX
650                 });
651
652                 return false;
653             }
654
655             // returns the list of selected item objects
656             grid.getSelectedItems = function() {
657                 return $scope.items.filter(
658                     function(item) {
659                         return Boolean($scope.selected[grid.indexValue(item)]);
660                     }
661                 );
662             }
663
664             grid.getItemByIndex = function(index) {
665                 for (var i = 0; i < $scope.items.length; i++) {
666                     var item = $scope.items[i];
667                     if (grid.indexValue(item) == index) 
668                         return item;
669                 }
670             }
671
672             // selects one row after deselecting all of the others
673             grid.selectOneItem = function(index) {
674                 $scope.selected = {};
675                 $scope.selected[index] = true;
676             }
677
678             // selects or deselects an item, without affecting the others.
679             // returns true if the item is selected; false if de-selected.
680             // we overwrite the object so that we can watch $scope.selected
681             grid.toggleSelectOneItem = function(index) {
682                 if ($scope.selected[index]) {
683                     delete $scope.selected[index];
684                     $scope.selected = angular.copy($scope.selected);
685                     return false;
686                 } else {
687                     $scope.selected[index] = true;
688                     $scope.selected = angular.copy($scope.selected);
689                     return true;
690                 }
691             }
692
693             $scope.updateSelected = function () { 
694                     return $scope.selected = angular.copy($scope.selected);
695             };
696
697             grid.selectAllItems = function() {
698                 angular.forEach($scope.items, function(item) {
699                     $scope.selected[grid.indexValue(item)] = true
700                 }); 
701                 $scope.selected = angular.copy($scope.selected);
702             }
703
704             $scope.$watch('selectAll', function(newVal) {
705                 if (newVal) {
706                     grid.selectAllItems();
707                 } else {
708                     $scope.selected = {};
709                 }
710             });
711
712             if ($scope.onSelect) {
713                 $scope.$watch('selected', function(newVal) {
714                     $scope.onSelect(grid.getSelectedItems());
715                     if ($scope.afterSelect) $scope.afterSelect();
716                 });
717             }
718
719             // returns true if item1 appears in the list before item2;
720             // false otherwise.  this is slightly more efficient that
721             // finding the position of each then comparing them.
722             // item1 / item2 may be an item or an item index
723             grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
724                 var idx1 = grid.indexValue(itemOrIndex1);
725                 var idx2 = grid.indexValue(itemOrIndex2);
726
727                 // use for() for early exit
728                 for (var i = 0; i < $scope.items.length; i++) {
729                     var idx = grid.indexValue($scope.items[i]);
730                     if (idx == idx1) return true;
731                     if (idx == idx2) return false;
732                 }
733                 return false;
734             }
735
736             // 0-based position of item in the current data set
737             grid.indexOf = function(item) {
738                 var idx = grid.indexValue(item);
739                 for (var i = 0; i < $scope.items.length; i++) {
740                     if (grid.indexValue($scope.items[i]) == idx)
741                         return i;
742                 }
743                 return -1;
744             }
745
746             grid.modifyColumnFlex = function(column, val) {
747                 column.flex += val;
748                 // prevent flex:0;  use hiding instead
749                 if (column.flex < 1)
750                     column.flex = 1;
751             }
752             $scope.modifyColumnFlex = function(col, val) {
753                 $scope.lastModColumn = col.name;
754                 grid.modifyColumnFlex(col, val);
755             }
756
757             grid.modifyColumnPos = function(col, diff) {
758                 var srcIdx, targetIdx;
759                 angular.forEach(grid.columnsProvider.columns,
760                     function(c, i) { if (c.name == col.name) srcIdx = i });
761
762                 targetIdx = srcIdx + diff;
763                 if (targetIdx < 0) {
764                     targetIdx = 0;
765                 } else if (targetIdx >= grid.columnsProvider.columns.length) {
766                     // Target index follows the last visible column.
767                     var lastVisible = 0;
768                     angular.forEach(grid.columnsProvider.columns, 
769                         function(column, idx) {
770                             if (column.visible) lastVisible = idx;
771                         }
772                     );
773                     targetIdx = lastVisible + 1;
774                 }
775
776                 // Splice column out of old position, insert at new position.
777                 grid.columnsProvider.columns.splice(srcIdx, 1);
778                 grid.columnsProvider.columns.splice(targetIdx, 0, col);
779             }
780
781             $scope.modifyColumnPos = function(col, diff) {
782                 $scope.lastModColumn = col.name;
783                 return grid.modifyColumnPos(col, diff);
784             }
785
786
787             // handles click, control-click, and shift-click
788             $scope.handleRowClick = function($event, item) {
789                 var index = grid.indexValue(item);
790
791                 var origSelected = Object.keys($scope.selected);
792
793                 if (!$scope.canMultiSelect) {
794                     grid.selectOneItem(index);
795                     grid.lastSelectedItemIndex = index;
796                     return;
797                 }
798
799                 if ($event.ctrlKey || $event.metaKey /* mac command */) {
800                     // control-click
801                     if (grid.toggleSelectOneItem(index)) 
802                         grid.lastSelectedItemIndex = index;
803
804                 } else if ($event.shiftKey) { 
805                     // shift-click
806
807                     if (!grid.lastSelectedItemIndex || 
808                             index == grid.lastSelectedItemIndex) {
809                         grid.selectOneItem(index);
810                         grid.lastSelectedItemIndex = index;
811
812                     } else {
813
814                         var selecting = false;
815                         var ascending = grid.itemComesBefore(
816                             grid.lastSelectedItemIndex, item);
817                         var startPos = 
818                             grid.indexOf(grid.lastSelectedItemIndex);
819
820                         // update to new last-selected
821                         grid.lastSelectedItemIndex = index;
822
823                         // select each row between the last selected and 
824                         // currently selected items
825                         while (true) {
826                             startPos += ascending ? 1 : -1;
827                             var curItem = $scope.items[startPos];
828                             if (!curItem) break;
829                             var curIdx = grid.indexValue(curItem);
830                             $scope.selected[curIdx] = true;
831                             if (curIdx == index) break; // all done
832                         }
833                         $scope.selected = angular.copy($scope.selected);
834                     }
835                         
836                 } else {
837                     grid.selectOneItem(index);
838                     grid.lastSelectedItemIndex = index;
839                 }
840             }
841
842             // Builds a sort expression from column sort priorities.
843             // called on page load and any time the priorities are modified.
844             grid.compileSort = function() {
845                 var sortList = grid.columnsProvider.columns.filter(
846                     function(col) { return Number(col.sort) != 0 }
847                 ).sort( 
848                     function(a, b) { 
849                         if (Math.abs(a.sort) < Math.abs(b.sort))
850                             return -1;
851                         return 1;
852                     }
853                 );
854
855                 if (sortList.length) {
856                     grid.dataProvider.sort = sortList.map(function(col) {
857                         var blob = {};
858                         blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
859                         return blob;
860                     });
861                 }
862             }
863
864             // builds a sort expression using a single column, 
865             // toggling between ascending and descending sort.
866             $scope.quickSort = function(col_name) {
867                 var sort = grid.dataProvider.sort;
868                 if (sort && sort.length &&
869                     sort[0] == col_name) {
870                     var blob = {};
871                     blob[col_name] = 'desc';
872                     grid.dataProvider.sort = [blob];
873                 } else {
874                     grid.dataProvider.sort = [col_name];
875                 }
876
877                 grid.offset = 0;
878                 grid.collect();
879             }
880
881             // show / hide the grid configuration row
882             $scope.toggleConfDisplay = function() {
883                 if ($scope.showGridConf) {
884                     $scope.showGridConf = false;
885                     if (grid.columnsProvider.hasSortableColumn()) {
886                         // only refresh the grid if the user has the
887                         // ability to modify the sort priorities.
888                         grid.compileSort();
889                         grid.offset = 0;
890                         grid.collect();
891                     }
892                 } else {
893                     $scope.showGridConf = true;
894                 }
895
896                 delete $scope.lastModColumn;
897                 $scope.gridColumnPickerIsOpen = false;
898             }
899
900             // called when a dragged column is dropped onto itself
901             // or any other column
902             grid.onColumnDrop = function(target) {
903                 if (angular.isUndefined(target)) return;
904                 if (target == grid.dragColumn) return;
905                 var srcIdx, targetIdx, srcCol;
906                 angular.forEach(grid.columnsProvider.columns,
907                     function(col, idx) {
908                         if (col.name == grid.dragColumn) {
909                             srcIdx = idx;
910                             srcCol = col;
911                         } else if (col.name == target) {
912                             targetIdx = idx;
913                         }
914                     }
915                 );
916
917                 if (srcIdx < targetIdx) targetIdx--;
918
919                 // move src column from old location to new location in 
920                 // the columns array, then force a page refresh
921                 grid.columnsProvider.columns.splice(srcIdx, 1);
922                 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
923                 $scope.$apply(); 
924             }
925
926             // prepares a string for inclusion within a CSV document
927             // by escaping commas and quotes and removing newlines.
928             grid.csvDatum = function(str) {
929                 str = ''+str;
930                 if (!str) return '';
931                 str = str.replace(/\n/g, '');
932                 if (str.match(/\,/) || str.match(/"/)) {                                     
933                     str = str.replace(/"/g, '""');
934                     str = '"' + str + '"';                                           
935                 } 
936                 return str;
937             }
938
939             // sets the download file name and inserts the current CSV
940             // into a Blob URL for browser download.
941             $scope.generateCSVExportURL = function() {
942                 $scope.gridColumnPickerIsOpen = false;
943
944                 // let the file name describe the grid
945                 $scope.csvExportFileName = 
946                     ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
947                     .replace(/\s+/g, '_') + '_' + $scope.page();
948
949                 // toss the CSV into a Blob and update the export URL
950                 var csv = grid.generateCSV();
951                 var blob = new Blob([csv], {type : 'text/plain'});
952                 $scope.csvExportURL = 
953                     ($window.URL || $window.webkitURL).createObjectURL(blob);
954             }
955
956             $scope.printCSV = function() {
957                 $scope.gridColumnPickerIsOpen = false;
958                 egCore.print.print({
959                     context : 'default', 
960                     content : grid.generateCSV(),
961                     content_type : 'text/plain'
962                 });
963             }
964
965             // generates CSV for the currently visible grid contents
966             grid.generateCSV = function() {
967                 var csvStr = '';
968                 var colCount = grid.columnsProvider.columns.length;
969
970                 // columns
971                 angular.forEach(grid.columnsProvider.columns,
972                     function(col) {
973                         if (!col.visible) return;
974                         csvStr += grid.csvDatum(col.label);
975                         csvStr += ',';
976                     }
977                 );
978
979                 csvStr = csvStr.replace(/,$/,'\n');
980
981                 // items
982                 angular.forEach($scope.items, function(item) {
983                     angular.forEach(grid.columnsProvider.columns, 
984                         function(col) {
985                             if (!col.visible) return;
986                             // bare value
987                             var val = grid.dataProvider.itemFieldValue(item, col);
988                             // filtered value (dates, etc.)
989                             val = $filter('egGridValueFilter')(val, col);
990                             csvStr += grid.csvDatum(val);
991                             csvStr += ',';
992                         }
993                     );
994                     csvStr = csvStr.replace(/,$/,'\n');
995                 });
996
997                 return csvStr;
998             }
999
1000             // Interpolate the value for column.linkpath within the context
1001             // of the row item to generate the final link URL.
1002             $scope.generateLinkPath = function(col, item) {
1003                 return egCore.strings.$replace(col.linkpath, {item : item});
1004             }
1005
1006             // If a column provides its own HTML template, translate it,
1007             // using the current item for the template scope.
1008             // note: $sce is required to avoid security restrictions and
1009             // is OK here, since the template comes directly from a
1010             // local HTML template (not user input).
1011             $scope.translateCellTemplate = function(col, item) {
1012                 var html = egCore.strings.$replace(col.template, {item : item});
1013                 return $sce.trustAsHtml(html);
1014             }
1015
1016             $scope.collect = function() { grid.collect() }
1017
1018             // asks the dataProvider for a page of data
1019             grid.collect = function() {
1020
1021                 // avoid firing the collect if there is nothing to collect.
1022                 if (grid.selfManagedData && !grid.dataProvider.query) return;
1023
1024                 if (grid.collecting) return; // avoid parallel collect()
1025                 grid.collecting = true;
1026
1027                 console.debug('egGrid.collect() offset=' 
1028                     + grid.offset + '; limit=' + grid.limit);
1029
1030                 // ensure all of our dropdowns are closed
1031                 // TODO: git rid of these and just use dropdown-toggle, 
1032                 // which is more reliable.
1033                 $scope.gridColumnPickerIsOpen = false;
1034                 $scope.gridRowCountIsOpen = false;
1035                 $scope.gridPageSelectIsOpen = false;
1036
1037                 $scope.items = [];
1038                 $scope.selected = {};
1039
1040                 // Inform the caller we've asked the data provider
1041                 // for data.  This is useful for knowing when collection
1042                 // has started (e.g. to display a progress dialg) when 
1043                 // using the stock (flattener) data provider, where the 
1044                 // user is not directly defining a get() handler.
1045                 if (grid.controls.collectStarted)
1046                     grid.controls.collectStarted(grid.offset, grid.limit);
1047
1048                 grid.dataProvider.get(grid.offset, grid.limit).then(
1049                 function() {
1050                     if (grid.controls.allItemsRetrieved)
1051                         grid.controls.allItemsRetrieved();
1052                 },
1053                 null, 
1054                 function(item) {
1055                     if (item) {
1056                         $scope.items.push(item)
1057                         if (grid.controls.itemRetrieved)
1058                             grid.controls.itemRetrieved(item);
1059                         if ($scope.selectAll)
1060                             $scope.selected[grid.indexValue(item)] = true
1061                     }
1062                 }).finally(function() { 
1063                     console.debug('egGrid.collect() complete');
1064                     grid.collecting = false 
1065                     $scope.selected = angular.copy($scope.selected);
1066                 });
1067             }
1068
1069             grid.init();
1070         }]
1071     };
1072 })
1073
1074 /**
1075  * eg-grid-field : used for collecting custom field data from the templates.
1076  * This directive does not direct display, it just passes data up to the 
1077  * parent grid.
1078  */
1079 .directive('egGridField', function() {
1080     return {
1081         require : '^egGrid',
1082         restrict : 'AE',
1083         scope : {
1084             flesher: '=', // optional; function that can flesh a linked field, given the value
1085             name  : '@', // required; unique name
1086             path  : '@', // optional; flesh path
1087             ignore: '@', // optional; fields to ignore when path is a wildcard
1088             label : '@', // optional; display label
1089             flex  : '@',  // optional; default flex width
1090             align  : '@',  // optional; default alignment, left/center/right
1091             dateformat : '@', // optional: passed down to egGridValueFilter
1092
1093             // if a field is part of an IDL object, but we are unable to
1094             // determine the class, because it's nested within a hash
1095             // (i.e. we can't navigate directly to the object via the IDL),
1096             // idlClass lets us specify the class.  This is particularly
1097             // useful for nested wildcard fields.
1098             parentIdlClass : '@', 
1099
1100             // optional: for non-IDL columns, specifying a datatype
1101             // lets the caller control which display filter is used.
1102             // datatype should match the standard IDL datatypes.
1103             datatype : '@'
1104         },
1105         link : function(scope, element, attrs, egGridCtrl) {
1106
1107             // boolean fields are presented as value-less attributes
1108             angular.forEach(
1109                 [
1110                     'visible', 
1111                     'hidden', 
1112                     'sortable', 
1113                     'nonsortable',
1114                     'multisortable',
1115                     'nonmultisortable',
1116                     'required' // if set, always fetch data for this column
1117                 ],
1118                 function(field) {
1119                     if (angular.isDefined(attrs[field]))
1120                         scope[field] = true;
1121                 }
1122             );
1123
1124             // any HTML content within the field is its custom template
1125             var tmpl = element.html();
1126             if (tmpl && !tmpl.match(/^\s*$/))
1127                 scope.template = tmpl
1128
1129             egGridCtrl.columnsProvider.add(scope);
1130             scope.$destroy();
1131         }
1132     };
1133 })
1134
1135 /**
1136  * eg-grid-action : used for specifying actions which may be applied
1137  * to items within the grid.
1138  */
1139 .directive('egGridAction', function() {
1140     return {
1141         require : '^egGrid',
1142         restrict : 'AE',
1143         transclude : true,
1144         scope : {
1145             group   : '@', // Action group, ungrouped if not set
1146             label   : '@', // Action label
1147             handler : '=',  // Action function handler
1148             hide    : '=',
1149             disabled : '=', // function
1150             divider : '='
1151         },
1152         link : function(scope, element, attrs, egGridCtrl) {
1153             egGridCtrl.addAction({
1154                 hide  : scope.hide,
1155                 group : scope.group,
1156                 label : scope.label,
1157                 divider : scope.divider,
1158                 handler : scope.handler,
1159                 disabled : scope.disabled,
1160             });
1161             scope.$destroy();
1162         }
1163     };
1164 })
1165
1166 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1167
1168     function ColumnsProvider(args) {
1169         var cols = this;
1170         cols.columns = [];
1171         cols.stockVisible = [];
1172         cols.idlClass = args.idlClass;
1173         cols.defaultToHidden = args.defaultToHidden;
1174         cols.defaultToNoSort = args.defaultToNoSort;
1175         cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1176         cols.defaultDateFormat = args.defaultDateFormat;
1177
1178         // resets column width, visibility, and sort behavior
1179         // Visibility resets to the visibility settings defined in the 
1180         // template (i.e. the original egGridField values).
1181         cols.reset = function() {
1182             angular.forEach(cols.columns, function(col) {
1183                 col.align = 'left';
1184                 col.flex = 2;
1185                 col.sort = 0;
1186                 if (cols.stockVisible.indexOf(col.name) > -1) {
1187                     col.visible = true;
1188                 } else {
1189                     col.visible = false;
1190                 }
1191             });
1192         }
1193
1194         // returns true if any columns are sortable
1195         cols.hasSortableColumn = function() {
1196             return cols.columns.filter(
1197                 function(col) {
1198                     return col.sortable || col.multisortable;
1199                 }
1200             ).length > 0;
1201         }
1202
1203         cols.showAllColumns = function() {
1204             angular.forEach(cols.columns, function(column) {
1205                 column.visible = true;
1206             });
1207         }
1208
1209         cols.hideAllColumns = function() {
1210             angular.forEach(cols.columns, function(col) {
1211                 delete col.visible;
1212             });
1213         }
1214
1215         cols.indexOf = function(name) {
1216             for (var i = 0; i < cols.columns.length; i++) {
1217                 if (cols.columns[i].name == name) 
1218                     return i;
1219             }
1220             return -1;
1221         }
1222
1223         cols.findColumn = function(name) {
1224             return cols.columns[cols.indexOf(name)];
1225         }
1226
1227         cols.compileAutoColumns = function() {
1228             var idl_class = egCore.idl.classes[cols.idlClass];
1229
1230             angular.forEach(
1231                 idl_class.fields,
1232                 function(field) {
1233                     if (field.virtual) return;
1234                     if (field.datatype == 'link' || field.datatype == 'org_unit') {
1235                         // if the field is a link and the linked class has a
1236                         // "selector" field specified, use the selector field
1237                         // as the display field for the columns.
1238                         // flattener will take care of the fleshing.
1239                         if (field['class']) {
1240                             var selector_field = egCore.idl.classes[field['class']].fields
1241                                 .filter(function(f) { return Boolean(f.selector) })[0];
1242                             if (selector_field) {
1243                                 field.path = field.name + '.' + selector_field.selector;
1244                             }
1245                         }
1246                     }
1247                     cols.add(field, true);
1248                 }
1249             );
1250         }
1251
1252         // if a column definition has a path with a wildcard, create
1253         // columns for all non-virtual fields at the specified 
1254         // position in the path.
1255         cols.expandPath = function(colSpec) {
1256
1257             var ignoreList = [];
1258             if (colSpec.ignore)
1259                 ignoreList = colSpec.ignore.split(' ');
1260
1261             var dotpath = colSpec.path.replace(/\.?\*$/,'');
1262             var class_obj;
1263             var idl_field;
1264
1265             if (colSpec.parentIdlClass) {
1266                 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1267             } else {
1268                 class_obj = egCore.idl.classes[cols.idlClass];
1269             }
1270             var idl_parent = class_obj;
1271             var old_field_label = '';
1272
1273             if (!class_obj) return;
1274
1275             console.debug('egGrid: auto dotpath is: ' + dotpath);
1276             var path_parts = dotpath.split(/\./);
1277
1278             // find the IDL class definition for the last element in the
1279             // path before the .*
1280             // an empty path_parts means expand the root class
1281             if (path_parts) {
1282                 var old_field;
1283                 for (var path_idx in path_parts) {
1284                     old_field = idl_field;
1285
1286                     var part = path_parts[path_idx];
1287                     idl_field = class_obj.field_map[part];
1288
1289                     // unless we're at the end of the list, this field should
1290                     // link to another class.
1291                     if (idl_field && idl_field['class'] && (
1292                         idl_field.datatype == 'link' || 
1293                         idl_field.datatype == 'org_unit')) {
1294                         if (old_field_label) old_field_label += ' : ';
1295                         old_field_label += idl_field.label;
1296                         class_obj = egCore.idl.classes[idl_field['class']];
1297                         if (old_field) idl_parent = old_field;
1298                     } else {
1299                         if (path_idx < (path_parts.length - 1)) {
1300                             // we ran out of classes to hop through before
1301                             // we ran out of path components
1302                             console.error("egGrid: invalid IDL path: " + dotpath);
1303                         }
1304                     }
1305                 }
1306             }
1307
1308             if (class_obj) {
1309                 angular.forEach(class_obj.fields, function(field) {
1310
1311                     // Only show wildcard fields where we have data to show
1312                     // Virtual and un-fleshed links will not have any data.
1313                     if (field.virtual ||
1314                         (field.datatype == 'link' || field.datatype == 'org_unit') ||
1315                         ignoreList.indexOf(field.name) > -1
1316                     )
1317                         return;
1318
1319                     var col = cols.cloneFromScope(colSpec);
1320                     col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1321
1322                     // log line below is very chatty.  disable until needed.
1323                     // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1324                     cols.add(col, false, true, 
1325                         {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1326                 });
1327
1328                 cols.columns = cols.columns.sort(
1329                     function(a, b) {
1330                         if (a.explicit) return -1;
1331                         if (b.explicit) return 1;
1332
1333                         if (a.idlclass && b.idlclass) {
1334                             if (a.idlclass < b.idlclass) return -1;
1335                             if (b.idlclass < a.idlclass) return 1;
1336                         }
1337
1338                         if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1339                             if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1340                             if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1341                         }
1342
1343                         if (a.label && b.label) {
1344                             if (a.label < b.label) return -1;
1345                             if (b.label < a.label) return 1;
1346                         }
1347
1348                         return a.name < b.name ? -1 : 1;
1349                     }
1350                 );
1351
1352
1353             } else {
1354                 console.error(
1355                     "egGrid: wildcard path does not resolve to an object: "
1356                     + dotpath);
1357             }
1358         }
1359
1360         // angular.clone(scopeObject) is not permittable.  Manually copy
1361         // the fields over that we need (so the scope object can go away).
1362         cols.cloneFromScope = function(colSpec) {
1363             return {
1364                 flesher  : colSpec.flesher,
1365                 name  : colSpec.name,
1366                 label : colSpec.label,
1367                 path  : colSpec.path,
1368                 align  : colSpec.align || 'left',
1369                 flex  : Number(colSpec.flex) || 2,
1370                 sort  : Number(colSpec.sort) || 0,
1371                 required : colSpec.required,
1372                 linkpath : colSpec.linkpath,
1373                 template : colSpec.template,
1374                 visible  : colSpec.visible,
1375                 hidden   : colSpec.hidden,
1376                 datatype : colSpec.datatype,
1377                 sortable : colSpec.sortable,
1378                 nonsortable      : colSpec.nonsortable,
1379                 multisortable    : colSpec.multisortable,
1380                 nonmultisortable : colSpec.nonmultisortable,
1381                 dateformat       : colSpec.dateformat,
1382                 parentIdlClass   : colSpec.parentIdlClass
1383             };
1384         }
1385
1386
1387         // Add a column to the columns collection.
1388         // Columns may come from a slim eg-columns-field or 
1389         // directly from the IDL.
1390         cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1391
1392             // First added column with the specified path takes precedence.
1393             // This allows for specific definitions followed by wildcard
1394             // definitions.  If a match is found, back out.
1395             if (cols.columns.filter(function(c) {
1396                 return (c.path == colSpec.path) })[0]) {
1397                 console.debug('skipping pre-existing column ' + colSpec.path);
1398                 return;
1399             }
1400
1401             var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1402
1403             if (column.path && column.path.match(/\*$/)) 
1404                 return cols.expandPath(colSpec);
1405
1406             if (!fromExpand) column.explicit = true;
1407
1408             if (!column.name) column.name = column.path;
1409             if (!column.path) column.path = column.name;
1410
1411             if (column.visible || (!cols.defaultToHidden && !column.hidden))
1412                 column.visible = true;
1413
1414             if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1415                 column.sortable = true;
1416
1417             if (column.multisortable || 
1418                 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1419                 column.multisortable = true;
1420
1421             if (cols.defaultDateFormat && ! column.dateformat) {
1422                 column.dateformat = cols.defaultDateFormat;
1423             }
1424
1425             cols.columns.push(column);
1426
1427             // Track which columns are visible by default in case we
1428             // need to reset column visibility
1429             if (column.visible) 
1430                 cols.stockVisible.push(column.name);
1431
1432             if (fromIDL) return; // directly from egIDL.  nothing left to do.
1433
1434             // lookup the matching IDL field
1435             if (!idl_info && cols.idlClass) 
1436                 idl_info = cols.idlFieldFromPath(column.path);
1437
1438             if (!idl_info) {
1439                 // column is not represented within the IDL
1440                 column.adhoc = true; 
1441                 return; 
1442             }
1443
1444             column.datatype = idl_info.idl_field.datatype;
1445             
1446             if (!column.label) {
1447                 column.label = idl_info.idl_field.label || column.name;
1448             }
1449
1450             if (fromExpand && idl_info.idl_class) {
1451                 column.idlclass = '';
1452                 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1453                     column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1454                 } else {
1455                     column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1456                 }
1457             }
1458         },
1459
1460         // finds the IDL field from the dotpath, using the columns
1461         // idlClass as the base.
1462         cols.idlFieldFromPath = function(dotpath) {
1463             var class_obj = egCore.idl.classes[cols.idlClass];
1464             var path_parts = dotpath.split(/\./);
1465
1466             var idl_parent;
1467             var idl_field;
1468             for (var path_idx in path_parts) {
1469                 var part = path_parts[path_idx];
1470                 idl_parent = idl_field;
1471                 idl_field = class_obj.field_map[part];
1472
1473                 if (idl_field) {
1474                     if (idl_field['class'] && (
1475                         idl_field.datatype == 'link' || 
1476                         idl_field.datatype == 'org_unit')) {
1477                         class_obj = egCore.idl.classes[idl_field['class']];
1478                     }
1479                 } else {
1480                     return null;
1481                 }
1482             }
1483
1484             return {
1485                 idl_parent: idl_parent,
1486                 idl_field : idl_field,
1487                 idl_class : class_obj
1488             };
1489         }
1490     }
1491
1492     return {
1493         instance : function(args) { return new ColumnsProvider(args) }
1494     }
1495 }])
1496
1497
1498 /*
1499  * Generic data provider template class.  This is basically an abstract
1500  * class factory service whose instances can be locally modified to 
1501  * meet the needs of each individual grid.
1502  */
1503 .factory('egGridDataProvider', 
1504            ['$q','$timeout','$filter','egCore',
1505     function($q , $timeout , $filter , egCore) {
1506
1507         function GridDataProvider(args) {
1508             var gridData = this;
1509             if (!args) args = {};
1510
1511             gridData.sort = [];
1512             gridData.get = args.get;
1513             gridData.query = args.query;
1514             gridData.idlClass = args.idlClass;
1515             gridData.columnsProvider = args.columnsProvider;
1516
1517             // Delivers a stream of array data via promise.notify()
1518             // Useful for passing an array of data to egGrid.get()
1519             // If a count is provided, the array will be trimmed to
1520             // the range defined by count and offset
1521             gridData.arrayNotifier = function(arr, offset, count) {
1522                 if (!arr || arr.length == 0) return $q.when();
1523                 if (count) arr = arr.slice(offset, offset + count);
1524                 var def = $q.defer();
1525                 // promise notifications are only witnessed when delivered
1526                 // after the caller has his hands on the promise object
1527                 $timeout(function() {
1528                     angular.forEach(arr, def.notify);
1529                     def.resolve();
1530                 });
1531                 return def.promise;
1532             }
1533
1534             // Calls the grid refresh function.  Once instantiated, the
1535             // grid will replace this function with it's own refresh()
1536             gridData.refresh = function(noReset) { }
1537
1538             if (!gridData.get) {
1539                 // returns a promise whose notify() delivers items
1540                 gridData.get = function(index, count) {
1541                     console.error("egGridDataProvider.get() not implemented");
1542                 }
1543             }
1544
1545             // attempts a flat field lookup first.  If the column is not
1546             // found on the top-level object, attempts a nested lookup
1547             // TODO: consider a caching layer to speed up template 
1548             // rendering, particularly for nested objects?
1549             gridData.itemFieldValue = function(item, column) {
1550                 var val;
1551                 if (column.name in item) {
1552                     if (typeof item[column.name] == 'function') {
1553                         val = item[column.name]();
1554                     } else {
1555                         val = item[column.name];
1556                     }
1557                 } else {
1558                     val = gridData.nestedItemFieldValue(item, column);
1559                 }
1560
1561                 return val;
1562             }
1563
1564             // TODO: deprecate me
1565             gridData.flatItemFieldValue = function(item, column) {
1566                 console.warn('gridData.flatItemFieldValue deprecated; '
1567                     + 'leave provider.itemFieldValue unset');
1568                 return item[column.name];
1569             }
1570
1571             // given an object and a dot-separated path to a field,
1572             // extract the value of the field.  The path can refer
1573             // to function names or object attributes.  If the final
1574             // value is an IDL field, run the value through its
1575             // corresponding output filter.
1576             gridData.nestedItemFieldValue = function(obj, column) {
1577                 item = obj; // keep a copy around
1578
1579                 if (obj === null || obj === undefined || obj === '') return '';
1580                 if (!column.path) return obj;
1581
1582                 var idl_field;
1583                 var parts = column.path.split('.');
1584
1585                 angular.forEach(parts, function(step, idx) {
1586                     // object is not fleshed to the expected extent
1587                     if (typeof obj != 'object') {
1588                         if (typeof obj != 'undefined' && column.flesher) {
1589                             obj = column.flesher(obj, column, item);
1590                         } else {
1591                             obj = '';
1592                             return;
1593                         }
1594                     }
1595
1596                     if (!obj) return '';
1597
1598                     var cls = obj.classname;
1599                     if (cls && (class_obj = egCore.idl.classes[cls])) {
1600                         idl_field = class_obj.field_map[step];
1601                         obj = obj[step] ? obj[step]() : '';
1602                     } else {
1603                         if (angular.isFunction(obj[step])) {
1604                             obj = obj[step]();
1605                         } else {
1606                             obj = obj[step];
1607                         }
1608                     }
1609                 });
1610
1611                 // We found a nested IDL object which may or may not have 
1612                 // been configured as a top-level column.  Grab the datatype.
1613                 if (idl_field && !column.datatype) 
1614                     column.datatype = idl_field.datatype;
1615
1616                 if (obj === null || obj === undefined || obj === '') return '';
1617                 return obj;
1618             }
1619         }
1620
1621         return {
1622             instance : function(args) {
1623                 return new GridDataProvider(args);
1624             }
1625         };
1626     }
1627 ])
1628
1629
1630 // Factory service for egGridDataManager instances, which are
1631 // responsible for collecting flattened grid data.
1632 .factory('egGridFlatDataProvider', 
1633            ['$q','egCore','egGridDataProvider',
1634     function($q , egCore , egGridDataProvider) {
1635
1636         return {
1637             instance : function(args) {
1638                 var provider = egGridDataProvider.instance(args);
1639
1640                 provider.get = function(offset, count) {
1641
1642                     // no query means no call
1643                     if (!provider.query || 
1644                             angular.equals(provider.query, {})) 
1645                         return $q.when();
1646
1647                     // find all of the currently visible columns
1648                     var queryFields = {}
1649                     angular.forEach(provider.columnsProvider.columns, 
1650                         function(col) {
1651                             // only query IDL-tracked columns
1652                             if (!col.adhoc && (col.required || col.visible))
1653                                 queryFields[col.name] = col.path;
1654                         }
1655                     );
1656
1657                     return egCore.net.request(
1658                         'open-ils.fielder',
1659                         'open-ils.fielder.flattened_search',
1660                         egCore.auth.token(), provider.idlClass, 
1661                         queryFields, provider.query,
1662                         {   sort : provider.sort,
1663                             limit : count,
1664                             offset : offset
1665                         }
1666                     );
1667                 }
1668                 //provider.itemFieldValue = provider.flatItemFieldValue;
1669                 return provider;
1670             }
1671         };
1672     }
1673 ])
1674
1675 .directive('egGridColumnDragSource', function() {
1676     return {
1677         restrict : 'A',
1678         require : '^egGrid',
1679         link : function(scope, element, attrs, egGridCtrl) {
1680             angular.element(element).attr('draggable', 'true');
1681
1682             element.bind('dragstart', function(e) {
1683                 egGridCtrl.dragColumn = attrs.column;
1684                 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1685                 egGridCtrl.colResizeDir = 0;
1686
1687                 if (egGridCtrl.dragType == 'move') {
1688                     // style the column getting moved
1689                     angular.element(e.target).addClass(
1690                         'eg-grid-column-move-handle-active');
1691                 }
1692             });
1693
1694             element.bind('dragend', function(e) {
1695                 if (egGridCtrl.dragType == 'move') {
1696                     angular.element(e.target).removeClass(
1697                         'eg-grid-column-move-handle-active');
1698                 }
1699             });
1700         }
1701     };
1702 })
1703
1704 .directive('egGridColumnDragDest', function() {
1705     return {
1706         restrict : 'A',
1707         require : '^egGrid',
1708         link : function(scope, element, attrs, egGridCtrl) {
1709
1710             element.bind('dragover', function(e) { // required for drop
1711                 e.stopPropagation();
1712                 e.preventDefault();
1713                 e.dataTransfer.dropEffect = 'move';
1714
1715                 if (egGridCtrl.colResizeDir == 0) return; // move
1716
1717                 var cols = egGridCtrl.columnsProvider;
1718                 var srcCol = egGridCtrl.dragColumn;
1719                 var srcColIdx = cols.indexOf(srcCol);
1720
1721                 if (egGridCtrl.colResizeDir == -1) {
1722                     if (cols.indexOf(attrs.column) <= srcColIdx) {
1723                         egGridCtrl.modifyColumnFlex(
1724                             egGridCtrl.columnsProvider.findColumn(
1725                                 egGridCtrl.dragColumn), -1);
1726                         if (cols.columns[srcColIdx+1]) {
1727                             // source column shrinks by one, column to the
1728                             // right grows by one.
1729                             egGridCtrl.modifyColumnFlex(
1730                                 cols.columns[srcColIdx+1], 1);
1731                         }
1732                         scope.$apply();
1733                     }
1734                 } else {
1735                     if (cols.indexOf(attrs.column) > srcColIdx) {
1736                         egGridCtrl.modifyColumnFlex( 
1737                             egGridCtrl.columnsProvider.findColumn(
1738                                 egGridCtrl.dragColumn), 1);
1739                         if (cols.columns[srcColIdx+1]) {
1740                             // source column grows by one, column to the 
1741                             // right grows by one.
1742                             egGridCtrl.modifyColumnFlex(
1743                                 cols.columns[srcColIdx+1], -1);
1744                         }
1745
1746                         scope.$apply();
1747                     }
1748                 }
1749             });
1750
1751             element.bind('dragenter', function(e) {
1752                 e.stopPropagation();
1753                 e.preventDefault();
1754                 if (egGridCtrl.dragType == 'move') {
1755                     angular.element(e.target).addClass('eg-grid-col-hover');
1756                 } else {
1757                     // resize grips are on the right side of each column.
1758                     // dragenter will either occur on the source column 
1759                     // (dragging left) or the column to the right.
1760                     if (egGridCtrl.colResizeDir == 0) {
1761                         if (egGridCtrl.dragColumn == attrs.column) {
1762                             egGridCtrl.colResizeDir = -1; // west
1763                         } else {
1764                             egGridCtrl.colResizeDir = 1; // east
1765                         }
1766                     }
1767                 }
1768             });
1769
1770             element.bind('dragleave', function(e) {
1771                 e.stopPropagation();
1772                 e.preventDefault();
1773                 if (egGridCtrl.dragType == 'move') {
1774                     angular.element(e.target).removeClass('eg-grid-col-hover');
1775                 }
1776             });
1777
1778             element.bind('drop', function(e) {
1779                 e.stopPropagation();
1780                 e.preventDefault();
1781                 egGridCtrl.colResizeDir = 0;
1782                 if (egGridCtrl.dragType == 'move') {
1783                     angular.element(e.target).removeClass('eg-grid-col-hover');
1784                     egGridCtrl.onColumnDrop(attrs.column); // move the column
1785                 }
1786             });
1787         }
1788     };
1789 })
1790  
1791 .directive('egGridMenuItem', function() {
1792     return {
1793         restrict : 'AE',
1794         require : '^egGrid',
1795         scope : {
1796             label : '@',  
1797             checkbox : '@',  
1798             checked : '=',  
1799             standalone : '=',  
1800             handler : '=', // onclick handler function
1801             divider : '=', // if true, show a divider only
1802             handlerData : '=', // if set, passed as second argument to handler
1803             disabled : '=', // function
1804             hidden : '=' // function
1805         },
1806         link : function(scope, element, attrs, egGridCtrl) {
1807             egGridCtrl.addMenuItem({
1808                 checkbox : scope.checkbox,
1809                 checked : scope.checked ? true : false,
1810                 label : scope.label,
1811                 standalone : scope.standalone ? true : false,
1812                 handler : scope.handler,
1813                 divider : scope.divider,
1814                 disabled : scope.disabled,
1815                 hidden : scope.hidden,
1816                 handlerData : scope.handlerData
1817             });
1818             scope.$destroy();
1819         }
1820     };
1821 })
1822
1823
1824
1825 /**
1826  * Translates bare IDL object values into display values.
1827  * 1. Passes dates through the angular date filter
1828  * 2. Translates bools to Booleans so the browser can display translated 
1829  *    value.  (Though we could manually translate instead..)
1830  * Others likely to follow...
1831  */
1832 .filter('egGridValueFilter', ['$filter', function($filter) {                         
1833     return function(value, column) {                                             
1834         switch(column.datatype) {                                                
1835             case 'bool':                                                       
1836                 switch(value) {
1837                     // Browser will translate true/false for us                    
1838                     case 't' : 
1839                     case '1' :  // legacy
1840                     case true:
1841                         return ''+true;
1842                     case 'f' : 
1843                     case '0' :  // legacy
1844                     case false:
1845                         return ''+false;
1846                     // value may be null,  '', etc.
1847                     default : return '';
1848                 }
1849             case 'timestamp':                                                  
1850                 // canned angular date filter FTW                              
1851                 if (!column.dateformat) 
1852                     column.dateformat = 'shortDate';
1853                 return $filter('date')(value, column.dateformat);
1854             case 'money':                                                  
1855                 return $filter('currency')(value);
1856             default:                                                           
1857                 return value;                                                  
1858         }                                                                      
1859     }                                                                          
1860 }]);
1861