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