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