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