]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/grid.js
LP#1402797 If no row is currently selected on right-click, select the clicked row
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / services / grid.js
1 angular.module('egGridMod', 
2     ['egCoreMod', 'egUiMod', 'ui.bootstrap'])
3
4 .directive('egGrid', function() {
5     return {
6         restrict : 'AE',
7         transclude : true,
8         scope : {
9
10             // IDL class hint (e.g. "aou")
11             idlClass : '@',
12
13             // default page size
14             pageSize : '@',
15
16             // if true, grid columns are derived from all non-virtual
17             // fields on the base idlClass
18             autoFields : '@',
19
20             // grid preferences will be stored / retrieved with this key
21             persistKey : '@',
22
23             // field whose value is unique and may be used for item
24             // reference / lookup.  This will usually be someting like
25             // "id".  This is not needed when using autoFields, since we
26             // can determine the primary key directly from the IDL.
27             idField : '@',
28
29             // Reference to externally provided egGridDataProvider
30             itemsProvider : '=',
31
32             // comma-separated list of supported or disabled grid features
33             // supported features:
34             //  -display : columns are hidden by default
35             //  -sort    : columns are unsortable by default 
36             //  -multisort : sort priorities config disabled by default
37             features : '@',
38
39             // optional primary grid label
40             mainLabel : '@',
41
42             // if true, use the IDL class label as the mainLabel
43             autoLabel : '=', 
44
45             // optional context menu label
46             menuLabel : '@',
47
48             // Hash of control functions.
49             //
50             //  These functions are defined by the calling scope and 
51             //  invoked as-is by the grid w/ the specified parameters.
52             //
53             //  itemRetrieved     : function(item) {}
54             //  allItemsRetrieved : function() {}
55             //
56             //  ---------------
57             //  These functions are defined by the grid and thus
58             //  replace any values defined for these attributes from the
59             //  calling scope.
60             //
61             //  activateItem  : function(item) {}
62             //  allItems      : function(allItems) {}
63             //  selectedItems : function(selected) {}
64             //  selectItems   : function(ids) {}
65             //  setQuery      : function(queryStruct) {} // causes reload
66             //  setSort       : function(sortSturct) {} // causes reload
67             gridControls : '=',
68         },
69
70         // TODO: avoid hard-coded url
71         templateUrl : '/eg/staff/share/t_autogrid', 
72
73         link : function(scope, element, attrs) {     
74             // link() is called after page compilation, which means our
75             // eg-grid-field's have been parsed and loaded.  Now it's 
76             // safe to perform our initial page load.
77
78             // load auto fields after eg-grid-field's so they are not clobbered
79             scope.handleAutoFields();
80             scope.collect();
81
82             scope.grid_element = element;
83             $(element)
84                 .find('.eg-grid-content-body')
85                 .bind('contextmenu', scope.showActionContextMenu);
86         },
87
88         controller : [
89                     '$scope','$q','egCore','egGridFlatDataProvider','$location',
90                     'egGridColumnsProvider','$filter','$window','$sce','$timeout',
91             function($scope,  $q , egCore,  egGridFlatDataProvider , $location,
92                      egGridColumnsProvider , $filter , $window , $sce , $timeout) {
93
94             var grid = this;
95
96             grid.init = function() {
97                 grid.offset = 0;
98                 $scope.items = [];
99                 $scope.showGridConf = false;
100                 grid.totalCount = -1;
101                 $scope.selected = {};
102                 $scope.actions = []; // actions for selected items
103                 $scope.menuItems = []; // global actions
104
105                 // remove some unneeded values from the scope to reduce bloat
106
107                 grid.idlClass = $scope.idlClass;
108                 delete $scope.idlClass;
109
110                 grid.persistKey = $scope.persistKey;
111                 delete $scope.persistKey;
112
113                 var stored_limit = 0;
114                 if (grid.persistKey) {
115                     var stored_limit = Number(
116                         egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
117                     );
118                 }
119                 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
120
121                 grid.indexField = $scope.idField;
122                 delete $scope.idField;
123
124                 grid.dataProvider = $scope.itemsProvider;
125
126                 var features = ($scope.features) ? 
127                     $scope.features.split(',') : [];
128                 delete $scope.features;
129
130                 if (!grid.indexField && grid.idlClass)
131                     grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
132
133                 grid.columnsProvider = egGridColumnsProvider.instance({
134                     idlClass : grid.idlClass,
135                     defaultToHidden : (features.indexOf('-display') > -1),
136                     defaultToNoSort : (features.indexOf('-sort') > -1),
137                     defaultToNoMultiSort : (features.indexOf('-multisort') > -1)
138                 });
139
140                 $scope.handleAutoFields = function() {
141                     if ($scope.autoFields) {
142                         if (grid.autoLabel) {
143                             $scope.mainLabel = 
144                                 egCore.idl.classes[grid.idlClass].label;
145                         }
146                         grid.columnsProvider.compileAutoColumns();
147                         delete $scope.autoFields;
148                     }
149                 }
150    
151                 if (!grid.dataProvider) {
152                     // no provider, um, provided.
153                     // Use a flat data provider
154
155                     grid.selfManagedData = true;
156                     grid.dataProvider = egGridFlatDataProvider.instance({
157                         indexField : grid.indexField,
158                         idlClass : grid.idlClass,
159                         columnsProvider : grid.columnsProvider,
160                         query : $scope.query
161                     });
162                 }
163
164                 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
165                 $scope.indexValue = function(item) {
166                     return grid.indexValue(item)
167                 };
168
169                 grid.applyControlFunctions();
170
171                 grid.loadConfig().then(function() { 
172                     // link columns to scope after loadConfig(), since it
173                     // replaces the columns array.
174                     $scope.columns = grid.columnsProvider.columns;
175                 });
176
177                 // NOTE: grid.collect() is first called from link(), not here.
178             }
179
180             // link our control functions into the gridControls 
181             // scope object so the caller can access them.
182             grid.applyControlFunctions = function() {
183
184                 // we use some of these controls internally, so sett
185                 // them up even if the caller doesn't request them.
186                 var controls = $scope.gridControls || {};
187
188                 // link in the control functions
189                 controls.selectedItems = function() {
190                     return grid.getSelectedItems()
191                 }
192
193                 controls.allItems = function() {
194                     return $scope.items;
195                 }
196
197                 controls.selectItems = function(ids) {
198                     if (!ids) return;
199                     $scope.selected = {};
200                     angular.forEach(ids, function(i) {
201                         $scope.selected[''+i] = true;
202                     });
203                 }
204
205                 // if the caller provided a functional setQuery,
206                 // extract the value before replacing it
207                 if (controls.setQuery) {
208                     grid.dataProvider.query = 
209                         controls.setQuery();
210                 }
211
212                 controls.setQuery = function(query) {
213                     grid.dataProvider.query = query;
214                     controls.refresh();
215                 }
216
217                 // if the caller provided a functional setSort
218                 // extract the value before replacing it
219                 grid.dataProvider.sort = 
220                     controls.setSort ?  controls.setSort() : [];
221
222                 controls.setSort = function(sort) {
223                     controls.refresh();
224                 }
225
226                 controls.refresh = function(noReset) {
227                     if (!noReset) grid.offset = 0;
228                     grid.collect();
229                 }
230
231                 controls.setLimit = function(limit,forget) {
232                     if (!forget && grid.persistKey)
233                         egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
234                     grid.limit = limit;
235                 }
236                 controls.getLimit = function() {
237                     return grid.limit;
238                 }
239                 controls.setOffset = function(offset) {
240                     grid.offset = offset;
241                 }
242                 controls.getOffset = function() {
243                     return grid.offset;
244                 }
245
246                 grid.dataProvider.refresh = controls.refresh;
247                 grid.controls = controls;
248             }
249
250             // add a new (global) grid menu item
251             grid.addMenuItem = function(item) {
252                 $scope.menuItems.push(item);
253                 var handler = item.handler;
254                 item.handler = function() {
255                     $scope.gridMenuIsOpen = false; // close menu
256                     if (handler) {
257                         handler(item, 
258                             item.handlerData, grid.getSelectedItems());
259                     }
260                 }
261             }
262
263             // add a selected-items action
264             grid.addAction = function(act) {
265                 $scope.actions.push(act);
266             }
267
268             // remove the stored column configuration preferenc, then recover 
269             // the column visibility information from the initial page load.
270             $scope.resetColumns = function() {
271                 $scope.gridColumnPickerIsOpen = false;
272                 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
273                 .then(function() {
274                     grid.columnsProvider.reset(); 
275                     if (grid.selfManagedData) grid.collect();
276                 });
277             }
278
279             $scope.showAllColumns = function() {
280                 $scope.gridColumnPickerIsOpen = false;
281                 grid.columnsProvider.showAllColumns();
282                 if (grid.selfManagedData) grid.collect();
283             }
284
285             $scope.hideAllColumns = function() {
286                 $scope.gridColumnPickerIsOpen = false;
287                 grid.columnsProvider.hideAllColumns();
288                 // note: no need to fetch new data if no columns are visible
289             }
290
291             $scope.toggleColumnVisibility = function(col) {
292                 $scope.gridColumnPickerIsOpen = false;
293                 col.visible = !col.visible;
294
295                 // egGridFlatDataProvider only retrieves data to be
296                 // displayed.  When column visibility changes, it's
297                 // necessary to fetch the newly visible column data.
298                 if (grid.selfManagedData) grid.collect();
299             }
300
301             // save the columns configuration (position, sort, width) to
302             // eg.grid.<persist-key>
303             $scope.saveConfig = function() {
304                 $scope.gridColumnPickerIsOpen = false;
305
306                 if (!grid.persistKey) {
307                     console.warn(
308                         "Cannot save settings without a grid persist-key");
309                     return;
310                 }
311
312                 // only store information about visible columns.
313                 var conf = grid.columnsProvider.columns.filter(
314                     function(col) {return Boolean(col.visible) });
315
316                 // now scrunch the data down to just the needed info
317                 conf = conf.map(function(col) {
318                     var c = {name : col.name}
319                     // Apart from the name, only store non-default values.
320                     // No need to store col.visible, since that's implicit
321                     if (col.flex != 2) c.flex = col.flex;
322                     if (Number(col.sort)) c.sort = Number(c.sort);
323                     return c;
324                 });
325
326                 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
327                 .then(function() { 
328                     // Save operation performed from the grid configuration UI.
329                     // Hide the configuration UI and re-draw w/ sort applied
330                     if ($scope.showGridConf) 
331                         $scope.toggleConfDisplay();
332                 });
333             }
334
335             // load the columns configuration (position, sort, width) from
336             // eg.grid.<persist-key> and apply the loaded settings to the
337             // columns on our columnsProvider
338             grid.loadConfig = function() {
339                 if (!grid.persistKey) return $q.when();
340
341                 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
342                 .then(function(conf) {
343                     if (!conf) return;
344
345                     var columns = grid.columnsProvider.columns;
346                     var new_cols = [];
347
348                     angular.forEach(conf, function(col) {
349                         var grid_col = columns.filter(
350                             function(c) {return c.name == col.name})[0];
351
352                         if (!grid_col) {
353                             // saved column does not match a column in the 
354                             // current grid.  skip it.
355                             return;
356                         }
357
358                         grid_col.flex = col.flex || 2;
359                         grid_col.sort = col.sort || 0;
360                         // all saved columns are assumed to be true
361                         grid_col.visible = true;
362                         new_cols.push(grid_col);
363                     });
364
365                     // columns which are not expressed within the saved 
366                     // configuration are marked as non-visible and 
367                     // appended to the end of the new list of columns.
368                     angular.forEach(columns, function(col) {
369                         var found = conf.filter(
370                             function(c) {return (c.name == col.name)})[0];
371                         if (!found) {
372                             col.visible = false;
373                             new_cols.push(col);
374                         }
375                     });
376
377                     grid.columnsProvider.columns = new_cols;
378                     grid.compileSort();
379                 });
380             }
381
382             $scope.onContextMenu = function($event) {
383                 var col = angular.element($event.target).attr('column');
384                 console.log('selected column ' + col);
385             }
386
387             $scope.page = function() {
388                 return (grid.offset / grid.limit) + 1;
389             }
390
391             $scope.goToPage = function(page) {
392                 page = Number(page);
393                 if (angular.isNumber(page) && page > 0) {
394                     grid.offset = (page - 1) * grid.limit;
395                     grid.collect();
396                 }
397             }
398
399             $scope.offset = function(o) {
400                 if (angular.isNumber(o))
401                     grid.offset = o;
402                 return grid.offset 
403             }
404
405             $scope.limit = function(l) { 
406                 if (angular.isNumber(l)) {
407                     if (grid.persistKey)
408                         egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
409                     grid.limit = l;
410                 }
411                 return grid.limit 
412             }
413
414             $scope.onFirstPage = function() {
415                 return grid.offset == 0;
416             }
417
418             $scope.hasNextPage = function() {
419                 // we have less data than requested, there must
420                 // not be any more pages
421                 if (grid.count() < grid.limit) return false;
422
423                 // if the total count is not known, assume that a full
424                 // page of data implies more pages are available.
425                 if (grid.totalCount == -1) return true;
426
427                 // we have a full page of data, but is there more?
428                 return grid.totalCount > (grid.offset + grid.count());
429             }
430
431             $scope.incrementPage = function() {
432                 grid.offset += grid.limit;
433                 grid.collect();
434             }
435
436             $scope.decrementPage = function() {
437                 if (grid.offset < grid.limit) {
438                     grid.offset = 0;
439                 } else {
440                     grid.offset -= grid.limit;
441                 }
442                 grid.collect();
443             }
444
445             // number of items loaded for the current page of results
446             grid.count = function() {
447                 return $scope.items.length;
448             }
449
450             // returns the unique identifier value for the provided item
451             // for internal consistency, indexValue is always coerced 
452             // into a string.
453             grid.indexValue = function(item) {
454                 if (angular.isObject(item)) {
455                     if (item !== null) {
456                         if (angular.isFunction(item[grid.indexField]))
457                             return ''+item[grid.indexField]();
458                         return ''+item[grid.indexField]; // flat data
459                     }
460                 }
461                 // passed a non-object; assume it's an index
462                 return ''+item; 
463             }
464
465             // fires the hide handler function for a context action
466             $scope.actionHide = function(action) {
467                 if (!action.hide) {
468                     return false;
469                 }
470                 return action.hide(action);
471             }
472
473             // fires the action handler function for a context action
474             $scope.actionLauncher = function(action) {
475                 if (!action.handler) {
476                     console.error(
477                         'No handler specified for "' + action.label + '"');
478                 } else {
479
480                     try {
481                         action.handler(grid.getSelectedItems());
482                     } catch(E) {
483                         console.error('Error executing handler for "' 
484                             + action.label + '" => ' + E + "\n" + E.stack);
485                     }
486
487                     if ($scope.action_context_y || $scope.action_context_x)
488                         $scope.hideActionContextMenu();
489                 }
490
491             }
492
493             $scope.hideActionContextMenu = function () {
494                 var menu_dom = $('body').find('.grid-action-dropdown')[0];
495                 $(menu_dom).css({
496                     display: '',
497                     width: $scope.action_context_width,
498                     top: $scope.action_context_y,
499                     left: $scope.action_context_x
500                 });
501                 $($scope.action_context_parent).append(menu_dom);
502                 $scope.action_context_oldy = $scope.action_context_oldx = 0;
503                 $('body').unbind('click.remove_context_menu');
504                 $scope.action_context_showing = false;
505             }
506
507             $scope.action_context_showing = false;
508             $scope.showActionContextMenu = function ($event) {
509                 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
510                     $event.target.click();
511
512                 var current_parent = $scope.grid_element;
513                 if ($scope.action_context_showing) {
514                     current_parent = $('body');
515                 }
516
517                 var menu_dom = $(current_parent).find('.grid-action-dropdown')[0];
518
519                 if (!$scope.action_context_showing) {
520                     $scope.action_context_width = $(menu_dom).css('width');
521                     $scope.action_context_y = $(menu_dom).css('top');
522                     $scope.action_context_x = $(menu_dom).css('left');
523                     $scope.action_context_parent = $(menu_dom).parent();
524                     $scope.action_context_showing = true;
525
526                     $('body').append($(menu_dom));
527                     $('body').bind('click.remove_context_menu', $scope.hideActionContextMenu);
528                 }
529
530                 $(menu_dom).css({
531                     display: 'block',
532                     width: $scope.action_context_width,
533                     top: $event.pageY,
534                     left: $event.pageX
535                 });
536
537                 return false;
538             }
539
540             // returns the list of selected item objects
541             grid.getSelectedItems = function() {
542                 return $scope.items.filter(
543                     function(item) {
544                         return Boolean($scope.selected[grid.indexValue(item)]);
545                     }
546                 );
547             }
548
549             grid.getItemByIndex = function(index) {
550                 for (var i = 0; i < $scope.items.length; i++) {
551                     var item = $scope.items[i];
552                     if (grid.indexValue(item) == index) 
553                         return item;
554                 }
555             }
556
557             // selects one row after deselecting all of the others
558             grid.selectOneItem = function(index) {
559                 $scope.selected = {};
560                 $scope.selected[index] = true;
561             }
562
563             // selects or deselects an item, without affecting the others.
564             // returns true if the item is selected; false if de-selected.
565             grid.toggleSelectOneItem = function(index) {
566                 if ($scope.selected[index]) {
567                     delete $scope.selected[index];
568                     return false;
569                 } else {
570                     return $scope.selected[index] = true;
571                 }
572             }
573
574             grid.selectAllItems = function() {
575                 angular.forEach($scope.items, function(item) {
576                     $scope.selected[grid.indexValue(item)] = true
577                 });
578             }
579
580             $scope.$watch('selectAll', function(newVal) {
581                 if (newVal) {
582                     grid.selectAllItems();
583                 } else {
584                     $scope.selected = {};
585                 }
586             });
587
588             // returns true if item1 appears in the list before item2;
589             // false otherwise.  this is slightly more efficient that
590             // finding the position of each then comparing them.
591             // item1 / item2 may be an item or an item index
592             grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
593                 var idx1 = grid.indexValue(itemOrIndex1);
594                 var idx2 = grid.indexValue(itemOrIndex2);
595
596                 // use for() for early exit
597                 for (var i = 0; i < $scope.items.length; i++) {
598                     var idx = grid.indexValue($scope.items[i]);
599                     if (idx == idx1) return true;
600                     if (idx == idx2) return false;
601                 }
602                 return false;
603             }
604
605             // 0-based position of item in the current data set
606             grid.indexOf = function(item) {
607                 var idx = grid.indexValue(item);
608                 for (var i = 0; i < $scope.items.length; i++) {
609                     if (grid.indexValue($scope.items[i]) == idx)
610                         return i;
611                 }
612                 return -1;
613             }
614
615             grid.modifyColumnFlex = function(column, val) {
616                 column.flex += val;
617                 // prevent flex:0;  use hiding instead
618                 if (column.flex < 1)
619                     column.flex = 1;
620             }
621             $scope.modifyColumnFlex = function(col, val) {
622                 grid.modifyColumnFlex(col, val);
623             }
624
625             // handles click, control-click, and shift-click
626             $scope.handleRowClick = function($event, item) {
627                 var index = grid.indexValue(item);
628
629                 var origSelected = Object.keys($scope.selected);
630
631                 if ($event.ctrlKey || $event.metaKey /* mac command */) {
632                     // control-click
633                     if (grid.toggleSelectOneItem(index)) 
634                         grid.lastSelectedItemIndex = index;
635
636                 } else if ($event.shiftKey) { 
637                     // shift-click
638
639                     if (!grid.lastSelectedItemIndex || 
640                             index == grid.lastSelectedItemIndex) {
641                         grid.selectOneItem(index);
642                         grid.lastSelectedItemIndex = index;
643
644                     } else {
645
646                         var selecting = false;
647                         var ascending = grid.itemComesBefore(
648                             grid.lastSelectedItemIndex, item);
649                         var startPos = 
650                             grid.indexOf(grid.lastSelectedItemIndex);
651
652                         // update to new last-selected
653                         grid.lastSelectedItemIndex = index;
654
655                         // select each row between the last selected and 
656                         // currently selected items
657                         while (true) {
658                             startPos += ascending ? 1 : -1;
659                             var curItem = $scope.items[startPos];
660                             if (!curItem) break;
661                             var curIdx = grid.indexValue(curItem);
662                             $scope.selected[curIdx] = true;
663                             if (curIdx == index) break; // all done
664                         }
665                     }
666                         
667                 } else {
668                     grid.selectOneItem(index);
669                     grid.lastSelectedItemIndex = index;
670                 }
671             }
672
673             // Builds a sort expression from column sort priorities.
674             // called on page load and any time the priorities are modified.
675             grid.compileSort = function() {
676                 var sortList = grid.columnsProvider.columns.filter(
677                     function(col) { return Number(col.sort) != 0 }
678                 ).sort( 
679                     function(a, b) { 
680                         if (Math.abs(a.sort) < Math.abs(b.sort))
681                             return -1;
682                         return 1;
683                     }
684                 );
685
686                 if (sortList.length) {
687                     grid.dataProvider.sort = sortList.map(function(col) {
688                         var blob = {};
689                         blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
690                         return blob;
691                     });
692                 }
693             }
694
695             // builds a sort expression using a single column, 
696             // toggling between ascending and descending sort.
697             $scope.quickSort = function(col_name) {
698                 var sort = grid.dataProvider.sort;
699                 if (sort && sort.length &&
700                     sort[0] == col_name) {
701                     var blob = {};
702                     blob[col_name] = 'desc';
703                     grid.dataProvider.sort = [blob];
704                 } else {
705                     grid.dataProvider.sort = [col_name];
706                 }
707
708                 grid.offset = 0;
709                 grid.collect();
710             }
711
712             // show / hide the grid configuration row
713             $scope.toggleConfDisplay = function() {
714                 if ($scope.showGridConf) {
715                     $scope.showGridConf = false;
716                     if (grid.columnsProvider.hasSortableColumn()) {
717                         // only refresh the grid if the user has the
718                         // ability to modify the sort priorities.
719                         grid.compileSort();
720                         grid.offset = 0;
721                         grid.collect();
722                     }
723                 } else {
724                     $scope.showGridConf = true;
725                 }
726
727                 $scope.gridColumnPickerIsOpen = false;
728             }
729
730             // called when a dragged column is dropped onto itself
731             // or any other column
732             grid.onColumnDrop = function(target) {
733                 if (angular.isUndefined(target)) return;
734                 if (target == grid.dragColumn) return;
735                 var srcIdx, targetIdx, srcCol;
736                 angular.forEach(grid.columnsProvider.columns,
737                     function(col, idx) {
738                         if (col.name == grid.dragColumn) {
739                             srcIdx = idx;
740                             srcCol = col;
741                         } else if (col.name == target) {
742                             targetIdx = idx;
743                         }
744                     }
745                 );
746
747                 if (srcIdx < targetIdx) targetIdx--;
748
749                 // move src column from old location to new location in 
750                 // the columns array, then force a page refresh
751                 grid.columnsProvider.columns.splice(srcIdx, 1);
752                 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
753                 $scope.$apply(); 
754             }
755
756             // prepares a string for inclusion within a CSV document
757             // by escaping commas and quotes and removing newlines.
758             grid.csvDatum = function(str) {
759                 str = ''+str;
760                 if (!str) return '';
761                 str = str.replace(/\n/g, '');
762                 if (str.match(/\,/) || str.match(/"/)) {                                     
763                     str = str.replace(/"/g, '""');
764                     str = '"' + str + '"';                                           
765                 } 
766                 return str;
767             }
768
769             // sets the download file name and inserts the current CSV
770             // into a Blob URL for browser download.
771             $scope.generateCSVExportURL = function() {
772                 $scope.gridColumnPickerIsOpen = false;
773
774                 // let the file name describe the grid
775                 $scope.csvExportFileName = 
776                     ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
777                     .replace(/\s+/g, '_') + '_' + $scope.page();
778
779                 // toss the CSV into a Blob and update the export URL
780                 var csv = grid.generateCSV();
781                 var blob = new Blob([csv], {type : 'text/plain'});
782                 $scope.csvExportURL = 
783                     ($window.URL || $window.webkitURL).createObjectURL(blob);
784             }
785
786             $scope.printCSV = function() {
787                 $scope.gridColumnPickerIsOpen = false;
788                 egCore.print.print({
789                     context : 'default', 
790                     content : grid.generateCSV(),
791                     content_type : 'text/plain'
792                 });
793             }
794
795             // generates CSV for the currently visible grid contents
796             grid.generateCSV = function() {
797                 var csvStr = '';
798                 var colCount = grid.columnsProvider.columns.length;
799
800                 // columns
801                 angular.forEach(grid.columnsProvider.columns,
802                     function(col) {
803                         if (!col.visible) return;
804                         csvStr += grid.csvDatum(col.label);
805                         csvStr += ',';
806                     }
807                 );
808
809                 csvStr = csvStr.replace(/,$/,'\n');
810
811                 // items
812                 angular.forEach($scope.items, function(item) {
813                     angular.forEach(grid.columnsProvider.columns, 
814                         function(col) {
815                             if (!col.visible) return;
816                             // bare value
817                             var val = grid.dataProvider.itemFieldValue(item, col);
818                             // filtered value (dates, etc.)
819                             val = $filter('egGridValueFilter')(val, col);
820                             csvStr += grid.csvDatum(val);
821                             csvStr += ',';
822                         }
823                     );
824                     csvStr = csvStr.replace(/,$/,'\n');
825                 });
826
827                 return csvStr;
828             }
829
830             // Interpolate the value for column.linkpath within the context
831             // of the row item to generate the final link URL.
832             $scope.generateLinkPath = function(col, item) {
833                 return egCore.strings.$replace(col.linkpath, {item : item});
834             }
835
836             // If a column provides its own HTML template, translate it,
837             // using the current item for the template scope.
838             // note: $sce is required to avoid security restrictions and
839             // is OK here, since the template comes directly from a
840             // local HTML template (not user input).
841             $scope.translateCellTemplate = function(col, item) {
842                 var html = egCore.strings.$replace(col.template, {item : item});
843                 return $sce.trustAsHtml(html);
844             }
845
846             $scope.collect = function() { grid.collect() }
847
848             // asks the dataProvider for a page of data
849             grid.collect = function() {
850
851                 // avoid firing the collect if there is nothing to collect.
852                 if (grid.selfManagedData && !grid.dataProvider.query) return;
853
854                 if (grid.collecting) return; // avoid parallel collect()
855                 grid.collecting = true;
856
857                 console.debug('egGrid.collect() offset=' 
858                     + grid.offset + '; limit=' + grid.limit);
859
860                 // ensure all of our dropdowns are closed
861                 // TODO: git rid of these and just use dropdown-toggle, 
862                 // which is more reliable.
863                 $scope.gridColumnPickerIsOpen = false;
864                 $scope.gridRowCountIsOpen = false;
865                 $scope.gridPageSelectIsOpen = false;
866
867                 $scope.items = [];
868                 $scope.selected = {};
869                 grid.dataProvider.get(grid.offset, grid.limit).then(
870                 function() {
871                     if (grid.controls.allItemsRetrieved)
872                         grid.controls.allItemsRetrieved();
873                 },
874                 null, 
875                 function(item) {
876                     if (item) {
877                         $scope.items.push(item)
878                         if (grid.controls.itemRetrieved)
879                             grid.controls.itemRetrieved(item);
880                     }
881                 }).finally(function() { 
882                     console.debug('egGrid.collect() complete');
883                     grid.collecting = false 
884                 });
885             }
886
887             grid.init();
888         }]
889     };
890 })
891
892 /**
893  * eg-grid-field : used for collecting custom field data from the templates.
894  * This directive does not direct display, it just passes data up to the 
895  * parent grid.
896  */
897 .directive('egGridField', function() {
898     return {
899         require : '^egGrid',
900         restrict : 'AE',
901         scope : {
902             name  : '@', // required; unique name
903             path  : '@', // optional; flesh path
904             ignore: '@', // optional; fields to ignore when path is a wildcard
905             label : '@', // optional; display label
906             flex  : '@',  // optional; default flex width
907             dateformat : '@', // optional: passed down to egGridValueFilter
908
909             // if a field is part of an IDL object, but we are unable to
910             // determine the class, because it's nested within a hash
911             // (i.e. we can't navigate directly to the object via the IDL),
912             // idlClass lets us specify the class.  This is particularly
913             // useful for nested wildcard fields.
914             parentIdlClass : '@', 
915
916             // optional: for non-IDL columns, specifying a datatype
917             // lets the caller control which display filter is used.
918             // datatype should match the standard IDL datatypes.
919             datatype : '@'
920         },
921         link : function(scope, element, attrs, egGridCtrl) {
922
923             // boolean fields are presented as value-less attributes
924             angular.forEach(
925                 [
926                     'visible', 
927                     'hidden', 
928                     'sortable', 
929                     'nonsortable',
930                     'multisortable',
931                     'nonmultisortable',
932                     'required' // if set, always fetch data for this column
933                 ],
934                 function(field) {
935                     if (angular.isDefined(attrs[field]))
936                         scope[field] = true;
937                 }
938             );
939
940             // any HTML content within the field is its custom template
941             var tmpl = element.html();
942             if (tmpl && !tmpl.match(/^\s*$/))
943                 scope.template = tmpl
944
945             egGridCtrl.columnsProvider.add(scope);
946             scope.$destroy();
947         }
948     };
949 })
950
951 /**
952  * eg-grid-action : used for specifying actions which may be applied
953  * to items within the grid.
954  */
955 .directive('egGridAction', function() {
956     return {
957         require : '^egGrid',
958         restrict : 'AE',
959         transclude : true,
960         scope : {
961             label   : '@', // Action label
962             handler : '=',  // Action function handler
963             hide    : '=',
964             divider : '='
965         },
966         link : function(scope, element, attrs, egGridCtrl) {
967             egGridCtrl.addAction({
968                 hide  : scope.hide,
969                 label : scope.label,
970                 divider : scope.divider,
971                 handler : scope.handler
972             });
973             scope.$destroy();
974         }
975     };
976 })
977
978 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
979
980     function ColumnsProvider(args) {
981         var cols = this;
982         cols.columns = [];
983         cols.stockVisible = [];
984         cols.idlClass = args.idlClass;
985         cols.defaultToHidden = args.defaultToHidden;
986         cols.defaultToNoSort = args.defaultToNoSort;
987         cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
988
989         // resets column width, visibility, and sort behavior
990         // Visibility resets to the visibility settings defined in the 
991         // template (i.e. the original egGridField values).
992         cols.reset = function() {
993             angular.forEach(cols.columns, function(col) {
994                 col.flex = 2;
995                 col.sort = 0;
996                 if (cols.stockVisible.indexOf(col.name) > -1) {
997                     col.visible = true;
998                 } else {
999                     col.visible = false;
1000                 }
1001             });
1002         }
1003
1004         // returns true if any columns are sortable
1005         cols.hasSortableColumn = function() {
1006             return cols.columns.filter(
1007                 function(col) {
1008                     return col.sortable || col.multisortable;
1009                 }
1010             ).length > 0;
1011         }
1012
1013         cols.showAllColumns = function() {
1014             angular.forEach(cols.columns, function(column) {
1015                 column.visible = true;
1016             });
1017         }
1018
1019         cols.hideAllColumns = function() {
1020             angular.forEach(cols.columns, function(col) {
1021                 delete col.visible;
1022             });
1023         }
1024
1025         cols.indexOf = function(name) {
1026             for (var i = 0; i < cols.columns.length; i++) {
1027                 if (cols.columns[i].name == name) 
1028                     return i;
1029             }
1030             return -1;
1031         }
1032
1033         cols.findColumn = function(name) {
1034             return cols.columns[cols.indexOf(name)];
1035         }
1036
1037         cols.compileAutoColumns = function() {
1038             var idl_class = egCore.idl.classes[cols.idlClass];
1039
1040             angular.forEach(
1041                 idl_class.fields.sort(
1042                     function(a, b) { return a.name < b.name ? -1 : 1 }),
1043                 function(field) {
1044                     if (field.virtual) return;
1045                     if (field.datatype == 'link' || field.datatype == 'org_unit') {
1046                         // if the field is a link and the linked class has a
1047                         // "selector" field specified, use the selector field
1048                         // as the display field for the columns.
1049                         // flattener will take care of the fleshing.
1050                         if (field['class']) {
1051                             var selector_field = egCore.idl.classes[field['class']].fields
1052                                 .filter(function(f) { return Boolean(f.selector) })[0];
1053                             if (selector_field) {
1054                                 field.path = field.name + '.' + selector_field.selector;
1055                             }
1056                         }
1057                     }
1058                     cols.add(field, true);
1059                 }
1060             );
1061         }
1062
1063         // if a column definition has a path with a wildcard, create
1064         // columns for all non-virtual fields at the specified 
1065         // position in the path.
1066         cols.expandPath = function(colSpec) {
1067
1068             var ignoreList = [];
1069             if (colSpec.ignore)
1070                 ignoreList = colSpec.ignore.split(' ');
1071
1072             var dotpath = colSpec.path.replace(/\.?\*$/,'');
1073             var class_obj;
1074             var idl_field;
1075
1076             if (colSpec.parentIdlClass) {
1077                 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1078             } else {
1079                 class_obj = egCore.idl.classes[cols.idlClass];
1080             }
1081
1082             if (!class_obj) return;
1083
1084             console.debug('egGrid: auto dotpath is: ' + dotpath);
1085             var path_parts = dotpath.split(/\./);
1086
1087             // find the IDL class definition for the last element in the
1088             // path before the .*
1089             // an empty path_parts means expand the root class
1090             if (path_parts) {
1091                 for (var path_idx in path_parts) {
1092                     var part = path_parts[path_idx];
1093                     idl_field = class_obj.field_map[part];
1094
1095                     // unless we're at the end of the list, this field should
1096                     // link to another class.
1097                     if (idl_field && idl_field['class'] && (
1098                         idl_field.datatype == 'link' || 
1099                         idl_field.datatype == 'org_unit')) {
1100                         class_obj = egCore.idl.classes[idl_field['class']];
1101                     } else {
1102                         if (path_idx < (path_parts.length - 1)) {
1103                             // we ran out of classes to hop through before
1104                             // we ran out of path components
1105                             console.error("egGrid: invalid IDL path: " + dotpath);
1106                         }
1107                     }
1108                 }
1109             }
1110
1111             if (class_obj) {
1112                 angular.forEach(class_obj.fields, function(field) {
1113
1114                     // Only show wildcard fields where we have data to show
1115                     // Virtual and un-fleshed links will not have any data.
1116                     if (field.virtual ||
1117                         (field.datatype == 'link' || field.datatype == 'org_unit') ||
1118                         ignoreList.indexOf(field.name) > -1
1119                     )
1120                         return;
1121
1122                     var col = cols.cloneFromScope(colSpec);
1123                     col.path = dotpath + '.' + field.name;
1124                     console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_field));
1125                     cols.add(col, false, true, 
1126                         {idl_parent : idl_field, idl_field : field, idl_class : class_obj});
1127                 });
1128
1129                 cols.columns = cols.columns.sort(
1130                     function(a, b) {
1131                         if (a.explicit) return -1;
1132                         if (b.explicit) return 1;
1133                         if (a.idlclass && b.idlclass) {
1134                             return a.idlclass < b.idlclass ? -1 : 1;
1135                             return a.idlclass > b.idlclass ? 1 : -1;
1136                         }
1137                         if (a.path && b.path) {
1138                             return a.path < b.path ? -1 : 1;
1139                             return a.path > b.path ? 1 : -1;
1140                         }
1141
1142                         return a.label < b.label ? -1 : 1;
1143                     }
1144                 );
1145
1146
1147             } else {
1148                 console.error(
1149                     "egGrid: wildcard path does not resolve to an object: "
1150                     + dotpath);
1151             }
1152         }
1153
1154         // angular.clone(scopeObject) is not permittable.  Manually copy
1155         // the fields over that we need (so the scope object can go away).
1156         cols.cloneFromScope = function(colSpec) {
1157             return {
1158                 name  : colSpec.name,
1159                 label : colSpec.label,
1160                 path  : colSpec.path,
1161                 flex  : Number(colSpec.flex) || 2,
1162                 sort  : Number(colSpec.sort) || 0,
1163                 required : colSpec.required,
1164                 linkpath : colSpec.linkpath,
1165                 template : colSpec.template,
1166                 visible  : colSpec.visible,
1167                 hidden   : colSpec.hidden,
1168                 datatype : colSpec.datatype,
1169                 sortable : colSpec.sortable,
1170                 nonsortable      : colSpec.nonsortable,
1171                 multisortable    : colSpec.multisortable,
1172                 nonmultisortable : colSpec.nonmultisortable,
1173                 dateformat       : colSpec.dateformat,
1174                 parentIdlClass   : colSpec.parentIdlClass
1175             };
1176         }
1177
1178
1179         // Add a column to the columns collection.
1180         // Columns may come from a slim eg-columns-field or 
1181         // directly from the IDL.
1182         cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1183
1184             // First added column with the specified path takes precedence.
1185             // This allows for specific definitions followed by wildcard
1186             // definitions.  If a match is found, back out.
1187             if (cols.columns.filter(function(c) {
1188                 return (c.path == colSpec.path) })[0]) {
1189                 console.debug('skipping pre-existing column ' + colSpec.path);
1190                 return;
1191             }
1192
1193             var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1194
1195             if (column.path && column.path.match(/\*$/)) 
1196                 return cols.expandPath(colSpec);
1197
1198             if (!fromExpand) column.explicit = true;
1199
1200             if (!column.name) column.name = column.path;
1201             if (!column.path) column.path = column.name;
1202
1203             if (column.visible || (!cols.defaultToHidden && !column.hidden))
1204                 column.visible = true;
1205
1206             if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1207                 column.sortable = true;
1208
1209             if (column.multisortable || 
1210                 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1211                 column.multisortable = true;
1212
1213             cols.columns.push(column);
1214
1215             // Track which columns are visible by default in case we
1216             // need to reset column visibility
1217             if (column.visible) 
1218                 cols.stockVisible.push(column.name);
1219
1220             if (fromIDL) return; // directly from egIDL.  nothing left to do.
1221
1222             // lookup the matching IDL field
1223             if (!idl_info && cols.idlClass) 
1224                 idl_info = cols.idlFieldFromPath(column.path);
1225
1226             if (!idl_info) {
1227                 // column is not represented within the IDL
1228                 column.adhoc = true; 
1229                 return; 
1230             }
1231
1232             column.datatype = idl_info.idl_field.datatype;
1233             
1234             if (!column.label) {
1235                 column.label = idl_info.idl_field.label || column.name;
1236             }
1237
1238             if (fromExpand && idl_info.idl_class) {
1239                 column.idlclass = '';
1240                 if (idl_info.idl_parent) {
1241                     column.idlclass = idl_info.idl_parent.label || idl_info.idl_parent.name;
1242                 } else {
1243                     column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1244                 }
1245             }
1246         },
1247
1248         // finds the IDL field from the dotpath, using the columns
1249         // idlClass as the base.
1250         cols.idlFieldFromPath = function(dotpath) {
1251             var class_obj = egCore.idl.classes[cols.idlClass];
1252             var path_parts = dotpath.split(/\./);
1253
1254             var idl_parent;
1255             var idl_field;
1256             for (var path_idx in path_parts) {
1257                 var part = path_parts[path_idx];
1258                 idl_parent = idl_field;
1259                 idl_field = class_obj.field_map[part];
1260
1261                 if (idl_field && idl_field['class'] && (
1262                     idl_field.datatype == 'link' || 
1263                     idl_field.datatype == 'org_unit')) {
1264                     class_obj = egCore.idl.classes[idl_field['class']];
1265                 }
1266                 // else, path is not in the IDL, which is fine
1267             }
1268
1269             if (!idl_field) return null;
1270
1271             return {
1272                 idl_parent: idl_parent,
1273                 idl_field : idl_field,
1274                 idl_class : class_obj
1275             };
1276         }
1277     }
1278
1279     return {
1280         instance : function(args) { return new ColumnsProvider(args) }
1281     }
1282 }])
1283
1284
1285 /*
1286  * Generic data provider template class.  This is basically an abstract
1287  * class factory service whose instances can be locally modified to 
1288  * meet the needs of each individual grid.
1289  */
1290 .factory('egGridDataProvider', 
1291            ['$q','$timeout','$filter','egCore',
1292     function($q , $timeout , $filter , egCore) {
1293
1294         function GridDataProvider(args) {
1295             var gridData = this;
1296             if (!args) args = {};
1297
1298             gridData.sort = [];
1299             gridData.get = args.get;
1300             gridData.query = args.query;
1301             gridData.idlClass = args.idlClass;
1302             gridData.columnsProvider = args.columnsProvider;
1303
1304             // Delivers a stream of array data via promise.notify()
1305             // Useful for passing an array of data to egGrid.get()
1306             // If a count is provided, the array will be trimmed to
1307             // the range defined by count and offset
1308             gridData.arrayNotifier = function(arr, offset, count) {
1309                 if (!arr || arr.length == 0) return $q.when();
1310                 if (count) arr = arr.slice(offset, offset + count);
1311                 var def = $q.defer();
1312                 // promise notifications are only witnessed when delivered
1313                 // after the caller has his hands on the promise object
1314                 $timeout(function() {
1315                     angular.forEach(arr, def.notify);
1316                     def.resolve();
1317                 });
1318                 return def.promise;
1319             }
1320
1321             // Calls the grid refresh function.  Once instantiated, the
1322             // grid will replace this function with it's own refresh()
1323             gridData.refresh = function(noReset) { }
1324
1325             if (!gridData.get) {
1326                 // returns a promise whose notify() delivers items
1327                 gridData.get = function(index, count) {
1328                     console.error("egGridDataProvider.get() not implemented");
1329                 }
1330             }
1331
1332             // attempts a flat field lookup first.  If the column is not
1333             // found on the top-level object, attempts a nested lookup
1334             // TODO: consider a caching layer to speed up template 
1335             // rendering, particularly for nested objects?
1336             gridData.itemFieldValue = function(item, column) {
1337                 if (column.name in item) {
1338                     if (typeof item[column.name] == 'function') {
1339                         return item[column.name]();
1340                     } else {
1341                         return item[column.name];
1342                     }
1343                 } else {
1344                     return gridData.nestedItemFieldValue(item, column);
1345                 }
1346             }
1347
1348             // TODO: deprecate me
1349             gridData.flatItemFieldValue = function(item, column) {
1350                 console.warn('gridData.flatItemFieldValue deprecated; '
1351                     + 'leave provider.itemFieldValue unset');
1352                 return item[column.name];
1353             }
1354
1355             // given an object and a dot-separated path to a field,
1356             // extract the value of the field.  The path can refer
1357             // to function names or object attributes.  If the final
1358             // value is an IDL field, run the value through its
1359             // corresponding output filter.
1360             gridData.nestedItemFieldValue = function(obj, column) {
1361                 if (obj === null || obj === undefined || obj === '') return '';
1362                 if (!column.path) return obj;
1363
1364                 var idl_field;
1365                 var parts = column.path.split('.');
1366
1367                 angular.forEach(parts, function(step, idx) {
1368                     // object is not fleshed to the expected extent
1369                     if (!obj || typeof obj != 'object') {
1370                         obj = '';
1371                         return;
1372                     }
1373
1374                     var cls = obj.classname;
1375                     if (cls && (class_obj = egCore.idl.classes[cls])) {
1376                         idl_field = class_obj.field_map[step];
1377                         obj = obj[step] ? obj[step]() : '';
1378                     } else {
1379                         if (angular.isFunction(obj[step])) {
1380                             obj = obj[step]();
1381                         } else {
1382                             obj = obj[step];
1383                         }
1384                     }
1385                 });
1386
1387                 // We found a nested IDL object which may or may not have 
1388                 // been configured as a top-level column.  Grab the datatype.
1389                 if (idl_field && !column.datatype) 
1390                     column.datatype = idl_field.datatype;
1391
1392                 if (obj === null || obj === undefined || obj === '') return '';
1393                 return obj;
1394             }
1395         }
1396
1397         return {
1398             instance : function(args) {
1399                 return new GridDataProvider(args);
1400             }
1401         };
1402     }
1403 ])
1404
1405
1406 // Factory service for egGridDataManager instances, which are
1407 // responsible for collecting flattened grid data.
1408 .factory('egGridFlatDataProvider', 
1409            ['$q','egCore','egGridDataProvider',
1410     function($q , egCore , egGridDataProvider) {
1411
1412         return {
1413             instance : function(args) {
1414                 var provider = egGridDataProvider.instance(args);
1415
1416                 provider.get = function(offset, count) {
1417
1418                     // no query means no call
1419                     if (!provider.query || 
1420                             angular.equals(provider.query, {})) 
1421                         return $q.when();
1422
1423                     // find all of the currently visible columns
1424                     var queryFields = {}
1425                     angular.forEach(provider.columnsProvider.columns, 
1426                         function(col) {
1427                             // only query IDL-tracked columns
1428                             if (!col.adhoc && (col.required || col.visible))
1429                                 queryFields[col.name] = col.path;
1430                         }
1431                     );
1432
1433                     return egCore.net.request(
1434                         'open-ils.fielder',
1435                         'open-ils.fielder.flattened_search',
1436                         egCore.auth.token(), provider.idlClass, 
1437                         queryFields, provider.query,
1438                         {   sort : provider.sort,
1439                             limit : count,
1440                             offset : offset
1441                         }
1442                     );
1443                 }
1444                 //provider.itemFieldValue = provider.flatItemFieldValue;
1445                 return provider;
1446             }
1447         };
1448     }
1449 ])
1450
1451 .directive('egGridColumnDragSource', function() {
1452     return {
1453         restrict : 'A',
1454         require : '^egGrid',
1455         link : function(scope, element, attrs, egGridCtrl) {
1456             angular.element(element).attr('draggable', 'true');
1457
1458             element.bind('dragstart', function(e) {
1459                 egGridCtrl.dragColumn = attrs.column;
1460                 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1461                 egGridCtrl.colResizeDir = 0;
1462
1463                 if (egGridCtrl.dragType == 'move') {
1464                     // style the column getting moved
1465                     angular.element(e.target).addClass(
1466                         'eg-grid-column-move-handle-active');
1467                 }
1468             });
1469
1470             element.bind('dragend', function(e) {
1471                 if (egGridCtrl.dragType == 'move') {
1472                     angular.element(e.target).removeClass(
1473                         'eg-grid-column-move-handle-active');
1474                 }
1475             });
1476         }
1477     };
1478 })
1479
1480 .directive('egGridColumnDragDest', function() {
1481     return {
1482         restrict : 'A',
1483         require : '^egGrid',
1484         link : function(scope, element, attrs, egGridCtrl) {
1485
1486             element.bind('dragover', function(e) { // required for drop
1487                 e.stopPropagation();
1488                 e.preventDefault();
1489                 e.dataTransfer.dropEffect = 'move';
1490
1491                 if (egGridCtrl.colResizeDir == 0) return; // move
1492
1493                 var cols = egGridCtrl.columnsProvider;
1494                 var srcCol = egGridCtrl.dragColumn;
1495                 var srcColIdx = cols.indexOf(srcCol);
1496
1497                 if (egGridCtrl.colResizeDir == -1) {
1498                     if (cols.indexOf(attrs.column) <= srcColIdx) {
1499                         egGridCtrl.modifyColumnFlex(
1500                             egGridCtrl.columnsProvider.findColumn(
1501                                 egGridCtrl.dragColumn), -1);
1502                         if (cols.columns[srcColIdx+1]) {
1503                             // source column shrinks by one, column to the
1504                             // right grows by one.
1505                             egGridCtrl.modifyColumnFlex(
1506                                 cols.columns[srcColIdx+1], 1);
1507                         }
1508                         scope.$apply();
1509                     }
1510                 } else {
1511                     if (cols.indexOf(attrs.column) > srcColIdx) {
1512                         egGridCtrl.modifyColumnFlex( 
1513                             egGridCtrl.columnsProvider.findColumn(
1514                                 egGridCtrl.dragColumn), 1);
1515                         if (cols.columns[srcColIdx+1]) {
1516                             // source column grows by one, column to the 
1517                             // right grows by one.
1518                             egGridCtrl.modifyColumnFlex(
1519                                 cols.columns[srcColIdx+1], -1);
1520                         }
1521
1522                         scope.$apply();
1523                     }
1524                 }
1525             });
1526
1527             element.bind('dragenter', function(e) {
1528                 e.stopPropagation();
1529                 e.preventDefault();
1530                 if (egGridCtrl.dragType == 'move') {
1531                     angular.element(e.target).addClass('eg-grid-col-hover');
1532                 } else {
1533                     // resize grips are on the right side of each column.
1534                     // dragenter will either occur on the source column 
1535                     // (dragging left) or the column to the right.
1536                     if (egGridCtrl.colResizeDir == 0) {
1537                         if (egGridCtrl.dragColumn == attrs.column) {
1538                             egGridCtrl.colResizeDir = -1; // west
1539                         } else {
1540                             egGridCtrl.colResizeDir = 1; // east
1541                         }
1542                     }
1543                 }
1544             });
1545
1546             element.bind('dragleave', function(e) {
1547                 e.stopPropagation();
1548                 e.preventDefault();
1549                 if (egGridCtrl.dragType == 'move') {
1550                     angular.element(e.target).removeClass('eg-grid-col-hover');
1551                 }
1552             });
1553
1554             element.bind('drop', function(e) {
1555                 e.stopPropagation();
1556                 e.preventDefault();
1557                 egGridCtrl.colResizeDir = 0;
1558                 if (egGridCtrl.dragType == 'move') {
1559                     angular.element(e.target).removeClass('eg-grid-col-hover');
1560                     egGridCtrl.onColumnDrop(attrs.column); // move the column
1561                 }
1562             });
1563         }
1564     };
1565 })
1566  
1567 .directive('egGridMenuItem', function() {
1568     return {
1569         restrict : 'AE',
1570         require : '^egGrid',
1571         scope : {
1572             label : '@',  
1573             handler : '=', // onclick handler function
1574             divider : '=', // if true, show a divider only
1575             handlerData : '=', // if set, passed as second argument to handler
1576             disabled : '=', // function
1577             hidden : '=' // function
1578         },
1579         link : function(scope, element, attrs, egGridCtrl) {
1580             egGridCtrl.addMenuItem({
1581                 label : scope.label,
1582                 handler : scope.handler,
1583                 divider : scope.divider,
1584                 disabled : scope.disabled,
1585                 hidden : scope.hidden,
1586                 handlerData : scope.handlerData
1587             });
1588             scope.$destroy();
1589         }
1590     };
1591 })
1592
1593
1594
1595 /**
1596  * Translates bare IDL object values into display values.
1597  * 1. Passes dates through the angular date filter
1598  * 2. Translates bools to Booleans so the browser can display translated 
1599  *    value.  (Though we could manually translate instead..)
1600  * Others likely to follow...
1601  */
1602 .filter('egGridValueFilter', ['$filter', function($filter) {                         
1603     return function(value, column) {                                             
1604         switch(column.datatype) {                                                
1605             case 'bool':                                                       
1606                 switch(value) {
1607                     // Browser will translate true/false for us                    
1608                     case 't' : 
1609                     case '1' :  // legacy
1610                     case true:
1611                         return ''+true;
1612                     case 'f' : 
1613                     case '0' :  // legacy
1614                     case false:
1615                         return ''+false;
1616                     // value may be null,  '', etc.
1617                     default : return '';
1618                 }
1619             case 'timestamp':                                                  
1620                 // canned angular date filter FTW                              
1621                 if (!column.dateformat) 
1622                     column.dateformat = 'shortDate';
1623                 return $filter('date')(value, column.dateformat);
1624             case 'money':                                                  
1625                 return $filter('currency')(value);
1626             default:                                                           
1627                 return value;                                                  
1628         }                                                                      
1629     }                                                                          
1630 }]);
1631