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