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