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