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