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