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