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