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