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