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