1 angular.module('egGridMod',
2 ['egCoreMod', 'egUiMod', 'ui.bootstrap'])
4 .directive('egGrid', function() {
10 // IDL class hint (e.g. "aou")
16 // if true, grid columns are derived from all non-virtual
17 // fields on the base idlClass
20 // grid preferences will be stored / retrieved with this key
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.
29 // Reference to externally provided egGridDataProvider
32 // Reference to externally provided item-selection handler
35 // Reference to externally provided after-item-selection handler
38 // comma-separated list of supported or disabled grid features
39 // supported features:
40 // startSelected : init the grid with all rows selected by default
41 // allowAll : add an "All" option to row count (really 10000)
42 // -menu : don't show any menu buttons (or use space for them)
43 // -picker : don't show the column picker
44 // -pagination : don't show any pagination elements, and set
46 // -actions : don't show the actions dropdown
47 // -index : don't show the row index column (can't use "index"
48 // as the idField in this case)
49 // -display : columns are hidden by default
50 // -sort : columns are unsortable by default
51 // -multisort : sort priorities config disabled by default
52 // -multiselect : only one row at a time can be selected;
53 // choosing this also disables the checkbox
57 // optional primary grid label
60 // if true, use the IDL class label as the mainLabel
63 // optional context menu label
66 dateformat : '@', // optional: passed down to egGridValueFilter
67 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
68 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
69 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
71 // Hash of control functions.
73 // These functions are defined by the calling scope and
74 // invoked as-is by the grid w/ the specified parameters.
76 // collectStarted : function() {}
77 // itemRetrieved : function(item) {}
78 // allItemsRetrieved : function() {}
81 // If defined, the grid will watch the return value from
82 // the function defined at watchQuery on each digest and
83 // re-draw the grid when query changes occur.
85 // watchQuery : function() { /* return grid query */ }
88 // These functions are defined by the grid and thus
89 // replace any values defined for these attributes from the
92 // activateItem : function(item) {}
93 // allItems : function(allItems) {}
94 // selectedItems : function(selected) {}
95 // selectItems : function(ids) {}
96 // setQuery : function(queryStruct) {} // causes reload
97 // setSort : function(sortSturct) {} // causes reload
101 // TODO: avoid hard-coded url
102 templateUrl : '/eg/staff/share/t_autogrid',
104 link : function(scope, element, attrs) {
105 // link() is called after page compilation, which means our
106 // eg-grid-field's have been parsed and loaded. Now it's
107 // safe to perform our initial page load.
109 // load auto fields after eg-grid-field's so they are not clobbered
110 scope.handleAutoFields();
113 scope.grid_element = element;
115 .find('.eg-grid-content-body')
116 .bind('contextmenu', scope.showActionContextMenu);
120 '$scope','$q','egCore','egGridFlatDataProvider','$location',
121 'egGridColumnsProvider','$filter','$window','$sce','$timeout',
122 function($scope, $q , egCore, egGridFlatDataProvider , $location,
123 egGridColumnsProvider , $filter , $window , $sce , $timeout) {
127 grid.init = function() {
130 $scope.showGridConf = false;
131 grid.totalCount = -1;
132 $scope.selected = {};
133 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
134 $scope.menuItems = []; // global actions
136 // returns true if any rows are selected.
137 $scope.hasSelected = function() {
138 return grid.getSelectedItems().length > 0 };
140 var features = ($scope.features) ?
141 $scope.features.split(',') : [];
142 delete $scope.features;
144 $scope.showIndex = (features.indexOf('-index') == -1);
146 $scope.allowAll = (features.indexOf('allowAll') > -1);
147 $scope.startSelected = $scope.selectAll = (features.indexOf('startSelected') > -1);
148 $scope.showActions = (features.indexOf('-actions') == -1);
149 $scope.showPagination = (features.indexOf('-pagination') == -1);
150 $scope.showPicker = (features.indexOf('-picker') == -1);
152 $scope.showMenu = (features.indexOf('-menu') == -1);
154 // remove some unneeded values from the scope to reduce bloat
156 grid.idlClass = $scope.idlClass;
157 delete $scope.idlClass;
159 grid.persistKey = $scope.persistKey;
160 delete $scope.persistKey;
162 var stored_limit = 0;
163 if ($scope.showPagination) {
164 if (grid.persistKey) {
165 var stored_limit = Number(
166 egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
170 stored_limit = 10000; // maybe support "Inf"?
173 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
175 grid.indexField = $scope.idField;
176 delete $scope.idField;
178 grid.dataProvider = $scope.itemsProvider;
180 if (!grid.indexField && grid.idlClass)
181 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
183 grid.columnsProvider = egGridColumnsProvider.instance({
184 idlClass : grid.idlClass,
185 clientSort : (features.indexOf('clientsort') > -1 && features.indexOf('-clientsort') == -1),
186 defaultToHidden : (features.indexOf('-display') > -1),
187 defaultToNoSort : (features.indexOf('-sort') > -1),
188 defaultToNoMultiSort : (features.indexOf('-multisort') > -1),
189 defaultDateFormat : $scope.dateformat,
190 defaultDateContext : $scope.datecontext,
191 defaultDateFilter : $scope.datefilter,
192 defaultDateOnlyInterval : $scope.dateonlyinterval
194 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
196 $scope.handleAutoFields = function() {
197 if ($scope.autoFields) {
198 if (grid.autoLabel) {
200 egCore.idl.classes[grid.idlClass].label;
202 grid.columnsProvider.compileAutoColumns();
203 delete $scope.autoFields;
207 if (!grid.dataProvider) {
208 // no provider, um, provided.
209 // Use a flat data provider
211 grid.selfManagedData = true;
212 grid.dataProvider = egGridFlatDataProvider.instance({
213 indexField : grid.indexField,
214 idlClass : grid.idlClass,
215 columnsProvider : grid.columnsProvider,
220 grid.dataProvider.columnsProvider = grid.columnsProvider;
222 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
223 $scope.indexValue = function(item) {
224 return grid.indexValue(item)
227 grid.applyControlFunctions();
229 grid.loadConfig().then(function() {
230 // link columns to scope after loadConfig(), since it
231 // replaces the columns array.
232 $scope.columns = grid.columnsProvider.columns;
235 // NOTE: grid.collect() is first called from link(), not here.
238 // link our control functions into the gridControls
239 // scope object so the caller can access them.
240 grid.applyControlFunctions = function() {
242 // we use some of these controls internally, so sett
243 // them up even if the caller doesn't request them.
244 var controls = $scope.gridControls || {};
246 controls.columnMap = function() {
248 angular.forEach(grid.columnsProvider.columns, function (c) {
254 controls.columnsProvider = function() {
255 return grid.columnsProvider;
258 // link in the control functions
259 controls.selectedItems = function() {
260 return grid.getSelectedItems()
263 controls.allItems = function() {
267 controls.selectItems = function(ids) {
269 $scope.selected = {};
270 angular.forEach(ids, function(i) {
271 $scope.selected[''+i] = true;
275 // if the caller provided a functional setQuery,
276 // extract the value before replacing it
277 if (controls.setQuery) {
278 grid.dataProvider.query =
282 controls.setQuery = function(query) {
283 grid.dataProvider.query = query;
287 if (controls.watchQuery) {
288 // capture the initial query value
289 grid.dataProvider.query = controls.watchQuery();
292 $scope.gridWatchQuery = controls.watchQuery;
293 $scope.$watch('gridWatchQuery()', function(newv) {
294 controls.setQuery(newv);
298 // if the caller provided a functional setSort
299 // extract the value before replacing it
300 grid.dataProvider.sort =
301 controls.setSort ? controls.setSort() : [];
303 controls.setSort = function(sort) {
307 controls.refresh = function(noReset) {
308 if (!noReset) grid.offset = 0;
312 controls.setLimit = function(limit,forget) {
313 if (!forget && grid.persistKey)
314 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
317 controls.getLimit = function() {
320 controls.setOffset = function(offset) {
321 grid.offset = offset;
323 controls.getOffset = function() {
327 controls.saveConfig = function () {
328 return $scope.saveConfig();
331 grid.dataProvider.refresh = controls.refresh;
332 grid.controls = controls;
335 // If a menu item provides its own HTML template, translate it,
336 // using the menu item for the template scope.
337 // note: $sce is required to avoid security restrictions and
338 // is OK here, since the template comes directly from a
339 // local HTML template (not user input).
340 $scope.translateMenuItemTemplate = function(item) {
341 var html = egCore.strings.$replace(item.template, {item : item});
342 return $sce.trustAsHtml(html);
345 // add a new (global) grid menu item
346 grid.addMenuItem = function(item) {
347 $scope.menuItems.push(item);
348 var handler = item.handler;
349 item.handler = function() {
350 $scope.gridMenuIsOpen = false; // close menu
353 item.handlerData, grid.getSelectedItems());
358 // add a selected-items action
359 grid.addAction = function(act) {
361 $scope.actionGroups.forEach(function(g){
362 if (g.label === act.group) {
368 $scope.actionGroups.push({
375 // remove the stored column configuration preferenc, then recover
376 // the column visibility information from the initial page load.
377 $scope.resetColumns = function() {
378 $scope.gridColumnPickerIsOpen = false;
379 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
381 grid.columnsProvider.reset();
382 if (grid.selfManagedData) grid.collect();
386 $scope.showAllColumns = function() {
387 $scope.gridColumnPickerIsOpen = false;
388 grid.columnsProvider.showAllColumns();
389 if (grid.selfManagedData) grid.collect();
392 $scope.hideAllColumns = function() {
393 $scope.gridColumnPickerIsOpen = false;
394 grid.columnsProvider.hideAllColumns();
395 // note: no need to fetch new data if no columns are visible
398 $scope.toggleColumnVisibility = function(col) {
399 $scope.gridColumnPickerIsOpen = false;
400 col.visible = !col.visible;
402 // egGridFlatDataProvider only retrieves data to be
403 // displayed. When column visibility changes, it's
404 // necessary to fetch the newly visible column data.
405 if (grid.selfManagedData) grid.collect();
408 // save the columns configuration (position, sort, width) to
409 // eg.grid.<persist-key>
410 $scope.saveConfig = function() {
411 $scope.gridColumnPickerIsOpen = false;
413 if (!grid.persistKey) {
415 "Cannot save settings without a grid persist-key");
419 // only store information about visible columns.
420 var conf = grid.columnsProvider.columns.filter(
421 function(col) {return Boolean(col.visible) });
423 // now scrunch the data down to just the needed info
424 conf = conf.map(function(col) {
425 var c = {name : col.name}
426 // Apart from the name, only store non-default values.
427 // No need to store col.visible, since that's implicit
428 if (col.align != 'left') c.align = col.align;
429 if (col.flex != 2) c.flex = col.flex;
430 if (Number(col.sort)) c.sort = Number(c.sort);
434 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
436 // Save operation performed from the grid configuration UI.
437 // Hide the configuration UI and re-draw w/ sort applied
438 if ($scope.showGridConf)
439 $scope.toggleConfDisplay();
444 // load the columns configuration (position, sort, width) from
445 // eg.grid.<persist-key> and apply the loaded settings to the
446 // columns on our columnsProvider
447 grid.loadConfig = function() {
448 if (!grid.persistKey) return $q.when();
450 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
451 .then(function(conf) {
454 var columns = grid.columnsProvider.columns;
457 angular.forEach(conf, function(col) {
458 var grid_col = columns.filter(
459 function(c) {return c.name == col.name})[0];
462 // saved column does not match a column in the
463 // current grid. skip it.
467 grid_col.align = col.align || 'left';
468 grid_col.flex = col.flex || 2;
469 grid_col.sort = col.sort || 0;
470 // all saved columns are assumed to be true
471 grid_col.visible = true;
473 .filter(function (c) {
474 return c.name == grid_col.name;
477 new_cols.push(grid_col);
480 // columns which are not expressed within the saved
481 // configuration are marked as non-visible and
482 // appended to the end of the new list of columns.
483 angular.forEach(columns, function(col) {
484 var found = conf.filter(
485 function(c) {return (c.name == col.name)})[0];
492 grid.columnsProvider.columns = new_cols;
498 $scope.onContextMenu = function($event) {
499 var col = angular.element($event.target).attr('column');
500 console.log('selected column ' + col);
503 $scope.page = function() {
504 return (grid.offset / grid.limit) + 1;
507 $scope.goToPage = function(page) {
509 if (angular.isNumber(page) && page > 0) {
510 grid.offset = (page - 1) * grid.limit;
515 $scope.offset = function(o) {
516 if (angular.isNumber(o))
521 $scope.limit = function(l) {
522 if (angular.isNumber(l)) {
524 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
530 $scope.onFirstPage = function() {
531 return grid.offset == 0;
534 $scope.hasNextPage = function() {
535 // we have less data than requested, there must
536 // not be any more pages
537 if (grid.count() < grid.limit) return false;
539 // if the total count is not known, assume that a full
540 // page of data implies more pages are available.
541 if (grid.totalCount == -1) return true;
543 // we have a full page of data, but is there more?
544 return grid.totalCount > (grid.offset + grid.count());
547 $scope.incrementPage = function() {
548 grid.offset += grid.limit;
552 $scope.decrementPage = function() {
553 if (grid.offset < grid.limit) {
556 grid.offset -= grid.limit;
561 // number of items loaded for the current page of results
562 grid.count = function() {
563 return $scope.items.length;
566 // returns the unique identifier value for the provided item
567 // for internal consistency, indexValue is always coerced
569 grid.indexValue = function(item) {
570 if (angular.isObject(item)) {
572 if (angular.isFunction(item[grid.indexField]))
573 return ''+item[grid.indexField]();
574 return ''+item[grid.indexField]; // flat data
577 // passed a non-object; assume it's an index
581 // fires the hide handler function for a context action
582 $scope.actionHide = function(action) {
583 if (typeof action.hide == 'undefined') {
586 if (angular.isFunction(action.hide))
587 return action.hide(action);
591 // fires the disable handler function for a context action
592 $scope.actionDisable = function(action) {
593 if (typeof action.disabled == 'undefined') {
596 if (angular.isFunction(action.disabled))
597 return action.disabled(action);
598 return action.disabled;
601 // fires the action handler function for a context action
602 $scope.actionLauncher = function(action) {
603 if (!action.handler) {
605 'No handler specified for "' + action.label + '"');
609 action.handler(grid.getSelectedItems());
611 console.error('Error executing handler for "'
612 + action.label + '" => ' + E + "\n" + E.stack);
615 if ($scope.action_context_showing) $scope.hideActionContextMenu();
620 $scope.hideActionContextMenu = function () {
621 $($scope.menu_dom).css({
623 width: $scope.action_context_width,
624 top: $scope.action_context_y,
625 left: $scope.action_context_x
627 $($scope.action_context_parent).append($scope.menu_dom);
628 $scope.action_context_oldy = $scope.action_context_oldx = 0;
629 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
630 $scope.action_context_showing = false;
633 $scope.action_context_showing = false;
634 $scope.showActionContextMenu = function ($event) {
636 // Have to gather these here, instead of inside link()
637 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
638 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
640 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
641 $event.target.click();
643 if (!$scope.action_context_showing) {
644 $scope.action_context_width = $($scope.menu_dom).css('width');
645 $scope.action_context_y = $($scope.menu_dom).css('top');
646 $scope.action_context_x = $($scope.menu_dom).css('left');
647 $scope.action_context_showing = true;
648 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
650 $('body').append($($scope.menu_dom));
651 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
654 $($scope.menu_dom).css({
656 width: $scope.action_context_width,
664 // returns the list of selected item objects
665 grid.getSelectedItems = function() {
666 return $scope.items.filter(
668 return Boolean($scope.selected[grid.indexValue(item)]);
673 grid.getItemByIndex = function(index) {
674 for (var i = 0; i < $scope.items.length; i++) {
675 var item = $scope.items[i];
676 if (grid.indexValue(item) == index)
681 // selects one row after deselecting all of the others
682 grid.selectOneItem = function(index) {
683 $scope.selected = {};
684 $scope.selected[index] = true;
687 // selects or deselects an item, without affecting the others.
688 // returns true if the item is selected; false if de-selected.
689 // we overwrite the object so that we can watch $scope.selected
690 grid.toggleSelectOneItem = function(index) {
691 if ($scope.selected[index]) {
692 delete $scope.selected[index];
693 $scope.selected = angular.copy($scope.selected);
696 $scope.selected[index] = true;
697 $scope.selected = angular.copy($scope.selected);
702 $scope.updateSelected = function () {
703 return $scope.selected = angular.copy($scope.selected);
706 grid.selectAllItems = function() {
707 angular.forEach($scope.items, function(item) {
708 $scope.selected[grid.indexValue(item)] = true
710 $scope.selected = angular.copy($scope.selected);
713 $scope.$watch('selectAll', function(newVal) {
715 grid.selectAllItems();
717 $scope.selected = {};
721 if ($scope.onSelect) {
722 $scope.$watch('selected', function(newVal) {
723 $scope.onSelect(grid.getSelectedItems());
724 if ($scope.afterSelect) $scope.afterSelect();
728 // returns true if item1 appears in the list before item2;
729 // false otherwise. this is slightly more efficient that
730 // finding the position of each then comparing them.
731 // item1 / item2 may be an item or an item index
732 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
733 var idx1 = grid.indexValue(itemOrIndex1);
734 var idx2 = grid.indexValue(itemOrIndex2);
736 // use for() for early exit
737 for (var i = 0; i < $scope.items.length; i++) {
738 var idx = grid.indexValue($scope.items[i]);
739 if (idx == idx1) return true;
740 if (idx == idx2) return false;
745 // 0-based position of item in the current data set
746 grid.indexOf = function(item) {
747 var idx = grid.indexValue(item);
748 for (var i = 0; i < $scope.items.length; i++) {
749 if (grid.indexValue($scope.items[i]) == idx)
755 grid.modifyColumnFlex = function(column, val) {
757 // prevent flex:0; use hiding instead
761 $scope.modifyColumnFlex = function(col, val) {
762 $scope.lastModColumn = col.name;
763 grid.modifyColumnFlex(col, val);
766 grid.modifyColumnPos = function(col, diff) {
767 var srcIdx, targetIdx;
768 angular.forEach(grid.columnsProvider.columns,
769 function(c, i) { if (c.name == col.name) srcIdx = i });
771 targetIdx = srcIdx + diff;
774 } else if (targetIdx >= grid.columnsProvider.columns.length) {
775 // Target index follows the last visible column.
777 angular.forEach(grid.columnsProvider.columns,
778 function(column, idx) {
779 if (column.visible) lastVisible = idx;
782 targetIdx = lastVisible + 1;
785 // Splice column out of old position, insert at new position.
786 grid.columnsProvider.columns.splice(srcIdx, 1);
787 grid.columnsProvider.columns.splice(targetIdx, 0, col);
790 $scope.modifyColumnPos = function(col, diff) {
791 $scope.lastModColumn = col.name;
792 return grid.modifyColumnPos(col, diff);
796 // handles click, control-click, and shift-click
797 $scope.handleRowClick = function($event, item) {
798 var index = grid.indexValue(item);
800 var origSelected = Object.keys($scope.selected);
802 if (!$scope.canMultiSelect) {
803 grid.selectOneItem(index);
804 grid.lastSelectedItemIndex = index;
808 if ($event.ctrlKey || $event.metaKey /* mac command */) {
810 if (grid.toggleSelectOneItem(index))
811 grid.lastSelectedItemIndex = index;
813 } else if ($event.shiftKey) {
816 if (!grid.lastSelectedItemIndex ||
817 index == grid.lastSelectedItemIndex) {
818 grid.selectOneItem(index);
819 grid.lastSelectedItemIndex = index;
823 var selecting = false;
824 var ascending = grid.itemComesBefore(
825 grid.lastSelectedItemIndex, item);
827 grid.indexOf(grid.lastSelectedItemIndex);
829 // update to new last-selected
830 grid.lastSelectedItemIndex = index;
832 // select each row between the last selected and
833 // currently selected items
835 startPos += ascending ? 1 : -1;
836 var curItem = $scope.items[startPos];
838 var curIdx = grid.indexValue(curItem);
839 $scope.selected[curIdx] = true;
840 if (curIdx == index) break; // all done
842 $scope.selected = angular.copy($scope.selected);
846 grid.selectOneItem(index);
847 grid.lastSelectedItemIndex = index;
851 // Builds a sort expression from column sort priorities.
852 // called on page load and any time the priorities are modified.
853 grid.compileSort = function() {
854 var sortList = grid.columnsProvider.columns.filter(
855 function(col) { return Number(col.sort) != 0 }
858 if (Math.abs(a.sort) < Math.abs(b.sort))
864 if (sortList.length) {
865 grid.dataProvider.sort = sortList.map(function(col) {
867 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
873 // builds a sort expression using a single column,
874 // toggling between ascending and descending sort.
875 $scope.quickSort = function(col_name) {
876 var sort = grid.dataProvider.sort;
877 if (sort && sort.length &&
878 sort[0] == col_name) {
880 blob[col_name] = 'desc';
881 grid.dataProvider.sort = [blob];
883 grid.dataProvider.sort = [col_name];
890 // show / hide the grid configuration row
891 $scope.toggleConfDisplay = function() {
892 if ($scope.showGridConf) {
893 $scope.showGridConf = false;
894 if (grid.columnsProvider.hasSortableColumn()) {
895 // only refresh the grid if the user has the
896 // ability to modify the sort priorities.
902 $scope.showGridConf = true;
905 delete $scope.lastModColumn;
906 $scope.gridColumnPickerIsOpen = false;
909 // called when a dragged column is dropped onto itself
910 // or any other column
911 grid.onColumnDrop = function(target) {
912 if (angular.isUndefined(target)) return;
913 if (target == grid.dragColumn) return;
914 var srcIdx, targetIdx, srcCol;
915 angular.forEach(grid.columnsProvider.columns,
917 if (col.name == grid.dragColumn) {
920 } else if (col.name == target) {
926 if (srcIdx < targetIdx) targetIdx--;
928 // move src column from old location to new location in
929 // the columns array, then force a page refresh
930 grid.columnsProvider.columns.splice(srcIdx, 1);
931 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
935 // prepares a string for inclusion within a CSV document
936 // by escaping commas and quotes and removing newlines.
937 grid.csvDatum = function(str) {
940 str = str.replace(/\n/g, '');
941 if (str.match(/\,/) || str.match(/"/)) {
942 str = str.replace(/"/g, '""');
943 str = '"' + str + '"';
948 // sets the download file name and inserts the current CSV
949 // into a Blob URL for browser download.
950 $scope.generateCSVExportURL = function() {
951 $scope.gridColumnPickerIsOpen = false;
953 // let the file name describe the grid
954 $scope.csvExportFileName =
955 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
956 .replace(/\s+/g, '_') + '_' + $scope.page();
958 // toss the CSV into a Blob and update the export URL
959 var csv = grid.generateCSV();
960 var blob = new Blob([csv], {type : 'text/plain'});
961 $scope.csvExportURL =
962 ($window.URL || $window.webkitURL).createObjectURL(blob);
965 $scope.printCSV = function() {
966 $scope.gridColumnPickerIsOpen = false;
969 content : grid.generateCSV(),
970 content_type : 'text/plain'
974 // generates CSV for the currently visible grid contents
975 grid.generateCSV = function() {
977 var colCount = grid.columnsProvider.columns.length;
980 angular.forEach(grid.columnsProvider.columns,
982 if (!col.visible) return;
983 csvStr += grid.csvDatum(col.label);
988 csvStr = csvStr.replace(/,$/,'\n');
991 angular.forEach($scope.items, function(item) {
992 angular.forEach(grid.columnsProvider.columns,
994 if (!col.visible) return;
996 var val = grid.dataProvider.itemFieldValue(item, col);
997 // filtered value (dates, etc.)
998 val = $filter('egGridValueFilter')(val, col, item);
999 csvStr += grid.csvDatum(val);
1003 csvStr = csvStr.replace(/,$/,'\n');
1009 // Interpolate the value for column.linkpath within the context
1010 // of the row item to generate the final link URL.
1011 $scope.generateLinkPath = function(col, item) {
1012 return egCore.strings.$replace(col.linkpath, {item : item});
1015 // If a column provides its own HTML template, translate it,
1016 // using the current item for the template scope.
1017 // note: $sce is required to avoid security restrictions and
1018 // is OK here, since the template comes directly from a
1019 // local HTML template (not user input).
1020 $scope.translateCellTemplate = function(col, item) {
1021 var html = egCore.strings.$replace(col.template, {item : item});
1022 return $sce.trustAsHtml(html);
1025 $scope.collect = function() { grid.collect() }
1027 // asks the dataProvider for a page of data
1028 grid.collect = function() {
1030 // avoid firing the collect if there is nothing to collect.
1031 if (grid.selfManagedData && !grid.dataProvider.query) return;
1033 if (grid.collecting) return; // avoid parallel collect()
1034 grid.collecting = true;
1036 console.debug('egGrid.collect() offset='
1037 + grid.offset + '; limit=' + grid.limit);
1039 // ensure all of our dropdowns are closed
1040 // TODO: git rid of these and just use dropdown-toggle,
1041 // which is more reliable.
1042 $scope.gridColumnPickerIsOpen = false;
1043 $scope.gridRowCountIsOpen = false;
1044 $scope.gridPageSelectIsOpen = false;
1047 $scope.selected = {};
1049 // Inform the caller we've asked the data provider
1050 // for data. This is useful for knowing when collection
1051 // has started (e.g. to display a progress dialg) when
1052 // using the stock (flattener) data provider, where the
1053 // user is not directly defining a get() handler.
1054 if (grid.controls.collectStarted)
1055 grid.controls.collectStarted(grid.offset, grid.limit);
1057 grid.dataProvider.get(grid.offset, grid.limit).then(
1059 if (grid.controls.allItemsRetrieved)
1060 grid.controls.allItemsRetrieved();
1065 $scope.items.push(item)
1066 if (grid.controls.itemRetrieved)
1067 grid.controls.itemRetrieved(item);
1068 if ($scope.selectAll)
1069 $scope.selected[grid.indexValue(item)] = true
1071 }).finally(function() {
1072 console.debug('egGrid.collect() complete');
1073 grid.collecting = false
1074 $scope.selected = angular.copy($scope.selected);
1084 * eg-grid-field : used for collecting custom field data from the templates.
1085 * This directive does not direct display, it just passes data up to the
1088 .directive('egGridField', function() {
1090 require : '^egGrid',
1093 flesher: '=', // optional; function that can flesh a linked field, given the value
1094 comparator: '=', // optional; function that can sort the thing at the end of 'path'
1095 name : '@', // required; unique name
1096 path : '@', // optional; flesh path
1097 ignore: '@', // optional; fields to ignore when path is a wildcard
1098 label : '@', // optional; display label
1099 flex : '@', // optional; default flex width
1100 align : '@', // optional; default alignment, left/center/right
1101 dateformat : '@', // optional: passed down to egGridValueFilter
1102 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
1103 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
1104 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
1106 // if a field is part of an IDL object, but we are unable to
1107 // determine the class, because it's nested within a hash
1108 // (i.e. we can't navigate directly to the object via the IDL),
1109 // idlClass lets us specify the class. This is particularly
1110 // useful for nested wildcard fields.
1111 parentIdlClass : '@',
1113 // optional: for non-IDL columns, specifying a datatype
1114 // lets the caller control which display filter is used.
1115 // datatype should match the standard IDL datatypes.
1118 link : function(scope, element, attrs, egGridCtrl) {
1120 // boolean fields are presented as value-less attributes
1129 'required' // if set, always fetch data for this column
1132 if (angular.isDefined(attrs[field]))
1133 scope[field] = true;
1137 // any HTML content within the field is its custom template
1138 var tmpl = element.html();
1139 if (tmpl && !tmpl.match(/^\s*$/))
1140 scope.template = tmpl
1142 egGridCtrl.columnsProvider.add(scope);
1149 * eg-grid-action : used for specifying actions which may be applied
1150 * to items within the grid.
1152 .directive('egGridAction', function() {
1154 require : '^egGrid',
1158 group : '@', // Action group, ungrouped if not set
1159 label : '@', // Action label
1160 handler : '=', // Action function handler
1162 disabled : '=', // function
1165 link : function(scope, element, attrs, egGridCtrl) {
1166 egGridCtrl.addAction({
1168 group : scope.group,
1169 label : scope.label,
1170 divider : scope.divider,
1171 handler : scope.handler,
1172 disabled : scope.disabled,
1179 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1181 function ColumnsProvider(args) {
1184 cols.stockVisible = [];
1185 cols.idlClass = args.idlClass;
1186 cols.clientSort = args.clientSort;
1187 cols.defaultToHidden = args.defaultToHidden;
1188 cols.defaultToNoSort = args.defaultToNoSort;
1189 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1190 cols.defaultDateFormat = args.defaultDateFormat;
1191 cols.defaultDateContext = args.defaultDateContext;
1193 // resets column width, visibility, and sort behavior
1194 // Visibility resets to the visibility settings defined in the
1195 // template (i.e. the original egGridField values).
1196 cols.reset = function() {
1197 angular.forEach(cols.columns, function(col) {
1201 if (cols.stockVisible.indexOf(col.name) > -1) {
1204 col.visible = false;
1209 // returns true if any columns are sortable
1210 cols.hasSortableColumn = function() {
1211 return cols.columns.filter(
1213 return col.sortable || col.multisortable;
1218 cols.showAllColumns = function() {
1219 angular.forEach(cols.columns, function(column) {
1220 column.visible = true;
1224 cols.hideAllColumns = function() {
1225 angular.forEach(cols.columns, function(col) {
1230 cols.indexOf = function(name) {
1231 for (var i = 0; i < cols.columns.length; i++) {
1232 if (cols.columns[i].name == name)
1238 cols.findColumn = function(name) {
1239 return cols.columns[cols.indexOf(name)];
1242 cols.compileAutoColumns = function() {
1243 var idl_class = egCore.idl.classes[cols.idlClass];
1248 if (field.virtual) return;
1249 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1250 // if the field is a link and the linked class has a
1251 // "selector" field specified, use the selector field
1252 // as the display field for the columns.
1253 // flattener will take care of the fleshing.
1254 if (field['class']) {
1255 var selector_field = egCore.idl.classes[field['class']].fields
1256 .filter(function(f) { return Boolean(f.selector) })[0];
1257 if (selector_field) {
1258 field.path = field.name + '.' + selector_field.selector;
1262 cols.add(field, true);
1267 // if a column definition has a path with a wildcard, create
1268 // columns for all non-virtual fields at the specified
1269 // position in the path.
1270 cols.expandPath = function(colSpec) {
1272 var ignoreList = [];
1274 ignoreList = colSpec.ignore.split(' ');
1276 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1280 if (colSpec.parentIdlClass) {
1281 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1283 class_obj = egCore.idl.classes[cols.idlClass];
1285 var idl_parent = class_obj;
1286 var old_field_label = '';
1288 if (!class_obj) return;
1290 console.debug('egGrid: auto dotpath is: ' + dotpath);
1291 var path_parts = dotpath.split(/\./);
1293 // find the IDL class definition for the last element in the
1294 // path before the .*
1295 // an empty path_parts means expand the root class
1298 for (var path_idx in path_parts) {
1299 old_field = idl_field;
1301 var part = path_parts[path_idx];
1302 idl_field = class_obj.field_map[part];
1304 // unless we're at the end of the list, this field should
1305 // link to another class.
1306 if (idl_field && idl_field['class'] && (
1307 idl_field.datatype == 'link' ||
1308 idl_field.datatype == 'org_unit')) {
1309 if (old_field_label) old_field_label += ' : ';
1310 old_field_label += idl_field.label;
1311 class_obj = egCore.idl.classes[idl_field['class']];
1312 if (old_field) idl_parent = old_field;
1314 if (path_idx < (path_parts.length - 1)) {
1315 // we ran out of classes to hop through before
1316 // we ran out of path components
1317 console.error("egGrid: invalid IDL path: " + dotpath);
1324 angular.forEach(class_obj.fields, function(field) {
1326 // Only show wildcard fields where we have data to show
1327 // Virtual and un-fleshed links will not have any data.
1328 if (field.virtual ||
1329 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1330 ignoreList.indexOf(field.name) > -1
1334 var col = cols.cloneFromScope(colSpec);
1335 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1337 // log line below is very chatty. disable until needed.
1338 // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1339 cols.add(col, false, true,
1340 {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1343 cols.columns = cols.columns.sort(
1345 if (a.explicit) return -1;
1346 if (b.explicit) return 1;
1348 if (a.idlclass && b.idlclass) {
1349 if (a.idlclass < b.idlclass) return -1;
1350 if (b.idlclass < a.idlclass) return 1;
1353 if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1354 if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1355 if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1358 if (a.label && b.label) {
1359 if (a.label < b.label) return -1;
1360 if (b.label < a.label) return 1;
1363 return a.name < b.name ? -1 : 1;
1370 "egGrid: wildcard path does not resolve to an object: "
1375 // angular.clone(scopeObject) is not permittable. Manually copy
1376 // the fields over that we need (so the scope object can go away).
1377 cols.cloneFromScope = function(colSpec) {
1379 flesher : colSpec.flesher,
1380 comparator : colSpec.comparator,
1381 name : colSpec.name,
1382 label : colSpec.label,
1383 path : colSpec.path,
1384 align : colSpec.align || 'left',
1385 flex : Number(colSpec.flex) || 2,
1386 sort : Number(colSpec.sort) || 0,
1387 required : colSpec.required,
1388 linkpath : colSpec.linkpath,
1389 template : colSpec.template,
1390 visible : colSpec.visible,
1391 hidden : colSpec.hidden,
1392 datatype : colSpec.datatype,
1393 sortable : colSpec.sortable,
1394 nonsortable : colSpec.nonsortable,
1395 multisortable : colSpec.multisortable,
1396 nonmultisortable : colSpec.nonmultisortable,
1397 dateformat : colSpec.dateformat,
1398 datecontext : colSpec.datecontext,
1399 datefilter : colSpec.datefilter,
1400 dateonlyinterval : colSpec.dateonlyinterval,
1401 parentIdlClass : colSpec.parentIdlClass
1406 // Add a column to the columns collection.
1407 // Columns may come from a slim eg-columns-field or
1408 // directly from the IDL.
1409 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1411 // First added column with the specified path takes precedence.
1412 // This allows for specific definitions followed by wildcard
1413 // definitions. If a match is found, back out.
1414 if (cols.columns.filter(function(c) {
1415 return (c.path == colSpec.path) })[0]) {
1416 console.debug('skipping pre-existing column ' + colSpec.path);
1420 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1422 if (column.path && column.path.match(/\*$/))
1423 return cols.expandPath(colSpec);
1425 if (!fromExpand) column.explicit = true;
1427 if (!column.name) column.name = column.path;
1428 if (!column.path) column.path = column.name;
1430 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1431 column.visible = true;
1433 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1434 column.sortable = true;
1436 if (column.multisortable ||
1437 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1438 column.multisortable = true;
1440 if (cols.defaultDateFormat && ! column.dateformat) {
1441 column.dateformat = cols.defaultDateFormat;
1444 if (cols.defaultDateOnlyInterval && ! column.dateonlyinterval) {
1445 column.dateonlyinterval = cols.defaultDateOnlyInterval;
1448 if (cols.defaultDateContext && ! column.datecontext) {
1449 column.datecontext = cols.defaultDateContext;
1452 if (cols.defaultDateFilter && ! column.datefilter) {
1453 column.datefilter = cols.defaultDateFilter;
1456 cols.columns.push(column);
1458 // Track which columns are visible by default in case we
1459 // need to reset column visibility
1461 cols.stockVisible.push(column.name);
1463 if (fromIDL) return; // directly from egIDL. nothing left to do.
1465 // lookup the matching IDL field
1466 if (!idl_info && cols.idlClass)
1467 idl_info = cols.idlFieldFromPath(column.path);
1470 // column is not represented within the IDL
1471 column.adhoc = true;
1475 column.datatype = idl_info.idl_field.datatype;
1477 if (!column.label) {
1478 column.label = idl_info.idl_field.label || column.name;
1481 if (fromExpand && idl_info.idl_class) {
1482 column.idlclass = '';
1483 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1484 column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1486 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1491 // finds the IDL field from the dotpath, using the columns
1492 // idlClass as the base.
1493 cols.idlFieldFromPath = function(dotpath) {
1494 var class_obj = egCore.idl.classes[cols.idlClass];
1495 var path_parts = dotpath.split(/\./);
1499 for (var path_idx in path_parts) {
1500 var part = path_parts[path_idx];
1501 idl_parent = idl_field;
1502 idl_field = class_obj.field_map[part];
1505 if (idl_field['class'] && (
1506 idl_field.datatype == 'link' ||
1507 idl_field.datatype == 'org_unit')) {
1508 class_obj = egCore.idl.classes[idl_field['class']];
1516 idl_parent: idl_parent,
1517 idl_field : idl_field,
1518 idl_class : class_obj
1524 instance : function(args) { return new ColumnsProvider(args) }
1530 * Generic data provider template class. This is basically an abstract
1531 * class factory service whose instances can be locally modified to
1532 * meet the needs of each individual grid.
1534 .factory('egGridDataProvider',
1535 ['$q','$timeout','$filter','egCore',
1536 function($q , $timeout , $filter , egCore) {
1538 function GridDataProvider(args) {
1539 var gridData = this;
1540 if (!args) args = {};
1543 gridData.get = args.get;
1544 gridData.query = args.query;
1545 gridData.idlClass = args.idlClass;
1546 gridData.columnsProvider = args.columnsProvider;
1548 // Delivers a stream of array data via promise.notify()
1549 // Useful for passing an array of data to egGrid.get()
1550 // If a count is provided, the array will be trimmed to
1551 // the range defined by count and offset
1552 gridData.arrayNotifier = function(arr, offset, count) {
1553 if (!arr || arr.length == 0) return $q.when();
1555 if (gridData.columnsProvider.clientSort
1557 && gridData.sort.length > 0
1559 var sorter_cache = [];
1560 arr.sort(function(a,b) {
1561 for (var si = 0; si < gridData.sort.length; si++) {
1562 if (!sorter_cache[si]) { // Build sort structure on first comparison, reuse thereafter
1563 var field = gridData.sort[si];
1566 if (angular.isObject(field)) {
1567 dir = Object.values(field)[0];
1568 field = Object.keys(field)[0];
1571 var path = gridData.columnsProvider.findColumn(field).path || field;
1572 var comparator = gridData.columnsProvider.findColumn(field).comparator ||
1573 function (x,y) { if (x < y) return -1; if (x > y) return 1; return 0 };
1575 sorter_cache[si] = {
1578 comparator : comparator
1582 var sc = sorter_cache[si];
1586 if (a._isfieldmapper || angular.isFunction(a[sc.field])) {
1587 try {af = a[sc.field](); bf = b[sc.field]() } catch (e) {};
1589 af = a[sc.field]; bf = b[sc.field];
1591 if (af === undefined && sc.field.indexOf('.') > -1) { // assume an object, not flat path
1592 var parts = sc.field.split('.');
1595 angular.forEach(parts, function (p) {
1597 if (af._isfieldmapper || angular.isFunction(af[p])) af = af[p]();
1601 if (bf._isfieldmapper || angular.isFunction(bf[p])) bf = bf[p]();
1607 if (af === undefined) af = null;
1608 if (bf === undefined) bf = null;
1610 if (af === null && bf !== null) return 1;
1611 if (bf === null && af !== null) return -1;
1613 if (!(bf === null && af === null)) {
1614 var partial = sc.comparator(af,bf);
1616 if (sc.dir == 'desc') {
1617 if (partial > 0) return -1;
1629 if (count) arr = arr.slice(offset, offset + count);
1630 var def = $q.defer();
1631 // promise notifications are only witnessed when delivered
1632 // after the caller has his hands on the promise object
1633 $timeout(function() {
1634 angular.forEach(arr, def.notify);
1640 // Calls the grid refresh function. Once instantiated, the
1641 // grid will replace this function with it's own refresh()
1642 gridData.refresh = function(noReset) { }
1644 if (!gridData.get) {
1645 // returns a promise whose notify() delivers items
1646 gridData.get = function(index, count) {
1647 console.error("egGridDataProvider.get() not implemented");
1651 // attempts a flat field lookup first. If the column is not
1652 // found on the top-level object, attempts a nested lookup
1653 // TODO: consider a caching layer to speed up template
1654 // rendering, particularly for nested objects?
1655 gridData.itemFieldValue = function(item, column) {
1657 if (column.name in item) {
1658 if (typeof item[column.name] == 'function') {
1659 val = item[column.name]();
1661 val = item[column.name];
1664 val = gridData.nestedItemFieldValue(item, column);
1670 // TODO: deprecate me
1671 gridData.flatItemFieldValue = function(item, column) {
1672 console.warn('gridData.flatItemFieldValue deprecated; '
1673 + 'leave provider.itemFieldValue unset');
1674 return item[column.name];
1677 // given an object and a dot-separated path to a field,
1678 // extract the value of the field. The path can refer
1679 // to function names or object attributes. If the final
1680 // value is an IDL field, run the value through its
1681 // corresponding output filter.
1682 gridData.nestedItemFieldValue = function(obj, column) {
1683 item = obj; // keep a copy around
1685 if (obj === null || obj === undefined || obj === '') return '';
1686 if (!column.path) return obj;
1689 var parts = column.path.split('.');
1691 angular.forEach(parts, function(step, idx) {
1692 // object is not fleshed to the expected extent
1693 if (typeof obj != 'object') {
1694 if (typeof obj != 'undefined' && column.flesher) {
1695 obj = column.flesher(obj, column, item);
1702 if (!obj) return '';
1704 var cls = obj.classname;
1705 if (cls && (class_obj = egCore.idl.classes[cls])) {
1706 idl_field = class_obj.field_map[step];
1707 obj = obj[step] ? obj[step]() : '';
1709 if (angular.isFunction(obj[step])) {
1717 // We found a nested IDL object which may or may not have
1718 // been configured as a top-level column. Grab the datatype.
1719 if (idl_field && !column.datatype)
1720 column.datatype = idl_field.datatype;
1722 if (obj === null || obj === undefined || obj === '') return '';
1728 instance : function(args) {
1729 return new GridDataProvider(args);
1736 // Factory service for egGridDataManager instances, which are
1737 // responsible for collecting flattened grid data.
1738 .factory('egGridFlatDataProvider',
1739 ['$q','egCore','egGridDataProvider',
1740 function($q , egCore , egGridDataProvider) {
1743 instance : function(args) {
1744 var provider = egGridDataProvider.instance(args);
1746 provider.get = function(offset, count) {
1748 // no query means no call
1749 if (!provider.query ||
1750 angular.equals(provider.query, {}))
1753 // find all of the currently visible columns
1754 var queryFields = {}
1755 angular.forEach(provider.columnsProvider.columns,
1757 // only query IDL-tracked columns
1758 if (!col.adhoc && (col.required || col.visible))
1759 queryFields[col.name] = col.path;
1763 return egCore.net.request(
1765 'open-ils.fielder.flattened_search',
1766 egCore.auth.token(), provider.idlClass,
1767 queryFields, provider.query,
1768 { sort : provider.sort,
1774 //provider.itemFieldValue = provider.flatItemFieldValue;
1781 .directive('egGridColumnDragSource', function() {
1784 require : '^egGrid',
1785 link : function(scope, element, attrs, egGridCtrl) {
1786 angular.element(element).attr('draggable', 'true');
1788 element.bind('dragstart', function(e) {
1789 egGridCtrl.dragColumn = attrs.column;
1790 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1791 egGridCtrl.colResizeDir = 0;
1793 if (egGridCtrl.dragType == 'move') {
1794 // style the column getting moved
1795 angular.element(e.target).addClass(
1796 'eg-grid-column-move-handle-active');
1800 element.bind('dragend', function(e) {
1801 if (egGridCtrl.dragType == 'move') {
1802 angular.element(e.target).removeClass(
1803 'eg-grid-column-move-handle-active');
1810 .directive('egGridColumnDragDest', function() {
1813 require : '^egGrid',
1814 link : function(scope, element, attrs, egGridCtrl) {
1816 element.bind('dragover', function(e) { // required for drop
1817 e.stopPropagation();
1819 e.dataTransfer.dropEffect = 'move';
1821 if (egGridCtrl.colResizeDir == 0) return; // move
1823 var cols = egGridCtrl.columnsProvider;
1824 var srcCol = egGridCtrl.dragColumn;
1825 var srcColIdx = cols.indexOf(srcCol);
1827 if (egGridCtrl.colResizeDir == -1) {
1828 if (cols.indexOf(attrs.column) <= srcColIdx) {
1829 egGridCtrl.modifyColumnFlex(
1830 egGridCtrl.columnsProvider.findColumn(
1831 egGridCtrl.dragColumn), -1);
1832 if (cols.columns[srcColIdx+1]) {
1833 // source column shrinks by one, column to the
1834 // right grows by one.
1835 egGridCtrl.modifyColumnFlex(
1836 cols.columns[srcColIdx+1], 1);
1841 if (cols.indexOf(attrs.column) > srcColIdx) {
1842 egGridCtrl.modifyColumnFlex(
1843 egGridCtrl.columnsProvider.findColumn(
1844 egGridCtrl.dragColumn), 1);
1845 if (cols.columns[srcColIdx+1]) {
1846 // source column grows by one, column to the
1847 // right grows by one.
1848 egGridCtrl.modifyColumnFlex(
1849 cols.columns[srcColIdx+1], -1);
1857 element.bind('dragenter', function(e) {
1858 e.stopPropagation();
1860 if (egGridCtrl.dragType == 'move') {
1861 angular.element(e.target).addClass('eg-grid-col-hover');
1863 // resize grips are on the right side of each column.
1864 // dragenter will either occur on the source column
1865 // (dragging left) or the column to the right.
1866 if (egGridCtrl.colResizeDir == 0) {
1867 if (egGridCtrl.dragColumn == attrs.column) {
1868 egGridCtrl.colResizeDir = -1; // west
1870 egGridCtrl.colResizeDir = 1; // east
1876 element.bind('dragleave', function(e) {
1877 e.stopPropagation();
1879 if (egGridCtrl.dragType == 'move') {
1880 angular.element(e.target).removeClass('eg-grid-col-hover');
1884 element.bind('drop', function(e) {
1885 e.stopPropagation();
1887 egGridCtrl.colResizeDir = 0;
1888 if (egGridCtrl.dragType == 'move') {
1889 angular.element(e.target).removeClass('eg-grid-col-hover');
1890 egGridCtrl.onColumnDrop(attrs.column); // move the column
1897 .directive('egGridMenuItem', function() {
1900 require : '^egGrid',
1906 handler : '=', // onclick handler function
1907 divider : '=', // if true, show a divider only
1908 handlerData : '=', // if set, passed as second argument to handler
1909 disabled : '=', // function
1910 hidden : '=' // function
1912 link : function(scope, element, attrs, egGridCtrl) {
1913 egGridCtrl.addMenuItem({
1914 checkbox : scope.checkbox,
1915 checked : scope.checked ? true : false,
1916 label : scope.label,
1917 standalone : scope.standalone ? true : false,
1918 handler : scope.handler,
1919 divider : scope.divider,
1920 disabled : scope.disabled,
1921 hidden : scope.hidden,
1922 handlerData : scope.handlerData
1932 * Translates bare IDL object values into display values.
1933 * 1. Passes dates through the angular date filter
1934 * 2. Translates bools to Booleans so the browser can display translated
1935 * value. (Though we could manually translate instead..)
1936 * Others likely to follow...
1938 .filter('egGridValueFilter', ['$filter','egCore', function($filter,egCore) {
1939 var GVF = function(value, column, item) {
1940 switch(column.datatype) {
1943 // Browser will translate true/false for us
1945 case '1' : // legacy
1949 case '0' : // legacy
1952 // value may be null, '', etc.
1953 default : return '';
1956 var interval = angular.isFunction(item[column.dateonlyinterval])
1957 ? item[column.dateonlyinterval]()
1958 : item[column.dateonlyinterval];
1960 var context = angular.isFunction(item[column.datecontext])
1961 ? item[column.datecontext]()
1962 : item[column.datecontext];
1964 var date_filter = column.datefilter || 'egOrgDateInContext';
1966 return $filter(date_filter)(value, column.dateformat, context, interval);
1968 return $filter('currency')(value);
1974 GVF.$stateful = true;