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