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