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