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