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