]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/grid.js
50c27860cee93030ed9964e45a5fa0d8b4da5ec2
[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             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 action handler function for a context action
461             $scope.actionLauncher = function(action) {
462                 if (!action.handler) {
463                     console.error(
464                         'No handler specified for "' + action.label + '"');
465                     return;
466                 }
467
468                 try {
469                     action.handler(grid.getSelectedItems());
470                 } catch(E) {
471                     console.error('Error executing handler for "' 
472                         + action.label + '" => ' + E + "\n" + E.stack);
473                 }
474             }
475
476             // returns the list of selected item objects
477             grid.getSelectedItems = function() {
478                 return $scope.items.filter(
479                     function(item) {
480                         return Boolean($scope.selected[grid.indexValue(item)]);
481                     }
482                 );
483             }
484
485             grid.getItemByIndex = function(index) {
486                 for (var i = 0; i < $scope.items.length; i++) {
487                     var item = $scope.items[i];
488                     if (grid.indexValue(item) == index) 
489                         return item;
490                 }
491             }
492
493             // selects one row after deselecting all of the others
494             grid.selectOneItem = function(index) {
495                 $scope.selected = {};
496                 $scope.selected[index] = true;
497             }
498
499             // selects or deselects an item, without affecting the others.
500             // returns true if the item is selected; false if de-selected.
501             grid.toggleSelectOneItem = function(index) {
502                 if ($scope.selected[index]) {
503                     delete $scope.selected[index];
504                     return false;
505                 } else {
506                     return $scope.selected[index] = true;
507                 }
508             }
509
510             grid.selectAllItems = function() {
511                 angular.forEach($scope.items, function(item) {
512                     $scope.selected[grid.indexValue(item)] = true
513                 });
514             }
515
516             $scope.$watch('selectAll', function(newVal) {
517                 if (newVal) {
518                     grid.selectAllItems();
519                 } else {
520                     $scope.selected = {};
521                 }
522             });
523
524             // returns true if item1 appears in the list before item2;
525             // false otherwise.  this is slightly more efficient that
526             // finding the position of each then comparing them.
527             // item1 / item2 may be an item or an item index
528             grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
529                 var idx1 = grid.indexValue(itemOrIndex1);
530                 var idx2 = grid.indexValue(itemOrIndex2);
531
532                 // use for() for early exit
533                 for (var i = 0; i < $scope.items.length; i++) {
534                     var idx = grid.indexValue($scope.items[i]);
535                     if (idx == idx1) return true;
536                     if (idx == idx2) return false;
537                 }
538                 return false;
539             }
540
541             // 0-based position of item in the current data set
542             grid.indexOf = function(item) {
543                 var idx = grid.indexValue(item);
544                 for (var i = 0; i < $scope.items.length; i++) {
545                     if (grid.indexValue($scope.items[i]) == idx)
546                         return i;
547                 }
548                 return -1;
549             }
550
551             grid.modifyColumnFlex = function(column, val) {
552                 column.flex += val;
553                 // prevent flex:0;  use hiding instead
554                 if (column.flex < 1)
555                     column.flex = 1;
556             }
557             $scope.modifyColumnFlex = function(col, val) {
558                 grid.modifyColumnFlex(col, val);
559             }
560
561             // handles click, control-click, and shift-click
562             $scope.handleRowClick = function($event, item) {
563                 var index = grid.indexValue(item);
564
565                 var origSelected = Object.keys($scope.selected);
566
567                 if ($event.ctrlKey || $event.metaKey /* mac command */) {
568                     // control-click
569                     if (grid.toggleSelectOneItem(index)) 
570                         grid.lastSelectedItemIndex = index;
571
572                 } else if ($event.shiftKey) { 
573                     // shift-click
574
575                     if (!grid.lastSelectedItemIndex || 
576                             index == grid.lastSelectedItemIndex) {
577                         grid.selectOneItem(index);
578                         grid.lastSelectedItemIndex = index;
579
580                     } else {
581
582                         var selecting = false;
583                         var ascending = grid.itemComesBefore(
584                             grid.lastSelectedItemIndex, item);
585                         var startPos = 
586                             grid.indexOf(grid.lastSelectedItemIndex);
587
588                         // update to new last-selected
589                         grid.lastSelectedItemIndex = index;
590
591                         // select each row between the last selected and 
592                         // currently selected items
593                         while (true) {
594                             startPos += ascending ? 1 : -1;
595                             var curItem = $scope.items[startPos];
596                             if (!curItem) break;
597                             var curIdx = grid.indexValue(curItem);
598                             $scope.selected[curIdx] = true;
599                             if (curIdx == index) break; // all done
600                         }
601                     }
602                         
603                 } else {
604                     grid.selectOneItem(index);
605                     grid.lastSelectedItemIndex = index;
606                 }
607             }
608
609             // Builds a sort expression from column sort priorities.
610             // called on page load and any time the priorities are modified.
611             grid.compileSort = function() {
612                 var sortList = grid.columnsProvider.columns.filter(
613                     function(col) { return Number(col.sort) != 0 }
614                 ).sort( 
615                     function(a, b) { 
616                         if (Math.abs(a.sort) < Math.abs(b.sort))
617                             return -1;
618                         return 1;
619                     }
620                 );
621
622                 if (sortList.length) {
623                     grid.dataProvider.sort = sortList.map(function(col) {
624                         var blob = {};
625                         blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
626                         return blob;
627                     });
628                 }
629             }
630
631             // builds a sort expression using a single column, 
632             // toggling between ascending and descending sort.
633             $scope.quickSort = function(col_name) {
634                 var sort = grid.dataProvider.sort;
635                 if (sort && sort.length &&
636                     sort[0] == col_name) {
637                     var blob = {};
638                     blob[col_name] = 'desc';
639                     grid.dataProvider.sort = [blob];
640                 } else {
641                     grid.dataProvider.sort = [col_name];
642                 }
643
644                 grid.offset = 0;
645                 grid.collect();
646             }
647
648             // show / hide the grid configuration row
649             $scope.toggleConfDisplay = function() {
650                 if ($scope.showGridConf) {
651                     $scope.showGridConf = false;
652                     if (grid.columnsProvider.hasSortableColumn()) {
653                         // only refresh the grid if the user has the
654                         // ability to modify the sort priorities.
655                         grid.compileSort();
656                         grid.offset = 0;
657                         grid.collect();
658                     }
659                 } else {
660                     $scope.showGridConf = true;
661                 }
662
663                 $scope.gridColumnPickerIsOpen = false;
664             }
665
666             // called when a dragged column is dropped onto itself
667             // or any other column
668             grid.onColumnDrop = function(target) {
669                 if (angular.isUndefined(target)) return;
670                 if (target == grid.dragColumn) return;
671                 var srcIdx, targetIdx, srcCol;
672                 angular.forEach(grid.columnsProvider.columns,
673                     function(col, idx) {
674                         if (col.name == grid.dragColumn) {
675                             srcIdx = idx;
676                             srcCol = col;
677                         } else if (col.name == target) {
678                             targetIdx = idx;
679                         }
680                     }
681                 );
682
683                 if (srcIdx < targetIdx) targetIdx--;
684
685                 // move src column from old location to new location in 
686                 // the columns array, then force a page refresh
687                 grid.columnsProvider.columns.splice(srcIdx, 1);
688                 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
689                 $scope.$apply(); 
690             }
691
692             // prepares a string for inclusion within a CSV document
693             // by escaping commas and quotes and removing newlines.
694             grid.csvDatum = function(str) {
695                 str = ''+str;
696                 if (!str) return '';
697                 str = str.replace(/\n/g, '');
698                 if (str.match(/\,/) || str.match(/"/)) {                                     
699                     str = str.replace(/"/g, '""');
700                     str = '"' + str + '"';                                           
701                 } 
702                 return str;
703             }
704
705             // sets the download file name and inserts the current CSV
706             // into a Blob URL for browser download.
707             $scope.generateCSVExportURL = function() {
708                 $scope.gridColumnPickerIsOpen = false;
709
710                 // let the file name describe the grid
711                 $scope.csvExportFileName = 
712                     ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
713                     .replace(/\s+/g, '_') + '_' + $scope.page();
714
715                 // toss the CSV into a Blob and update the export URL
716                 var csv = grid.generateCSV();
717                 var blob = new Blob([csv], {type : 'text/plain'});
718                 $scope.csvExportURL = 
719                     ($window.URL || $window.webkitURL).createObjectURL(blob);
720             }
721
722             $scope.printCSV = function() {
723                 $scope.gridColumnPickerIsOpen = false;
724                 egCore.print.print({
725                     context : 'default', 
726                     content : grid.generateCSV(),
727                     content_type : 'text/plain'
728                 });
729             }
730
731             // generates CSV for the currently visible grid contents
732             grid.generateCSV = function() {
733                 var csvStr = '';
734                 var colCount = grid.columnsProvider.columns.length;
735
736                 // columns
737                 angular.forEach(grid.columnsProvider.columns,
738                     function(col) {
739                         if (!col.visible) return;
740                         csvStr += grid.csvDatum(col.label);
741                         csvStr += ',';
742                     }
743                 );
744
745                 csvStr = csvStr.replace(/,$/,'\n');
746
747                 // items
748                 angular.forEach($scope.items, function(item) {
749                     angular.forEach(grid.columnsProvider.columns, 
750                         function(col) {
751                             if (!col.visible) return;
752                             // bare value
753                             var val = grid.dataProvider.itemFieldValue(item, col);
754                             // filtered value (dates, etc.)
755                             val = $filter('egGridValueFilter')(val, col);
756                             csvStr += grid.csvDatum(val);
757                             csvStr += ',';
758                         }
759                     );
760                     csvStr = csvStr.replace(/,$/,'\n');
761                 });
762
763                 return csvStr;
764             }
765
766             // Interpolate the value for column.linkpath within the context
767             // of the row item to generate the final link URL.
768             $scope.generateLinkPath = function(col, item) {
769                 return egCore.strings.$replace(col.linkpath, {item : item});
770             }
771
772             // If a column provides its own HTML template, translate it,
773             // using the current item for the template scope.
774             // note: $sce is required to avoid security restrictions and
775             // is OK here, since the template comes directly from a
776             // local HTML template (not user input).
777             $scope.translateCellTemplate = function(col, item) {
778                 var html = egCore.strings.$replace(col.template, {item : item});
779                 return $sce.trustAsHtml(html);
780             }
781
782             $scope.collect = function() { grid.collect() }
783
784             // asks the dataProvider for a page of data
785             grid.collect = function() {
786
787                 // avoid firing the collect if there is nothing to collect.
788                 if (grid.selfManagedData && !grid.dataProvider.query) return;
789
790                 if (grid.collecting) return; // avoid parallel collect()
791                 grid.collecting = true;
792
793                 console.debug('egGrid.collect() offset=' 
794                     + grid.offset + '; limit=' + grid.limit);
795
796                 // ensure all of our dropdowns are closed
797                 // TODO: git rid of these and just use dropdown-toggle, 
798                 // which is more reliable.
799                 $scope.gridColumnPickerIsOpen = false;
800                 $scope.gridRowCountIsOpen = false;
801                 $scope.gridPageSelectIsOpen = false;
802
803                 $scope.items = [];
804                 $scope.selected = {};
805                 grid.dataProvider.get(grid.offset, grid.limit).then(
806                 function() {
807                     if (grid.controls.allItemsRetrieved)
808                         grid.controls.allItemsRetrieved();
809                 },
810                 null, 
811                 function(item) {
812                     if (item) {
813                         $scope.items.push(item)
814                         if (grid.controls.itemRetrieved)
815                             grid.controls.itemRetrieved(item);
816                     }
817                 }).finally(function() { 
818                     console.debug('egGrid.collect() complete');
819                     grid.collecting = false 
820                 });
821             }
822
823             grid.init();
824         }]
825     };
826 })
827
828 /**
829  * eg-grid-field : used for collecting custom field data from the templates.
830  * This directive does not direct display, it just passes data up to the 
831  * parent grid.
832  */
833 .directive('egGridField', function() {
834     return {
835         require : '^egGrid',
836         restrict : 'AE',
837         scope : {
838             name  : '@', // required; unique name
839             path  : '@', // optional; flesh path
840             ignore: '@', // optional; fields to ignore when path is a wildcard
841             label : '@', // optional; display label
842             flex  : '@',  // optional; default flex width
843             dateformat : '@', // optional: passed down to egGridValueFilter
844
845             // if a field is part of an IDL object, but we are unable to
846             // determine the class, because it's nested within a hash
847             // (i.e. we can't navigate directly to the object via the IDL),
848             // idlClass lets us specify the class.  This is particularly
849             // useful for nested wildcard fields.
850             parentIdlClass : '@', 
851
852             // optional: for non-IDL columns, specifying a datatype
853             // lets the caller control which display filter is used.
854             // datatype should match the standard IDL datatypes.
855             datatype : '@'
856         },
857         link : function(scope, element, attrs, egGridCtrl) {
858
859             // boolean fields are presented as value-less attributes
860             angular.forEach(
861                 [
862                     'visible', 
863                     'hidden', 
864                     'sortable', 
865                     'nonsortable',
866                     'multisortable',
867                     'nonmultisortable',
868                     'required' // if set, always fetch data for this column
869                 ],
870                 function(field) {
871                     if (angular.isDefined(attrs[field]))
872                         scope[field] = true;
873                 }
874             );
875
876             // any HTML content within the field is its custom template
877             var tmpl = element.html();
878             if (tmpl && !tmpl.match(/^\s*$/))
879                 scope.template = tmpl
880
881             egGridCtrl.columnsProvider.add(scope);
882             scope.$destroy();
883         }
884     };
885 })
886
887 /**
888  * eg-grid-action : used for specifying actions which may be applied
889  * to items within the grid.
890  */
891 .directive('egGridAction', function() {
892     return {
893         require : '^egGrid',
894         restrict : 'AE',
895         transclude : true,
896         scope : {
897             label   : '@', // Action label
898             handler : '=',  // Action function handler
899             divider : '='
900         },
901         link : function(scope, element, attrs, egGridCtrl) {
902             egGridCtrl.addAction({
903                 label : scope.label,
904                 divider : scope.divider,
905                 handler : scope.handler
906             });
907             scope.$destroy();
908         }
909     };
910 })
911
912 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
913
914     function ColumnsProvider(args) {
915         var cols = this;
916         cols.columns = [];
917         cols.stockVisible = [];
918         cols.idlClass = args.idlClass;
919         cols.defaultToHidden = args.defaultToHidden;
920         cols.defaultToNoSort = args.defaultToNoSort;
921         cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
922
923         // resets column width, visibility, and sort behavior
924         // Visibility resets to the visibility settings defined in the 
925         // template (i.e. the original egGridField values).
926         cols.reset = function() {
927             angular.forEach(cols.columns, function(col) {
928                 col.flex = 2;
929                 col.sort = 0;
930                 if (cols.stockVisible.indexOf(col.name) > -1) {
931                     col.visible = true;
932                 } else {
933                     col.visible = false;
934                 }
935             });
936         }
937
938         // returns true if any columns are sortable
939         cols.hasSortableColumn = function() {
940             return cols.columns.filter(
941                 function(col) {
942                     return col.sortable || col.multisortable;
943                 }
944             ).length > 0;
945         }
946
947         cols.showAllColumns = function() {
948             angular.forEach(cols.columns, function(column) {
949                 column.visible = true;
950             });
951         }
952
953         cols.hideAllColumns = function() {
954             angular.forEach(cols.columns, function(col) {
955                 delete col.visible;
956             });
957         }
958
959         cols.indexOf = function(name) {
960             for (var i = 0; i < cols.columns.length; i++) {
961                 if (cols.columns[i].name == name) 
962                     return i;
963             }
964             return -1;
965         }
966
967         cols.findColumn = function(name) {
968             return cols.columns[cols.indexOf(name)];
969         }
970
971         cols.compileAutoColumns = function() {
972             var idl_class = egCore.idl.classes[cols.idlClass];
973
974             angular.forEach(
975                 idl_class.fields.sort(
976                     function(a, b) { return a.name < b.name ? -1 : 1 }),
977                 function(field) {
978                     if (field.virtual) return;
979                     if (field.datatype == 'link' || field.datatype == 'org_unit') {
980                         // if the field is a link and the linked class has a
981                         // "selector" field specified, use the selector field
982                         // as the display field for the columns.
983                         // flattener will take care of the fleshing.
984                         if (field['class']) {
985                             var selector_field = egCore.idl.classes[field['class']].fields
986                                 .filter(function(f) { return Boolean(f.selector) })[0];
987                             if (selector_field) {
988                                 field.path = field.name + '.' + selector_field.selector;
989                             }
990                         }
991                     }
992                     cols.add(field, true);
993                 }
994             );
995         }
996
997         // if a column definition has a path with a wildcard, create
998         // columns for all non-virtual fields at the specified 
999         // position in the path.
1000         cols.expandPath = function(colSpec) {
1001
1002             var ignoreList = [];
1003             if (colSpec.ignore)
1004                 ignoreList = colSpec.ignore.split(' ');
1005
1006             var dotpath = colSpec.path.replace(/\.?\*$/,'');
1007             var class_obj;
1008             var idl_field;
1009
1010             if (colSpec.parentIdlClass) {
1011                 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1012             } else {
1013                 class_obj = egCore.idl.classes[cols.idlClass];
1014             }
1015
1016             if (!class_obj) return;
1017
1018             console.debug('egGrid: auto dotpath is: ' + dotpath);
1019             var path_parts = dotpath.split(/\./);
1020
1021             // find the IDL class definition for the last element in the
1022             // path before the .*
1023             // an empty path_parts means expand the root class
1024             if (path_parts) {
1025                 for (var path_idx in path_parts) {
1026                     var part = path_parts[path_idx];
1027                     idl_field = class_obj.field_map[part];
1028
1029                     // unless we're at the end of the list, this field should
1030                     // link to another class.
1031                     if (idl_field && idl_field['class'] && (
1032                         idl_field.datatype == 'link' || 
1033                         idl_field.datatype == 'org_unit')) {
1034                         class_obj = egCore.idl.classes[idl_field['class']];
1035                     } else {
1036                         if (path_idx < (path_parts.length - 1)) {
1037                             // we ran out of classes to hop through before
1038                             // we ran out of path components
1039                             console.error("egGrid: invalid IDL path: " + dotpath);
1040                         }
1041                     }
1042                 }
1043             }
1044
1045             if (class_obj) {
1046                 angular.forEach(class_obj.fields, function(field) {
1047
1048                     // Only show wildcard fields where we have data to show
1049                     // Virtual and un-fleshed links will not have any data.
1050                     if (field.virtual ||
1051                         (field.datatype == 'link' || field.datatype == 'org_unit') ||
1052                         ignoreList.indexOf(field.name) > -1
1053                     )
1054                         return;
1055
1056                     var col = cols.cloneFromScope(colSpec);
1057                     col.path = dotpath + '.' + field.name;
1058                     console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_field));
1059                     cols.add(col, false, true, 
1060                         {idl_parent : idl_field, idl_field : field, idl_class : class_obj});
1061                 });
1062
1063                 cols.columns = cols.columns.sort(
1064                     function(a, b) {
1065                         if (a.explicit) return -1;
1066                         if (b.explicit) return 1;
1067                         if (a.idlclass && b.idlclass) {
1068                             return a.idlclass < b.idlclass ? -1 : 1;
1069                             return a.idlclass > b.idlclass ? 1 : -1;
1070                         }
1071                         if (a.path && b.path) {
1072                             return a.path < b.path ? -1 : 1;
1073                             return a.path > b.path ? 1 : -1;
1074                         }
1075
1076                         return a.label < b.label ? -1 : 1;
1077                     }
1078                 );
1079
1080
1081             } else {
1082                 console.error(
1083                     "egGrid: wildcard path does not resolve to an object: "
1084                     + dotpath);
1085             }
1086         }
1087
1088         // angular.clone(scopeObject) is not permittable.  Manually copy
1089         // the fields over that we need (so the scope object can go away).
1090         cols.cloneFromScope = function(colSpec) {
1091             return {
1092                 name  : colSpec.name,
1093                 label : colSpec.label,
1094                 path  : colSpec.path,
1095                 flex  : Number(colSpec.flex) || 2,
1096                 sort  : Number(colSpec.sort) || 0,
1097                 required : colSpec.required,
1098                 linkpath : colSpec.linkpath,
1099                 template : colSpec.template,
1100                 visible  : colSpec.visible,
1101                 hidden   : colSpec.hidden,
1102                 datatype : colSpec.datatype,
1103                 sortable : colSpec.sortable,
1104                 nonsortable      : colSpec.nonsortable,
1105                 multisortable    : colSpec.multisortable,
1106                 nonmultisortable : colSpec.nonmultisortable,
1107                 dateformat       : colSpec.dateformat,
1108                 parentIdlClass   : colSpec.parentIdlClass
1109             };
1110         }
1111
1112
1113         // Add a column to the columns collection.
1114         // Columns may come from a slim eg-columns-field or 
1115         // directly from the IDL.
1116         cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1117
1118             // First added column with the specified path takes precedence.
1119             // This allows for specific definitions followed by wildcard
1120             // definitions.  If a match is found, back out.
1121             if (cols.columns.filter(function(c) {
1122                 return (c.path == colSpec.path) })[0]) {
1123                 console.debug('skipping pre-existing column ' + colSpec.path);
1124                 return;
1125             }
1126
1127             var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1128
1129             if (column.path && column.path.match(/\*$/)) 
1130                 return cols.expandPath(colSpec);
1131
1132             if (!fromExpand) column.explicit = true;
1133
1134             if (!column.name) column.name = column.path;
1135             if (!column.path) column.path = column.name;
1136
1137             if (column.visible || (!cols.defaultToHidden && !column.hidden))
1138                 column.visible = true;
1139
1140             if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1141                 column.sortable = true;
1142
1143             if (column.multisortable || 
1144                 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1145                 column.multisortable = true;
1146
1147             cols.columns.push(column);
1148
1149             // Track which columns are visible by default in case we
1150             // need to reset column visibility
1151             if (column.visible) 
1152                 cols.stockVisible.push(column.name);
1153
1154             if (fromIDL) return; // directly from egIDL.  nothing left to do.
1155
1156             // lookup the matching IDL field
1157             if (!idl_info && cols.idlClass) 
1158                 idl_info = cols.idlFieldFromPath(column.path);
1159
1160             if (!idl_info) {
1161                 // column is not represented within the IDL
1162                 column.adhoc = true; 
1163                 return; 
1164             }
1165
1166             column.datatype = idl_info.idl_field.datatype;
1167             
1168             if (!column.label) {
1169                 column.label = idl_info.idl_field.label || column.name;
1170             }
1171
1172             if (fromExpand && idl_info.idl_class) {
1173                 column.idlclass = '';
1174                 if (idl_info.idl_parent) {
1175                     column.idlclass = idl_info.idl_parent.label || idl_info.idl_parent.name;
1176                 } else {
1177                     column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1178                 }
1179             }
1180         },
1181
1182         // finds the IDL field from the dotpath, using the columns
1183         // idlClass as the base.
1184         cols.idlFieldFromPath = function(dotpath) {
1185             var class_obj = egCore.idl.classes[cols.idlClass];
1186             var path_parts = dotpath.split(/\./);
1187
1188             var idl_parent;
1189             var idl_field;
1190             for (var path_idx in path_parts) {
1191                 var part = path_parts[path_idx];
1192                 idl_parent = idl_field;
1193                 idl_field = class_obj.field_map[part];
1194
1195                 if (idl_field && idl_field['class'] && (
1196                     idl_field.datatype == 'link' || 
1197                     idl_field.datatype == 'org_unit')) {
1198                     class_obj = egCore.idl.classes[idl_field['class']];
1199                 }
1200                 // else, path is not in the IDL, which is fine
1201             }
1202
1203             if (!idl_field) return null;
1204
1205             return {
1206                 idl_parent: idl_parent,
1207                 idl_field : idl_field,
1208                 idl_class : class_obj
1209             };
1210         }
1211     }
1212
1213     return {
1214         instance : function(args) { return new ColumnsProvider(args) }
1215     }
1216 }])
1217
1218
1219 /*
1220  * Generic data provider template class.  This is basically an abstract
1221  * class factory service whose instances can be locally modified to 
1222  * meet the needs of each individual grid.
1223  */
1224 .factory('egGridDataProvider', 
1225            ['$q','$timeout','$filter','egCore',
1226     function($q , $timeout , $filter , egCore) {
1227
1228         function GridDataProvider(args) {
1229             var gridData = this;
1230             if (!args) args = {};
1231
1232             gridData.sort = [];
1233             gridData.get = args.get;
1234             gridData.query = args.query;
1235             gridData.idlClass = args.idlClass;
1236             gridData.columnsProvider = args.columnsProvider;
1237
1238             // Delivers a stream of array data via promise.notify()
1239             // Useful for passing an array of data to egGrid.get()
1240             // If a count is provided, the array will be trimmed to
1241             // the range defined by count and offset
1242             gridData.arrayNotifier = function(arr, offset, count) {
1243                 if (!arr || arr.length == 0) return $q.when();
1244                 if (count) arr = arr.slice(offset, offset + count);
1245                 var def = $q.defer();
1246                 // promise notifications are only witnessed when delivered
1247                 // after the caller has his hands on the promise object
1248                 $timeout(function() {
1249                     angular.forEach(arr, def.notify);
1250                     def.resolve();
1251                 });
1252                 return def.promise;
1253             }
1254
1255             // Calls the grid refresh function.  Once instantiated, the
1256             // grid will replace this function with it's own refresh()
1257             gridData.refresh = function(noReset) { }
1258
1259             if (!gridData.get) {
1260                 // returns a promise whose notify() delivers items
1261                 gridData.get = function(index, count) {
1262                     console.error("egGridDataProvider.get() not implemented");
1263                 }
1264             }
1265
1266             // attempts a flat field lookup first.  If the column is not
1267             // found on the top-level object, attempts a nested lookup
1268             // TODO: consider a caching layer to speed up template 
1269             // rendering, particularly for nested objects?
1270             gridData.itemFieldValue = function(item, column) {
1271                 if (column.name in item) {
1272                     if (typeof item[column.name] == 'function') {
1273                         return item[column.name]();
1274                     } else {
1275                         return item[column.name];
1276                     }
1277                 } else {
1278                     return gridData.nestedItemFieldValue(item, column);
1279                 }
1280             }
1281
1282             // TODO: deprecate me
1283             gridData.flatItemFieldValue = function(item, column) {
1284                 console.warn('gridData.flatItemFieldValue deprecated; '
1285                     + 'leave provider.itemFieldValue unset');
1286                 return item[column.name];
1287             }
1288
1289             // given an object and a dot-separated path to a field,
1290             // extract the value of the field.  The path can refer
1291             // to function names or object attributes.  If the final
1292             // value is an IDL field, run the value through its
1293             // corresponding output filter.
1294             gridData.nestedItemFieldValue = function(obj, column) {
1295                 if (obj === null || obj === undefined || obj === '') return '';
1296                 if (!column.path) return obj;
1297
1298                 var idl_field;
1299                 var parts = column.path.split('.');
1300
1301                 angular.forEach(parts, function(step, idx) {
1302                     // object is not fleshed to the expected extent
1303                     if (!obj || typeof obj != 'object') {
1304                         obj = '';
1305                         return;
1306                     }
1307
1308                     var cls = obj.classname;
1309                     if (cls && (class_obj = egCore.idl.classes[cls])) {
1310                         idl_field = class_obj.field_map[step];
1311                         obj = obj[step] ? obj[step]() : '';
1312                     } else {
1313                         if (angular.isFunction(obj[step])) {
1314                             obj = obj[step]();
1315                         } else {
1316                             obj = obj[step];
1317                         }
1318                     }
1319                 });
1320
1321                 // We found a nested IDL object which may or may not have 
1322                 // been configured as a top-level column.  Grab the datatype.
1323                 if (idl_field && !column.datatype) 
1324                     column.datatype = idl_field.datatype;
1325
1326                 if (obj === null || obj === undefined || obj === '') return '';
1327                 return obj;
1328             }
1329         }
1330
1331         return {
1332             instance : function(args) {
1333                 return new GridDataProvider(args);
1334             }
1335         };
1336     }
1337 ])
1338
1339
1340 // Factory service for egGridDataManager instances, which are
1341 // responsible for collecting flattened grid data.
1342 .factory('egGridFlatDataProvider', 
1343            ['$q','egCore','egGridDataProvider',
1344     function($q , egCore , egGridDataProvider) {
1345
1346         return {
1347             instance : function(args) {
1348                 var provider = egGridDataProvider.instance(args);
1349
1350                 provider.get = function(offset, count) {
1351
1352                     // no query means no call
1353                     if (!provider.query || 
1354                             angular.equals(provider.query, {})) 
1355                         return $q.when();
1356
1357                     // find all of the currently visible columns
1358                     var queryFields = {}
1359                     angular.forEach(provider.columnsProvider.columns, 
1360                         function(col) {
1361                             // only query IDL-tracked columns
1362                             if (!col.adhoc && (col.required || col.visible))
1363                                 queryFields[col.name] = col.path;
1364                         }
1365                     );
1366
1367                     return egCore.net.request(
1368                         'open-ils.fielder',
1369                         'open-ils.fielder.flattened_search',
1370                         egCore.auth.token(), provider.idlClass, 
1371                         queryFields, provider.query,
1372                         {   sort : provider.sort,
1373                             limit : count,
1374                             offset : offset
1375                         }
1376                     );
1377                 }
1378                 //provider.itemFieldValue = provider.flatItemFieldValue;
1379                 return provider;
1380             }
1381         };
1382     }
1383 ])
1384
1385 .directive('egGridColumnDragSource', function() {
1386     return {
1387         restrict : 'A',
1388         require : '^egGrid',
1389         link : function(scope, element, attrs, egGridCtrl) {
1390             angular.element(element).attr('draggable', 'true');
1391
1392             element.bind('dragstart', function(e) {
1393                 egGridCtrl.dragColumn = attrs.column;
1394                 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1395                 egGridCtrl.colResizeDir = 0;
1396
1397                 if (egGridCtrl.dragType == 'move') {
1398                     // style the column getting moved
1399                     angular.element(e.target).addClass(
1400                         'eg-grid-column-move-handle-active');
1401                 }
1402             });
1403
1404             element.bind('dragend', function(e) {
1405                 if (egGridCtrl.dragType == 'move') {
1406                     angular.element(e.target).removeClass(
1407                         'eg-grid-column-move-handle-active');
1408                 }
1409             });
1410         }
1411     };
1412 })
1413
1414 .directive('egGridColumnDragDest', function() {
1415     return {
1416         restrict : 'A',
1417         require : '^egGrid',
1418         link : function(scope, element, attrs, egGridCtrl) {
1419
1420             element.bind('dragover', function(e) { // required for drop
1421                 e.stopPropagation();
1422                 e.preventDefault();
1423                 e.dataTransfer.dropEffect = 'move';
1424
1425                 if (egGridCtrl.colResizeDir == 0) return; // move
1426
1427                 var cols = egGridCtrl.columnsProvider;
1428                 var srcCol = egGridCtrl.dragColumn;
1429                 var srcColIdx = cols.indexOf(srcCol);
1430
1431                 if (egGridCtrl.colResizeDir == -1) {
1432                     if (cols.indexOf(attrs.column) <= srcColIdx) {
1433                         egGridCtrl.modifyColumnFlex(
1434                             egGridCtrl.columnsProvider.findColumn(
1435                                 egGridCtrl.dragColumn), -1);
1436                         if (cols.columns[srcColIdx+1]) {
1437                             // source column shrinks by one, column to the
1438                             // right grows by one.
1439                             egGridCtrl.modifyColumnFlex(
1440                                 cols.columns[srcColIdx+1], 1);
1441                         }
1442                         scope.$apply();
1443                     }
1444                 } else {
1445                     if (cols.indexOf(attrs.column) > srcColIdx) {
1446                         egGridCtrl.modifyColumnFlex( 
1447                             egGridCtrl.columnsProvider.findColumn(
1448                                 egGridCtrl.dragColumn), 1);
1449                         if (cols.columns[srcColIdx+1]) {
1450                             // source column grows by one, column to the 
1451                             // right grows by one.
1452                             egGridCtrl.modifyColumnFlex(
1453                                 cols.columns[srcColIdx+1], -1);
1454                         }
1455
1456                         scope.$apply();
1457                     }
1458                 }
1459             });
1460
1461             element.bind('dragenter', function(e) {
1462                 e.stopPropagation();
1463                 e.preventDefault();
1464                 if (egGridCtrl.dragType == 'move') {
1465                     angular.element(e.target).addClass('eg-grid-col-hover');
1466                 } else {
1467                     // resize grips are on the right side of each column.
1468                     // dragenter will either occur on the source column 
1469                     // (dragging left) or the column to the right.
1470                     if (egGridCtrl.colResizeDir == 0) {
1471                         if (egGridCtrl.dragColumn == attrs.column) {
1472                             egGridCtrl.colResizeDir = -1; // west
1473                         } else {
1474                             egGridCtrl.colResizeDir = 1; // east
1475                         }
1476                     }
1477                 }
1478             });
1479
1480             element.bind('dragleave', function(e) {
1481                 e.stopPropagation();
1482                 e.preventDefault();
1483                 if (egGridCtrl.dragType == 'move') {
1484                     angular.element(e.target).removeClass('eg-grid-col-hover');
1485                 }
1486             });
1487
1488             element.bind('drop', function(e) {
1489                 e.stopPropagation();
1490                 e.preventDefault();
1491                 egGridCtrl.colResizeDir = 0;
1492                 if (egGridCtrl.dragType == 'move') {
1493                     angular.element(e.target).removeClass('eg-grid-col-hover');
1494                     egGridCtrl.onColumnDrop(attrs.column); // move the column
1495                 }
1496             });
1497         }
1498     };
1499 })
1500  
1501 .directive('egGridMenuItem', function() {
1502     return {
1503         restrict : 'AE',
1504         require : '^egGrid',
1505         scope : {
1506             label : '@',  
1507             handler : '=', // onclick handler function
1508             divider : '=', // if true, show a divider only
1509             handlerData : '=', // if set, passed as second argument to handler
1510             disabled : '=', // function
1511             hidden : '=' // function
1512         },
1513         link : function(scope, element, attrs, egGridCtrl) {
1514             egGridCtrl.addMenuItem({
1515                 label : scope.label,
1516                 handler : scope.handler,
1517                 divider : scope.divider,
1518                 disabled : scope.disabled,
1519                 hidden : scope.hidden,
1520                 handlerData : scope.handlerData
1521             });
1522             scope.$destroy();
1523         }
1524     };
1525 })
1526
1527
1528
1529 /**
1530  * Translates bare IDL object values into display values.
1531  * 1. Passes dates through the angular date filter
1532  * 2. Translates bools to Booleans so the browser can display translated 
1533  *    value.  (Though we could manually translate instead..)
1534  * Others likely to follow...
1535  */
1536 .filter('egGridValueFilter', ['$filter', function($filter) {                         
1537     return function(value, column) {                                             
1538         switch(column.datatype) {                                                
1539             case 'bool':                                                       
1540                 switch(value) {
1541                     // Browser will translate true/false for us                    
1542                     case 't' : 
1543                     case '1' :  // legacy
1544                     case true:
1545                         return ''+true;
1546                     case 'f' : 
1547                     case '0' :  // legacy
1548                     case false:
1549                         return ''+false;
1550                     // value may be null,  '', etc.
1551                     default : return '';
1552                 }
1553             case 'timestamp':                                                  
1554                 // canned angular date filter FTW                              
1555                 if (!column.dateformat) 
1556                     column.dateformat = 'shortDate';
1557                 return $filter('date')(value, column.dateformat);
1558             case 'money':                                                  
1559                 return $filter('currency')(value);
1560             default:                                                           
1561                 return value;                                                  
1562         }                                                                      
1563     }                                                                          
1564 }]);
1565