]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/grid.js
webstaff: Teach the grid how to flesh the last step in a path if it is unfleshed
[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             flesher: '=', // optional; function that can flesh a linked field, given the value
983             name  : '@', // required; unique name
984             path  : '@', // optional; flesh path
985             ignore: '@', // optional; fields to ignore when path is a wildcard
986             label : '@', // optional; display label
987             flex  : '@',  // optional; default flex width
988             align  : '@',  // optional; default alignment, left/center/right
989             dateformat : '@', // optional: passed down to egGridValueFilter
990
991             // if a field is part of an IDL object, but we are unable to
992             // determine the class, because it's nested within a hash
993             // (i.e. we can't navigate directly to the object via the IDL),
994             // idlClass lets us specify the class.  This is particularly
995             // useful for nested wildcard fields.
996             parentIdlClass : '@', 
997
998             // optional: for non-IDL columns, specifying a datatype
999             // lets the caller control which display filter is used.
1000             // datatype should match the standard IDL datatypes.
1001             datatype : '@'
1002         },
1003         link : function(scope, element, attrs, egGridCtrl) {
1004
1005             // boolean fields are presented as value-less attributes
1006             angular.forEach(
1007                 [
1008                     'visible', 
1009                     'hidden', 
1010                     'sortable', 
1011                     'nonsortable',
1012                     'multisortable',
1013                     'nonmultisortable',
1014                     'required' // if set, always fetch data for this column
1015                 ],
1016                 function(field) {
1017                     if (angular.isDefined(attrs[field]))
1018                         scope[field] = true;
1019                 }
1020             );
1021
1022             // any HTML content within the field is its custom template
1023             var tmpl = element.html();
1024             if (tmpl && !tmpl.match(/^\s*$/))
1025                 scope.template = tmpl
1026
1027             egGridCtrl.columnsProvider.add(scope);
1028             scope.$destroy();
1029         }
1030     };
1031 })
1032
1033 /**
1034  * eg-grid-action : used for specifying actions which may be applied
1035  * to items within the grid.
1036  */
1037 .directive('egGridAction', function() {
1038     return {
1039         require : '^egGrid',
1040         restrict : 'AE',
1041         transclude : true,
1042         scope : {
1043             group   : '@', // Action group, ungrouped if not set
1044             label   : '@', // Action label
1045             handler : '=',  // Action function handler
1046             hide    : '=',
1047             disabled : '=', // function
1048             divider : '='
1049         },
1050         link : function(scope, element, attrs, egGridCtrl) {
1051             egGridCtrl.addAction({
1052                 hide  : scope.hide,
1053                 group : scope.group,
1054                 label : scope.label,
1055                 divider : scope.divider,
1056                 handler : scope.handler,
1057                 disabled : scope.disabled,
1058             });
1059             scope.$destroy();
1060         }
1061     };
1062 })
1063
1064 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1065
1066     function ColumnsProvider(args) {
1067         var cols = this;
1068         cols.columns = [];
1069         cols.stockVisible = [];
1070         cols.idlClass = args.idlClass;
1071         cols.defaultToHidden = args.defaultToHidden;
1072         cols.defaultToNoSort = args.defaultToNoSort;
1073         cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1074
1075         // resets column width, visibility, and sort behavior
1076         // Visibility resets to the visibility settings defined in the 
1077         // template (i.e. the original egGridField values).
1078         cols.reset = function() {
1079             angular.forEach(cols.columns, function(col) {
1080                 col.align = 'left';
1081                 col.flex = 2;
1082                 col.sort = 0;
1083                 if (cols.stockVisible.indexOf(col.name) > -1) {
1084                     col.visible = true;
1085                 } else {
1086                     col.visible = false;
1087                 }
1088             });
1089         }
1090
1091         // returns true if any columns are sortable
1092         cols.hasSortableColumn = function() {
1093             return cols.columns.filter(
1094                 function(col) {
1095                     return col.sortable || col.multisortable;
1096                 }
1097             ).length > 0;
1098         }
1099
1100         cols.showAllColumns = function() {
1101             angular.forEach(cols.columns, function(column) {
1102                 column.visible = true;
1103             });
1104         }
1105
1106         cols.hideAllColumns = function() {
1107             angular.forEach(cols.columns, function(col) {
1108                 delete col.visible;
1109             });
1110         }
1111
1112         cols.indexOf = function(name) {
1113             for (var i = 0; i < cols.columns.length; i++) {
1114                 if (cols.columns[i].name == name) 
1115                     return i;
1116             }
1117             return -1;
1118         }
1119
1120         cols.findColumn = function(name) {
1121             return cols.columns[cols.indexOf(name)];
1122         }
1123
1124         cols.compileAutoColumns = function() {
1125             var idl_class = egCore.idl.classes[cols.idlClass];
1126
1127             angular.forEach(
1128                 idl_class.fields.sort(
1129                     function(a, b) { return a.name < b.name ? -1 : 1 }),
1130                 function(field) {
1131                     if (field.virtual) return;
1132                     if (field.datatype == 'link' || field.datatype == 'org_unit') {
1133                         // if the field is a link and the linked class has a
1134                         // "selector" field specified, use the selector field
1135                         // as the display field for the columns.
1136                         // flattener will take care of the fleshing.
1137                         if (field['class']) {
1138                             var selector_field = egCore.idl.classes[field['class']].fields
1139                                 .filter(function(f) { return Boolean(f.selector) })[0];
1140                             if (selector_field) {
1141                                 field.path = field.name + '.' + selector_field.selector;
1142                             }
1143                         }
1144                     }
1145                     cols.add(field, true);
1146                 }
1147             );
1148         }
1149
1150         // if a column definition has a path with a wildcard, create
1151         // columns for all non-virtual fields at the specified 
1152         // position in the path.
1153         cols.expandPath = function(colSpec) {
1154
1155             var ignoreList = [];
1156             if (colSpec.ignore)
1157                 ignoreList = colSpec.ignore.split(' ');
1158
1159             var dotpath = colSpec.path.replace(/\.?\*$/,'');
1160             var class_obj;
1161             var idl_field;
1162
1163             if (colSpec.parentIdlClass) {
1164                 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1165             } else {
1166                 class_obj = egCore.idl.classes[cols.idlClass];
1167             }
1168
1169             if (!class_obj) return;
1170
1171             console.debug('egGrid: auto dotpath is: ' + dotpath);
1172             var path_parts = dotpath.split(/\./);
1173
1174             // find the IDL class definition for the last element in the
1175             // path before the .*
1176             // an empty path_parts means expand the root class
1177             if (path_parts) {
1178                 for (var path_idx in path_parts) {
1179                     var part = path_parts[path_idx];
1180                     idl_field = class_obj.field_map[part];
1181
1182                     // unless we're at the end of the list, this field should
1183                     // link to another class.
1184                     if (idl_field && idl_field['class'] && (
1185                         idl_field.datatype == 'link' || 
1186                         idl_field.datatype == 'org_unit')) {
1187                         class_obj = egCore.idl.classes[idl_field['class']];
1188                     } else {
1189                         if (path_idx < (path_parts.length - 1)) {
1190                             // we ran out of classes to hop through before
1191                             // we ran out of path components
1192                             console.error("egGrid: invalid IDL path: " + dotpath);
1193                         }
1194                     }
1195                 }
1196             }
1197
1198             if (class_obj) {
1199                 angular.forEach(class_obj.fields, function(field) {
1200
1201                     // Only show wildcard fields where we have data to show
1202                     // Virtual and un-fleshed links will not have any data.
1203                     if (field.virtual ||
1204                         (field.datatype == 'link' || field.datatype == 'org_unit') ||
1205                         ignoreList.indexOf(field.name) > -1
1206                     )
1207                         return;
1208
1209                     var col = cols.cloneFromScope(colSpec);
1210                     col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1211                     console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_field));
1212                     cols.add(col, false, true, 
1213                         {idl_parent : idl_field, idl_field : field, idl_class : class_obj});
1214                 });
1215
1216                 cols.columns = cols.columns.sort(
1217                     function(a, b) {
1218                         if (a.explicit) return -1;
1219                         if (b.explicit) return 1;
1220                         if (a.idlclass && b.idlclass) {
1221                             return a.idlclass < b.idlclass ? -1 : 1;
1222                             return a.idlclass > b.idlclass ? 1 : -1;
1223                         }
1224                         if (a.path && b.path) {
1225                             return a.path < b.path ? -1 : 1;
1226                             return a.path > b.path ? 1 : -1;
1227                         }
1228
1229                         return a.label < b.label ? -1 : 1;
1230                     }
1231                 );
1232
1233
1234             } else {
1235                 console.error(
1236                     "egGrid: wildcard path does not resolve to an object: "
1237                     + dotpath);
1238             }
1239         }
1240
1241         // angular.clone(scopeObject) is not permittable.  Manually copy
1242         // the fields over that we need (so the scope object can go away).
1243         cols.cloneFromScope = function(colSpec) {
1244             return {
1245                 flesher  : colSpec.flesher,
1246                 name  : colSpec.name,
1247                 label : colSpec.label,
1248                 path  : colSpec.path,
1249                 align  : colSpec.align || 'left',
1250                 flex  : Number(colSpec.flex) || 2,
1251                 sort  : Number(colSpec.sort) || 0,
1252                 required : colSpec.required,
1253                 linkpath : colSpec.linkpath,
1254                 template : colSpec.template,
1255                 visible  : colSpec.visible,
1256                 hidden   : colSpec.hidden,
1257                 datatype : colSpec.datatype,
1258                 sortable : colSpec.sortable,
1259                 nonsortable      : colSpec.nonsortable,
1260                 multisortable    : colSpec.multisortable,
1261                 nonmultisortable : colSpec.nonmultisortable,
1262                 dateformat       : colSpec.dateformat,
1263                 parentIdlClass   : colSpec.parentIdlClass
1264             };
1265         }
1266
1267
1268         // Add a column to the columns collection.
1269         // Columns may come from a slim eg-columns-field or 
1270         // directly from the IDL.
1271         cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1272
1273             // First added column with the specified path takes precedence.
1274             // This allows for specific definitions followed by wildcard
1275             // definitions.  If a match is found, back out.
1276             if (cols.columns.filter(function(c) {
1277                 return (c.path == colSpec.path) })[0]) {
1278                 console.debug('skipping pre-existing column ' + colSpec.path);
1279                 return;
1280             }
1281
1282             var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1283
1284             if (column.path && column.path.match(/\*$/)) 
1285                 return cols.expandPath(colSpec);
1286
1287             if (!fromExpand) column.explicit = true;
1288
1289             if (!column.name) column.name = column.path;
1290             if (!column.path) column.path = column.name;
1291
1292             if (column.visible || (!cols.defaultToHidden && !column.hidden))
1293                 column.visible = true;
1294
1295             if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1296                 column.sortable = true;
1297
1298             if (column.multisortable || 
1299                 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1300                 column.multisortable = true;
1301
1302             cols.columns.push(column);
1303
1304             // Track which columns are visible by default in case we
1305             // need to reset column visibility
1306             if (column.visible) 
1307                 cols.stockVisible.push(column.name);
1308
1309             if (fromIDL) return; // directly from egIDL.  nothing left to do.
1310
1311             // lookup the matching IDL field
1312             if (!idl_info && cols.idlClass) 
1313                 idl_info = cols.idlFieldFromPath(column.path);
1314
1315             if (!idl_info) {
1316                 // column is not represented within the IDL
1317                 column.adhoc = true; 
1318                 return; 
1319             }
1320
1321             column.datatype = idl_info.idl_field.datatype;
1322             
1323             if (!column.label) {
1324                 column.label = idl_info.idl_field.label || column.name;
1325             }
1326
1327             if (fromExpand && idl_info.idl_class) {
1328                 column.idlclass = '';
1329                 if (idl_info.idl_parent) {
1330                     column.idlclass = idl_info.idl_parent.label || idl_info.idl_parent.name;
1331                 } else {
1332                     column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1333                 }
1334             }
1335         },
1336
1337         // finds the IDL field from the dotpath, using the columns
1338         // idlClass as the base.
1339         cols.idlFieldFromPath = function(dotpath) {
1340             var class_obj = egCore.idl.classes[cols.idlClass];
1341             var path_parts = dotpath.split(/\./);
1342
1343             var idl_parent;
1344             var idl_field;
1345             for (var path_idx in path_parts) {
1346                 var part = path_parts[path_idx];
1347                 idl_parent = idl_field;
1348                 idl_field = class_obj.field_map[part];
1349
1350                 if (idl_field && idl_field['class'] && (
1351                     idl_field.datatype == 'link' || 
1352                     idl_field.datatype == 'org_unit')) {
1353                     class_obj = egCore.idl.classes[idl_field['class']];
1354                 }
1355                 // else, path is not in the IDL, which is fine
1356             }
1357
1358             if (!idl_field) return null;
1359
1360             return {
1361                 idl_parent: idl_parent,
1362                 idl_field : idl_field,
1363                 idl_class : class_obj
1364             };
1365         }
1366     }
1367
1368     return {
1369         instance : function(args) { return new ColumnsProvider(args) }
1370     }
1371 }])
1372
1373
1374 /*
1375  * Generic data provider template class.  This is basically an abstract
1376  * class factory service whose instances can be locally modified to 
1377  * meet the needs of each individual grid.
1378  */
1379 .factory('egGridDataProvider', 
1380            ['$q','$timeout','$filter','egCore',
1381     function($q , $timeout , $filter , egCore) {
1382
1383         function GridDataProvider(args) {
1384             var gridData = this;
1385             if (!args) args = {};
1386
1387             gridData.sort = [];
1388             gridData.get = args.get;
1389             gridData.query = args.query;
1390             gridData.idlClass = args.idlClass;
1391             gridData.columnsProvider = args.columnsProvider;
1392
1393             // Delivers a stream of array data via promise.notify()
1394             // Useful for passing an array of data to egGrid.get()
1395             // If a count is provided, the array will be trimmed to
1396             // the range defined by count and offset
1397             gridData.arrayNotifier = function(arr, offset, count) {
1398                 if (!arr || arr.length == 0) return $q.when();
1399                 if (count) arr = arr.slice(offset, offset + count);
1400                 var def = $q.defer();
1401                 // promise notifications are only witnessed when delivered
1402                 // after the caller has his hands on the promise object
1403                 $timeout(function() {
1404                     angular.forEach(arr, def.notify);
1405                     def.resolve();
1406                 });
1407                 return def.promise;
1408             }
1409
1410             // Calls the grid refresh function.  Once instantiated, the
1411             // grid will replace this function with it's own refresh()
1412             gridData.refresh = function(noReset) { }
1413
1414             if (!gridData.get) {
1415                 // returns a promise whose notify() delivers items
1416                 gridData.get = function(index, count) {
1417                     console.error("egGridDataProvider.get() not implemented");
1418                 }
1419             }
1420
1421             // attempts a flat field lookup first.  If the column is not
1422             // found on the top-level object, attempts a nested lookup
1423             // TODO: consider a caching layer to speed up template 
1424             // rendering, particularly for nested objects?
1425             gridData.itemFieldValue = function(item, column) {
1426                 var val;
1427                 if (column.name in item) {
1428                     if (typeof item[column.name] == 'function') {
1429                         val = item[column.name]();
1430                     } else {
1431                         val = item[column.name];
1432                     }
1433                 } else {
1434                     val = gridData.nestedItemFieldValue(item, column);
1435                 }
1436
1437                 return val;
1438             }
1439
1440             // TODO: deprecate me
1441             gridData.flatItemFieldValue = function(item, column) {
1442                 console.warn('gridData.flatItemFieldValue deprecated; '
1443                     + 'leave provider.itemFieldValue unset');
1444                 return item[column.name];
1445             }
1446
1447             // given an object and a dot-separated path to a field,
1448             // extract the value of the field.  The path can refer
1449             // to function names or object attributes.  If the final
1450             // value is an IDL field, run the value through its
1451             // corresponding output filter.
1452             gridData.nestedItemFieldValue = function(obj, column) {
1453                 item = obj; // keep a copy around
1454
1455                 if (obj === null || obj === undefined || obj === '') return '';
1456                 if (!column.path) return obj;
1457
1458                 var idl_field;
1459                 var parts = column.path.split('.');
1460
1461                 angular.forEach(parts, function(step, idx) {
1462                     // object is not fleshed to the expected extent
1463                     if (typeof obj != 'object') {
1464                         if (typeof obj != 'undefined' && column.flesher) {
1465                             obj = column.flesher(obj, column, item);
1466                         } else {
1467                             obj = '';
1468                             return;
1469                         }
1470                     }
1471
1472                     var cls = obj.classname;
1473                     if (cls && (class_obj = egCore.idl.classes[cls])) {
1474                         idl_field = class_obj.field_map[step];
1475                         obj = obj[step] ? obj[step]() : '';
1476                     } else {
1477                         if (angular.isFunction(obj[step])) {
1478                             obj = obj[step]();
1479                         } else {
1480                             obj = obj[step];
1481                         }
1482                     }
1483                 });
1484
1485                 // We found a nested IDL object which may or may not have 
1486                 // been configured as a top-level column.  Grab the datatype.
1487                 if (idl_field && !column.datatype) 
1488                     column.datatype = idl_field.datatype;
1489
1490                 if (obj === null || obj === undefined || obj === '') return '';
1491                 return obj;
1492             }
1493         }
1494
1495         return {
1496             instance : function(args) {
1497                 return new GridDataProvider(args);
1498             }
1499         };
1500     }
1501 ])
1502
1503
1504 // Factory service for egGridDataManager instances, which are
1505 // responsible for collecting flattened grid data.
1506 .factory('egGridFlatDataProvider', 
1507            ['$q','egCore','egGridDataProvider',
1508     function($q , egCore , egGridDataProvider) {
1509
1510         return {
1511             instance : function(args) {
1512                 var provider = egGridDataProvider.instance(args);
1513
1514                 provider.get = function(offset, count) {
1515
1516                     // no query means no call
1517                     if (!provider.query || 
1518                             angular.equals(provider.query, {})) 
1519                         return $q.when();
1520
1521                     // find all of the currently visible columns
1522                     var queryFields = {}
1523                     angular.forEach(provider.columnsProvider.columns, 
1524                         function(col) {
1525                             // only query IDL-tracked columns
1526                             if (!col.adhoc && (col.required || col.visible))
1527                                 queryFields[col.name] = col.path;
1528                         }
1529                     );
1530
1531                     return egCore.net.request(
1532                         'open-ils.fielder',
1533                         'open-ils.fielder.flattened_search',
1534                         egCore.auth.token(), provider.idlClass, 
1535                         queryFields, provider.query,
1536                         {   sort : provider.sort,
1537                             limit : count,
1538                             offset : offset
1539                         }
1540                     );
1541                 }
1542                 //provider.itemFieldValue = provider.flatItemFieldValue;
1543                 return provider;
1544             }
1545         };
1546     }
1547 ])
1548
1549 .directive('egGridColumnDragSource', function() {
1550     return {
1551         restrict : 'A',
1552         require : '^egGrid',
1553         link : function(scope, element, attrs, egGridCtrl) {
1554             angular.element(element).attr('draggable', 'true');
1555
1556             element.bind('dragstart', function(e) {
1557                 egGridCtrl.dragColumn = attrs.column;
1558                 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1559                 egGridCtrl.colResizeDir = 0;
1560
1561                 if (egGridCtrl.dragType == 'move') {
1562                     // style the column getting moved
1563                     angular.element(e.target).addClass(
1564                         'eg-grid-column-move-handle-active');
1565                 }
1566             });
1567
1568             element.bind('dragend', function(e) {
1569                 if (egGridCtrl.dragType == 'move') {
1570                     angular.element(e.target).removeClass(
1571                         'eg-grid-column-move-handle-active');
1572                 }
1573             });
1574         }
1575     };
1576 })
1577
1578 .directive('egGridColumnDragDest', function() {
1579     return {
1580         restrict : 'A',
1581         require : '^egGrid',
1582         link : function(scope, element, attrs, egGridCtrl) {
1583
1584             element.bind('dragover', function(e) { // required for drop
1585                 e.stopPropagation();
1586                 e.preventDefault();
1587                 e.dataTransfer.dropEffect = 'move';
1588
1589                 if (egGridCtrl.colResizeDir == 0) return; // move
1590
1591                 var cols = egGridCtrl.columnsProvider;
1592                 var srcCol = egGridCtrl.dragColumn;
1593                 var srcColIdx = cols.indexOf(srcCol);
1594
1595                 if (egGridCtrl.colResizeDir == -1) {
1596                     if (cols.indexOf(attrs.column) <= srcColIdx) {
1597                         egGridCtrl.modifyColumnFlex(
1598                             egGridCtrl.columnsProvider.findColumn(
1599                                 egGridCtrl.dragColumn), -1);
1600                         if (cols.columns[srcColIdx+1]) {
1601                             // source column shrinks by one, column to the
1602                             // right grows by one.
1603                             egGridCtrl.modifyColumnFlex(
1604                                 cols.columns[srcColIdx+1], 1);
1605                         }
1606                         scope.$apply();
1607                     }
1608                 } else {
1609                     if (cols.indexOf(attrs.column) > srcColIdx) {
1610                         egGridCtrl.modifyColumnFlex( 
1611                             egGridCtrl.columnsProvider.findColumn(
1612                                 egGridCtrl.dragColumn), 1);
1613                         if (cols.columns[srcColIdx+1]) {
1614                             // source column grows by one, column to the 
1615                             // right grows by one.
1616                             egGridCtrl.modifyColumnFlex(
1617                                 cols.columns[srcColIdx+1], -1);
1618                         }
1619
1620                         scope.$apply();
1621                     }
1622                 }
1623             });
1624
1625             element.bind('dragenter', function(e) {
1626                 e.stopPropagation();
1627                 e.preventDefault();
1628                 if (egGridCtrl.dragType == 'move') {
1629                     angular.element(e.target).addClass('eg-grid-col-hover');
1630                 } else {
1631                     // resize grips are on the right side of each column.
1632                     // dragenter will either occur on the source column 
1633                     // (dragging left) or the column to the right.
1634                     if (egGridCtrl.colResizeDir == 0) {
1635                         if (egGridCtrl.dragColumn == attrs.column) {
1636                             egGridCtrl.colResizeDir = -1; // west
1637                         } else {
1638                             egGridCtrl.colResizeDir = 1; // east
1639                         }
1640                     }
1641                 }
1642             });
1643
1644             element.bind('dragleave', function(e) {
1645                 e.stopPropagation();
1646                 e.preventDefault();
1647                 if (egGridCtrl.dragType == 'move') {
1648                     angular.element(e.target).removeClass('eg-grid-col-hover');
1649                 }
1650             });
1651
1652             element.bind('drop', function(e) {
1653                 e.stopPropagation();
1654                 e.preventDefault();
1655                 egGridCtrl.colResizeDir = 0;
1656                 if (egGridCtrl.dragType == 'move') {
1657                     angular.element(e.target).removeClass('eg-grid-col-hover');
1658                     egGridCtrl.onColumnDrop(attrs.column); // move the column
1659                 }
1660             });
1661         }
1662     };
1663 })
1664  
1665 .directive('egGridMenuItem', function() {
1666     return {
1667         restrict : 'AE',
1668         require : '^egGrid',
1669         scope : {
1670             label : '@',  
1671             checkbox : '@',  
1672             checked : '=',  
1673             standalone : '=',  
1674             handler : '=', // onclick handler function
1675             divider : '=', // if true, show a divider only
1676             handlerData : '=', // if set, passed as second argument to handler
1677             disabled : '=', // function
1678             hidden : '=' // function
1679         },
1680         link : function(scope, element, attrs, egGridCtrl) {
1681             egGridCtrl.addMenuItem({
1682                 checkbox : scope.checkbox,
1683                 checked : scope.checked ? true : false,
1684                 label : scope.label,
1685                 standalone : scope.standalone ? true : false,
1686                 handler : scope.handler,
1687                 divider : scope.divider,
1688                 disabled : scope.disabled,
1689                 hidden : scope.hidden,
1690                 handlerData : scope.handlerData
1691             });
1692             scope.$destroy();
1693         }
1694     };
1695 })
1696
1697
1698
1699 /**
1700  * Translates bare IDL object values into display values.
1701  * 1. Passes dates through the angular date filter
1702  * 2. Translates bools to Booleans so the browser can display translated 
1703  *    value.  (Though we could manually translate instead..)
1704  * Others likely to follow...
1705  */
1706 .filter('egGridValueFilter', ['$filter', function($filter) {                         
1707     return function(value, column) {                                             
1708         switch(column.datatype) {                                                
1709             case 'bool':                                                       
1710                 switch(value) {
1711                     // Browser will translate true/false for us                    
1712                     case 't' : 
1713                     case '1' :  // legacy
1714                     case true:
1715                         return ''+true;
1716                     case 'f' : 
1717                     case '0' :  // legacy
1718                     case false:
1719                         return ''+false;
1720                     // value may be null,  '', etc.
1721                     default : return '';
1722                 }
1723             case 'timestamp':                                                  
1724                 // canned angular date filter FTW                              
1725                 if (!column.dateformat) 
1726                     column.dateformat = 'shortDate';
1727                 return $filter('date')(value, column.dateformat);
1728             case 'money':                                                  
1729                 return $filter('currency')(value);
1730             default:                                                           
1731                 return value;                                                  
1732         }                                                                      
1733     }                                                                          
1734 }]);
1735