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