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