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