]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/grid.js
LP#1740412 Grid cell tooltips limited to long content
[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 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
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                 // select the right-clicked row if it is not already selected (lp1776557):
695                 if(!$scope.selected[grid.indexValue(s.item)]){ $event.target.click(); }
696
697                 if (!$scope.action_context_showing) {
698                     $scope.action_context_width = $($scope.menu_dom).css('width');
699                     $scope.action_context_y = $($scope.menu_dom).css('top');
700                     $scope.action_context_x = $($scope.menu_dom).css('left');
701                     $scope.action_context_showing = true;
702                     $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
703
704                     $('body').append($($scope.menu_dom));
705                     $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
706                 }
707
708                 $($scope.menu_dom).css({
709                     display: 'block',
710                     width: $scope.action_context_width,
711                     top: $event.pageY,
712                     left: $event.pageX
713                 });
714
715                 return false;
716             }
717
718             // returns the list of selected item objects
719             grid.getSelectedItems = function() {
720                 return $scope.items.filter(
721                     function(item) {
722                         return Boolean($scope.selected[grid.indexValue(item)]);
723                     }
724                 );
725             }
726
727             grid.getItemByIndex = function(index) {
728                 for (var i = 0; i < $scope.items.length; i++) {
729                     var item = $scope.items[i];
730                     if (grid.indexValue(item) == index) 
731                         return item;
732                 }
733             }
734
735             // selects one row after deselecting all of the others
736             grid.selectOneItem = function(index) {
737                 $scope.selected = {};
738                 $scope.selected[index] = true;
739             }
740
741             // selects or deselects an item, without affecting the others.
742             // returns true if the item is selected; false if de-selected.
743             // we overwrite the object so that we can watch $scope.selected
744             grid.toggleSelectOneItem = function(index) {
745                 if ($scope.selected[index]) {
746                     delete $scope.selected[index];
747                     $scope.selected = angular.copy($scope.selected);
748                     return false;
749                 } else {
750                     $scope.selected[index] = true;
751                     $scope.selected = angular.copy($scope.selected);
752                     return true;
753                 }
754             }
755
756             $scope.updateSelected = function () { 
757                     return $scope.selected = angular.copy($scope.selected);
758             };
759
760             grid.selectAllItems = function() {
761                 angular.forEach($scope.items, function(item) {
762                     $scope.selected[grid.indexValue(item)] = true
763                 }); 
764                 $scope.selected = angular.copy($scope.selected);
765             }
766
767             $scope.$watch('selectAll', function(newVal) {
768                 if (newVal) {
769                     grid.selectAllItems();
770                 } else {
771                     $scope.selected = {};
772                 }
773             });
774
775             if ($scope.onSelect) {
776                 $scope.$watch('selected', function(newVal) {
777                     $scope.onSelect(grid.getSelectedItems());
778                     if ($scope.afterSelect) $scope.afterSelect();
779                 });
780             }
781
782             // returns true if item1 appears in the list before item2;
783             // false otherwise.  this is slightly more efficient that
784             // finding the position of each then comparing them.
785             // item1 / item2 may be an item or an item index
786             grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
787                 var idx1 = grid.indexValue(itemOrIndex1);
788                 var idx2 = grid.indexValue(itemOrIndex2);
789
790                 // use for() for early exit
791                 for (var i = 0; i < $scope.items.length; i++) {
792                     var idx = grid.indexValue($scope.items[i]);
793                     if (idx == idx1) return true;
794                     if (idx == idx2) return false;
795                 }
796                 return false;
797             }
798
799             // 0-based position of item in the current data set
800             grid.indexOf = function(item) {
801                 var idx = grid.indexValue(item);
802                 for (var i = 0; i < $scope.items.length; i++) {
803                     if (grid.indexValue($scope.items[i]) == idx)
804                         return i;
805                 }
806                 return -1;
807             }
808
809             grid.modifyColumnFlex = function(column, val) {
810                 column.flex += val;
811                 // prevent flex:0;  use hiding instead
812                 if (column.flex < 1)
813                     column.flex = 1;
814             }
815             $scope.modifyColumnFlex = function(col, val) {
816                 $scope.lastModColumn = col;
817                 grid.modifyColumnFlex(col, val);
818             }
819
820             $scope.isLastModifiedColumn = function(col) {
821                 if ($scope.lastModColumn)
822                     return $scope.lastModColumn === col;
823                 return false;
824             }
825
826             grid.modifyColumnPos = function(col, diff) {
827                 var srcIdx, targetIdx;
828                 angular.forEach(grid.columnsProvider.columns,
829                     function(c, i) { if (c.name == col.name) srcIdx = i });
830
831                 targetIdx = srcIdx + diff;
832                 if (targetIdx < 0) {
833                     targetIdx = 0;
834                 } else if (targetIdx >= grid.columnsProvider.columns.length) {
835                     // Target index follows the last visible column.
836                     var lastVisible = 0;
837                     angular.forEach(grid.columnsProvider.columns, 
838                         function(column, idx) {
839                             if (column.visible) lastVisible = idx;
840                         }
841                     );
842
843                     // When moving a column (down) causes one or more
844                     // visible columns to shuffle forward, our column
845                     // moves into the slot of the last visible column.
846                     // Otherwise, put it into the slot directly following 
847                     // the last visible column.
848                     targetIdx = 
849                         srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
850                 }
851
852                 // Splice column out of old position, insert at new position.
853                 grid.columnsProvider.columns.splice(srcIdx, 1);
854                 grid.columnsProvider.columns.splice(targetIdx, 0, col);
855             }
856
857             $scope.modifyColumnPos = function(col, diff) {
858                 $scope.lastModColumn = col;
859                 return grid.modifyColumnPos(col, diff);
860             }
861
862             // Returns true of the contents of the cell overflow its container.
863             // parentDepth tells the code how far up the DOM tree to traverse
864             // via parentNode before stopping to inspect the value.
865             // There's no way to pass a reference to a DOM node directly via
866             // a scope function (except ng-click, etc.) so pass the 
867             // DOM id instead and get the node from there.
868             $scope.cellOverflowed = function(id, parentDepth) {
869                 var node = document.getElementById(id);
870                 if (!node) return;
871                 for (var i = 0; i < parentDepth; i++) {
872                     node = node.parentNode;
873                 }
874                 return node.scrollHeight > node.clientHeight 
875                     || node.scrollWidth > node.clientWidth;
876             }
877
878             // Generates a unique identifier per cell per grid.
879             $scope.cellId = function(col, item) {
880                 if (!col || !item) return '';
881                 return 'grid-cell-span-' 
882                     // differentiate grids
883                     + ($scope.persistKey || $scope.idlClass || $scope.grid_element.id)
884                     // differentiate rows and columns.
885                     + '-' + col.name + '-' + $scope.indexValue(item);
886
887             }
888
889             // handles click, control-click, and shift-click
890             $scope.handleRowClick = function($event, item) {
891                 var index = grid.indexValue(item);
892
893                 var origSelected = Object.keys($scope.selected);
894
895                 if (!$scope.canMultiSelect) {
896                     grid.selectOneItem(index);
897                     grid.lastSelectedItemIndex = index;
898                     return;
899                 }
900
901                 if ($event.ctrlKey || $event.metaKey /* mac command */) {
902                     // control-click
903                     if (grid.toggleSelectOneItem(index)) 
904                         grid.lastSelectedItemIndex = index;
905
906                 } else if ($event.shiftKey) { 
907                     // shift-click
908
909                     if (!grid.lastSelectedItemIndex || 
910                             index == grid.lastSelectedItemIndex) {
911                         grid.selectOneItem(index);
912                         grid.lastSelectedItemIndex = index;
913
914                     } else {
915
916                         var selecting = false;
917                         var ascending = grid.itemComesBefore(
918                             grid.lastSelectedItemIndex, item);
919                         var startPos = 
920                             grid.indexOf(grid.lastSelectedItemIndex);
921
922                         // update to new last-selected
923                         grid.lastSelectedItemIndex = index;
924
925                         // select each row between the last selected and 
926                         // currently selected items
927                         while (true) {
928                             startPos += ascending ? 1 : -1;
929                             var curItem = $scope.items[startPos];
930                             if (!curItem) break;
931                             var curIdx = grid.indexValue(curItem);
932                             $scope.selected[curIdx] = true;
933                             if (curIdx == index) break; // all done
934                         }
935                         $scope.selected = angular.copy($scope.selected);
936                     }
937                         
938                 } else {
939                     grid.selectOneItem(index);
940                     grid.lastSelectedItemIndex = index;
941                 }
942             }
943
944             // Builds a sort expression from column sort priorities.
945             // called on page load and any time the priorities are modified.
946             grid.compileSort = function() {
947                 var sortList = grid.columnsProvider.columns.filter(
948                     function(col) { return Number(col.sort) != 0 }
949                 ).sort( 
950                     function(a, b) { 
951                         if (Math.abs(a.sort) < Math.abs(b.sort))
952                             return -1;
953                         return 1;
954                     }
955                 );
956
957                 if (sortList.length) {
958                     grid.dataProvider.sort = sortList.map(function(col) {
959                         var blob = {};
960                         blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
961                         return blob;
962                     });
963                 }
964             }
965
966             // builds a sort expression using a single column, 
967             // toggling between ascending and descending sort.
968             $scope.quickSort = function(col_name) {
969                 var sort = grid.dataProvider.sort;
970                 if (sort && sort.length &&
971                     sort[0] == col_name) {
972                     var blob = {};
973                     blob[col_name] = 'desc';
974                     grid.dataProvider.sort = [blob];
975                 } else {
976                     grid.dataProvider.sort = [col_name];
977                 }
978
979                 grid.offset = 0;
980                 grid.collect();
981             }
982
983             // show / hide the grid configuration row
984             $scope.toggleConfDisplay = function() {
985                 if ($scope.showGridConf) {
986                     $scope.showGridConf = false;
987                     if (grid.columnsProvider.hasSortableColumn()) {
988                         // only refresh the grid if the user has the
989                         // ability to modify the sort priorities.
990                         grid.compileSort();
991                         grid.offset = 0;
992                         grid.collect();
993                     }
994                 } else {
995                     $scope.showGridConf = true;
996                 }
997
998                 delete $scope.lastModColumn;
999                 $scope.gridColumnPickerIsOpen = false;
1000             }
1001
1002             // called when a dragged column is dropped onto itself
1003             // or any other column
1004             grid.onColumnDrop = function(target) {
1005                 if (angular.isUndefined(target)) return;
1006                 if (target == grid.dragColumn) return;
1007                 var srcIdx, targetIdx, srcCol;
1008                 angular.forEach(grid.columnsProvider.columns,
1009                     function(col, idx) {
1010                         if (col.name == grid.dragColumn) {
1011                             srcIdx = idx;
1012                             srcCol = col;
1013                         } else if (col.name == target) {
1014                             targetIdx = idx;
1015                         }
1016                     }
1017                 );
1018
1019                 if (srcIdx < targetIdx) targetIdx--;
1020
1021                 // move src column from old location to new location in 
1022                 // the columns array, then force a page refresh
1023                 grid.columnsProvider.columns.splice(srcIdx, 1);
1024                 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
1025                 $scope.$apply(); 
1026             }
1027
1028             // prepares a string for inclusion within a CSV document
1029             // by escaping commas and quotes and removing newlines.
1030             grid.csvDatum = function(str) {
1031                 str = ''+str;
1032                 if (!str) return '';
1033                 str = str.replace(/\n/g, '');
1034                 if (str.match(/\,/) || str.match(/"/)) {                                     
1035                     str = str.replace(/"/g, '""');
1036                     str = '"' + str + '"';                                           
1037                 } 
1038                 return str;
1039             }
1040
1041             /** Export the full data set as CSV.
1042              *  Flow of events:
1043              *  1. User clicks the 'download csv' link
1044              *  2. All grid data is retrieved asychronously
1045              *  3. Once all data is all present and CSV-ized, the download 
1046              *     attributes are linked to the href.
1047              *  4. The href .click() action is prgrammatically fired again,
1048              *     telling the browser to download the data, now that the
1049              *     data is available for download.
1050              *  5 Once downloaded, the href attributes are reset.
1051              */
1052             grid.csvExportInProgress = false;
1053             $scope.generateCSVExportURL = function($event) {
1054
1055                 if (grid.csvExportInProgress) {
1056                     // This is secondary href click handler.  Give the
1057                     // browser a moment to start the download, then reset
1058                     // the CSV download attributes / state.
1059                     $timeout(
1060                         function() {
1061                             $scope.csvExportURL = '';
1062                             $scope.csvExportFileName = ''; 
1063                             grid.csvExportInProgress = false;
1064                         }, 500
1065                     );
1066                     return;
1067                 } 
1068
1069                 grid.csvExportInProgress = true;
1070                 $scope.gridColumnPickerIsOpen = false;
1071
1072                 // let the file name describe the grid
1073                 $scope.csvExportFileName = 
1074                     ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
1075                     .replace(/\s+/g, '_') + '_' + $scope.page();
1076
1077                 // toss the CSV into a Blob and update the export URL
1078                 grid.generateCSV().then(function(csv) {
1079                     var blob = new Blob([csv], {type : 'text/plain'});
1080                     $scope.csvExportURL = 
1081                         ($window.URL || $window.webkitURL).createObjectURL(blob);
1082
1083                     // Fire the 2nd click event now that the browser has
1084                     // information on how to download the CSV file.
1085                     $timeout(function() {$event.target.click()});
1086                 });
1087             }
1088
1089             /*
1090              * TODO: does this serve any purpose given we can 
1091              * print formatted HTML?  If so, generateCSV() now
1092              * returns a promise, needs light refactoring...
1093             $scope.printCSV = function() {
1094                 $scope.gridColumnPickerIsOpen = false;
1095                 egCore.print.print({
1096                     context : 'default', 
1097                     content : grid.generateCSV(),
1098                     content_type : 'text/plain'
1099                 });
1100             }
1101             */
1102
1103             // Given a row item and column definition, extract the
1104             // text content for printing.  Templated columns must be
1105             // processed and parsed as HTML, then boiled down to their 
1106             // text content.
1107             grid.getItemTextContent = function(item, col) {
1108                 var val;
1109                 if (col.template) {
1110                     val = $scope.translateCellTemplate(col, item);
1111                     if (val) {
1112                         var node = new DOMParser()
1113                             .parseFromString(val, 'text/html');
1114                         val = $(node).text();
1115                     }
1116                 } else {
1117                     val = grid.dataProvider.itemFieldValue(item, col);
1118                     val = $filter('egGridValueFilter')(val, col, item);
1119                 }
1120                 return val;
1121             }
1122
1123             /**
1124              * Fetches all grid data and transates each item into a simple
1125              * key-value pair of column name => text-value.
1126              * Included in the response for convenience is the list of 
1127              * currently visible column definitions.
1128              * TODO: currently fetches a maximum of 10k rows.  Does this
1129              * need to be configurable?
1130              */
1131             grid.getAllItemsAsText = function() {
1132                 var text_items = [];
1133
1134                 // we don't know the total number of rows we're about
1135                 // to retrieve, but we can indicate the number retrieved
1136                 // so far as each item arrives.
1137                 egProgressDialog.open({value : 0});
1138
1139                 var visible_cols = grid.columnsProvider.columns.filter(
1140                     function(c) { return c.visible });
1141
1142                 return grid.dataProvider.get(0, 10000).then(
1143                     function() { 
1144                         return {items : text_items, columns : visible_cols};
1145                     }, 
1146                     null,
1147                     function(item) { 
1148                         egProgressDialog.increment();
1149                         var text_item = {};
1150                         angular.forEach(visible_cols, function(col) {
1151                             text_item[col.name] = 
1152                                 grid.getItemTextContent(item, col);
1153                         });
1154                         text_items.push(text_item);
1155                     }
1156                 ).finally(egProgressDialog.close);
1157             }
1158
1159             // Fetch "all" of the grid data, translate it into print-friendly 
1160             // text, and send it to the printer service.
1161             $scope.printHTML = function() {
1162                 $scope.gridColumnPickerIsOpen = false;
1163                 return grid.getAllItemsAsText().then(function(text_items) {
1164                     return egCore.print.print({
1165                         template : 'grid_html',
1166                         scope : text_items
1167                     });
1168                 });
1169             }
1170
1171             $scope.showColumnDialog = function() {
1172                 return $uibModal.open({
1173                     templateUrl: './share/t_grid_columns',
1174                     backdrop: 'static',
1175                     size : 'lg',
1176                     controller: ['$scope', '$uibModalInstance',
1177                         function($dialogScope, $uibModalInstance) {
1178                             $dialogScope.modifyColumnPos = $scope.modifyColumnPos;
1179                             $dialogScope.disableMultiSort = $scope.disableMultiSort;
1180                             $dialogScope.columns = $scope.columns;
1181
1182                             // Push visible columns to the top of the list
1183                             $dialogScope.elevateVisible = function() {
1184                                 var new_cols = [];
1185                                 angular.forEach($dialogScope.columns, function(col) {
1186                                     if (col.visible) new_cols.push(col);
1187                                 });
1188                                 angular.forEach($dialogScope.columns, function(col) {
1189                                     if (!col.visible) new_cols.push(col);
1190                                 });
1191
1192                                 // Update all references to the list of columns
1193                                 $dialogScope.columns = 
1194                                     $scope.columns = 
1195                                     grid.columnsProvider.columns = 
1196                                     new_cols;
1197                             }
1198
1199                             $dialogScope.toggle = function(col) {
1200                                 col.visible = !Boolean(col.visible);
1201                             }
1202                             $dialogScope.ok = $dialogScope.cancel = function() {
1203                                 delete $scope.lastModColumn;
1204                                 $uibModalInstance.close()
1205                             }
1206                         }
1207                     ]
1208                 });
1209             },
1210
1211             // generates CSV for the currently visible grid contents
1212             grid.generateCSV = function() {
1213                 return grid.getAllItemsAsText().then(function(text_items) {
1214                     var columns = text_items.columns;
1215                     var items = text_items.items;
1216                     var csvStr = '';
1217
1218                     // column headers
1219                     angular.forEach(columns, function(col) {
1220                         csvStr += grid.csvDatum(col.label);
1221                         csvStr += ',';
1222                     });
1223
1224                     csvStr = csvStr.replace(/,$/,'\n');
1225
1226                     // items
1227                     angular.forEach(items, function(item) {
1228                         angular.forEach(columns, function(col) {
1229                             csvStr += grid.csvDatum(item[col.name]);
1230                             csvStr += ',';
1231                         });
1232                         csvStr = csvStr.replace(/,$/,'\n');
1233                     });
1234
1235                     return csvStr;
1236                 });
1237             }
1238
1239             // Interpolate the value for column.linkpath within the context
1240             // of the row item to generate the final link URL.
1241             $scope.generateLinkPath = function(col, item) {
1242                 return egCore.strings.$replace(col.linkpath, {item : item});
1243             }
1244
1245             // If a column provides its own HTML template, translate it,
1246             // using the current item for the template scope.
1247             // note: $sce is required to avoid security restrictions and
1248             // is OK here, since the template comes directly from a
1249             // local HTML template (not user input).
1250             $scope.translateCellTemplate = function(col, item) {
1251                 var html = egCore.strings.$replace(col.template, {item : item});
1252                 return $sce.trustAsHtml(html);
1253             }
1254
1255             $scope.collect = function() { grid.collect() }
1256
1257
1258             $scope.confirmAllowAllAndCollect = function(){
1259                 egConfirmDialog.open(egStrings.CONFIRM_LONG_RUNNING_ACTION_ALL_ROWS_TITLE,
1260                     egStrings.CONFIRM_LONG_RUNNING_ACTION_MSG)
1261                     .result
1262                     .then(function(){
1263                         $scope.offset(0);
1264                         $scope.limit(10000);
1265                         grid.collect();
1266                 });
1267             }
1268
1269             // asks the dataProvider for a page of data
1270             grid.collect = function() {
1271
1272                 // avoid firing the collect if there is nothing to collect.
1273                 if (grid.selfManagedData && !grid.dataProvider.query) return;
1274
1275                 if (grid.collecting) return; // avoid parallel collect()
1276                 grid.collecting = true;
1277
1278                 console.debug('egGrid.collect() offset=' 
1279                     + grid.offset + '; limit=' + grid.limit);
1280
1281                 // ensure all of our dropdowns are closed
1282                 // TODO: git rid of these and just use dropdown-toggle, 
1283                 // which is more reliable.
1284                 $scope.gridColumnPickerIsOpen = false;
1285                 $scope.gridRowCountIsOpen = false;
1286                 $scope.gridPageSelectIsOpen = false;
1287
1288                 $scope.items = [];
1289                 $scope.selected = {};
1290
1291                 // Inform the caller we've asked the data provider
1292                 // for data.  This is useful for knowing when collection
1293                 // has started (e.g. to display a progress dialg) when 
1294                 // using the stock (flattener) data provider, where the 
1295                 // user is not directly defining a get() handler.
1296                 if (grid.controls.collectStarted)
1297                     grid.controls.collectStarted(grid.offset, grid.limit);
1298
1299                 grid.dataProvider.get(grid.offset, grid.limit).then(
1300                 function() {
1301                     if (grid.controls.allItemsRetrieved)
1302                         grid.controls.allItemsRetrieved();
1303                 },
1304                 null, 
1305                 function(item) {
1306                     if (item) {
1307                         $scope.items.push(item)
1308                         if (grid.controls.itemRetrieved)
1309                             grid.controls.itemRetrieved(item);
1310                         if ($scope.selectAll)
1311                             $scope.selected[grid.indexValue(item)] = true
1312                     }
1313                 }).finally(function() { 
1314                     console.debug('egGrid.collect() complete');
1315                     grid.collecting = false 
1316                     $scope.selected = angular.copy($scope.selected);
1317                 });
1318             }
1319
1320             grid.init();
1321         }]
1322     };
1323 })
1324
1325 /**
1326  * eg-grid-field : used for collecting custom field data from the templates.
1327  * This directive does not direct display, it just passes data up to the 
1328  * parent grid.
1329  */
1330 .directive('egGridField', function() {
1331     return {
1332         require : '^egGrid',
1333         restrict : 'AE',
1334         scope : {
1335             flesher: '=', // optional; function that can flesh a linked field, given the value
1336             comparator: '=', // optional; function that can sort the thing at the end of 'path' 
1337             name  : '@', // required; unique name
1338             path  : '@', // optional; flesh path
1339             ignore: '@', // optional; fields to ignore when path is a wildcard
1340             label : '@', // optional; display label
1341             flex  : '@',  // optional; default flex width
1342             align  : '@',  // optional; default alignment, left/center/right
1343             dateformat : '@', // optional: passed down to egGridValueFilter
1344             datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
1345             datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
1346             dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
1347
1348             // if a field is part of an IDL object, but we are unable to
1349             // determine the class, because it's nested within a hash
1350             // (i.e. we can't navigate directly to the object via the IDL),
1351             // idlClass lets us specify the class.  This is particularly
1352             // useful for nested wildcard fields.
1353             parentIdlClass : '@', 
1354
1355             // optional: for non-IDL columns, specifying a datatype
1356             // lets the caller control which display filter is used.
1357             // datatype should match the standard IDL datatypes.
1358             datatype : '@',
1359
1360             // optional hash of functions that can be imported into
1361             // the directive's scope; meant for cases where the "compiled"
1362             // attribute is set
1363             handlers : '='
1364         },
1365         link : function(scope, element, attrs, egGridCtrl) {
1366
1367             // boolean fields are presented as value-less attributes
1368             angular.forEach(
1369                 [
1370                     'visible', 
1371                     'compiled', 
1372                     'hidden', 
1373                     'sortable', 
1374                     'nonsortable',
1375                     'multisortable',
1376                     'nonmultisortable',
1377                     'required' // if set, always fetch data for this column
1378                 ],
1379                 function(field) {
1380                     if (angular.isDefined(attrs[field]))
1381                         scope[field] = true;
1382                 }
1383             );
1384
1385             // any HTML content within the field is its custom template
1386             var tmpl = element.html();
1387             if (tmpl && !tmpl.match(/^\s*$/))
1388                 scope.template = tmpl
1389
1390             egGridCtrl.columnsProvider.add(scope);
1391             scope.$destroy();
1392         }
1393     };
1394 })
1395
1396 /**
1397  * eg-grid-action : used for specifying actions which may be applied
1398  * to items within the grid.
1399  */
1400 .directive('egGridAction', function() {
1401     return {
1402         require : '^egGrid',
1403         restrict : 'AE',
1404         transclude : true,
1405         scope : {
1406             group   : '@', // Action group, ungrouped if not set
1407             label   : '@', // Action label
1408             handler : '=',  // Action function handler
1409             hide    : '=',
1410             disabled : '=', // function
1411             divider : '='
1412         },
1413         link : function(scope, element, attrs, egGridCtrl) {
1414             egGridCtrl.addAction({
1415                 hide  : scope.hide,
1416                 group : scope.group,
1417                 label : scope.label,
1418                 divider : scope.divider,
1419                 handler : scope.handler,
1420                 disabled : scope.disabled,
1421             });
1422             scope.$destroy();
1423         }
1424     };
1425 })
1426
1427 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1428
1429     function ColumnsProvider(args) {
1430         var cols = this;
1431         cols.columns = [];
1432         cols.stockVisible = [];
1433         cols.idlClass = args.idlClass;
1434         cols.clientSort = args.clientSort;
1435         cols.defaultToHidden = args.defaultToHidden;
1436         cols.defaultToNoSort = args.defaultToNoSort;
1437         cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1438         cols.defaultDateFormat = args.defaultDateFormat;
1439         cols.defaultDateContext = args.defaultDateContext;
1440
1441         // resets column width, visibility, and sort behavior
1442         // Visibility resets to the visibility settings defined in the 
1443         // template (i.e. the original egGridField values).
1444         cols.reset = function() {
1445             angular.forEach(cols.columns, function(col) {
1446                 col.align = 'left';
1447                 col.flex = 2;
1448                 col.sort = 0;
1449                 if (cols.stockVisible.indexOf(col.name) > -1) {
1450                     col.visible = true;
1451                 } else {
1452                     col.visible = false;
1453                 }
1454             });
1455         }
1456
1457         // returns true if any columns are sortable
1458         cols.hasSortableColumn = function() {
1459             return cols.columns.filter(
1460                 function(col) {
1461                     return col.sortable || col.multisortable;
1462                 }
1463             ).length > 0;
1464         }
1465
1466         cols.showAllColumns = function() {
1467             angular.forEach(cols.columns, function(column) {
1468                 column.visible = true;
1469             });
1470         }
1471
1472         cols.hideAllColumns = function() {
1473             angular.forEach(cols.columns, function(col) {
1474                 delete col.visible;
1475             });
1476         }
1477
1478         cols.indexOf = function(name) {
1479             for (var i = 0; i < cols.columns.length; i++) {
1480                 if (cols.columns[i].name == name) 
1481                     return i;
1482             }
1483             return -1;
1484         }
1485
1486         cols.findColumn = function(name) {
1487             return cols.columns[cols.indexOf(name)];
1488         }
1489
1490         cols.compileAutoColumns = function() {
1491             var idl_class = egCore.idl.classes[cols.idlClass];
1492
1493             angular.forEach(
1494                 idl_class.fields,
1495                 function(field) {
1496                     if (field.virtual) return;
1497                     if (field.datatype == 'link' || field.datatype == 'org_unit') {
1498                         // if the field is a link and the linked class has a
1499                         // "selector" field specified, use the selector field
1500                         // as the display field for the columns.
1501                         // flattener will take care of the fleshing.
1502                         if (field['class']) {
1503                             var selector_field = egCore.idl.classes[field['class']].fields
1504                                 .filter(function(f) { return Boolean(f.selector) })[0];
1505                             if (selector_field) {
1506                                 field.path = field.name + '.' + selector_field.selector;
1507                             }
1508                         }
1509                     }
1510                     cols.add(field, true);
1511                 }
1512             );
1513         }
1514
1515         // if a column definition has a path with a wildcard, create
1516         // columns for all non-virtual fields at the specified 
1517         // position in the path.
1518         cols.expandPath = function(colSpec) {
1519
1520             var ignoreList = [];
1521             if (colSpec.ignore)
1522                 ignoreList = colSpec.ignore.split(' ');
1523
1524             var dotpath = colSpec.path.replace(/\.?\*$/,'');
1525             var class_obj;
1526             var idl_field;
1527
1528             if (colSpec.parentIdlClass) {
1529                 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1530             } else {
1531                 class_obj = egCore.idl.classes[cols.idlClass];
1532             }
1533             var idl_parent = class_obj;
1534             var old_field_label = '';
1535
1536             if (!class_obj) return;
1537
1538             //console.debug('egGrid: auto dotpath is: ' + dotpath);
1539             var path_parts = dotpath.split(/\./);
1540
1541             // find the IDL class definition for the last element in the
1542             // path before the .*
1543             // an empty path_parts means expand the root class
1544             if (path_parts) {
1545                 var old_field;
1546                 for (var path_idx in path_parts) {
1547                     old_field = idl_field;
1548
1549                     var part = path_parts[path_idx];
1550                     idl_field = class_obj.field_map[part];
1551
1552                     // unless we're at the end of the list, this field should
1553                     // link to another class.
1554                     if (idl_field && idl_field['class'] && (
1555                         idl_field.datatype == 'link' || 
1556                         idl_field.datatype == 'org_unit')) {
1557                         if (old_field_label) old_field_label += ' : ';
1558                         old_field_label += idl_field.label;
1559                         class_obj = egCore.idl.classes[idl_field['class']];
1560                         if (old_field) idl_parent = old_field;
1561                     } else {
1562                         if (path_idx < (path_parts.length - 1)) {
1563                             // we ran out of classes to hop through before
1564                             // we ran out of path components
1565                             console.error("egGrid: invalid IDL path: " + dotpath);
1566                         }
1567                     }
1568                 }
1569             }
1570
1571             if (class_obj) {
1572                 angular.forEach(class_obj.fields, function(field) {
1573
1574                     // Only show wildcard fields where we have data to show
1575                     // Virtual and un-fleshed links will not have any data.
1576                     if (field.virtual ||
1577                         (field.datatype == 'link' || field.datatype == 'org_unit') ||
1578                         ignoreList.indexOf(field.name) > -1
1579                     )
1580                         return;
1581
1582                     var col = cols.cloneFromScope(colSpec);
1583                     col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1584
1585                     // log line below is very chatty.  disable until needed.
1586                     // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1587                     cols.add(col, false, true, 
1588                         {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1589                 });
1590
1591                 cols.columns = cols.columns.sort(
1592                     function(a, b) {
1593                         if (a.explicit) return -1;
1594                         if (b.explicit) return 1;
1595
1596                         if (a.idlclass && b.idlclass) {
1597                             if (a.idlclass < b.idlclass) return -1;
1598                             if (b.idlclass < a.idlclass) return 1;
1599                         }
1600
1601                         if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1602                             if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1603                             if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1604                         }
1605
1606                         if (a.label && b.label) {
1607                             if (a.label < b.label) return -1;
1608                             if (b.label < a.label) return 1;
1609                         }
1610
1611                         return a.name < b.name ? -1 : 1;
1612                     }
1613                 );
1614
1615
1616             } else {
1617                 console.error(
1618                     "egGrid: wildcard path does not resolve to an object: "
1619                     + dotpath);
1620             }
1621         }
1622
1623         // angular.clone(scopeObject) is not permittable.  Manually copy
1624         // the fields over that we need (so the scope object can go away).
1625         cols.cloneFromScope = function(colSpec) {
1626             return {
1627                 flesher  : colSpec.flesher,
1628                 comparator  : colSpec.comparator,
1629                 name  : colSpec.name,
1630                 label : colSpec.label,
1631                 path  : colSpec.path,
1632                 align  : colSpec.align || 'left',
1633                 flex  : Number(colSpec.flex) || 2,
1634                 sort  : Number(colSpec.sort) || 0,
1635                 required : colSpec.required,
1636                 linkpath : colSpec.linkpath,
1637                 template : colSpec.template,
1638                 visible  : colSpec.visible,
1639                 compiled : colSpec.compiled,
1640                 handlers : colSpec.handlers,
1641                 hidden   : colSpec.hidden,
1642                 datatype : colSpec.datatype,
1643                 sortable : colSpec.sortable,
1644                 nonsortable      : colSpec.nonsortable,
1645                 multisortable    : colSpec.multisortable,
1646                 nonmultisortable : colSpec.nonmultisortable,
1647                 dateformat       : colSpec.dateformat,
1648                 datecontext      : colSpec.datecontext,
1649                 datefilter      : colSpec.datefilter,
1650                 dateonlyinterval : colSpec.dateonlyinterval,
1651                 parentIdlClass   : colSpec.parentIdlClass
1652             };
1653         }
1654
1655
1656         // Add a column to the columns collection.
1657         // Columns may come from a slim eg-columns-field or 
1658         // directly from the IDL.
1659         cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1660
1661             // First added column with the specified path takes precedence.
1662             // This allows for specific definitions followed by wildcard
1663             // definitions.  If a match is found, back out.
1664             if (cols.columns.filter(function(c) {
1665                 return (c.path == colSpec.path) })[0]) {
1666                 console.debug('skipping pre-existing column ' + colSpec.path);
1667                 return;
1668             }
1669
1670             var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1671
1672             if (column.path && column.path.match(/\*$/)) 
1673                 return cols.expandPath(colSpec);
1674
1675             if (!fromExpand) column.explicit = true;
1676
1677             if (!column.name) column.name = column.path;
1678             if (!column.path) column.path = column.name;
1679
1680             if (column.visible || (!cols.defaultToHidden && !column.hidden))
1681                 column.visible = true;
1682
1683             if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1684                 column.sortable = true;
1685
1686             if (column.multisortable || 
1687                 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1688                 column.multisortable = true;
1689
1690             if (cols.defaultDateFormat && ! column.dateformat) {
1691                 column.dateformat = cols.defaultDateFormat;
1692             }
1693
1694             if (cols.defaultDateOnlyInterval && ! column.dateonlyinterval) {
1695                 column.dateonlyinterval = cols.defaultDateOnlyInterval;
1696             }
1697
1698             if (cols.defaultDateContext && ! column.datecontext) {
1699                 column.datecontext = cols.defaultDateContext;
1700             }
1701
1702             if (cols.defaultDateFilter && ! column.datefilter) {
1703                 column.datefilter = cols.defaultDateFilter;
1704             }
1705
1706             cols.columns.push(column);
1707
1708             // Track which columns are visible by default in case we
1709             // need to reset column visibility
1710             if (column.visible) 
1711                 cols.stockVisible.push(column.name);
1712
1713             if (fromIDL) return; // directly from egIDL.  nothing left to do.
1714
1715             // lookup the matching IDL field
1716             if (!idl_info && cols.idlClass) 
1717                 idl_info = cols.idlFieldFromPath(column.path);
1718
1719             if (!idl_info) {
1720                 // column is not represented within the IDL
1721                 column.adhoc = true; 
1722                 return; 
1723             }
1724
1725             column.datatype = idl_info.idl_field.datatype;
1726             
1727             if (!column.label) {
1728                 column.label = idl_info.idl_field.label || column.name;
1729             }
1730
1731             if (fromExpand && idl_info.idl_class) {
1732                 column.idlclass = '';
1733                 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1734                     column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1735                 } else {
1736                     column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1737                 }
1738             }
1739         },
1740
1741         // finds the IDL field from the dotpath, using the columns
1742         // idlClass as the base.
1743         cols.idlFieldFromPath = function(dotpath) {
1744             var class_obj = egCore.idl.classes[cols.idlClass];
1745             if (!dotpath) return null;
1746
1747             var path_parts = dotpath.split(/\./);
1748
1749             var idl_parent;
1750             var idl_field;
1751             for (var path_idx in path_parts) {
1752                 var part = path_parts[path_idx];
1753                 idl_parent = idl_field;
1754                 idl_field = class_obj.field_map[part];
1755
1756                 if (idl_field) {
1757                     if (idl_field['class'] && (
1758                         idl_field.datatype == 'link' || 
1759                         idl_field.datatype == 'org_unit')) {
1760                         class_obj = egCore.idl.classes[idl_field['class']];
1761                     }
1762                 } else {
1763                     return null;
1764                 }
1765             }
1766
1767             return {
1768                 idl_parent: idl_parent,
1769                 idl_field : idl_field,
1770                 idl_class : class_obj
1771             };
1772         }
1773     }
1774
1775     return {
1776         instance : function(args) { return new ColumnsProvider(args) }
1777     }
1778 }])
1779
1780
1781 /*
1782  * Generic data provider template class.  This is basically an abstract
1783  * class factory service whose instances can be locally modified to 
1784  * meet the needs of each individual grid.
1785  */
1786 .factory('egGridDataProvider', 
1787            ['$q','$timeout','$filter','egCore',
1788     function($q , $timeout , $filter , egCore) {
1789
1790         function GridDataProvider(args) {
1791             var gridData = this;
1792             if (!args) args = {};
1793
1794             gridData.sort = [];
1795             gridData.get = args.get;
1796             gridData.query = args.query;
1797             gridData.idlClass = args.idlClass;
1798             gridData.columnsProvider = args.columnsProvider;
1799
1800             // Delivers a stream of array data via promise.notify()
1801             // Useful for passing an array of data to egGrid.get()
1802             // If a count is provided, the array will be trimmed to
1803             // the range defined by count and offset
1804             gridData.arrayNotifier = function(arr, offset, count) {
1805                 if (!arr || arr.length == 0) return $q.when();
1806
1807                 if (gridData.columnsProvider.clientSort
1808                     && gridData.sort
1809                     && gridData.sort.length > 0
1810                 ) {
1811                     var sorter_cache = [];
1812                     arr.sort(function(a,b) {
1813                         for (var si = 0; si < gridData.sort.length; si++) {
1814                             if (!sorter_cache[si]) { // Build sort structure on first comparison, reuse thereafter
1815                                 var field = gridData.sort[si];
1816                                 var dir = 'asc';
1817
1818                                 if (angular.isObject(field)) {
1819                                     dir = Object.values(field)[0];
1820                                     field = Object.keys(field)[0];
1821                                 }
1822
1823                                 var path = gridData.columnsProvider.findColumn(field).path || field;
1824                                 var comparator = gridData.columnsProvider.findColumn(field).comparator ||
1825                                     function (x,y) { if (x < y) return -1; if (x > y) return 1; return 0 };
1826
1827                                 sorter_cache[si] = {
1828                                     field       : path,
1829                                     dir         : dir,
1830                                     comparator  : comparator
1831                                 };
1832                             }
1833
1834                             var sc = sorter_cache[si];
1835
1836                             var af,bf;
1837
1838                             if (a._isfieldmapper || angular.isFunction(a[sc.field])) {
1839                                 try {af = a[sc.field](); bf = b[sc.field]() } catch (e) {};
1840                             } else {
1841                                 af = a[sc.field]; bf = b[sc.field];
1842                             }
1843                             if (af === undefined && sc.field.indexOf('.') > -1) { // assume an object, not flat path
1844                                 var parts = sc.field.split('.');
1845                                 af = a;
1846                                 bf = b;
1847                                 angular.forEach(parts, function (p) {
1848                                     if (af) {
1849                                         if (af._isfieldmapper || angular.isFunction(af[p])) af = af[p]();
1850                                         else af = af[p];
1851                                     }
1852                                     if (bf) {
1853                                         if (bf._isfieldmapper || angular.isFunction(bf[p])) bf = bf[p]();
1854                                         else bf = bf[p];
1855                                     }
1856                                 });
1857                             }
1858
1859                             if (af === undefined) af = null;
1860                             if (bf === undefined) bf = null;
1861
1862                             if (af === null && bf !== null) return 1;
1863                             if (bf === null && af !== null) return -1;
1864
1865                             if (!(bf === null && af === null)) {
1866                                 var partial = sc.comparator(af,bf);
1867                                 if (partial) {
1868                                     if (sc.dir == 'desc') {
1869                                         if (partial > 0) return -1;
1870                                         return 1;
1871                                     }
1872                                     return partial;
1873                                 }
1874                             }
1875                         }
1876
1877                         return 0;
1878                     });
1879                 }
1880
1881                 if (count) arr = arr.slice(offset, offset + count);
1882                 var def = $q.defer();
1883                 // promise notifications are only witnessed when delivered
1884                 // after the caller has his hands on the promise object
1885                 $timeout(function() {
1886                     angular.forEach(arr, def.notify);
1887                     def.resolve();
1888                 });
1889                 return def.promise;
1890             }
1891
1892             // Calls the grid refresh function.  Once instantiated, the
1893             // grid will replace this function with it's own refresh()
1894             gridData.refresh = function(noReset) { }
1895
1896             if (!gridData.get) {
1897                 // returns a promise whose notify() delivers items
1898                 gridData.get = function(index, count) {
1899                     console.error("egGridDataProvider.get() not implemented");
1900                 }
1901             }
1902
1903             // attempts a flat field lookup first.  If the column is not
1904             // found on the top-level object, attempts a nested lookup
1905             // TODO: consider a caching layer to speed up template 
1906             // rendering, particularly for nested objects?
1907             gridData.itemFieldValue = function(item, column) {
1908                 var val;
1909                 if (column.name in item) {
1910                     if (typeof item[column.name] == 'function') {
1911                         val = item[column.name]();
1912                     } else {
1913                         val = item[column.name];
1914                     }
1915                 } else {
1916                     val = gridData.nestedItemFieldValue(item, column);
1917                 }
1918
1919                 return val;
1920             }
1921
1922             // TODO: deprecate me
1923             gridData.flatItemFieldValue = function(item, column) {
1924                 console.warn('gridData.flatItemFieldValue deprecated; '
1925                     + 'leave provider.itemFieldValue unset');
1926                 return item[column.name];
1927             }
1928
1929             // given an object and a dot-separated path to a field,
1930             // extract the value of the field.  The path can refer
1931             // to function names or object attributes.  If the final
1932             // value is an IDL field, run the value through its
1933             // corresponding output filter.
1934             gridData.nestedItemFieldValue = function(obj, column) {
1935                 item = obj; // keep a copy around
1936
1937                 if (obj === null || obj === undefined || obj === '') return '';
1938                 if (!column.path) return obj;
1939
1940                 var idl_field;
1941                 var parts = column.path.split('.');
1942
1943                 angular.forEach(parts, function(step, idx) {
1944                     // object is not fleshed to the expected extent
1945                     if (typeof obj != 'object') {
1946                         if (typeof obj != 'undefined' && column.flesher) {
1947                             obj = column.flesher(obj, column, item);
1948                         } else {
1949                             obj = '';
1950                             return;
1951                         }
1952                     }
1953
1954                     if (!obj) return '';
1955
1956                     var cls = obj.classname;
1957                     if (cls && (class_obj = egCore.idl.classes[cls])) {
1958                         idl_field = class_obj.field_map[step];
1959                         obj = obj[step] ? obj[step]() : '';
1960                     } else {
1961                         if (angular.isFunction(obj[step])) {
1962                             obj = obj[step]();
1963                         } else {
1964                             obj = obj[step];
1965                         }
1966                     }
1967                 });
1968
1969                 // We found a nested IDL object which may or may not have 
1970                 // been configured as a top-level column.  Grab the datatype.
1971                 if (idl_field && !column.datatype) 
1972                     column.datatype = idl_field.datatype;
1973
1974                 if (obj === null || obj === undefined || obj === '') return '';
1975                 return obj;
1976             }
1977         }
1978
1979         return {
1980             instance : function(args) {
1981                 return new GridDataProvider(args);
1982             }
1983         };
1984     }
1985 ])
1986
1987
1988 // Factory service for egGridDataManager instances, which are
1989 // responsible for collecting flattened grid data.
1990 .factory('egGridFlatDataProvider', 
1991            ['$q','egCore','egGridDataProvider',
1992     function($q , egCore , egGridDataProvider) {
1993
1994         return {
1995             instance : function(args) {
1996                 var provider = egGridDataProvider.instance(args);
1997
1998                 provider.get = function(offset, count) {
1999
2000                     // no query means no call
2001                     if (!provider.query || 
2002                             angular.equals(provider.query, {})) 
2003                         return $q.when();
2004
2005                     // find all of the currently visible columns
2006                     var queryFields = {}
2007                     angular.forEach(provider.columnsProvider.columns, 
2008                         function(col) {
2009                             // only query IDL-tracked columns
2010                             if (!col.adhoc && col.name && col.path && (col.required || col.visible))
2011                                 queryFields[col.name] = col.path;
2012                         }
2013                     );
2014
2015                     return egCore.net.request(
2016                         'open-ils.fielder',
2017                         'open-ils.fielder.flattened_search',
2018                         egCore.auth.token(), provider.idlClass, 
2019                         queryFields, provider.query,
2020                         {   sort : provider.sort,
2021                             limit : count,
2022                             offset : offset
2023                         }
2024                     );
2025                 }
2026                 //provider.itemFieldValue = provider.flatItemFieldValue;
2027                 return provider;
2028             }
2029         };
2030     }
2031 ])
2032
2033 .directive('egGridColumnDragSource', function() {
2034     return {
2035         restrict : 'A',
2036         require : '^egGrid',
2037         link : function(scope, element, attrs, egGridCtrl) {
2038             angular.element(element).attr('draggable', 'true');
2039
2040             element.bind('dragstart', function(e) {
2041                 egGridCtrl.dragColumn = attrs.column;
2042                 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
2043                 egGridCtrl.colResizeDir = 0;
2044
2045                 if (egGridCtrl.dragType == 'move') {
2046                     // style the column getting moved
2047                     angular.element(e.target).addClass(
2048                         'eg-grid-column-move-handle-active');
2049                 }
2050             });
2051
2052             element.bind('dragend', function(e) {
2053                 if (egGridCtrl.dragType == 'move') {
2054                     angular.element(e.target).removeClass(
2055                         'eg-grid-column-move-handle-active');
2056                 }
2057             });
2058         }
2059     };
2060 })
2061
2062 .directive('egGridColumnDragDest', function() {
2063     return {
2064         restrict : 'A',
2065         require : '^egGrid',
2066         link : function(scope, element, attrs, egGridCtrl) {
2067
2068             element.bind('dragover', function(e) { // required for drop
2069                 e.stopPropagation();
2070                 e.preventDefault();
2071                 e.dataTransfer.dropEffect = 'move';
2072
2073                 if (egGridCtrl.colResizeDir == 0) return; // move
2074
2075                 var cols = egGridCtrl.columnsProvider;
2076                 var srcCol = egGridCtrl.dragColumn;
2077                 var srcColIdx = cols.indexOf(srcCol);
2078
2079                 if (egGridCtrl.colResizeDir == -1) {
2080                     if (cols.indexOf(attrs.column) <= srcColIdx) {
2081                         egGridCtrl.modifyColumnFlex(
2082                             egGridCtrl.columnsProvider.findColumn(
2083                                 egGridCtrl.dragColumn), -1);
2084                         if (cols.columns[srcColIdx+1]) {
2085                             // source column shrinks by one, column to the
2086                             // right grows by one.
2087                             egGridCtrl.modifyColumnFlex(
2088                                 cols.columns[srcColIdx+1], 1);
2089                         }
2090                         scope.$apply();
2091                     }
2092                 } else {
2093                     if (cols.indexOf(attrs.column) > srcColIdx) {
2094                         egGridCtrl.modifyColumnFlex( 
2095                             egGridCtrl.columnsProvider.findColumn(
2096                                 egGridCtrl.dragColumn), 1);
2097                         if (cols.columns[srcColIdx+1]) {
2098                             // source column grows by one, column to the 
2099                             // right grows by one.
2100                             egGridCtrl.modifyColumnFlex(
2101                                 cols.columns[srcColIdx+1], -1);
2102                         }
2103
2104                         scope.$apply();
2105                     }
2106                 }
2107             });
2108
2109             element.bind('dragenter', function(e) {
2110                 e.stopPropagation();
2111                 e.preventDefault();
2112                 if (egGridCtrl.dragType == 'move') {
2113                     angular.element(e.target).addClass('eg-grid-col-hover');
2114                 } else {
2115                     // resize grips are on the right side of each column.
2116                     // dragenter will either occur on the source column 
2117                     // (dragging left) or the column to the right.
2118                     if (egGridCtrl.colResizeDir == 0) {
2119                         if (egGridCtrl.dragColumn == attrs.column) {
2120                             egGridCtrl.colResizeDir = -1; // west
2121                         } else {
2122                             egGridCtrl.colResizeDir = 1; // east
2123                         }
2124                     }
2125                 }
2126             });
2127
2128             element.bind('dragleave', function(e) {
2129                 e.stopPropagation();
2130                 e.preventDefault();
2131                 if (egGridCtrl.dragType == 'move') {
2132                     angular.element(e.target).removeClass('eg-grid-col-hover');
2133                 }
2134             });
2135
2136             element.bind('drop', function(e) {
2137                 e.stopPropagation();
2138                 e.preventDefault();
2139                 egGridCtrl.colResizeDir = 0;
2140                 if (egGridCtrl.dragType == 'move') {
2141                     angular.element(e.target).removeClass('eg-grid-col-hover');
2142                     egGridCtrl.onColumnDrop(attrs.column); // move the column
2143                 }
2144             });
2145         }
2146     };
2147 })
2148  
2149 .directive('egGridMenuItem', function() {
2150     return {
2151         restrict : 'AE',
2152         require : '^egGrid',
2153         scope : {
2154             label : '@',  
2155             checkbox : '@',  
2156             checked : '=',  
2157             standalone : '=',  
2158             handler : '=', // onclick handler function
2159             divider : '=', // if true, show a divider only
2160             handlerData : '=', // if set, passed as second argument to handler
2161             disabled : '=', // function
2162             hidden : '=' // function
2163         },
2164         link : function(scope, element, attrs, egGridCtrl) {
2165             egGridCtrl.addMenuItem({
2166                 checkbox : scope.checkbox,
2167                 checked : scope.checked ? true : false,
2168                 label : scope.label,
2169                 standalone : scope.standalone ? true : false,
2170                 handler : scope.handler,
2171                 divider : scope.divider,
2172                 disabled : scope.disabled,
2173                 hidden : scope.hidden,
2174                 handlerData : scope.handlerData
2175             });
2176             scope.$destroy();
2177         }
2178     };
2179 })
2180
2181 /* https://stackoverflow.com/questions/17343696/adding-an-ng-click-event-inside-a-filter/17344875#17344875 */
2182 .directive('compile', ['$compile', function ($compile) {
2183     return function(scope, element, attrs) {
2184       // pass through column defs from grid cell's scope
2185       scope.col = scope.$parent.col;
2186       scope.$watch(
2187         function(scope) {
2188           // watch the 'compile' expression for changes
2189           return scope.$eval(attrs.compile);
2190         },
2191         function(value) {
2192           // when the 'compile' expression changes
2193           // assign it into the current DOM
2194           element.html(value);
2195
2196           // compile the new DOM and link it to the current
2197           // scope.
2198           // NOTE: we only compile .childNodes so that
2199           // we don't get into infinite loop compiling ourselves
2200           $compile(element.contents())(scope);
2201         }
2202     );
2203   };
2204 }])
2205
2206
2207
2208 /**
2209  * Translates bare IDL object values into display values.
2210  * 1. Passes dates through the angular date filter
2211  * 2. Converts bools to translated Yes/No strings
2212  * Others likely to follow...
2213  */
2214 .filter('egGridValueFilter', ['$filter','egCore', 'egStrings', function($filter,egCore,egStrings) {
2215     function traversePath(obj,path) {
2216         var list = path.split('.');
2217         for (var part in path) {
2218             if (obj[path]) obj = obj[path]
2219             else return null;
2220         }
2221         return obj;
2222     }
2223
2224     var GVF = function(value, column, item) {
2225         switch(column.datatype) {
2226             case 'bool':
2227                 switch(value) {
2228                     // Browser will translate true/false for us
2229                     case 't' : 
2230                     case '1' :  // legacy
2231                     case true:
2232                         return egStrings.YES;
2233                     case 'f' : 
2234                     case '0' :  // legacy
2235                     case false:
2236                         return egStrings.NO;
2237                     // value may be null,  '', etc.
2238                     default : return '';
2239                 }
2240             case 'timestamp':
2241                 var interval = angular.isFunction(item[column.dateonlyinterval])
2242                     ? item[column.dateonlyinterval]()
2243                     : item[column.dateonlyinterval];
2244
2245                 if (column.dateonlyinterval && !interval) // try it as a dotted path
2246                     interval = traversePath(item, column.dateonlyinterval);
2247
2248                 var context = angular.isFunction(item[column.datecontext])
2249                     ? item[column.datecontext]()
2250                     : item[column.datecontext];
2251
2252                 if (column.datecontext && !context) // try it as a dotted path
2253                     context = traversePath(item, column.datecontext);
2254
2255                 var date_filter = column.datefilter || 'egOrgDateInContext';
2256
2257                 return $filter(date_filter)(value, column.dateformat, context, interval);
2258             case 'money':
2259                 return $filter('currency')(value);
2260             default:
2261                 return value;
2262         }
2263     };
2264
2265     GVF.$stateful = true;
2266     return GVF;
2267 }]);
2268