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