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