]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/grid.js
LP#1402797 Make grid action context menu safe for multiple grids per page
[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_showing) $scope.hideActionContextMenu();
488                 }
489
490             }
491
492             $scope.hideActionContextMenu = function () {
493                 $($scope.menu_dom).css({
494                     display: '',
495                     width: $scope.action_context_width,
496                     top: $scope.action_context_y,
497                     left: $scope.action_context_x
498                 });
499                 $($scope.action_context_parent).append($scope.menu_dom);
500                 $scope.action_context_oldy = $scope.action_context_oldx = 0;
501                 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
502                 $scope.action_context_showing = false;
503             }
504
505             $scope.action_context_showing = false;
506             $scope.showActionContextMenu = function ($event) {
507
508                 // Have to gather these here, instead of inside link()
509                 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
510                 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
511
512                 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
513                     $event.target.click();
514
515                 if (!$scope.action_context_showing) {
516                     $scope.action_context_width = $($scope.menu_dom).css('width');
517                     $scope.action_context_y = $($scope.menu_dom).css('top');
518                     $scope.action_context_x = $($scope.menu_dom).css('left');
519                     $scope.action_context_showing = true;
520                     $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
521
522                     $('body').append($($scope.menu_dom));
523                     $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
524                 }
525
526                 $($scope.menu_dom).css({
527                     display: 'block',
528                     width: $scope.action_context_width,
529                     top: $event.pageY,
530                     left: $event.pageX
531                 });
532
533                 return false;
534             }
535
536             // returns the list of selected item objects
537             grid.getSelectedItems = function() {
538                 return $scope.items.filter(
539                     function(item) {
540                         return Boolean($scope.selected[grid.indexValue(item)]);
541                     }
542                 );
543             }
544
545             grid.getItemByIndex = function(index) {
546                 for (var i = 0; i < $scope.items.length; i++) {
547                     var item = $scope.items[i];
548                     if (grid.indexValue(item) == index) 
549                         return item;
550                 }
551             }
552
553             // selects one row after deselecting all of the others
554             grid.selectOneItem = function(index) {
555                 $scope.selected = {};
556                 $scope.selected[index] = true;
557             }
558
559             // selects or deselects an item, without affecting the others.
560             // returns true if the item is selected; false if de-selected.
561             grid.toggleSelectOneItem = function(index) {
562                 if ($scope.selected[index]) {
563                     delete $scope.selected[index];
564                     return false;
565                 } else {
566                     return $scope.selected[index] = true;
567                 }
568             }
569
570             grid.selectAllItems = function() {
571                 angular.forEach($scope.items, function(item) {
572                     $scope.selected[grid.indexValue(item)] = true
573                 });
574             }
575
576             $scope.$watch('selectAll', function(newVal) {
577                 if (newVal) {
578                     grid.selectAllItems();
579                 } else {
580                     $scope.selected = {};
581                 }
582             });
583
584             // returns true if item1 appears in the list before item2;
585             // false otherwise.  this is slightly more efficient that
586             // finding the position of each then comparing them.
587             // item1 / item2 may be an item or an item index
588             grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
589                 var idx1 = grid.indexValue(itemOrIndex1);
590                 var idx2 = grid.indexValue(itemOrIndex2);
591
592                 // use for() for early exit
593                 for (var i = 0; i < $scope.items.length; i++) {
594                     var idx = grid.indexValue($scope.items[i]);
595                     if (idx == idx1) return true;
596                     if (idx == idx2) return false;
597                 }
598                 return false;
599             }
600
601             // 0-based position of item in the current data set
602             grid.indexOf = function(item) {
603                 var idx = grid.indexValue(item);
604                 for (var i = 0; i < $scope.items.length; i++) {
605                     if (grid.indexValue($scope.items[i]) == idx)
606                         return i;
607                 }
608                 return -1;
609             }
610
611             grid.modifyColumnFlex = function(column, val) {
612                 column.flex += val;
613                 // prevent flex:0;  use hiding instead
614                 if (column.flex < 1)
615                     column.flex = 1;
616             }
617             $scope.modifyColumnFlex = function(col, val) {
618                 grid.modifyColumnFlex(col, val);
619             }
620
621             // handles click, control-click, and shift-click
622             $scope.handleRowClick = function($event, item) {
623                 var index = grid.indexValue(item);
624
625                 var origSelected = Object.keys($scope.selected);
626
627                 if ($event.ctrlKey || $event.metaKey /* mac command */) {
628                     // control-click
629                     if (grid.toggleSelectOneItem(index)) 
630                         grid.lastSelectedItemIndex = index;
631
632                 } else if ($event.shiftKey) { 
633                     // shift-click
634
635                     if (!grid.lastSelectedItemIndex || 
636                             index == grid.lastSelectedItemIndex) {
637                         grid.selectOneItem(index);
638                         grid.lastSelectedItemIndex = index;
639
640                     } else {
641
642                         var selecting = false;
643                         var ascending = grid.itemComesBefore(
644                             grid.lastSelectedItemIndex, item);
645                         var startPos = 
646                             grid.indexOf(grid.lastSelectedItemIndex);
647
648                         // update to new last-selected
649                         grid.lastSelectedItemIndex = index;
650
651                         // select each row between the last selected and 
652                         // currently selected items
653                         while (true) {
654                             startPos += ascending ? 1 : -1;
655                             var curItem = $scope.items[startPos];
656                             if (!curItem) break;
657                             var curIdx = grid.indexValue(curItem);
658                             $scope.selected[curIdx] = true;
659                             if (curIdx == index) break; // all done
660                         }
661                     }
662                         
663                 } else {
664                     grid.selectOneItem(index);
665                     grid.lastSelectedItemIndex = index;
666                 }
667             }
668
669             // Builds a sort expression from column sort priorities.
670             // called on page load and any time the priorities are modified.
671             grid.compileSort = function() {
672                 var sortList = grid.columnsProvider.columns.filter(
673                     function(col) { return Number(col.sort) != 0 }
674                 ).sort( 
675                     function(a, b) { 
676                         if (Math.abs(a.sort) < Math.abs(b.sort))
677                             return -1;
678                         return 1;
679                     }
680                 );
681
682                 if (sortList.length) {
683                     grid.dataProvider.sort = sortList.map(function(col) {
684                         var blob = {};
685                         blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
686                         return blob;
687                     });
688                 }
689             }
690
691             // builds a sort expression using a single column, 
692             // toggling between ascending and descending sort.
693             $scope.quickSort = function(col_name) {
694                 var sort = grid.dataProvider.sort;
695                 if (sort && sort.length &&
696                     sort[0] == col_name) {
697                     var blob = {};
698                     blob[col_name] = 'desc';
699                     grid.dataProvider.sort = [blob];
700                 } else {
701                     grid.dataProvider.sort = [col_name];
702                 }
703
704                 grid.offset = 0;
705                 grid.collect();
706             }
707
708             // show / hide the grid configuration row
709             $scope.toggleConfDisplay = function() {
710                 if ($scope.showGridConf) {
711                     $scope.showGridConf = false;
712                     if (grid.columnsProvider.hasSortableColumn()) {
713                         // only refresh the grid if the user has the
714                         // ability to modify the sort priorities.
715                         grid.compileSort();
716                         grid.offset = 0;
717                         grid.collect();
718                     }
719                 } else {
720                     $scope.showGridConf = true;
721                 }
722
723                 $scope.gridColumnPickerIsOpen = false;
724             }
725
726             // called when a dragged column is dropped onto itself
727             // or any other column
728             grid.onColumnDrop = function(target) {
729                 if (angular.isUndefined(target)) return;
730                 if (target == grid.dragColumn) return;
731                 var srcIdx, targetIdx, srcCol;
732                 angular.forEach(grid.columnsProvider.columns,
733                     function(col, idx) {
734                         if (col.name == grid.dragColumn) {
735                             srcIdx = idx;
736                             srcCol = col;
737                         } else if (col.name == target) {
738                             targetIdx = idx;
739                         }
740                     }
741                 );
742
743                 if (srcIdx < targetIdx) targetIdx--;
744
745                 // move src column from old location to new location in 
746                 // the columns array, then force a page refresh
747                 grid.columnsProvider.columns.splice(srcIdx, 1);
748                 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
749                 $scope.$apply(); 
750             }
751
752             // prepares a string for inclusion within a CSV document
753             // by escaping commas and quotes and removing newlines.
754             grid.csvDatum = function(str) {
755                 str = ''+str;
756                 if (!str) return '';
757                 str = str.replace(/\n/g, '');
758                 if (str.match(/\,/) || str.match(/"/)) {                                     
759                     str = str.replace(/"/g, '""');
760                     str = '"' + str + '"';                                           
761                 } 
762                 return str;
763             }
764
765             // sets the download file name and inserts the current CSV
766             // into a Blob URL for browser download.
767             $scope.generateCSVExportURL = function() {
768                 $scope.gridColumnPickerIsOpen = false;
769
770                 // let the file name describe the grid
771                 $scope.csvExportFileName = 
772                     ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
773                     .replace(/\s+/g, '_') + '_' + $scope.page();
774
775                 // toss the CSV into a Blob and update the export URL
776                 var csv = grid.generateCSV();
777                 var blob = new Blob([csv], {type : 'text/plain'});
778                 $scope.csvExportURL = 
779                     ($window.URL || $window.webkitURL).createObjectURL(blob);
780             }
781
782             $scope.printCSV = function() {
783                 $scope.gridColumnPickerIsOpen = false;
784                 egCore.print.print({
785                     context : 'default', 
786                     content : grid.generateCSV(),
787                     content_type : 'text/plain'
788                 });
789             }
790
791             // generates CSV for the currently visible grid contents
792             grid.generateCSV = function() {
793                 var csvStr = '';
794                 var colCount = grid.columnsProvider.columns.length;
795
796                 // columns
797                 angular.forEach(grid.columnsProvider.columns,
798                     function(col) {
799                         if (!col.visible) return;
800                         csvStr += grid.csvDatum(col.label);
801                         csvStr += ',';
802                     }
803                 );
804
805                 csvStr = csvStr.replace(/,$/,'\n');
806
807                 // items
808                 angular.forEach($scope.items, function(item) {
809                     angular.forEach(grid.columnsProvider.columns, 
810                         function(col) {
811                             if (!col.visible) return;
812                             // bare value
813                             var val = grid.dataProvider.itemFieldValue(item, col);
814                             // filtered value (dates, etc.)
815                             val = $filter('egGridValueFilter')(val, col);
816                             csvStr += grid.csvDatum(val);
817                             csvStr += ',';
818                         }
819                     );
820                     csvStr = csvStr.replace(/,$/,'\n');
821                 });
822
823                 return csvStr;
824             }
825
826             // Interpolate the value for column.linkpath within the context
827             // of the row item to generate the final link URL.
828             $scope.generateLinkPath = function(col, item) {
829                 return egCore.strings.$replace(col.linkpath, {item : item});
830             }
831
832             // If a column provides its own HTML template, translate it,
833             // using the current item for the template scope.
834             // note: $sce is required to avoid security restrictions and
835             // is OK here, since the template comes directly from a
836             // local HTML template (not user input).
837             $scope.translateCellTemplate = function(col, item) {
838                 var html = egCore.strings.$replace(col.template, {item : item});
839                 return $sce.trustAsHtml(html);
840             }
841
842             $scope.collect = function() { grid.collect() }
843
844             // asks the dataProvider for a page of data
845             grid.collect = function() {
846
847                 // avoid firing the collect if there is nothing to collect.
848                 if (grid.selfManagedData && !grid.dataProvider.query) return;
849
850                 if (grid.collecting) return; // avoid parallel collect()
851                 grid.collecting = true;
852
853                 console.debug('egGrid.collect() offset=' 
854                     + grid.offset + '; limit=' + grid.limit);
855
856                 // ensure all of our dropdowns are closed
857                 // TODO: git rid of these and just use dropdown-toggle, 
858                 // which is more reliable.
859                 $scope.gridColumnPickerIsOpen = false;
860                 $scope.gridRowCountIsOpen = false;
861                 $scope.gridPageSelectIsOpen = false;
862
863                 $scope.items = [];
864                 $scope.selected = {};
865                 grid.dataProvider.get(grid.offset, grid.limit).then(
866                 function() {
867                     if (grid.controls.allItemsRetrieved)
868                         grid.controls.allItemsRetrieved();
869                 },
870                 null, 
871                 function(item) {
872                     if (item) {
873                         $scope.items.push(item)
874                         if (grid.controls.itemRetrieved)
875                             grid.controls.itemRetrieved(item);
876                     }
877                 }).finally(function() { 
878                     console.debug('egGrid.collect() complete');
879                     grid.collecting = false 
880                 });
881             }
882
883             grid.init();
884         }]
885     };
886 })
887
888 /**
889  * eg-grid-field : used for collecting custom field data from the templates.
890  * This directive does not direct display, it just passes data up to the 
891  * parent grid.
892  */
893 .directive('egGridField', function() {
894     return {
895         require : '^egGrid',
896         restrict : 'AE',
897         scope : {
898             name  : '@', // required; unique name
899             path  : '@', // optional; flesh path
900             ignore: '@', // optional; fields to ignore when path is a wildcard
901             label : '@', // optional; display label
902             flex  : '@',  // optional; default flex width
903             dateformat : '@', // optional: passed down to egGridValueFilter
904
905             // if a field is part of an IDL object, but we are unable to
906             // determine the class, because it's nested within a hash
907             // (i.e. we can't navigate directly to the object via the IDL),
908             // idlClass lets us specify the class.  This is particularly
909             // useful for nested wildcard fields.
910             parentIdlClass : '@', 
911
912             // optional: for non-IDL columns, specifying a datatype
913             // lets the caller control which display filter is used.
914             // datatype should match the standard IDL datatypes.
915             datatype : '@'
916         },
917         link : function(scope, element, attrs, egGridCtrl) {
918
919             // boolean fields are presented as value-less attributes
920             angular.forEach(
921                 [
922                     'visible', 
923                     'hidden', 
924                     'sortable', 
925                     'nonsortable',
926                     'multisortable',
927                     'nonmultisortable',
928                     'required' // if set, always fetch data for this column
929                 ],
930                 function(field) {
931                     if (angular.isDefined(attrs[field]))
932                         scope[field] = true;
933                 }
934             );
935
936             // any HTML content within the field is its custom template
937             var tmpl = element.html();
938             if (tmpl && !tmpl.match(/^\s*$/))
939                 scope.template = tmpl
940
941             egGridCtrl.columnsProvider.add(scope);
942             scope.$destroy();
943         }
944     };
945 })
946
947 /**
948  * eg-grid-action : used for specifying actions which may be applied
949  * to items within the grid.
950  */
951 .directive('egGridAction', function() {
952     return {
953         require : '^egGrid',
954         restrict : 'AE',
955         transclude : true,
956         scope : {
957             label   : '@', // Action label
958             handler : '=',  // Action function handler
959             hide    : '=',
960             divider : '='
961         },
962         link : function(scope, element, attrs, egGridCtrl) {
963             egGridCtrl.addAction({
964                 hide  : scope.hide,
965                 label : scope.label,
966                 divider : scope.divider,
967                 handler : scope.handler
968             });
969             scope.$destroy();
970         }
971     };
972 })
973
974 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
975
976     function ColumnsProvider(args) {
977         var cols = this;
978         cols.columns = [];
979         cols.stockVisible = [];
980         cols.idlClass = args.idlClass;
981         cols.defaultToHidden = args.defaultToHidden;
982         cols.defaultToNoSort = args.defaultToNoSort;
983         cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
984
985         // resets column width, visibility, and sort behavior
986         // Visibility resets to the visibility settings defined in the 
987         // template (i.e. the original egGridField values).
988         cols.reset = function() {
989             angular.forEach(cols.columns, function(col) {
990                 col.flex = 2;
991                 col.sort = 0;
992                 if (cols.stockVisible.indexOf(col.name) > -1) {
993                     col.visible = true;
994                 } else {
995                     col.visible = false;
996                 }
997             });
998         }
999
1000         // returns true if any columns are sortable
1001         cols.hasSortableColumn = function() {
1002             return cols.columns.filter(
1003                 function(col) {
1004                     return col.sortable || col.multisortable;
1005                 }
1006             ).length > 0;
1007         }
1008
1009         cols.showAllColumns = function() {
1010             angular.forEach(cols.columns, function(column) {
1011                 column.visible = true;
1012             });
1013         }
1014
1015         cols.hideAllColumns = function() {
1016             angular.forEach(cols.columns, function(col) {
1017                 delete col.visible;
1018             });
1019         }
1020
1021         cols.indexOf = function(name) {
1022             for (var i = 0; i < cols.columns.length; i++) {
1023                 if (cols.columns[i].name == name) 
1024                     return i;
1025             }
1026             return -1;
1027         }
1028
1029         cols.findColumn = function(name) {
1030             return cols.columns[cols.indexOf(name)];
1031         }
1032
1033         cols.compileAutoColumns = function() {
1034             var idl_class = egCore.idl.classes[cols.idlClass];
1035
1036             angular.forEach(
1037                 idl_class.fields.sort(
1038                     function(a, b) { return a.name < b.name ? -1 : 1 }),
1039                 function(field) {
1040                     if (field.virtual) return;
1041                     if (field.datatype == 'link' || field.datatype == 'org_unit') {
1042                         // if the field is a link and the linked class has a
1043                         // "selector" field specified, use the selector field
1044                         // as the display field for the columns.
1045                         // flattener will take care of the fleshing.
1046                         if (field['class']) {
1047                             var selector_field = egCore.idl.classes[field['class']].fields
1048                                 .filter(function(f) { return Boolean(f.selector) })[0];
1049                             if (selector_field) {
1050                                 field.path = field.name + '.' + selector_field.selector;
1051                             }
1052                         }
1053                     }
1054                     cols.add(field, true);
1055                 }
1056             );
1057         }
1058
1059         // if a column definition has a path with a wildcard, create
1060         // columns for all non-virtual fields at the specified 
1061         // position in the path.
1062         cols.expandPath = function(colSpec) {
1063
1064             var ignoreList = [];
1065             if (colSpec.ignore)
1066                 ignoreList = colSpec.ignore.split(' ');
1067
1068             var dotpath = colSpec.path.replace(/\.?\*$/,'');
1069             var class_obj;
1070             var idl_field;
1071
1072             if (colSpec.parentIdlClass) {
1073                 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1074             } else {
1075                 class_obj = egCore.idl.classes[cols.idlClass];
1076             }
1077
1078             if (!class_obj) return;
1079
1080             console.debug('egGrid: auto dotpath is: ' + dotpath);
1081             var path_parts = dotpath.split(/\./);
1082
1083             // find the IDL class definition for the last element in the
1084             // path before the .*
1085             // an empty path_parts means expand the root class
1086             if (path_parts) {
1087                 for (var path_idx in path_parts) {
1088                     var part = path_parts[path_idx];
1089                     idl_field = class_obj.field_map[part];
1090
1091                     // unless we're at the end of the list, this field should
1092                     // link to another class.
1093                     if (idl_field && idl_field['class'] && (
1094                         idl_field.datatype == 'link' || 
1095                         idl_field.datatype == 'org_unit')) {
1096                         class_obj = egCore.idl.classes[idl_field['class']];
1097                     } else {
1098                         if (path_idx < (path_parts.length - 1)) {
1099                             // we ran out of classes to hop through before
1100                             // we ran out of path components
1101                             console.error("egGrid: invalid IDL path: " + dotpath);
1102                         }
1103                     }
1104                 }
1105             }
1106
1107             if (class_obj) {
1108                 angular.forEach(class_obj.fields, function(field) {
1109
1110                     // Only show wildcard fields where we have data to show
1111                     // Virtual and un-fleshed links will not have any data.
1112                     if (field.virtual ||
1113                         (field.datatype == 'link' || field.datatype == 'org_unit') ||
1114                         ignoreList.indexOf(field.name) > -1
1115                     )
1116                         return;
1117
1118                     var col = cols.cloneFromScope(colSpec);
1119                     col.path = dotpath + '.' + field.name;
1120                     console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_field));
1121                     cols.add(col, false, true, 
1122                         {idl_parent : idl_field, idl_field : field, idl_class : class_obj});
1123                 });
1124
1125                 cols.columns = cols.columns.sort(
1126                     function(a, b) {
1127                         if (a.explicit) return -1;
1128                         if (b.explicit) return 1;
1129                         if (a.idlclass && b.idlclass) {
1130                             return a.idlclass < b.idlclass ? -1 : 1;
1131                             return a.idlclass > b.idlclass ? 1 : -1;
1132                         }
1133                         if (a.path && b.path) {
1134                             return a.path < b.path ? -1 : 1;
1135                             return a.path > b.path ? 1 : -1;
1136                         }
1137
1138                         return a.label < b.label ? -1 : 1;
1139                     }
1140                 );
1141
1142
1143             } else {
1144                 console.error(
1145                     "egGrid: wildcard path does not resolve to an object: "
1146                     + dotpath);
1147             }
1148         }
1149
1150         // angular.clone(scopeObject) is not permittable.  Manually copy
1151         // the fields over that we need (so the scope object can go away).
1152         cols.cloneFromScope = function(colSpec) {
1153             return {
1154                 name  : colSpec.name,
1155                 label : colSpec.label,
1156                 path  : colSpec.path,
1157                 flex  : Number(colSpec.flex) || 2,
1158                 sort  : Number(colSpec.sort) || 0,
1159                 required : colSpec.required,
1160                 linkpath : colSpec.linkpath,
1161                 template : colSpec.template,
1162                 visible  : colSpec.visible,
1163                 hidden   : colSpec.hidden,
1164                 datatype : colSpec.datatype,
1165                 sortable : colSpec.sortable,
1166                 nonsortable      : colSpec.nonsortable,
1167                 multisortable    : colSpec.multisortable,
1168                 nonmultisortable : colSpec.nonmultisortable,
1169                 dateformat       : colSpec.dateformat,
1170                 parentIdlClass   : colSpec.parentIdlClass
1171             };
1172         }
1173
1174
1175         // Add a column to the columns collection.
1176         // Columns may come from a slim eg-columns-field or 
1177         // directly from the IDL.
1178         cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1179
1180             // First added column with the specified path takes precedence.
1181             // This allows for specific definitions followed by wildcard
1182             // definitions.  If a match is found, back out.
1183             if (cols.columns.filter(function(c) {
1184                 return (c.path == colSpec.path) })[0]) {
1185                 console.debug('skipping pre-existing column ' + colSpec.path);
1186                 return;
1187             }
1188
1189             var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1190
1191             if (column.path && column.path.match(/\*$/)) 
1192                 return cols.expandPath(colSpec);
1193
1194             if (!fromExpand) column.explicit = true;
1195
1196             if (!column.name) column.name = column.path;
1197             if (!column.path) column.path = column.name;
1198
1199             if (column.visible || (!cols.defaultToHidden && !column.hidden))
1200                 column.visible = true;
1201
1202             if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1203                 column.sortable = true;
1204
1205             if (column.multisortable || 
1206                 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1207                 column.multisortable = true;
1208
1209             cols.columns.push(column);
1210
1211             // Track which columns are visible by default in case we
1212             // need to reset column visibility
1213             if (column.visible) 
1214                 cols.stockVisible.push(column.name);
1215
1216             if (fromIDL) return; // directly from egIDL.  nothing left to do.
1217
1218             // lookup the matching IDL field
1219             if (!idl_info && cols.idlClass) 
1220                 idl_info = cols.idlFieldFromPath(column.path);
1221
1222             if (!idl_info) {
1223                 // column is not represented within the IDL
1224                 column.adhoc = true; 
1225                 return; 
1226             }
1227
1228             column.datatype = idl_info.idl_field.datatype;
1229             
1230             if (!column.label) {
1231                 column.label = idl_info.idl_field.label || column.name;
1232             }
1233
1234             if (fromExpand && idl_info.idl_class) {
1235                 column.idlclass = '';
1236                 if (idl_info.idl_parent) {
1237                     column.idlclass = idl_info.idl_parent.label || idl_info.idl_parent.name;
1238                 } else {
1239                     column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1240                 }
1241             }
1242         },
1243
1244         // finds the IDL field from the dotpath, using the columns
1245         // idlClass as the base.
1246         cols.idlFieldFromPath = function(dotpath) {
1247             var class_obj = egCore.idl.classes[cols.idlClass];
1248             var path_parts = dotpath.split(/\./);
1249
1250             var idl_parent;
1251             var idl_field;
1252             for (var path_idx in path_parts) {
1253                 var part = path_parts[path_idx];
1254                 idl_parent = idl_field;
1255                 idl_field = class_obj.field_map[part];
1256
1257                 if (idl_field && idl_field['class'] && (
1258                     idl_field.datatype == 'link' || 
1259                     idl_field.datatype == 'org_unit')) {
1260                     class_obj = egCore.idl.classes[idl_field['class']];
1261                 }
1262                 // else, path is not in the IDL, which is fine
1263             }
1264
1265             if (!idl_field) return null;
1266
1267             return {
1268                 idl_parent: idl_parent,
1269                 idl_field : idl_field,
1270                 idl_class : class_obj
1271             };
1272         }
1273     }
1274
1275     return {
1276         instance : function(args) { return new ColumnsProvider(args) }
1277     }
1278 }])
1279
1280
1281 /*
1282  * Generic data provider template class.  This is basically an abstract
1283  * class factory service whose instances can be locally modified to 
1284  * meet the needs of each individual grid.
1285  */
1286 .factory('egGridDataProvider', 
1287            ['$q','$timeout','$filter','egCore',
1288     function($q , $timeout , $filter , egCore) {
1289
1290         function GridDataProvider(args) {
1291             var gridData = this;
1292             if (!args) args = {};
1293
1294             gridData.sort = [];
1295             gridData.get = args.get;
1296             gridData.query = args.query;
1297             gridData.idlClass = args.idlClass;
1298             gridData.columnsProvider = args.columnsProvider;
1299
1300             // Delivers a stream of array data via promise.notify()
1301             // Useful for passing an array of data to egGrid.get()
1302             // If a count is provided, the array will be trimmed to
1303             // the range defined by count and offset
1304             gridData.arrayNotifier = function(arr, offset, count) {
1305                 if (!arr || arr.length == 0) return $q.when();
1306                 if (count) arr = arr.slice(offset, offset + count);
1307                 var def = $q.defer();
1308                 // promise notifications are only witnessed when delivered
1309                 // after the caller has his hands on the promise object
1310                 $timeout(function() {
1311                     angular.forEach(arr, def.notify);
1312                     def.resolve();
1313                 });
1314                 return def.promise;
1315             }
1316
1317             // Calls the grid refresh function.  Once instantiated, the
1318             // grid will replace this function with it's own refresh()
1319             gridData.refresh = function(noReset) { }
1320
1321             if (!gridData.get) {
1322                 // returns a promise whose notify() delivers items
1323                 gridData.get = function(index, count) {
1324                     console.error("egGridDataProvider.get() not implemented");
1325                 }
1326             }
1327
1328             // attempts a flat field lookup first.  If the column is not
1329             // found on the top-level object, attempts a nested lookup
1330             // TODO: consider a caching layer to speed up template 
1331             // rendering, particularly for nested objects?
1332             gridData.itemFieldValue = function(item, column) {
1333                 if (column.name in item) {
1334                     if (typeof item[column.name] == 'function') {
1335                         return item[column.name]();
1336                     } else {
1337                         return item[column.name];
1338                     }
1339                 } else {
1340                     return gridData.nestedItemFieldValue(item, column);
1341                 }
1342             }
1343
1344             // TODO: deprecate me
1345             gridData.flatItemFieldValue = function(item, column) {
1346                 console.warn('gridData.flatItemFieldValue deprecated; '
1347                     + 'leave provider.itemFieldValue unset');
1348                 return item[column.name];
1349             }
1350
1351             // given an object and a dot-separated path to a field,
1352             // extract the value of the field.  The path can refer
1353             // to function names or object attributes.  If the final
1354             // value is an IDL field, run the value through its
1355             // corresponding output filter.
1356             gridData.nestedItemFieldValue = function(obj, column) {
1357                 if (obj === null || obj === undefined || obj === '') return '';
1358                 if (!column.path) return obj;
1359
1360                 var idl_field;
1361                 var parts = column.path.split('.');
1362
1363                 angular.forEach(parts, function(step, idx) {
1364                     // object is not fleshed to the expected extent
1365                     if (!obj || typeof obj != 'object') {
1366                         obj = '';
1367                         return;
1368                     }
1369
1370                     var cls = obj.classname;
1371                     if (cls && (class_obj = egCore.idl.classes[cls])) {
1372                         idl_field = class_obj.field_map[step];
1373                         obj = obj[step] ? obj[step]() : '';
1374                     } else {
1375                         if (angular.isFunction(obj[step])) {
1376                             obj = obj[step]();
1377                         } else {
1378                             obj = obj[step];
1379                         }
1380                     }
1381                 });
1382
1383                 // We found a nested IDL object which may or may not have 
1384                 // been configured as a top-level column.  Grab the datatype.
1385                 if (idl_field && !column.datatype) 
1386                     column.datatype = idl_field.datatype;
1387
1388                 if (obj === null || obj === undefined || obj === '') return '';
1389                 return obj;
1390             }
1391         }
1392
1393         return {
1394             instance : function(args) {
1395                 return new GridDataProvider(args);
1396             }
1397         };
1398     }
1399 ])
1400
1401
1402 // Factory service for egGridDataManager instances, which are
1403 // responsible for collecting flattened grid data.
1404 .factory('egGridFlatDataProvider', 
1405            ['$q','egCore','egGridDataProvider',
1406     function($q , egCore , egGridDataProvider) {
1407
1408         return {
1409             instance : function(args) {
1410                 var provider = egGridDataProvider.instance(args);
1411
1412                 provider.get = function(offset, count) {
1413
1414                     // no query means no call
1415                     if (!provider.query || 
1416                             angular.equals(provider.query, {})) 
1417                         return $q.when();
1418
1419                     // find all of the currently visible columns
1420                     var queryFields = {}
1421                     angular.forEach(provider.columnsProvider.columns, 
1422                         function(col) {
1423                             // only query IDL-tracked columns
1424                             if (!col.adhoc && (col.required || col.visible))
1425                                 queryFields[col.name] = col.path;
1426                         }
1427                     );
1428
1429                     return egCore.net.request(
1430                         'open-ils.fielder',
1431                         'open-ils.fielder.flattened_search',
1432                         egCore.auth.token(), provider.idlClass, 
1433                         queryFields, provider.query,
1434                         {   sort : provider.sort,
1435                             limit : count,
1436                             offset : offset
1437                         }
1438                     );
1439                 }
1440                 //provider.itemFieldValue = provider.flatItemFieldValue;
1441                 return provider;
1442             }
1443         };
1444     }
1445 ])
1446
1447 .directive('egGridColumnDragSource', function() {
1448     return {
1449         restrict : 'A',
1450         require : '^egGrid',
1451         link : function(scope, element, attrs, egGridCtrl) {
1452             angular.element(element).attr('draggable', 'true');
1453
1454             element.bind('dragstart', function(e) {
1455                 egGridCtrl.dragColumn = attrs.column;
1456                 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1457                 egGridCtrl.colResizeDir = 0;
1458
1459                 if (egGridCtrl.dragType == 'move') {
1460                     // style the column getting moved
1461                     angular.element(e.target).addClass(
1462                         'eg-grid-column-move-handle-active');
1463                 }
1464             });
1465
1466             element.bind('dragend', function(e) {
1467                 if (egGridCtrl.dragType == 'move') {
1468                     angular.element(e.target).removeClass(
1469                         'eg-grid-column-move-handle-active');
1470                 }
1471             });
1472         }
1473     };
1474 })
1475
1476 .directive('egGridColumnDragDest', function() {
1477     return {
1478         restrict : 'A',
1479         require : '^egGrid',
1480         link : function(scope, element, attrs, egGridCtrl) {
1481
1482             element.bind('dragover', function(e) { // required for drop
1483                 e.stopPropagation();
1484                 e.preventDefault();
1485                 e.dataTransfer.dropEffect = 'move';
1486
1487                 if (egGridCtrl.colResizeDir == 0) return; // move
1488
1489                 var cols = egGridCtrl.columnsProvider;
1490                 var srcCol = egGridCtrl.dragColumn;
1491                 var srcColIdx = cols.indexOf(srcCol);
1492
1493                 if (egGridCtrl.colResizeDir == -1) {
1494                     if (cols.indexOf(attrs.column) <= srcColIdx) {
1495                         egGridCtrl.modifyColumnFlex(
1496                             egGridCtrl.columnsProvider.findColumn(
1497                                 egGridCtrl.dragColumn), -1);
1498                         if (cols.columns[srcColIdx+1]) {
1499                             // source column shrinks by one, column to the
1500                             // right grows by one.
1501                             egGridCtrl.modifyColumnFlex(
1502                                 cols.columns[srcColIdx+1], 1);
1503                         }
1504                         scope.$apply();
1505                     }
1506                 } else {
1507                     if (cols.indexOf(attrs.column) > srcColIdx) {
1508                         egGridCtrl.modifyColumnFlex( 
1509                             egGridCtrl.columnsProvider.findColumn(
1510                                 egGridCtrl.dragColumn), 1);
1511                         if (cols.columns[srcColIdx+1]) {
1512                             // source column grows by one, column to the 
1513                             // right grows by one.
1514                             egGridCtrl.modifyColumnFlex(
1515                                 cols.columns[srcColIdx+1], -1);
1516                         }
1517
1518                         scope.$apply();
1519                     }
1520                 }
1521             });
1522
1523             element.bind('dragenter', function(e) {
1524                 e.stopPropagation();
1525                 e.preventDefault();
1526                 if (egGridCtrl.dragType == 'move') {
1527                     angular.element(e.target).addClass('eg-grid-col-hover');
1528                 } else {
1529                     // resize grips are on the right side of each column.
1530                     // dragenter will either occur on the source column 
1531                     // (dragging left) or the column to the right.
1532                     if (egGridCtrl.colResizeDir == 0) {
1533                         if (egGridCtrl.dragColumn == attrs.column) {
1534                             egGridCtrl.colResizeDir = -1; // west
1535                         } else {
1536                             egGridCtrl.colResizeDir = 1; // east
1537                         }
1538                     }
1539                 }
1540             });
1541
1542             element.bind('dragleave', function(e) {
1543                 e.stopPropagation();
1544                 e.preventDefault();
1545                 if (egGridCtrl.dragType == 'move') {
1546                     angular.element(e.target).removeClass('eg-grid-col-hover');
1547                 }
1548             });
1549
1550             element.bind('drop', function(e) {
1551                 e.stopPropagation();
1552                 e.preventDefault();
1553                 egGridCtrl.colResizeDir = 0;
1554                 if (egGridCtrl.dragType == 'move') {
1555                     angular.element(e.target).removeClass('eg-grid-col-hover');
1556                     egGridCtrl.onColumnDrop(attrs.column); // move the column
1557                 }
1558             });
1559         }
1560     };
1561 })
1562  
1563 .directive('egGridMenuItem', function() {
1564     return {
1565         restrict : 'AE',
1566         require : '^egGrid',
1567         scope : {
1568             label : '@',  
1569             handler : '=', // onclick handler function
1570             divider : '=', // if true, show a divider only
1571             handlerData : '=', // if set, passed as second argument to handler
1572             disabled : '=', // function
1573             hidden : '=' // function
1574         },
1575         link : function(scope, element, attrs, egGridCtrl) {
1576             egGridCtrl.addMenuItem({
1577                 label : scope.label,
1578                 handler : scope.handler,
1579                 divider : scope.divider,
1580                 disabled : scope.disabled,
1581                 hidden : scope.hidden,
1582                 handlerData : scope.handlerData
1583             });
1584             scope.$destroy();
1585         }
1586     };
1587 })
1588
1589
1590
1591 /**
1592  * Translates bare IDL object values into display values.
1593  * 1. Passes dates through the angular date filter
1594  * 2. Translates bools to Booleans so the browser can display translated 
1595  *    value.  (Though we could manually translate instead..)
1596  * Others likely to follow...
1597  */
1598 .filter('egGridValueFilter', ['$filter', function($filter) {                         
1599     return function(value, column) {                                             
1600         switch(column.datatype) {                                                
1601             case 'bool':                                                       
1602                 switch(value) {
1603                     // Browser will translate true/false for us                    
1604                     case 't' : 
1605                     case '1' :  // legacy
1606                     case true:
1607                         return ''+true;
1608                     case 'f' : 
1609                     case '0' :  // legacy
1610                     case false:
1611                         return ''+false;
1612                     // value may be null,  '', etc.
1613                     default : return '';
1614                 }
1615             case 'timestamp':                                                  
1616                 // canned angular date filter FTW                              
1617                 if (!column.dateformat) 
1618                     column.dateformat = 'shortDate';
1619                 return $filter('date')(value, column.dateformat);
1620             case 'money':                                                  
1621                 return $filter('currency')(value);
1622             default:                                                           
1623                 return value;                                                  
1624         }                                                                      
1625     }                                                                          
1626 }]);
1627