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