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