]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/grid.js
LP#1805895 Bucket grid configuration updates do not save
[Evergreen.git] / Open-ILS / web / js / ui / default / staff / services / grid.js
1 angular.module('egGridMod', 
2     ['egCoreMod', 'egUiMod', 'ui.bootstrap'])
3
4 .directive('egGrid', function() {
5     return {
6         restrict : 'AE',
7         transclude : true,
8         scope : {
9
10             // IDL class hint (e.g. "aou")
11             idlClass : '@',
12
13             // default page size
14             pageSize : '@',
15
16             // if true, grid columns are derived from all non-virtual
17             // fields on the base idlClass
18             autoFields : '@',
19
20             // grid preferences will be stored / retrieved with this key
21             persistKey : '@',
22
23             // field whose value is unique and may be used for item
24             // reference / lookup.  This will usually be someting like
25             // "id".  This is not needed when using autoFields, since we
26             // can determine the primary key directly from the IDL.
27             idField : '@',
28
29             // Reference to externally provided egGridDataProvider
30             itemsProvider : '=',
31
32             // Reference to externally provided item-selection handler
33             onSelect : '=',
34
35             // Reference to externally provided after-item-selection handler
36             afterSelect : '=',
37
38             // comma-separated list of supported or disabled grid features
39             // supported features:
40             //  startSelected : init the grid with all rows selected by default
41             //  allowAll : add an "All" option to row count (really 10000)
42             //  -menu : don't show any menu buttons (or use space for them)
43             //  -picker : don't show the column picker
44             //  -pagination : don't show any pagination elements, and set
45             //                the limit to 10000
46             //  -actions : don't show the actions dropdown
47             //  -index : don't show the row index column (can't use "index"
48             //           as the idField in this case)
49             //  -display : columns are hidden by default
50             //  -sort    : columns are unsortable by default 
51             //  -multisort : sort priorities config disabled by default
52             //  -multiselect : only one row at a time can be selected;
53             //                 choosing this also disables the checkbox
54             //                 column
55             features : '@',
56
57             // optional: object containing function to conditionally apply
58             //    class to each row.
59             rowClass : '=',
60
61             // optional: object that enables status icon field and contains
62             //    function to handle what status icons should exist and why.
63             statusColumn : '=',
64
65             // optional primary grid label
66             mainLabel : '@',
67
68             // if true, use the IDL class label as the mainLabel
69             autoLabel : '=', 
70
71             // optional context menu label
72             menuLabel : '@',
73
74             dateformat : '@', // optional: passed down to egGridValueFilter
75             datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
76             datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
77             dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
78
79             // Hash of control functions.
80             //
81             //  These functions are defined by the calling scope and 
82             //  invoked as-is by the grid w/ the specified parameters.
83             //
84             //  collectStarted    : function() {}
85             //  itemRetrieved     : function(item) {}
86             //  allItemsRetrieved : function() {}
87             //
88             //  ---
89             //  If defined, the grid will watch the return value from
90             //  the function defined at watchQuery on each digest and 
91             //  re-draw the grid when query changes occur.
92             //
93             //  watchQuery : function() { /* return grid query */ }
94             //
95             //  ---------------
96             //  These functions are defined by the grid and thus
97             //  replace any values defined for these attributes from the
98             //  calling scope.
99             //
100             //  activateItem  : function(item) {}
101             //  allItems      : function(allItems) {}
102             //  selectedItems : function(selected) {}
103             //  selectItems   : function(ids) {}
104             //  setQuery      : function(queryStruct) {} // causes reload
105             //  setSort       : function(sortSturct) {} // causes reload
106             gridControls : '=',
107         },
108
109         // TODO: avoid hard-coded url
110         templateUrl : '/eg/staff/share/t_autogrid', 
111
112         link : function(scope, element, attrs) {     
113
114             // Give the grid config loading steps time to fetch the 
115             // workstation setting and apply columns before loading data.
116             var loadPromise = scope.configLoadPromise || $q.when();
117             loadPromise.then(function() {
118
119                 // load auto fields after eg-grid-field's so they are not clobbered
120                 scope.handleAutoFields();
121                 scope.collect();
122
123                 scope.grid_element = element;
124
125                 if(!attrs.id){
126                     $(element).attr('id', attrs.persistKey);
127                 }
128
129                 $(element)
130                     .find('.eg-grid-content-body')
131                     .bind('contextmenu', scope.showActionContextMenu);
132             });
133         },
134
135         controller : [
136                     '$scope','$q','egCore','egGridFlatDataProvider','$location',
137                     'egGridColumnsProvider','$filter','$window','$sce','$timeout',
138                     'egProgressDialog','$uibModal','egConfirmDialog','egStrings',
139             function($scope,  $q , egCore,  egGridFlatDataProvider , $location,
140                      egGridColumnsProvider , $filter , $window , $sce , $timeout,
141                      egProgressDialog,  $uibModal , egConfirmDialog , egStrings) {
142
143             var grid = this;
144
145             grid.init = function() {
146                 grid.offset = 0;
147                 $scope.items = [];
148                 $scope.showGridConf = false;
149                 grid.totalCount = -1;
150                 $scope.selected = {};
151                 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
152                 $scope.menuItems = []; // global actions
153
154                 // returns true if any rows are selected.
155                 $scope.hasSelected = function() {
156                     return grid.getSelectedItems().length > 0 };
157
158                 var features = ($scope.features) ? 
159                     $scope.features.split(',') : [];
160                 delete $scope.features;
161
162                 $scope.showIndex = (features.indexOf('-index') == -1);
163
164                 $scope.allowAll = (features.indexOf('allowAll') > -1);
165                 $scope.startSelected = $scope.selectAll = (features.indexOf('startSelected') > -1);
166                 $scope.showActions = (features.indexOf('-actions') == -1);
167                 $scope.showPagination = (features.indexOf('-pagination') == -1);
168                 $scope.showPicker = (features.indexOf('-picker') == -1);
169
170                 $scope.showMenu = (features.indexOf('-menu') == -1);
171
172                 // remove some unneeded values from the scope to reduce bloat
173
174                 grid.idlClass = $scope.idlClass;
175                 delete $scope.idlClass;
176
177                 grid.persistKey = $scope.persistKey;
178                 delete $scope.persistKey;
179
180                 var stored_limit = 0;
181                 if ($scope.showPagination) {
182                     // localStorage of grid limits is deprecated. Limits 
183                     // are now stored along with the columns configuration.  
184                     // Values found in localStorage will be migrated upon 
185                     // config save.
186                     if (grid.persistKey) {
187                         var stored_limit = Number(
188                             egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
189                         );
190                     }
191                 } else {
192                     stored_limit = 10000; // maybe support "Inf"?
193                 }
194
195                 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
196
197                 grid.indexField = $scope.idField;
198                 delete $scope.idField;
199
200                 grid.dataProvider = $scope.itemsProvider;
201
202                 if (!grid.indexField && grid.idlClass)
203                     grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
204
205                 grid.columnsProvider = egGridColumnsProvider.instance({
206                     idlClass : grid.idlClass,
207                     clientSort : (features.indexOf('clientsort') > -1 && features.indexOf('-clientsort') == -1),
208                     defaultToHidden : (features.indexOf('-display') > -1),
209                     defaultToNoSort : (features.indexOf('-sort') > -1),
210                     defaultToNoMultiSort : (features.indexOf('-multisort') > -1),
211                     defaultDateFormat : $scope.dateformat,
212                     defaultDateContext : $scope.datecontext,
213                     defaultDateFilter : $scope.datefilter,
214                     defaultDateOnlyInterval : $scope.dateonlyinterval
215                 });
216                 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
217
218                 $scope.handleAutoFields = function() {
219                     if ($scope.autoFields) {
220                         if (grid.autoLabel) {
221                             $scope.mainLabel = 
222                                 egCore.idl.classes[grid.idlClass].label;
223                         }
224                         grid.columnsProvider.compileAutoColumns();
225                         delete $scope.autoFields;
226                     }
227                 }
228    
229                 if (!grid.dataProvider) {
230                     // no provider, um, provided.
231                     // Use a flat data provider
232
233                     grid.selfManagedData = true;
234                     grid.dataProvider = egGridFlatDataProvider.instance({
235                         indexField : grid.indexField,
236                         idlClass : grid.idlClass,
237                         columnsProvider : grid.columnsProvider,
238                         query : $scope.query
239                     });
240                 }
241
242                 // make grid ref available in get() to set totalCount, if known.
243                 // this allows us disable the 'next' paging button correctly
244                 grid.dataProvider.grid = grid;
245
246                 grid.dataProvider.columnsProvider = grid.columnsProvider;
247
248                 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
249                 $scope.indexValue = function(item) {
250                     return grid.indexValue(item)
251                 };
252
253                 grid.applyControlFunctions();
254
255                 $scope.configLoadPromise = grid.loadConfig().then(function() { 
256                     // link columns to scope after loadConfig(), since it
257                     // replaces the columns array.
258                     $scope.columns = grid.columnsProvider.columns;
259                 });
260
261                 // NOTE: grid.collect() is first called from link(), not here.
262             }
263
264             // link our control functions into the gridControls 
265             // scope object so the caller can access them.
266             grid.applyControlFunctions = function() {
267
268                 // we use some of these controls internally, so sett
269                 // them up even if the caller doesn't request them.
270                 var controls = $scope.gridControls || {};
271
272                 controls.columnMap = function() {
273                     var m = {};
274                     angular.forEach(grid.columnsProvider.columns, function (c) {
275                         m[c.name] = c;
276                     });
277                     return m;
278                 }
279
280                 controls.columnsProvider = function() {
281                     return grid.columnsProvider;
282                 }
283
284                 // link in the control functions
285                 controls.selectedItems = function() {
286                     return grid.getSelectedItems()
287                 }
288
289                 controls.selectItemsByValue = function(c,v) {
290                     return grid.selectItemsByValue(c,v)
291                 }
292
293                 controls.allItems = function() {
294                     return $scope.items;
295                 }
296
297                 controls.selectItems = function(ids) {
298                     if (!ids) return;
299                     $scope.selected = {};
300                     angular.forEach(ids, function(i) {
301                         $scope.selected[''+i] = true;
302                     });
303                 }
304
305                 // if the caller provided a functional setQuery,
306                 // extract the value before replacing it
307                 if (controls.setQuery) {
308                     grid.dataProvider.query = 
309                         controls.setQuery();
310                 }
311
312                 controls.setQuery = function(query) {
313                     grid.dataProvider.query = query;
314                     controls.refresh();
315                 }
316
317                 if (controls.watchQuery) {
318                     // capture the initial query value
319                     grid.dataProvider.query = controls.watchQuery();
320
321                     // watch for changes
322                     $scope.gridWatchQuery = controls.watchQuery;
323                     $scope.$watch('gridWatchQuery()', function(newv) {
324                         controls.setQuery(newv);
325                     }, true);
326                 }
327
328                 // if the caller provided a functional setSort
329                 // extract the value before replacing it
330                 grid.dataProvider.sort = 
331                     controls.setSort ?  controls.setSort() : [];
332
333                 controls.setSort = function(sort) {
334                     controls.refresh();
335                 }
336
337                 controls.refresh = function(noReset) {
338                     if (!noReset) grid.offset = 0;
339                     grid.collect();
340                 }
341
342                 controls.prepend = function(limit) {
343                     grid.prepend(limit);
344                 }
345
346                 controls.setLimit = function(limit,forget) {
347                     grid.limit = limit;
348                     if (!forget && grid.persistKey) {
349                         $scope.saveConfig();
350                     }
351                 }
352                 controls.getLimit = function() {
353                     return grid.limit;
354                 }
355                 controls.setOffset = function(offset) {
356                     grid.offset = offset;
357                 }
358                 controls.getOffset = function() {
359                     return grid.offset;
360                 }
361
362                 controls.saveConfig = function () {
363                     return $scope.saveConfig();
364                 }
365
366                 grid.dataProvider.refresh = controls.refresh;
367                 grid.dataProvider.prepend = controls.prepend;
368                 grid.controls = controls;
369             }
370
371             // If a menu item provides its own HTML template, translate it,
372             // using the menu item for the template scope.
373             // note: $sce is required to avoid security restrictions and
374             // is OK here, since the template comes directly from a
375             // local HTML template (not user input).
376             $scope.translateMenuItemTemplate = function(item) {
377                 var html = egCore.strings.$replace(item.template, {item : item});
378                 return $sce.trustAsHtml(html);
379             }
380
381             // add a new (global) grid menu item
382             grid.addMenuItem = function(item) {
383                 $scope.menuItems.push(item);
384                 var handler = item.handler;
385                 item.handler = function() {
386                     $scope.gridMenuIsOpen = false; // close menu
387                     if (handler) {
388                         handler(item, 
389                             item.handlerData, grid.getSelectedItems());
390                     }
391                 }
392             }
393
394             // add a selected-items action
395             grid.addAction = function(act) {
396                 var done = false;
397                 $scope.actionGroups.forEach(function(g){
398                     if (g.label === act.group) {
399                         g.actions.push(act);
400                         done = true;
401                     }
402                 });
403                 if (!done) {
404                     $scope.actionGroups.push({
405                         label : act.group,
406                         actions : [ act ]
407                     });
408                 }
409             }
410
411             // remove the stored column configuration preferenc, then recover 
412             // the column visibility information from the initial page load.
413             $scope.resetColumns = function() {
414                 $scope.gridColumnPickerIsOpen = false;
415                 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
416                 .then(function() {
417                     grid.columnsProvider.reset(); 
418                     if (grid.selfManagedData) grid.collect();
419                 });
420             }
421
422             $scope.showAllColumns = function() {
423                 $scope.gridColumnPickerIsOpen = false;
424                 grid.columnsProvider.showAllColumns();
425                 if (grid.selfManagedData) grid.collect();
426             }
427
428             $scope.hideAllColumns = function() {
429                 $scope.gridColumnPickerIsOpen = false;
430                 grid.columnsProvider.hideAllColumns();
431                 // note: no need to fetch new data if no columns are visible
432             }
433
434             $scope.toggleColumnVisibility = function(col) {
435                 $scope.gridColumnPickerIsOpen = false;
436                 col.visible = !col.visible;
437
438                 // egGridFlatDataProvider only retrieves data to be
439                 // displayed.  When column visibility changes, it's
440                 // necessary to fetch the newly visible column data.
441                 if (grid.selfManagedData) grid.collect();
442             }
443
444             // save the columns configuration (position, sort, width) to
445             // eg.grid.<persist-key>
446             $scope.saveConfig = function() {
447                 $scope.gridColumnPickerIsOpen = false;
448
449                 if (!grid.persistKey) {
450                     console.warn(
451                         "Cannot save settings without a grid persist-key");
452                     return;
453                 }
454
455                 // only store information about visible columns.
456                 var cols = grid.columnsProvider.columns.filter(
457                     function(col) {return Boolean(col.visible) });
458
459                 // now scrunch the data down to just the needed info
460                 cols = cols.map(function(col) {
461                     var c = {name : col.name}
462                     // Apart from the name, only store non-default values.
463                     // No need to store col.visible, since that's implicit
464                     if (col.align != 'left') c.align = col.align;
465                     if (col.flex != 2) c.flex = col.flex;
466                     if (Number(col.sort)) c.sort = Number(c.sort);
467                     return c;
468                 });
469
470                 var conf = {
471                     version: 2,
472                     limit: grid.limit,
473                     columns: cols
474                 };
475
476                 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
477                 .then(function() { 
478                     // Save operation performed from the grid configuration UI.
479                     // Hide the configuration UI and re-draw w/ sort applied
480                     if ($scope.showGridConf) 
481                         $scope.toggleConfDisplay();
482
483                     // Once a version-2 grid config is saved (with limit
484                     // included) we can remove the local limit pref.
485                     egCore.hatch.removeLocalItem(
486                         'eg.grid.' + grid.persistKey + '.limit');
487                 });
488             }
489
490
491             // load the columns configuration (position, sort, width) from
492             // eg.grid.<persist-key> and apply the loaded settings to the
493             // columns on our columnsProvider
494             grid.loadConfig = function() {
495                 if (!grid.persistKey) return $q.when();
496
497                 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
498                 .then(function(conf) {
499                     if (!conf) return;
500
501                     // 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                                 $uibModalInstance.close()
1219                             }
1220                         }
1221                     ]
1222                 });
1223             },
1224
1225             // generates CSV for the currently visible grid contents
1226             grid.generateCSV = function() {
1227                 return grid.getAllItemsAsText().then(function(text_items) {
1228                     var columns = text_items.columns;
1229                     var items = text_items.items;
1230                     var csvStr = '';
1231
1232                     // column headers
1233                     angular.forEach(columns, function(col) {
1234                         csvStr += grid.csvDatum(col.label);
1235                         csvStr += ',';
1236                     });
1237
1238                     csvStr = csvStr.replace(/,$/,'\n');
1239
1240                     // items
1241                     angular.forEach(items, function(item) {
1242                         angular.forEach(columns, function(col) {
1243                             csvStr += grid.csvDatum(item[col.name]);
1244                             csvStr += ',';
1245                         });
1246                         csvStr = csvStr.replace(/,$/,'\n');
1247                     });
1248
1249                     return csvStr;
1250                 });
1251             }
1252
1253             // Interpolate the value for column.linkpath within the context
1254             // of the row item to generate the final link URL.
1255             $scope.generateLinkPath = function(col, item) {
1256                 return egCore.strings.$replace(col.linkpath, {item : item});
1257             }
1258
1259             // If a column provides its own HTML template, translate it,
1260             // using the current item for the template scope.
1261             // note: $sce is required to avoid security restrictions and
1262             // is OK here, since the template comes directly from a
1263             // local HTML template (not user input).
1264             $scope.translateCellTemplate = function(col, item) {
1265                 var html = egCore.strings.$replace(col.template, {item : item});
1266                 return $sce.trustAsHtml(html);
1267             }
1268
1269             $scope.collect = function() { grid.collect() }
1270
1271
1272             $scope.confirmAllowAllAndCollect = function(){
1273                 egConfirmDialog.open(egStrings.CONFIRM_LONG_RUNNING_ACTION_ALL_ROWS_TITLE,
1274                     egStrings.CONFIRM_LONG_RUNNING_ACTION_MSG)
1275                     .result
1276                     .then(function(){
1277                         $scope.offset(0);
1278                         $scope.limit(10000);
1279                         grid.collect();
1280                 });
1281             }
1282
1283             // asks the dataProvider for a page of data
1284             grid.collect = function() {
1285
1286                 // avoid firing the collect if there is nothing to collect.
1287                 if (grid.selfManagedData && !grid.dataProvider.query) return;
1288
1289                 if (grid.collecting) return; // avoid parallel collect()
1290                 grid.collecting = true;
1291
1292                 console.debug('egGrid.collect() offset=' 
1293                     + grid.offset + '; limit=' + grid.limit);
1294
1295                 // ensure all of our dropdowns are closed
1296                 // TODO: git rid of these and just use dropdown-toggle, 
1297                 // which is more reliable.
1298                 $scope.gridColumnPickerIsOpen = false;
1299                 $scope.gridRowCountIsOpen = false;
1300                 $scope.gridPageSelectIsOpen = false;
1301
1302                 $scope.items = [];
1303                 $scope.selected = {};
1304
1305                 // Inform the caller we've asked the data provider
1306                 // for data.  This is useful for knowing when collection
1307                 // has started (e.g. to display a progress dialg) when 
1308                 // using the stock (flattener) data provider, where the 
1309                 // user is not directly defining a get() handler.
1310                 if (grid.controls.collectStarted)
1311                     grid.controls.collectStarted(grid.offset, grid.limit);
1312
1313                 grid.dataProvider.get(grid.offset, grid.limit).then(
1314                 function() {
1315                     if (grid.controls.allItemsRetrieved)
1316                         grid.controls.allItemsRetrieved();
1317                 },
1318                 null, 
1319                 function(item) {
1320                     if (item) {
1321                         $scope.items.push(item)
1322                         if (grid.controls.itemRetrieved)
1323                             grid.controls.itemRetrieved(item);
1324                         if ($scope.selectAll)
1325                             $scope.selected[grid.indexValue(item)] = true
1326                     }
1327                 }).finally(function() { 
1328                     console.debug('egGrid.collect() complete');
1329                     grid.collecting = false 
1330                     $scope.selected = angular.copy($scope.selected);
1331                 });
1332             }
1333
1334             grid.prepend = function(limit) {
1335                 var ran_into_duplicate = false;
1336                 var sort = grid.dataProvider.sort;
1337                 if (sort && sort.length) {
1338                     // If sorting is in effect, we have no way
1339                     // of knowing that the new item should be
1340                     // visible _if the sort order is retained_.
1341                     // However, since the grids that do prepending in
1342                     // the first place are ones where we always
1343                     // want the new row to show up on top, we'll
1344                     // remove the current sort options.
1345                     grid.dataProvider.sort = [];
1346                 }
1347                 if (grid.offset > 0) {
1348                     // if we're prepending, we're forcing the
1349                     // offset back to zero to display the top
1350                     // of the list
1351                     grid.offset = 0;
1352                     grid.collect();
1353                     return;
1354                 }
1355                 if (grid.collecting) return; // avoid parallel collect() or prepend()
1356                 grid.collecting = true;
1357                 console.debug('egGrid.prepend() starting');
1358                 // Note that we can count on the most-recently added
1359                 // item being at offset 0 in the data provider only
1360                 // for arrayNotifier data sources that do not have
1361                 // sort options currently set.
1362                 grid.dataProvider.get(0, 1).then(
1363                 null,
1364                 null,
1365                 function(item) {
1366                     if (item) {
1367                         var newIdx = grid.indexValue(item);
1368                         angular.forEach($scope.items, function(existing) {
1369                             if (grid.indexValue(existing) == newIdx) {
1370                                 console.debug('egGrid.prepend(): refusing to add duplicate item ' + newIdx);
1371                                 ran_into_duplicate = true;
1372                                 return;
1373                             }
1374                         });
1375                         $scope.items.unshift(item);
1376                         if (limit && $scope.items.length > limit) {
1377                             // this accommodates the checkin grid that
1378                             // allows the user to set a definite limit
1379                             // without requiring that entire collect()
1380                             $scope.items.length = limit;
1381                         }
1382                         if ($scope.items.length > grid.limit) {
1383                             $scope.items.length = grid.limit;
1384                         }
1385                         if (grid.controls.itemRetrieved)
1386                             grid.controls.itemRetrieved(item);
1387                         if ($scope.selectAll)
1388                             $scope.selected[grid.indexValue(item)] = true
1389                     }
1390                 }).finally(function() {
1391                     console.debug('egGrid.prepend() complete');
1392                     grid.collecting = false;
1393                     $scope.selected = angular.copy($scope.selected);
1394                     if (ran_into_duplicate) {
1395                         grid.collect();
1396                     }
1397                 });
1398             }
1399
1400             grid.init();
1401         }]
1402     };
1403 })
1404
1405 /**
1406  * eg-grid-field : used for collecting custom field data from the templates.
1407  * This directive does not direct display, it just passes data up to the 
1408  * parent grid.
1409  */
1410 .directive('egGridField', function() {
1411     return {
1412         require : '^egGrid',
1413         restrict : 'AE',
1414         scope : {
1415             flesher: '=', // optional; function that can flesh a linked field, given the value
1416             comparator: '=', // optional; function that can sort the thing at the end of 'path' 
1417             name  : '@', // required; unique name
1418             path  : '@', // optional; flesh path
1419             ignore: '@', // optional; fields to ignore when path is a wildcard
1420             label : '@', // optional; display label
1421             flex  : '@',  // optional; default flex width
1422             align  : '@',  // optional; default alignment, left/center/right
1423             dateformat : '@', // optional: passed down to egGridValueFilter
1424             datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
1425             datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
1426             dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
1427
1428             // if a field is part of an IDL object, but we are unable to
1429             // determine the class, because it's nested within a hash
1430             // (i.e. we can't navigate directly to the object via the IDL),
1431             // idlClass lets us specify the class.  This is particularly
1432             // useful for nested wildcard fields.
1433             parentIdlClass : '@', 
1434
1435             // optional: for non-IDL columns, specifying a datatype
1436             // lets the caller control which display filter is used.
1437             // datatype should match the standard IDL datatypes.
1438             datatype : '@',
1439
1440             // optional hash of functions that can be imported into
1441             // the directive's scope; meant for cases where the "compiled"
1442             // attribute is set
1443             handlers : '=',
1444
1445             // optional: CSS class name that we want to have for this field.
1446             // Auto generated from path if nothing is passed in via eg-grid-field declaration
1447             cssSelector : "@"
1448         },
1449         link : function(scope, element, attrs, egGridCtrl) {
1450
1451             // boolean fields are presented as value-less attributes
1452             angular.forEach(
1453                 [
1454                     'visible', 
1455                     'compiled', 
1456                     'hidden', 
1457                     'sortable', 
1458                     'nonsortable',
1459                     'multisortable',
1460                     'nonmultisortable',
1461                     'required' // if set, always fetch data for this column
1462                 ],
1463                 function(field) {
1464                     if (angular.isDefined(attrs[field]))
1465                         scope[field] = true;
1466                 }
1467             );
1468
1469             scope.cssSelector = attrs['cssSelector'] ? attrs['cssSelector'] : "";
1470
1471             // auto-generate CSS selector name for field if none declared in tt2 and there's a path
1472             if (scope.path && !scope.cssSelector){
1473                 var cssClass = 'grid' + "." + scope.path;
1474                 cssClass = cssClass.replace(/\./g,'-');
1475                 element.addClass(cssClass);
1476                 scope.cssSelector = cssClass;
1477             }
1478
1479             // any HTML content within the field is its custom template
1480             var tmpl = element.html();
1481             if (tmpl && !tmpl.match(/^\s*$/))
1482                 scope.template = tmpl
1483
1484             egGridCtrl.columnsProvider.add(scope);
1485             scope.$destroy();
1486         }
1487     };
1488 })
1489
1490 /**
1491  * eg-grid-action : used for specifying actions which may be applied
1492  * to items within the grid.
1493  */
1494 .directive('egGridAction', function() {
1495     return {
1496         require : '^egGrid',
1497         restrict : 'AE',
1498         transclude : true,
1499         scope : {
1500             group   : '@', // Action group, ungrouped if not set
1501             label   : '@', // Action label
1502             handler : '=',  // Action function handler
1503             hide    : '=',
1504             disabled : '=', // function
1505             divider : '='
1506         },
1507         link : function(scope, element, attrs, egGridCtrl) {
1508             egGridCtrl.addAction({
1509                 hide  : scope.hide,
1510                 group : scope.group,
1511                 label : scope.label,
1512                 divider : scope.divider,
1513                 handler : scope.handler,
1514                 disabled : scope.disabled,
1515             });
1516             scope.$destroy();
1517         }
1518     };
1519 })
1520
1521 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1522
1523     function ColumnsProvider(args) {
1524         var cols = this;
1525         cols.columns = [];
1526         cols.stockVisible = [];
1527         cols.idlClass = args.idlClass;
1528         cols.clientSort = args.clientSort;
1529         cols.defaultToHidden = args.defaultToHidden;
1530         cols.defaultToNoSort = args.defaultToNoSort;
1531         cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1532         cols.defaultDateFormat = args.defaultDateFormat;
1533         cols.defaultDateContext = args.defaultDateContext;
1534
1535         // resets column width, visibility, and sort behavior
1536         // Visibility resets to the visibility settings defined in the 
1537         // template (i.e. the original egGridField values).
1538         cols.reset = function() {
1539             angular.forEach(cols.columns, function(col) {
1540                 col.align = 'left';
1541                 col.flex = 2;
1542                 col.sort = 0;
1543                 if (cols.stockVisible.indexOf(col.name) > -1) {
1544                     col.visible = true;
1545                 } else {
1546                     col.visible = false;
1547                 }
1548             });
1549         }
1550
1551         // returns true if any columns are sortable
1552         cols.hasSortableColumn = function() {
1553             return cols.columns.filter(
1554                 function(col) {
1555                     return col.sortable || col.multisortable;
1556                 }
1557             ).length > 0;
1558         }
1559
1560         cols.showAllColumns = function() {
1561             angular.forEach(cols.columns, function(column) {
1562                 column.visible = true;
1563             });
1564         }
1565
1566         cols.hideAllColumns = function() {
1567             angular.forEach(cols.columns, function(col) {
1568                 delete col.visible;
1569             });
1570         }
1571
1572         cols.indexOf = function(name) {
1573             for (var i = 0; i < cols.columns.length; i++) {
1574                 if (cols.columns[i].name == name) 
1575                     return i;
1576             }
1577             return -1;
1578         }
1579
1580         cols.findColumn = function(name) {
1581             return cols.columns[cols.indexOf(name)];
1582         }
1583
1584         cols.compileAutoColumns = function() {
1585             var idl_class = egCore.idl.classes[cols.idlClass];
1586
1587             angular.forEach(
1588                 idl_class.fields,
1589                 function(field) {
1590                     if (field.virtual) return;
1591                     // Columns declared in the markup take precedence
1592                     // of matching auto-columns.
1593                     if (cols.findColumn(field.name)) return;
1594                     if (field.datatype == 'link' || field.datatype == 'org_unit') {
1595                         // if the field is a link and the linked class has a
1596                         // "selector" field specified, use the selector field
1597                         // as the display field for the columns.
1598                         // flattener will take care of the fleshing.
1599                         if (field['class']) {
1600                             var selector_field = egCore.idl.classes[field['class']].fields
1601                                 .filter(function(f) { return Boolean(f.selector) })[0];
1602                             if (selector_field) {
1603                                 field.path = field.name + '.' + selector_field.selector;
1604                             }
1605                         }
1606                     }
1607                     cols.add(field, true);
1608                 }
1609             );
1610         }
1611
1612         // if a column definition has a path with a wildcard, create
1613         // columns for all non-virtual fields at the specified 
1614         // position in the path.
1615         cols.expandPath = function(colSpec) {
1616
1617             var ignoreList = [];
1618             if (colSpec.ignore)
1619                 ignoreList = colSpec.ignore.split(' ');
1620
1621             var dotpath = colSpec.path.replace(/\.?\*$/,'');
1622             var class_obj;
1623             var idl_field;
1624
1625             if (colSpec.parentIdlClass) {
1626                 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1627             } else {
1628                 class_obj = egCore.idl.classes[cols.idlClass];
1629             }
1630             var idl_parent = class_obj;
1631             var old_field_label = '';
1632
1633             if (!class_obj) return;
1634
1635             //console.debug('egGrid: auto dotpath is: ' + dotpath);
1636             var path_parts = dotpath.split(/\./);
1637
1638             // find the IDL class definition for the last element in the
1639             // path before the .*
1640             // an empty path_parts means expand the root class
1641             if (path_parts) {
1642                 var old_field;
1643                 for (var path_idx in path_parts) {
1644                     old_field = idl_field;
1645
1646                     var part = path_parts[path_idx];
1647                     idl_field = class_obj.field_map[part];
1648
1649                     // unless we're at the end of the list, this field should
1650                     // link to another class.
1651                     if (idl_field && idl_field['class'] && (
1652                         idl_field.datatype == 'link' || 
1653                         idl_field.datatype == 'org_unit')) {
1654                         if (old_field_label) old_field_label += ' : ';
1655                         old_field_label += idl_field.label;
1656                         class_obj = egCore.idl.classes[idl_field['class']];
1657                         if (old_field) idl_parent = old_field;
1658                     } else {
1659                         if (path_idx < (path_parts.length - 1)) {
1660                             // we ran out of classes to hop through before
1661                             // we ran out of path components
1662                             console.error("egGrid: invalid IDL path: " + dotpath);
1663                         }
1664                     }
1665                 }
1666             }
1667
1668             if (class_obj) {
1669                 angular.forEach(class_obj.fields, function(field) {
1670
1671                     // Only show wildcard fields where we have data to show
1672                     // Virtual and un-fleshed links will not have any data.
1673                     if (field.virtual ||
1674                         (field.datatype == 'link' || field.datatype == 'org_unit') ||
1675                         ignoreList.indexOf(field.name) > -1
1676                     )
1677                         return;
1678
1679                     var col = cols.cloneFromScope(colSpec);
1680                     col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1681
1682                     // log line below is very chatty.  disable until needed.
1683                     // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1684                     cols.add(col, false, true, 
1685                         {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1686                 });
1687
1688                 cols.columns = cols.columns.sort(
1689                     function(a, b) {
1690                         if (a.explicit) return -1;
1691                         if (b.explicit) return 1;
1692
1693                         if (a.idlclass && b.idlclass) {
1694                             if (a.idlclass < b.idlclass) return -1;
1695                             if (b.idlclass < a.idlclass) return 1;
1696                         }
1697
1698                         if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1699                             if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1700                             if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1701                         }
1702
1703                         if (a.label && b.label) {
1704                             if (a.label < b.label) return -1;
1705                             if (b.label < a.label) return 1;
1706                         }
1707
1708                         return a.name < b.name ? -1 : 1;
1709                     }
1710                 );
1711
1712
1713             } else {
1714                 console.error(
1715                     "egGrid: wildcard path does not resolve to an object: "
1716                     + dotpath);
1717             }
1718         }
1719
1720         // angular.clone(scopeObject) is not permittable.  Manually copy
1721         // the fields over that we need (so the scope object can go away).
1722         cols.cloneFromScope = function(colSpec) {
1723             return {
1724                 flesher  : colSpec.flesher,
1725                 comparator  : colSpec.comparator,
1726                 name  : colSpec.name,
1727                 label : colSpec.label,
1728                 path  : colSpec.path,
1729                 align  : colSpec.align || 'left',
1730                 flex  : Number(colSpec.flex) || 2,
1731                 sort  : Number(colSpec.sort) || 0,
1732                 required : colSpec.required,
1733                 linkpath : colSpec.linkpath,
1734                 template : colSpec.template,
1735                 visible  : colSpec.visible,
1736                 compiled : colSpec.compiled,
1737                 handlers : colSpec.handlers,
1738                 hidden   : colSpec.hidden,
1739                 datatype : colSpec.datatype,
1740                 sortable : colSpec.sortable,
1741                 nonsortable      : colSpec.nonsortable,
1742                 multisortable    : colSpec.multisortable,
1743                 nonmultisortable : colSpec.nonmultisortable,
1744                 dateformat       : colSpec.dateformat,
1745                 datecontext      : colSpec.datecontext,
1746                 datefilter      : colSpec.datefilter,
1747                 dateonlyinterval : colSpec.dateonlyinterval,
1748                 parentIdlClass   : colSpec.parentIdlClass,
1749                 cssSelector      : colSpec.cssSelector
1750             };
1751         }
1752
1753
1754         // Add a column to the columns collection.
1755         // Columns may come from a slim eg-columns-field or 
1756         // directly from the IDL.
1757         cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1758
1759             // First added column with the specified path takes precedence.
1760             // This allows for specific definitions followed by wildcard
1761             // definitions.  If a match is found, back out.
1762             if (cols.columns.filter(function(c) {
1763                 return (c.path == colSpec.path) })[0]) {
1764                 console.debug('skipping pre-existing column ' + colSpec.path);
1765                 return;
1766             }
1767
1768             var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1769
1770             if (column.path && column.path.match(/\*$/)) 
1771                 return cols.expandPath(colSpec);
1772
1773             if (!fromExpand) column.explicit = true;
1774
1775             if (!column.name) column.name = column.path;
1776             if (!column.path) column.path = column.name;
1777
1778             if (column.visible || (!cols.defaultToHidden && !column.hidden))
1779                 column.visible = true;
1780
1781             if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1782                 column.sortable = true;
1783
1784             if (column.multisortable || 
1785                 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1786                 column.multisortable = true;
1787
1788             if (cols.defaultDateFormat && ! column.dateformat) {
1789                 column.dateformat = cols.defaultDateFormat;
1790             }
1791
1792             if (cols.defaultDateOnlyInterval && ! column.dateonlyinterval) {
1793                 column.dateonlyinterval = cols.defaultDateOnlyInterval;
1794             }
1795
1796             if (cols.defaultDateContext && ! column.datecontext) {
1797                 column.datecontext = cols.defaultDateContext;
1798             }
1799
1800             if (cols.defaultDateFilter && ! column.datefilter) {
1801                 column.datefilter = cols.defaultDateFilter;
1802             }
1803
1804             cols.columns.push(column);
1805
1806             // Track which columns are visible by default in case we
1807             // need to reset column visibility
1808             if (column.visible) 
1809                 cols.stockVisible.push(column.name);
1810
1811             if (fromIDL) return; // directly from egIDL.  nothing left to do.
1812
1813             // lookup the matching IDL field
1814             if (!idl_info && cols.idlClass) 
1815                 idl_info = cols.idlFieldFromPath(column.path);
1816
1817             if (!idl_info) {
1818                 // column is not represented within the IDL
1819                 column.adhoc = true; 
1820                 return; 
1821             }
1822
1823             column.datatype = idl_info.idl_field.datatype;
1824             
1825             if (!column.label) {
1826                 column.label = idl_info.idl_field.label || column.name;
1827             }
1828
1829             if (fromExpand && idl_info.idl_class) {
1830                 column.idlclass = '';
1831                 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1832                     column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1833                 } else {
1834                     column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1835                 }
1836             }
1837         },
1838
1839         // finds the IDL field from the dotpath, using the columns
1840         // idlClass as the base.
1841         cols.idlFieldFromPath = function(dotpath) {
1842             var class_obj = egCore.idl.classes[cols.idlClass];
1843             if (!dotpath) return null;
1844
1845             var path_parts = dotpath.split(/\./);
1846
1847             var idl_parent;
1848             var idl_field;
1849             for (var path_idx in path_parts) {
1850                 var part = path_parts[path_idx];
1851                 idl_parent = idl_field;
1852                 idl_field = class_obj.field_map[part];
1853
1854                 if (idl_field) {
1855                     if (idl_field['class'] && (
1856                         idl_field.datatype == 'link' || 
1857                         idl_field.datatype == 'org_unit')) {
1858                         class_obj = egCore.idl.classes[idl_field['class']];
1859                     }
1860                 } else {
1861                     return null;
1862                 }
1863             }
1864
1865             return {
1866                 idl_parent: idl_parent,
1867                 idl_field : idl_field,
1868                 idl_class : class_obj
1869             };
1870         }
1871     }
1872
1873     return {
1874         instance : function(args) { return new ColumnsProvider(args) }
1875     }
1876 }])
1877
1878
1879 /*
1880  * Generic data provider template class.  This is basically an abstract
1881  * class factory service whose instances can be locally modified to 
1882  * meet the needs of each individual grid.
1883  */
1884 .factory('egGridDataProvider', 
1885            ['$q','$timeout','$filter','egCore',
1886     function($q , $timeout , $filter , egCore) {
1887
1888         function GridDataProvider(args) {
1889             var gridData = this;
1890             if (!args) args = {};
1891
1892             gridData.sort = [];
1893             gridData.get = args.get;
1894             gridData.query = args.query;
1895             gridData.idlClass = args.idlClass;
1896             gridData.columnsProvider = args.columnsProvider;
1897
1898             // Delivers a stream of array data via promise.notify()
1899             // Useful for passing an array of data to egGrid.get()
1900             // If a count is provided, the array will be trimmed to
1901             // the range defined by count and offset
1902             gridData.arrayNotifier = function(arr, offset, count) {
1903                 if (!arr || arr.length == 0) return $q.when();
1904
1905                 if (gridData.columnsProvider.clientSort
1906                     && gridData.sort
1907                     && gridData.sort.length > 0
1908                 ) {
1909                     var sorter_cache = [];
1910                     arr.sort(function(a,b) {
1911                         for (var si = 0; si < gridData.sort.length; si++) {
1912                             if (!sorter_cache[si]) { // Build sort structure on first comparison, reuse thereafter
1913                                 var field = gridData.sort[si];
1914                                 var dir = 'asc';
1915
1916                                 if (angular.isObject(field)) {
1917                                     dir = Object.values(field)[0];
1918                                     field = Object.keys(field)[0];
1919                                 }
1920
1921                                 var path = gridData.columnsProvider.findColumn(field).path || field;
1922                                 var comparator = gridData.columnsProvider.findColumn(field).comparator ||
1923                                     function (x,y) { if (x < y) return -1; if (x > y) return 1; return 0 };
1924
1925                                 sorter_cache[si] = {
1926                                     field       : path,
1927                                     dir         : dir,
1928                                     comparator  : comparator
1929                                 };
1930                             }
1931
1932                             var sc = sorter_cache[si];
1933
1934                             var af,bf;
1935
1936                             if (a._isfieldmapper || angular.isFunction(a[sc.field])) {
1937                                 try {af = a[sc.field](); bf = b[sc.field]() } catch (e) {};
1938                             } else {
1939                                 af = a[sc.field]; bf = b[sc.field];
1940                             }
1941                             if (af === undefined && sc.field.indexOf('.') > -1) { // assume an object, not flat path
1942                                 var parts = sc.field.split('.');
1943                                 af = a;
1944                                 bf = b;
1945                                 angular.forEach(parts, function (p) {
1946                                     if (af) {
1947                                         if (af._isfieldmapper || angular.isFunction(af[p])) af = af[p]();
1948                                         else af = af[p];
1949                                     }
1950                                     if (bf) {
1951                                         if (bf._isfieldmapper || angular.isFunction(bf[p])) bf = bf[p]();
1952                                         else bf = bf[p];
1953                                     }
1954                                 });
1955                             }
1956
1957                             if (af === undefined) af = null;
1958                             if (bf === undefined) bf = null;
1959
1960                             if (af === null && bf !== null) return 1;
1961                             if (bf === null && af !== null) return -1;
1962
1963                             if (!(bf === null && af === null)) {
1964                                 var partial = sc.comparator(af,bf);
1965                                 if (partial) {
1966                                     if (sc.dir == 'desc') {
1967                                         if (partial > 0) return -1;
1968                                         return 1;
1969                                     }
1970                                     return partial;
1971                                 }
1972                             }
1973                         }
1974
1975                         return 0;
1976                     });
1977                 }
1978
1979                 if (count) arr = arr.slice(offset, offset + count);
1980                 var def = $q.defer();
1981                 // promise notifications are only witnessed when delivered
1982                 // after the caller has his hands on the promise object
1983                 $timeout(function() {
1984                     angular.forEach(arr, def.notify);
1985                     def.resolve();
1986                 });
1987                 return def.promise;
1988             }
1989
1990             // Calls the grid refresh function.  Once instantiated, the
1991             // grid will replace this function with it's own refresh()
1992             gridData.refresh = function(noReset) { }
1993             gridData.prepend = function(limit) { }
1994
1995             if (!gridData.get) {
1996                 // returns a promise whose notify() delivers items
1997                 gridData.get = function(index, count) {
1998                     console.error("egGridDataProvider.get() not implemented");
1999                 }
2000             }
2001
2002             // attempts a flat field lookup first.  If the column is not
2003             // found on the top-level object, attempts a nested lookup
2004             // TODO: consider a caching layer to speed up template 
2005             // rendering, particularly for nested objects?
2006             gridData.itemFieldValue = function(item, column) {
2007                 var val;
2008                 if (column.name in item) {
2009                     if (typeof item[column.name] == 'function') {
2010                         val = item[column.name]();
2011                     } else {
2012                         val = item[column.name];
2013                     }
2014                 } else {
2015                     val = gridData.nestedItemFieldValue(item, column);
2016                 }
2017
2018                 return val;
2019             }
2020
2021             // TODO: deprecate me
2022             gridData.flatItemFieldValue = function(item, column) {
2023                 console.warn('gridData.flatItemFieldValue deprecated; '
2024                     + 'leave provider.itemFieldValue unset');
2025                 return item[column.name];
2026             }
2027
2028             // given an object and a dot-separated path to a field,
2029             // extract the value of the field.  The path can refer
2030             // to function names or object attributes.  If the final
2031             // value is an IDL field, run the value through its
2032             // corresponding output filter.
2033             gridData.nestedItemFieldValue = function(obj, column) {
2034                 item = obj; // keep a copy around
2035
2036                 if (obj === null || obj === undefined || obj === '') return '';
2037                 if (!column.path) return obj;
2038
2039                 var idl_field;
2040                 var parts = column.path.split('.');
2041
2042                 angular.forEach(parts, function(step, idx) {
2043                     // object is not fleshed to the expected extent
2044                     if (typeof obj != 'object') {
2045                         if (typeof obj != 'undefined' && column.flesher) {
2046                             obj = column.flesher(obj, column, item);
2047                         } else {
2048                             obj = '';
2049                             return;
2050                         }
2051                     }
2052
2053                     if (!obj) return '';
2054
2055                     var cls = obj.classname;
2056                     if (cls && (class_obj = egCore.idl.classes[cls])) {
2057                         idl_field = class_obj.field_map[step];
2058                         obj = obj[step] ? obj[step]() : '';
2059                     } else {
2060                         if (angular.isFunction(obj[step])) {
2061                             obj = obj[step]();
2062                         } else {
2063                             obj = obj[step];
2064                         }
2065                     }
2066                 });
2067
2068                 // We found a nested IDL object which may or may not have 
2069                 // been configured as a top-level column.  Grab the datatype.
2070                 if (idl_field && !column.datatype) 
2071                     column.datatype = idl_field.datatype;
2072
2073                 if (obj === null || obj === undefined || obj === '') return '';
2074                 return obj;
2075             }
2076         }
2077
2078         return {
2079             instance : function(args) {
2080                 return new GridDataProvider(args);
2081             }
2082         };
2083     }
2084 ])
2085
2086
2087 // Factory service for egGridDataManager instances, which are
2088 // responsible for collecting flattened grid data.
2089 .factory('egGridFlatDataProvider', 
2090            ['$q','egCore','egGridDataProvider',
2091     function($q , egCore , egGridDataProvider) {
2092
2093         return {
2094             instance : function(args) {
2095                 var provider = egGridDataProvider.instance(args);
2096
2097                 provider.get = function(offset, count) {
2098
2099                     // no query means no call
2100                     if (!provider.query || 
2101                             angular.equals(provider.query, {})) 
2102                         return $q.when();
2103
2104                     // find all of the currently visible columns
2105                     var queryFields = {}
2106                     angular.forEach(provider.columnsProvider.columns, 
2107                         function(col) {
2108                             // only query IDL-tracked columns
2109                             if (!col.adhoc && col.name && col.path && (col.required || col.visible))
2110                                 queryFields[col.name] = col.path;
2111                         }
2112                     );
2113
2114                     return egCore.net.request(
2115                         'open-ils.fielder',
2116                         'open-ils.fielder.flattened_search',
2117                         egCore.auth.token(), provider.idlClass, 
2118                         queryFields, provider.query,
2119                         {   sort : provider.sort,
2120                             limit : count,
2121                             offset : offset
2122                         }
2123                     );
2124                 }
2125                 //provider.itemFieldValue = provider.flatItemFieldValue;
2126                 return provider;
2127             }
2128         };
2129     }
2130 ])
2131
2132 .directive('egGridColumnDragSource', function() {
2133     return {
2134         restrict : 'A',
2135         require : '^egGrid',
2136         link : function(scope, element, attrs, egGridCtrl) {
2137             angular.element(element).attr('draggable', 'true');
2138
2139             element.bind('dragstart', function(e) {
2140                 egGridCtrl.dragColumn = attrs.column;
2141                 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
2142                 egGridCtrl.colResizeDir = 0;
2143
2144                 if (egGridCtrl.dragType == 'move') {
2145                     // style the column getting moved
2146                     angular.element(e.target).addClass(
2147                         'eg-grid-column-move-handle-active');
2148                 }
2149             });
2150
2151             element.bind('dragend', function(e) {
2152                 if (egGridCtrl.dragType == 'move') {
2153                     angular.element(e.target).removeClass(
2154                         'eg-grid-column-move-handle-active');
2155                 }
2156             });
2157         }
2158     };
2159 })
2160
2161 .directive('egGridColumnDragDest', function() {
2162     return {
2163         restrict : 'A',
2164         require : '^egGrid',
2165         link : function(scope, element, attrs, egGridCtrl) {
2166
2167             element.bind('dragover', function(e) { // required for drop
2168                 e.stopPropagation();
2169                 e.preventDefault();
2170                 e.dataTransfer.dropEffect = 'move';
2171
2172                 if (egGridCtrl.colResizeDir == 0) return; // move
2173
2174                 var cols = egGridCtrl.columnsProvider;
2175                 var srcCol = egGridCtrl.dragColumn;
2176                 var srcColIdx = cols.indexOf(srcCol);
2177
2178                 if (egGridCtrl.colResizeDir == -1) {
2179                     if (cols.indexOf(attrs.column) <= srcColIdx) {
2180                         egGridCtrl.modifyColumnFlex(
2181                             egGridCtrl.columnsProvider.findColumn(
2182                                 egGridCtrl.dragColumn), -1);
2183                         if (cols.columns[srcColIdx+1]) {
2184                             // source column shrinks by one, column to the
2185                             // right grows by one.
2186                             egGridCtrl.modifyColumnFlex(
2187                                 cols.columns[srcColIdx+1], 1);
2188                         }
2189                         scope.$apply();
2190                     }
2191                 } else {
2192                     if (cols.indexOf(attrs.column) > srcColIdx) {
2193                         egGridCtrl.modifyColumnFlex( 
2194                             egGridCtrl.columnsProvider.findColumn(
2195                                 egGridCtrl.dragColumn), 1);
2196                         if (cols.columns[srcColIdx+1]) {
2197                             // source column grows by one, column to the 
2198                             // right grows by one.
2199                             egGridCtrl.modifyColumnFlex(
2200                                 cols.columns[srcColIdx+1], -1);
2201                         }
2202
2203                         scope.$apply();
2204                     }
2205                 }
2206             });
2207
2208             element.bind('dragenter', function(e) {
2209                 e.stopPropagation();
2210                 e.preventDefault();
2211                 if (egGridCtrl.dragType == 'move') {
2212                     angular.element(e.target).addClass('eg-grid-col-hover');
2213                 } else {
2214                     // resize grips are on the right side of each column.
2215                     // dragenter will either occur on the source column 
2216                     // (dragging left) or the column to the right.
2217                     if (egGridCtrl.colResizeDir == 0) {
2218                         if (egGridCtrl.dragColumn == attrs.column) {
2219                             egGridCtrl.colResizeDir = -1; // west
2220                         } else {
2221                             egGridCtrl.colResizeDir = 1; // east
2222                         }
2223                     }
2224                 }
2225             });
2226
2227             element.bind('dragleave', function(e) {
2228                 e.stopPropagation();
2229                 e.preventDefault();
2230                 if (egGridCtrl.dragType == 'move') {
2231                     angular.element(e.target).removeClass('eg-grid-col-hover');
2232                 }
2233             });
2234
2235             element.bind('drop', function(e) {
2236                 e.stopPropagation();
2237                 e.preventDefault();
2238                 egGridCtrl.colResizeDir = 0;
2239                 if (egGridCtrl.dragType == 'move') {
2240                     angular.element(e.target).removeClass('eg-grid-col-hover');
2241                     egGridCtrl.onColumnDrop(attrs.column); // move the column
2242                 }
2243             });
2244         }
2245     };
2246 })
2247  
2248 .directive('egGridMenuItem', function() {
2249     return {
2250         restrict : 'AE',
2251         require : '^egGrid',
2252         scope : {
2253             label : '@',  
2254             checkbox : '@',  
2255             checked : '=',  
2256             standalone : '=',  
2257             handler : '=', // onclick handler function
2258             divider : '=', // if true, show a divider only
2259             handlerData : '=', // if set, passed as second argument to handler
2260             disabled : '=', // function
2261             hidden : '=' // function
2262         },
2263         link : function(scope, element, attrs, egGridCtrl) {
2264             egGridCtrl.addMenuItem({
2265                 checkbox : scope.checkbox,
2266                 checked : scope.checked ? true : false,
2267                 label : scope.label,
2268                 standalone : scope.standalone ? true : false,
2269                 handler : scope.handler,
2270                 divider : scope.divider,
2271                 disabled : scope.disabled,
2272                 hidden : scope.hidden,
2273                 handlerData : scope.handlerData
2274             });
2275             scope.$destroy();
2276         }
2277     };
2278 })
2279
2280 /* https://stackoverflow.com/questions/17343696/adding-an-ng-click-event-inside-a-filter/17344875#17344875 */
2281 .directive('compile', ['$compile', function ($compile) {
2282     return function(scope, element, attrs) {
2283       // pass through column defs from grid cell's scope
2284       scope.col = scope.$parent.col;
2285       scope.$watch(
2286         function(scope) {
2287           // watch the 'compile' expression for changes
2288           return scope.$eval(attrs.compile);
2289         },
2290         function(value) {
2291           // when the 'compile' expression changes
2292           // assign it into the current DOM
2293           element.html(value);
2294
2295           // compile the new DOM and link it to the current
2296           // scope.
2297           // NOTE: we only compile .childNodes so that
2298           // we don't get into infinite loop compiling ourselves
2299           $compile(element.contents())(scope);
2300         }
2301     );
2302   };
2303 }])
2304
2305
2306
2307 /**
2308  * Translates bare IDL object values into display values.
2309  * 1. Passes dates through the angular date filter
2310  * 2. Converts bools to translated Yes/No strings
2311  * Others likely to follow...
2312  */
2313 .filter('egGridValueFilter', ['$filter','egCore', 'egStrings', function($filter,egCore,egStrings) {
2314     function traversePath(obj,path) {
2315         var list = path.split('.');
2316         for (var part in path) {
2317             if (obj[path]) obj = obj[path]
2318             else return null;
2319         }
2320         return obj;
2321     }
2322
2323     var GVF = function(value, column, item) {
2324         switch(column.datatype) {
2325             case 'bool':
2326                 switch(value) {
2327                     // Browser will translate true/false for us
2328                     case 't' : 
2329                     case '1' :  // legacy
2330                     case true:
2331                         return egStrings.YES;
2332                     case 'f' : 
2333                     case '0' :  // legacy
2334                     case false:
2335                         return egStrings.NO;
2336                     // value may be null,  '', etc.
2337                     default : return '';
2338                 }
2339             case 'timestamp':
2340                 var interval = angular.isFunction(item[column.dateonlyinterval])
2341                     ? item[column.dateonlyinterval]()
2342                     : item[column.dateonlyinterval];
2343
2344                 if (column.dateonlyinterval && !interval) // try it as a dotted path
2345                     interval = traversePath(item, column.dateonlyinterval);
2346
2347                 var context = angular.isFunction(item[column.datecontext])
2348                     ? item[column.datecontext]()
2349                     : item[column.datecontext];
2350
2351                 if (column.datecontext && !context) // try it as a dotted path
2352                     context = traversePath(item, column.datecontext);
2353
2354                 var date_filter = column.datefilter || 'egOrgDateInContext';
2355
2356                 return $filter(date_filter)(value, column.dateformat, context, interval);
2357             case 'money':
2358                 return $filter('currency')(value);
2359             default:
2360                 return value;
2361         }
2362     };
2363
2364     GVF.$stateful = true;
2365     return GVF;
2366 }]);
2367