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