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