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