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