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 'egProgressDialog','$uibModal',
123 function($scope, $q , egCore, egGridFlatDataProvider , $location,
124 egGridColumnsProvider , $filter , $window , $sce , $timeout,
125 egProgressDialog , $uibModal) {
129 grid.init = function() {
132 $scope.showGridConf = false;
133 grid.totalCount = -1;
134 $scope.selected = {};
135 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
136 $scope.menuItems = []; // global actions
138 // returns true if any rows are selected.
139 $scope.hasSelected = function() {
140 return grid.getSelectedItems().length > 0 };
142 var features = ($scope.features) ?
143 $scope.features.split(',') : [];
144 delete $scope.features;
146 $scope.showIndex = (features.indexOf('-index') == -1);
148 $scope.allowAll = (features.indexOf('allowAll') > -1);
149 $scope.startSelected = $scope.selectAll = (features.indexOf('startSelected') > -1);
150 $scope.showActions = (features.indexOf('-actions') == -1);
151 $scope.showPagination = (features.indexOf('-pagination') == -1);
152 $scope.showPicker = (features.indexOf('-picker') == -1);
154 $scope.showMenu = (features.indexOf('-menu') == -1);
156 // remove some unneeded values from the scope to reduce bloat
158 grid.idlClass = $scope.idlClass;
159 delete $scope.idlClass;
161 grid.persistKey = $scope.persistKey;
162 delete $scope.persistKey;
164 var stored_limit = 0;
165 if ($scope.showPagination) {
166 if (grid.persistKey) {
167 var stored_limit = Number(
168 egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
172 stored_limit = 10000; // maybe support "Inf"?
175 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
177 grid.indexField = $scope.idField;
178 delete $scope.idField;
180 grid.dataProvider = $scope.itemsProvider;
182 if (!grid.indexField && grid.idlClass)
183 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
185 grid.columnsProvider = egGridColumnsProvider.instance({
186 idlClass : grid.idlClass,
187 clientSort : (features.indexOf('clientsort') > -1 && features.indexOf('-clientsort') == -1),
188 defaultToHidden : (features.indexOf('-display') > -1),
189 defaultToNoSort : (features.indexOf('-sort') > -1),
190 defaultToNoMultiSort : (features.indexOf('-multisort') > -1),
191 defaultDateFormat : $scope.dateformat,
192 defaultDateContext : $scope.datecontext,
193 defaultDateFilter : $scope.datefilter,
194 defaultDateOnlyInterval : $scope.dateonlyinterval
196 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
198 $scope.handleAutoFields = function() {
199 if ($scope.autoFields) {
200 if (grid.autoLabel) {
202 egCore.idl.classes[grid.idlClass].label;
204 grid.columnsProvider.compileAutoColumns();
205 delete $scope.autoFields;
209 if (!grid.dataProvider) {
210 // no provider, um, provided.
211 // Use a flat data provider
213 grid.selfManagedData = true;
214 grid.dataProvider = egGridFlatDataProvider.instance({
215 indexField : grid.indexField,
216 idlClass : grid.idlClass,
217 columnsProvider : grid.columnsProvider,
222 grid.dataProvider.columnsProvider = grid.columnsProvider;
224 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
225 $scope.indexValue = function(item) {
226 return grid.indexValue(item)
229 grid.applyControlFunctions();
231 grid.loadConfig().then(function() {
232 // link columns to scope after loadConfig(), since it
233 // replaces the columns array.
234 $scope.columns = grid.columnsProvider.columns;
237 // NOTE: grid.collect() is first called from link(), not here.
240 // link our control functions into the gridControls
241 // scope object so the caller can access them.
242 grid.applyControlFunctions = function() {
244 // we use some of these controls internally, so sett
245 // them up even if the caller doesn't request them.
246 var controls = $scope.gridControls || {};
248 controls.columnMap = function() {
250 angular.forEach(grid.columnsProvider.columns, function (c) {
256 controls.columnsProvider = function() {
257 return grid.columnsProvider;
260 // link in the control functions
261 controls.selectedItems = function() {
262 return grid.getSelectedItems()
265 controls.allItems = function() {
269 controls.selectItems = function(ids) {
271 $scope.selected = {};
272 angular.forEach(ids, function(i) {
273 $scope.selected[''+i] = true;
277 // if the caller provided a functional setQuery,
278 // extract the value before replacing it
279 if (controls.setQuery) {
280 grid.dataProvider.query =
284 controls.setQuery = function(query) {
285 grid.dataProvider.query = query;
289 if (controls.watchQuery) {
290 // capture the initial query value
291 grid.dataProvider.query = controls.watchQuery();
294 $scope.gridWatchQuery = controls.watchQuery;
295 $scope.$watch('gridWatchQuery()', function(newv) {
296 controls.setQuery(newv);
300 // if the caller provided a functional setSort
301 // extract the value before replacing it
302 grid.dataProvider.sort =
303 controls.setSort ? controls.setSort() : [];
305 controls.setSort = function(sort) {
309 controls.refresh = function(noReset) {
310 if (!noReset) grid.offset = 0;
314 controls.setLimit = function(limit,forget) {
315 if (!forget && grid.persistKey)
316 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
319 controls.getLimit = function() {
322 controls.setOffset = function(offset) {
323 grid.offset = offset;
325 controls.getOffset = function() {
329 controls.saveConfig = function () {
330 return $scope.saveConfig();
333 grid.dataProvider.refresh = controls.refresh;
334 grid.controls = controls;
337 // If a menu item provides its own HTML template, translate it,
338 // using the menu item for the template scope.
339 // note: $sce is required to avoid security restrictions and
340 // is OK here, since the template comes directly from a
341 // local HTML template (not user input).
342 $scope.translateMenuItemTemplate = function(item) {
343 var html = egCore.strings.$replace(item.template, {item : item});
344 return $sce.trustAsHtml(html);
347 // add a new (global) grid menu item
348 grid.addMenuItem = function(item) {
349 $scope.menuItems.push(item);
350 var handler = item.handler;
351 item.handler = function() {
352 $scope.gridMenuIsOpen = false; // close menu
355 item.handlerData, grid.getSelectedItems());
360 // add a selected-items action
361 grid.addAction = function(act) {
363 $scope.actionGroups.forEach(function(g){
364 if (g.label === act.group) {
370 $scope.actionGroups.push({
377 // remove the stored column configuration preferenc, then recover
378 // the column visibility information from the initial page load.
379 $scope.resetColumns = function() {
380 $scope.gridColumnPickerIsOpen = false;
381 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
383 grid.columnsProvider.reset();
384 if (grid.selfManagedData) grid.collect();
388 $scope.showAllColumns = function() {
389 $scope.gridColumnPickerIsOpen = false;
390 grid.columnsProvider.showAllColumns();
391 if (grid.selfManagedData) grid.collect();
394 $scope.hideAllColumns = function() {
395 $scope.gridColumnPickerIsOpen = false;
396 grid.columnsProvider.hideAllColumns();
397 // note: no need to fetch new data if no columns are visible
400 $scope.toggleColumnVisibility = function(col) {
401 $scope.gridColumnPickerIsOpen = false;
402 col.visible = !col.visible;
404 // egGridFlatDataProvider only retrieves data to be
405 // displayed. When column visibility changes, it's
406 // necessary to fetch the newly visible column data.
407 if (grid.selfManagedData) grid.collect();
410 // save the columns configuration (position, sort, width) to
411 // eg.grid.<persist-key>
412 $scope.saveConfig = function() {
413 $scope.gridColumnPickerIsOpen = false;
415 if (!grid.persistKey) {
417 "Cannot save settings without a grid persist-key");
421 // only store information about visible columns.
422 var conf = grid.columnsProvider.columns.filter(
423 function(col) {return Boolean(col.visible) });
425 // now scrunch the data down to just the needed info
426 conf = conf.map(function(col) {
427 var c = {name : col.name}
428 // Apart from the name, only store non-default values.
429 // No need to store col.visible, since that's implicit
430 if (col.align != 'left') c.align = col.align;
431 if (col.flex != 2) c.flex = col.flex;
432 if (Number(col.sort)) c.sort = Number(c.sort);
436 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
438 // Save operation performed from the grid configuration UI.
439 // Hide the configuration UI and re-draw w/ sort applied
440 if ($scope.showGridConf)
441 $scope.toggleConfDisplay();
446 // load the columns configuration (position, sort, width) from
447 // eg.grid.<persist-key> and apply the loaded settings to the
448 // columns on our columnsProvider
449 grid.loadConfig = function() {
450 if (!grid.persistKey) return $q.when();
452 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
453 .then(function(conf) {
456 var columns = grid.columnsProvider.columns;
459 angular.forEach(conf, function(col) {
460 var grid_col = columns.filter(
461 function(c) {return c.name == col.name})[0];
464 // saved column does not match a column in the
465 // current grid. skip it.
469 grid_col.align = col.align || 'left';
470 grid_col.flex = col.flex || 2;
471 grid_col.sort = col.sort || 0;
472 // all saved columns are assumed to be true
473 grid_col.visible = true;
475 .filter(function (c) {
476 return c.name == grid_col.name;
479 new_cols.push(grid_col);
482 // columns which are not expressed within the saved
483 // configuration are marked as non-visible and
484 // appended to the end of the new list of columns.
485 angular.forEach(columns, function(col) {
486 var found = conf.filter(
487 function(c) {return (c.name == col.name)})[0];
494 grid.columnsProvider.columns = new_cols;
500 $scope.onContextMenu = function($event) {
501 var col = angular.element($event.target).attr('column');
502 console.log('selected column ' + col);
505 $scope.page = function() {
506 return (grid.offset / grid.limit) + 1;
509 $scope.goToPage = function(page) {
511 if (angular.isNumber(page) && page > 0) {
512 grid.offset = (page - 1) * grid.limit;
517 $scope.offset = function(o) {
518 if (angular.isNumber(o))
523 $scope.limit = function(l) {
524 if (angular.isNumber(l)) {
526 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
532 $scope.onFirstPage = function() {
533 return grid.offset == 0;
536 $scope.hasNextPage = function() {
537 // we have less data than requested, there must
538 // not be any more pages
539 if (grid.count() < grid.limit) return false;
541 // if the total count is not known, assume that a full
542 // page of data implies more pages are available.
543 if (grid.totalCount == -1) return true;
545 // we have a full page of data, but is there more?
546 return grid.totalCount > (grid.offset + grid.count());
549 $scope.incrementPage = function() {
550 grid.offset += grid.limit;
554 $scope.decrementPage = function() {
555 if (grid.offset < grid.limit) {
558 grid.offset -= grid.limit;
563 // number of items loaded for the current page of results
564 grid.count = function() {
565 return $scope.items.length;
568 // returns the unique identifier value for the provided item
569 // for internal consistency, indexValue is always coerced
571 grid.indexValue = function(item) {
572 if (angular.isObject(item)) {
574 if (angular.isFunction(item[grid.indexField]))
575 return ''+item[grid.indexField]();
576 return ''+item[grid.indexField]; // flat data
579 // passed a non-object; assume it's an index
583 // fires the hide handler function for a context action
584 $scope.actionHide = function(action) {
585 if (typeof action.hide == 'undefined') {
588 if (angular.isFunction(action.hide))
589 return action.hide(action);
593 // fires the disable handler function for a context action
594 $scope.actionDisable = function(action) {
595 if (typeof action.disabled == 'undefined') {
598 if (angular.isFunction(action.disabled))
599 return action.disabled(action);
600 return action.disabled;
603 // fires the action handler function for a context action
604 $scope.actionLauncher = function(action) {
605 if (!action.handler) {
607 'No handler specified for "' + action.label + '"');
611 action.handler(grid.getSelectedItems());
613 console.error('Error executing handler for "'
614 + action.label + '" => ' + E + "\n" + E.stack);
617 if ($scope.action_context_showing) $scope.hideActionContextMenu();
622 $scope.hideActionContextMenu = function () {
623 $($scope.menu_dom).css({
625 width: $scope.action_context_width,
626 top: $scope.action_context_y,
627 left: $scope.action_context_x
629 $($scope.action_context_parent).append($scope.menu_dom);
630 $scope.action_context_oldy = $scope.action_context_oldx = 0;
631 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
632 $scope.action_context_showing = false;
635 $scope.action_context_showing = false;
636 $scope.showActionContextMenu = function ($event) {
638 // Have to gather these here, instead of inside link()
639 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
640 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
642 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
643 $event.target.click();
645 if (!$scope.action_context_showing) {
646 $scope.action_context_width = $($scope.menu_dom).css('width');
647 $scope.action_context_y = $($scope.menu_dom).css('top');
648 $scope.action_context_x = $($scope.menu_dom).css('left');
649 $scope.action_context_showing = true;
650 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
652 $('body').append($($scope.menu_dom));
653 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
656 $($scope.menu_dom).css({
658 width: $scope.action_context_width,
666 // returns the list of selected item objects
667 grid.getSelectedItems = function() {
668 return $scope.items.filter(
670 return Boolean($scope.selected[grid.indexValue(item)]);
675 grid.getItemByIndex = function(index) {
676 for (var i = 0; i < $scope.items.length; i++) {
677 var item = $scope.items[i];
678 if (grid.indexValue(item) == index)
683 // selects one row after deselecting all of the others
684 grid.selectOneItem = function(index) {
685 $scope.selected = {};
686 $scope.selected[index] = true;
689 // selects or deselects an item, without affecting the others.
690 // returns true if the item is selected; false if de-selected.
691 // we overwrite the object so that we can watch $scope.selected
692 grid.toggleSelectOneItem = function(index) {
693 if ($scope.selected[index]) {
694 delete $scope.selected[index];
695 $scope.selected = angular.copy($scope.selected);
698 $scope.selected[index] = true;
699 $scope.selected = angular.copy($scope.selected);
704 $scope.updateSelected = function () {
705 return $scope.selected = angular.copy($scope.selected);
708 grid.selectAllItems = function() {
709 angular.forEach($scope.items, function(item) {
710 $scope.selected[grid.indexValue(item)] = true
712 $scope.selected = angular.copy($scope.selected);
715 $scope.$watch('selectAll', function(newVal) {
717 grid.selectAllItems();
719 $scope.selected = {};
723 if ($scope.onSelect) {
724 $scope.$watch('selected', function(newVal) {
725 $scope.onSelect(grid.getSelectedItems());
726 if ($scope.afterSelect) $scope.afterSelect();
730 // returns true if item1 appears in the list before item2;
731 // false otherwise. this is slightly more efficient that
732 // finding the position of each then comparing them.
733 // item1 / item2 may be an item or an item index
734 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
735 var idx1 = grid.indexValue(itemOrIndex1);
736 var idx2 = grid.indexValue(itemOrIndex2);
738 // use for() for early exit
739 for (var i = 0; i < $scope.items.length; i++) {
740 var idx = grid.indexValue($scope.items[i]);
741 if (idx == idx1) return true;
742 if (idx == idx2) return false;
747 // 0-based position of item in the current data set
748 grid.indexOf = function(item) {
749 var idx = grid.indexValue(item);
750 for (var i = 0; i < $scope.items.length; i++) {
751 if (grid.indexValue($scope.items[i]) == idx)
757 grid.modifyColumnFlex = function(column, val) {
759 // prevent flex:0; use hiding instead
763 $scope.modifyColumnFlex = function(col, val) {
764 $scope.lastModColumn = col.name;
765 grid.modifyColumnFlex(col, val);
768 grid.modifyColumnPos = function(col, diff) {
769 var srcIdx, targetIdx;
770 angular.forEach(grid.columnsProvider.columns,
771 function(c, i) { if (c.name == col.name) srcIdx = i });
773 targetIdx = srcIdx + diff;
776 } else if (targetIdx >= grid.columnsProvider.columns.length) {
777 // Target index follows the last visible column.
779 angular.forEach(grid.columnsProvider.columns,
780 function(column, idx) {
781 if (column.visible) lastVisible = idx;
784 targetIdx = lastVisible + 1;
787 // Splice column out of old position, insert at new position.
788 grid.columnsProvider.columns.splice(srcIdx, 1);
789 grid.columnsProvider.columns.splice(targetIdx, 0, col);
792 $scope.modifyColumnPos = function(col, diff) {
793 $scope.lastModColumn = col.name;
794 return grid.modifyColumnPos(col, diff);
798 // handles click, control-click, and shift-click
799 $scope.handleRowClick = function($event, item) {
800 var index = grid.indexValue(item);
802 var origSelected = Object.keys($scope.selected);
804 if (!$scope.canMultiSelect) {
805 grid.selectOneItem(index);
806 grid.lastSelectedItemIndex = index;
810 if ($event.ctrlKey || $event.metaKey /* mac command */) {
812 if (grid.toggleSelectOneItem(index))
813 grid.lastSelectedItemIndex = index;
815 } else if ($event.shiftKey) {
818 if (!grid.lastSelectedItemIndex ||
819 index == grid.lastSelectedItemIndex) {
820 grid.selectOneItem(index);
821 grid.lastSelectedItemIndex = index;
825 var selecting = false;
826 var ascending = grid.itemComesBefore(
827 grid.lastSelectedItemIndex, item);
829 grid.indexOf(grid.lastSelectedItemIndex);
831 // update to new last-selected
832 grid.lastSelectedItemIndex = index;
834 // select each row between the last selected and
835 // currently selected items
837 startPos += ascending ? 1 : -1;
838 var curItem = $scope.items[startPos];
840 var curIdx = grid.indexValue(curItem);
841 $scope.selected[curIdx] = true;
842 if (curIdx == index) break; // all done
844 $scope.selected = angular.copy($scope.selected);
848 grid.selectOneItem(index);
849 grid.lastSelectedItemIndex = index;
853 // Builds a sort expression from column sort priorities.
854 // called on page load and any time the priorities are modified.
855 grid.compileSort = function() {
856 var sortList = grid.columnsProvider.columns.filter(
857 function(col) { return Number(col.sort) != 0 }
860 if (Math.abs(a.sort) < Math.abs(b.sort))
866 if (sortList.length) {
867 grid.dataProvider.sort = sortList.map(function(col) {
869 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
875 // builds a sort expression using a single column,
876 // toggling between ascending and descending sort.
877 $scope.quickSort = function(col_name) {
878 var sort = grid.dataProvider.sort;
879 if (sort && sort.length &&
880 sort[0] == col_name) {
882 blob[col_name] = 'desc';
883 grid.dataProvider.sort = [blob];
885 grid.dataProvider.sort = [col_name];
892 // show / hide the grid configuration row
893 $scope.toggleConfDisplay = function() {
894 if ($scope.showGridConf) {
895 $scope.showGridConf = false;
896 if (grid.columnsProvider.hasSortableColumn()) {
897 // only refresh the grid if the user has the
898 // ability to modify the sort priorities.
904 $scope.showGridConf = true;
907 delete $scope.lastModColumn;
908 $scope.gridColumnPickerIsOpen = false;
911 // called when a dragged column is dropped onto itself
912 // or any other column
913 grid.onColumnDrop = function(target) {
914 if (angular.isUndefined(target)) return;
915 if (target == grid.dragColumn) return;
916 var srcIdx, targetIdx, srcCol;
917 angular.forEach(grid.columnsProvider.columns,
919 if (col.name == grid.dragColumn) {
922 } else if (col.name == target) {
928 if (srcIdx < targetIdx) targetIdx--;
930 // move src column from old location to new location in
931 // the columns array, then force a page refresh
932 grid.columnsProvider.columns.splice(srcIdx, 1);
933 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
937 // prepares a string for inclusion within a CSV document
938 // by escaping commas and quotes and removing newlines.
939 grid.csvDatum = function(str) {
942 str = str.replace(/\n/g, '');
943 if (str.match(/\,/) || str.match(/"/)) {
944 str = str.replace(/"/g, '""');
945 str = '"' + str + '"';
950 /** Export the full data set as CSV.
952 * 1. User clicks the 'download csv' link
953 * 2. All grid data is retrieved asychronously
954 * 3. Once all data is all present and CSV-ized, the download
955 * attributes are linked to the href.
956 * 4. The href .click() action is prgrammatically fired again,
957 * telling the browser to download the data, now that the
958 * data is available for download.
959 * 5 Once downloaded, the href attributes are reset.
961 grid.csvExportInProgress = false;
962 $scope.generateCSVExportURL = function($event) {
964 if (grid.csvExportInProgress) {
965 // This is secondary href click handler. Give the
966 // browser a moment to start the download, then reset
967 // the CSV download attributes / state.
970 $scope.csvExportURL = '';
971 $scope.csvExportFileName = '';
972 grid.csvExportInProgress = false;
978 grid.csvExportInProgress = true;
979 $scope.gridColumnPickerIsOpen = false;
981 // let the file name describe the grid
982 $scope.csvExportFileName =
983 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
984 .replace(/\s+/g, '_') + '_' + $scope.page();
986 // toss the CSV into a Blob and update the export URL
987 grid.generateCSV().then(function(csv) {
988 var blob = new Blob([csv], {type : 'text/plain'});
989 $scope.csvExportURL =
990 ($window.URL || $window.webkitURL).createObjectURL(blob);
992 // Fire the 2nd click event now that the browser has
993 // information on how to download the CSV file.
994 $timeout(function() {$event.target.click()});
999 * TODO: does this serve any purpose given we can
1000 * print formatted HTML? If so, generateCSV() now
1001 * returns a promise, needs light refactoring...
1002 $scope.printCSV = function() {
1003 $scope.gridColumnPickerIsOpen = false;
1004 egCore.print.print({
1005 context : 'default',
1006 content : grid.generateCSV(),
1007 content_type : 'text/plain'
1012 // Given a row item and column definition, extract the
1013 // text content for printing. Templated columns must be
1014 // processed and parsed as HTML, then boiled down to their
1016 grid.getItemTextContent = function(item, col) {
1019 val = $scope.translateCellTemplate(col, item);
1021 var node = new DOMParser()
1022 .parseFromString(val, 'text/html');
1023 val = $(node).text();
1026 val = grid.dataProvider.itemFieldValue(item, col);
1027 val = $filter('egGridValueFilter')(val, col, item);
1033 * Fetches all grid data and transates each item into a simple
1034 * key-value pair of column name => text-value.
1035 * Included in the response for convenience is the list of
1036 * currently visible column definitions.
1037 * TODO: currently fetches a maximum of 10k rows. Does this
1038 * need to be configurable?
1040 grid.getAllItemsAsText = function() {
1041 var text_items = [];
1043 // we don't know the total number of rows we're about
1044 // to retrieve, but we can indicate the number retrieved
1045 // so far as each item arrives.
1046 egProgressDialog.open({value : 0});
1048 var visible_cols = grid.columnsProvider.columns.filter(
1049 function(c) { return c.visible });
1051 return grid.dataProvider.get(0, 10000).then(
1053 return {items : text_items, columns : visible_cols};
1057 egProgressDialog.increment();
1059 angular.forEach(visible_cols, function(col) {
1060 text_item[col.name] =
1061 grid.getItemTextContent(item, col);
1063 text_items.push(text_item);
1065 ).finally(egProgressDialog.close);
1068 // Fetch "all" of the grid data, translate it into print-friendly
1069 // text, and send it to the printer service.
1070 $scope.printHTML = function() {
1071 $scope.gridColumnPickerIsOpen = false;
1072 return grid.getAllItemsAsText().then(function(text_items) {
1073 return egCore.print.print({
1074 template : 'grid_html',
1080 $scope.showColumnDialog = function() {
1081 return $uibModal.open({
1082 templateUrl: './share/t_grid_columns',
1085 controller: ['$scope', '$uibModalInstance',
1086 function($dialogScope, $uibModalInstance) {
1087 $dialogScope.modifyColumnPos = $scope.modifyColumnPos;
1088 $dialogScope.disableMultiSort = $scope.disableMultiSort;
1089 $dialogScope.columns = $scope.columns;
1091 // Push visible columns to the top of the list
1092 $dialogScope.elevateVisible = function() {
1094 angular.forEach($dialogScope.columns, function(col) {
1095 if (col.visible) new_cols.push(col);
1097 angular.forEach($dialogScope.columns, function(col) {
1098 if (!col.visible) new_cols.push(col);
1101 // Update all references to the list of columns
1102 $dialogScope.columns =
1104 grid.columnsProvider.columns =
1108 $dialogScope.toggle = function(col) {
1109 col.visible = !Boolean(col.visible);
1111 $dialogScope.ok = $dialogScope.cancel = function() {
1112 delete $scope.lastModColumn;
1113 $uibModalInstance.close()
1120 // generates CSV for the currently visible grid contents
1121 grid.generateCSV = function() {
1122 return grid.getAllItemsAsText().then(function(text_items) {
1123 var columns = text_items.columns;
1124 var items = text_items.items;
1128 angular.forEach(columns, function(col) {
1129 csvStr += grid.csvDatum(col.label);
1133 csvStr = csvStr.replace(/,$/,'\n');
1136 angular.forEach(items, function(item) {
1137 angular.forEach(columns, function(col) {
1138 csvStr += grid.csvDatum(item[col.name]);
1141 csvStr = csvStr.replace(/,$/,'\n');
1148 // Interpolate the value for column.linkpath within the context
1149 // of the row item to generate the final link URL.
1150 $scope.generateLinkPath = function(col, item) {
1151 return egCore.strings.$replace(col.linkpath, {item : item});
1154 // If a column provides its own HTML template, translate it,
1155 // using the current item for the template scope.
1156 // note: $sce is required to avoid security restrictions and
1157 // is OK here, since the template comes directly from a
1158 // local HTML template (not user input).
1159 $scope.translateCellTemplate = function(col, item) {
1160 var html = egCore.strings.$replace(col.template, {item : item});
1161 return $sce.trustAsHtml(html);
1164 $scope.collect = function() { grid.collect() }
1166 // asks the dataProvider for a page of data
1167 grid.collect = function() {
1169 // avoid firing the collect if there is nothing to collect.
1170 if (grid.selfManagedData && !grid.dataProvider.query) return;
1172 if (grid.collecting) return; // avoid parallel collect()
1173 grid.collecting = true;
1175 console.debug('egGrid.collect() offset='
1176 + grid.offset + '; limit=' + grid.limit);
1178 // ensure all of our dropdowns are closed
1179 // TODO: git rid of these and just use dropdown-toggle,
1180 // which is more reliable.
1181 $scope.gridColumnPickerIsOpen = false;
1182 $scope.gridRowCountIsOpen = false;
1183 $scope.gridPageSelectIsOpen = false;
1186 $scope.selected = {};
1188 // Inform the caller we've asked the data provider
1189 // for data. This is useful for knowing when collection
1190 // has started (e.g. to display a progress dialg) when
1191 // using the stock (flattener) data provider, where the
1192 // user is not directly defining a get() handler.
1193 if (grid.controls.collectStarted)
1194 grid.controls.collectStarted(grid.offset, grid.limit);
1196 grid.dataProvider.get(grid.offset, grid.limit).then(
1198 if (grid.controls.allItemsRetrieved)
1199 grid.controls.allItemsRetrieved();
1204 $scope.items.push(item)
1205 if (grid.controls.itemRetrieved)
1206 grid.controls.itemRetrieved(item);
1207 if ($scope.selectAll)
1208 $scope.selected[grid.indexValue(item)] = true
1210 }).finally(function() {
1211 console.debug('egGrid.collect() complete');
1212 grid.collecting = false
1213 $scope.selected = angular.copy($scope.selected);
1223 * eg-grid-field : used for collecting custom field data from the templates.
1224 * This directive does not direct display, it just passes data up to the
1227 .directive('egGridField', function() {
1229 require : '^egGrid',
1232 flesher: '=', // optional; function that can flesh a linked field, given the value
1233 comparator: '=', // optional; function that can sort the thing at the end of 'path'
1234 name : '@', // required; unique name
1235 path : '@', // optional; flesh path
1236 ignore: '@', // optional; fields to ignore when path is a wildcard
1237 label : '@', // optional; display label
1238 flex : '@', // optional; default flex width
1239 align : '@', // optional; default alignment, left/center/right
1240 dateformat : '@', // optional: passed down to egGridValueFilter
1241 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
1242 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
1243 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
1245 // if a field is part of an IDL object, but we are unable to
1246 // determine the class, because it's nested within a hash
1247 // (i.e. we can't navigate directly to the object via the IDL),
1248 // idlClass lets us specify the class. This is particularly
1249 // useful for nested wildcard fields.
1250 parentIdlClass : '@',
1252 // optional: for non-IDL columns, specifying a datatype
1253 // lets the caller control which display filter is used.
1254 // datatype should match the standard IDL datatypes.
1257 link : function(scope, element, attrs, egGridCtrl) {
1259 // boolean fields are presented as value-less attributes
1268 'required' // if set, always fetch data for this column
1271 if (angular.isDefined(attrs[field]))
1272 scope[field] = true;
1276 // any HTML content within the field is its custom template
1277 var tmpl = element.html();
1278 if (tmpl && !tmpl.match(/^\s*$/))
1279 scope.template = tmpl
1281 egGridCtrl.columnsProvider.add(scope);
1288 * eg-grid-action : used for specifying actions which may be applied
1289 * to items within the grid.
1291 .directive('egGridAction', function() {
1293 require : '^egGrid',
1297 group : '@', // Action group, ungrouped if not set
1298 label : '@', // Action label
1299 handler : '=', // Action function handler
1301 disabled : '=', // function
1304 link : function(scope, element, attrs, egGridCtrl) {
1305 egGridCtrl.addAction({
1307 group : scope.group,
1308 label : scope.label,
1309 divider : scope.divider,
1310 handler : scope.handler,
1311 disabled : scope.disabled,
1318 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1320 function ColumnsProvider(args) {
1323 cols.stockVisible = [];
1324 cols.idlClass = args.idlClass;
1325 cols.clientSort = args.clientSort;
1326 cols.defaultToHidden = args.defaultToHidden;
1327 cols.defaultToNoSort = args.defaultToNoSort;
1328 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1329 cols.defaultDateFormat = args.defaultDateFormat;
1330 cols.defaultDateContext = args.defaultDateContext;
1332 // resets column width, visibility, and sort behavior
1333 // Visibility resets to the visibility settings defined in the
1334 // template (i.e. the original egGridField values).
1335 cols.reset = function() {
1336 angular.forEach(cols.columns, function(col) {
1340 if (cols.stockVisible.indexOf(col.name) > -1) {
1343 col.visible = false;
1348 // returns true if any columns are sortable
1349 cols.hasSortableColumn = function() {
1350 return cols.columns.filter(
1352 return col.sortable || col.multisortable;
1357 cols.showAllColumns = function() {
1358 angular.forEach(cols.columns, function(column) {
1359 column.visible = true;
1363 cols.hideAllColumns = function() {
1364 angular.forEach(cols.columns, function(col) {
1369 cols.indexOf = function(name) {
1370 for (var i = 0; i < cols.columns.length; i++) {
1371 if (cols.columns[i].name == name)
1377 cols.findColumn = function(name) {
1378 return cols.columns[cols.indexOf(name)];
1381 cols.compileAutoColumns = function() {
1382 var idl_class = egCore.idl.classes[cols.idlClass];
1387 if (field.virtual) return;
1388 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1389 // if the field is a link and the linked class has a
1390 // "selector" field specified, use the selector field
1391 // as the display field for the columns.
1392 // flattener will take care of the fleshing.
1393 if (field['class']) {
1394 var selector_field = egCore.idl.classes[field['class']].fields
1395 .filter(function(f) { return Boolean(f.selector) })[0];
1396 if (selector_field) {
1397 field.path = field.name + '.' + selector_field.selector;
1401 cols.add(field, true);
1406 // if a column definition has a path with a wildcard, create
1407 // columns for all non-virtual fields at the specified
1408 // position in the path.
1409 cols.expandPath = function(colSpec) {
1411 var ignoreList = [];
1413 ignoreList = colSpec.ignore.split(' ');
1415 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1419 if (colSpec.parentIdlClass) {
1420 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1422 class_obj = egCore.idl.classes[cols.idlClass];
1424 var idl_parent = class_obj;
1425 var old_field_label = '';
1427 if (!class_obj) return;
1429 console.debug('egGrid: auto dotpath is: ' + dotpath);
1430 var path_parts = dotpath.split(/\./);
1432 // find the IDL class definition for the last element in the
1433 // path before the .*
1434 // an empty path_parts means expand the root class
1437 for (var path_idx in path_parts) {
1438 old_field = idl_field;
1440 var part = path_parts[path_idx];
1441 idl_field = class_obj.field_map[part];
1443 // unless we're at the end of the list, this field should
1444 // link to another class.
1445 if (idl_field && idl_field['class'] && (
1446 idl_field.datatype == 'link' ||
1447 idl_field.datatype == 'org_unit')) {
1448 if (old_field_label) old_field_label += ' : ';
1449 old_field_label += idl_field.label;
1450 class_obj = egCore.idl.classes[idl_field['class']];
1451 if (old_field) idl_parent = old_field;
1453 if (path_idx < (path_parts.length - 1)) {
1454 // we ran out of classes to hop through before
1455 // we ran out of path components
1456 console.error("egGrid: invalid IDL path: " + dotpath);
1463 angular.forEach(class_obj.fields, function(field) {
1465 // Only show wildcard fields where we have data to show
1466 // Virtual and un-fleshed links will not have any data.
1467 if (field.virtual ||
1468 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1469 ignoreList.indexOf(field.name) > -1
1473 var col = cols.cloneFromScope(colSpec);
1474 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1476 // log line below is very chatty. disable until needed.
1477 // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1478 cols.add(col, false, true,
1479 {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1482 cols.columns = cols.columns.sort(
1484 if (a.explicit) return -1;
1485 if (b.explicit) return 1;
1487 if (a.idlclass && b.idlclass) {
1488 if (a.idlclass < b.idlclass) return -1;
1489 if (b.idlclass < a.idlclass) return 1;
1492 if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1493 if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1494 if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1497 if (a.label && b.label) {
1498 if (a.label < b.label) return -1;
1499 if (b.label < a.label) return 1;
1502 return a.name < b.name ? -1 : 1;
1509 "egGrid: wildcard path does not resolve to an object: "
1514 // angular.clone(scopeObject) is not permittable. Manually copy
1515 // the fields over that we need (so the scope object can go away).
1516 cols.cloneFromScope = function(colSpec) {
1518 flesher : colSpec.flesher,
1519 comparator : colSpec.comparator,
1520 name : colSpec.name,
1521 label : colSpec.label,
1522 path : colSpec.path,
1523 align : colSpec.align || 'left',
1524 flex : Number(colSpec.flex) || 2,
1525 sort : Number(colSpec.sort) || 0,
1526 required : colSpec.required,
1527 linkpath : colSpec.linkpath,
1528 template : colSpec.template,
1529 visible : colSpec.visible,
1530 hidden : colSpec.hidden,
1531 datatype : colSpec.datatype,
1532 sortable : colSpec.sortable,
1533 nonsortable : colSpec.nonsortable,
1534 multisortable : colSpec.multisortable,
1535 nonmultisortable : colSpec.nonmultisortable,
1536 dateformat : colSpec.dateformat,
1537 datecontext : colSpec.datecontext,
1538 datefilter : colSpec.datefilter,
1539 dateonlyinterval : colSpec.dateonlyinterval,
1540 parentIdlClass : colSpec.parentIdlClass
1545 // Add a column to the columns collection.
1546 // Columns may come from a slim eg-columns-field or
1547 // directly from the IDL.
1548 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1550 // First added column with the specified path takes precedence.
1551 // This allows for specific definitions followed by wildcard
1552 // definitions. If a match is found, back out.
1553 if (cols.columns.filter(function(c) {
1554 return (c.path == colSpec.path) })[0]) {
1555 console.debug('skipping pre-existing column ' + colSpec.path);
1559 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1561 if (column.path && column.path.match(/\*$/))
1562 return cols.expandPath(colSpec);
1564 if (!fromExpand) column.explicit = true;
1566 if (!column.name) column.name = column.path;
1567 if (!column.path) column.path = column.name;
1569 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1570 column.visible = true;
1572 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1573 column.sortable = true;
1575 if (column.multisortable ||
1576 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1577 column.multisortable = true;
1579 if (cols.defaultDateFormat && ! column.dateformat) {
1580 column.dateformat = cols.defaultDateFormat;
1583 if (cols.defaultDateOnlyInterval && ! column.dateonlyinterval) {
1584 column.dateonlyinterval = cols.defaultDateOnlyInterval;
1587 if (cols.defaultDateContext && ! column.datecontext) {
1588 column.datecontext = cols.defaultDateContext;
1591 if (cols.defaultDateFilter && ! column.datefilter) {
1592 column.datefilter = cols.defaultDateFilter;
1595 cols.columns.push(column);
1597 // Track which columns are visible by default in case we
1598 // need to reset column visibility
1600 cols.stockVisible.push(column.name);
1602 if (fromIDL) return; // directly from egIDL. nothing left to do.
1604 // lookup the matching IDL field
1605 if (!idl_info && cols.idlClass)
1606 idl_info = cols.idlFieldFromPath(column.path);
1609 // column is not represented within the IDL
1610 column.adhoc = true;
1614 column.datatype = idl_info.idl_field.datatype;
1616 if (!column.label) {
1617 column.label = idl_info.idl_field.label || column.name;
1620 if (fromExpand && idl_info.idl_class) {
1621 column.idlclass = '';
1622 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1623 column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1625 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1630 // finds the IDL field from the dotpath, using the columns
1631 // idlClass as the base.
1632 cols.idlFieldFromPath = function(dotpath) {
1633 var class_obj = egCore.idl.classes[cols.idlClass];
1634 var path_parts = dotpath.split(/\./);
1638 for (var path_idx in path_parts) {
1639 var part = path_parts[path_idx];
1640 idl_parent = idl_field;
1641 idl_field = class_obj.field_map[part];
1644 if (idl_field['class'] && (
1645 idl_field.datatype == 'link' ||
1646 idl_field.datatype == 'org_unit')) {
1647 class_obj = egCore.idl.classes[idl_field['class']];
1655 idl_parent: idl_parent,
1656 idl_field : idl_field,
1657 idl_class : class_obj
1663 instance : function(args) { return new ColumnsProvider(args) }
1669 * Generic data provider template class. This is basically an abstract
1670 * class factory service whose instances can be locally modified to
1671 * meet the needs of each individual grid.
1673 .factory('egGridDataProvider',
1674 ['$q','$timeout','$filter','egCore',
1675 function($q , $timeout , $filter , egCore) {
1677 function GridDataProvider(args) {
1678 var gridData = this;
1679 if (!args) args = {};
1682 gridData.get = args.get;
1683 gridData.query = args.query;
1684 gridData.idlClass = args.idlClass;
1685 gridData.columnsProvider = args.columnsProvider;
1687 // Delivers a stream of array data via promise.notify()
1688 // Useful for passing an array of data to egGrid.get()
1689 // If a count is provided, the array will be trimmed to
1690 // the range defined by count and offset
1691 gridData.arrayNotifier = function(arr, offset, count) {
1692 if (!arr || arr.length == 0) return $q.when();
1694 if (gridData.columnsProvider.clientSort
1696 && gridData.sort.length > 0
1698 var sorter_cache = [];
1699 arr.sort(function(a,b) {
1700 for (var si = 0; si < gridData.sort.length; si++) {
1701 if (!sorter_cache[si]) { // Build sort structure on first comparison, reuse thereafter
1702 var field = gridData.sort[si];
1705 if (angular.isObject(field)) {
1706 dir = Object.values(field)[0];
1707 field = Object.keys(field)[0];
1710 var path = gridData.columnsProvider.findColumn(field).path || field;
1711 var comparator = gridData.columnsProvider.findColumn(field).comparator ||
1712 function (x,y) { if (x < y) return -1; if (x > y) return 1; return 0 };
1714 sorter_cache[si] = {
1717 comparator : comparator
1721 var sc = sorter_cache[si];
1725 if (a._isfieldmapper || angular.isFunction(a[sc.field])) {
1726 try {af = a[sc.field](); bf = b[sc.field]() } catch (e) {};
1728 af = a[sc.field]; bf = b[sc.field];
1730 if (af === undefined && sc.field.indexOf('.') > -1) { // assume an object, not flat path
1731 var parts = sc.field.split('.');
1734 angular.forEach(parts, function (p) {
1736 if (af._isfieldmapper || angular.isFunction(af[p])) af = af[p]();
1740 if (bf._isfieldmapper || angular.isFunction(bf[p])) bf = bf[p]();
1746 if (af === undefined) af = null;
1747 if (bf === undefined) bf = null;
1749 if (af === null && bf !== null) return 1;
1750 if (bf === null && af !== null) return -1;
1752 if (!(bf === null && af === null)) {
1753 var partial = sc.comparator(af,bf);
1755 if (sc.dir == 'desc') {
1756 if (partial > 0) return -1;
1768 if (count) arr = arr.slice(offset, offset + count);
1769 var def = $q.defer();
1770 // promise notifications are only witnessed when delivered
1771 // after the caller has his hands on the promise object
1772 $timeout(function() {
1773 angular.forEach(arr, def.notify);
1779 // Calls the grid refresh function. Once instantiated, the
1780 // grid will replace this function with it's own refresh()
1781 gridData.refresh = function(noReset) { }
1783 if (!gridData.get) {
1784 // returns a promise whose notify() delivers items
1785 gridData.get = function(index, count) {
1786 console.error("egGridDataProvider.get() not implemented");
1790 // attempts a flat field lookup first. If the column is not
1791 // found on the top-level object, attempts a nested lookup
1792 // TODO: consider a caching layer to speed up template
1793 // rendering, particularly for nested objects?
1794 gridData.itemFieldValue = function(item, column) {
1796 if (column.name in item) {
1797 if (typeof item[column.name] == 'function') {
1798 val = item[column.name]();
1800 val = item[column.name];
1803 val = gridData.nestedItemFieldValue(item, column);
1809 // TODO: deprecate me
1810 gridData.flatItemFieldValue = function(item, column) {
1811 console.warn('gridData.flatItemFieldValue deprecated; '
1812 + 'leave provider.itemFieldValue unset');
1813 return item[column.name];
1816 // given an object and a dot-separated path to a field,
1817 // extract the value of the field. The path can refer
1818 // to function names or object attributes. If the final
1819 // value is an IDL field, run the value through its
1820 // corresponding output filter.
1821 gridData.nestedItemFieldValue = function(obj, column) {
1822 item = obj; // keep a copy around
1824 if (obj === null || obj === undefined || obj === '') return '';
1825 if (!column.path) return obj;
1828 var parts = column.path.split('.');
1830 angular.forEach(parts, function(step, idx) {
1831 // object is not fleshed to the expected extent
1832 if (typeof obj != 'object') {
1833 if (typeof obj != 'undefined' && column.flesher) {
1834 obj = column.flesher(obj, column, item);
1841 if (!obj) return '';
1843 var cls = obj.classname;
1844 if (cls && (class_obj = egCore.idl.classes[cls])) {
1845 idl_field = class_obj.field_map[step];
1846 obj = obj[step] ? obj[step]() : '';
1848 if (angular.isFunction(obj[step])) {
1856 // We found a nested IDL object which may or may not have
1857 // been configured as a top-level column. Grab the datatype.
1858 if (idl_field && !column.datatype)
1859 column.datatype = idl_field.datatype;
1861 if (obj === null || obj === undefined || obj === '') return '';
1867 instance : function(args) {
1868 return new GridDataProvider(args);
1875 // Factory service for egGridDataManager instances, which are
1876 // responsible for collecting flattened grid data.
1877 .factory('egGridFlatDataProvider',
1878 ['$q','egCore','egGridDataProvider',
1879 function($q , egCore , egGridDataProvider) {
1882 instance : function(args) {
1883 var provider = egGridDataProvider.instance(args);
1885 provider.get = function(offset, count) {
1887 // no query means no call
1888 if (!provider.query ||
1889 angular.equals(provider.query, {}))
1892 // find all of the currently visible columns
1893 var queryFields = {}
1894 angular.forEach(provider.columnsProvider.columns,
1896 // only query IDL-tracked columns
1897 if (!col.adhoc && (col.required || col.visible))
1898 queryFields[col.name] = col.path;
1902 return egCore.net.request(
1904 'open-ils.fielder.flattened_search',
1905 egCore.auth.token(), provider.idlClass,
1906 queryFields, provider.query,
1907 { sort : provider.sort,
1913 //provider.itemFieldValue = provider.flatItemFieldValue;
1920 .directive('egGridColumnDragSource', function() {
1923 require : '^egGrid',
1924 link : function(scope, element, attrs, egGridCtrl) {
1925 angular.element(element).attr('draggable', 'true');
1927 element.bind('dragstart', function(e) {
1928 egGridCtrl.dragColumn = attrs.column;
1929 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1930 egGridCtrl.colResizeDir = 0;
1932 if (egGridCtrl.dragType == 'move') {
1933 // style the column getting moved
1934 angular.element(e.target).addClass(
1935 'eg-grid-column-move-handle-active');
1939 element.bind('dragend', function(e) {
1940 if (egGridCtrl.dragType == 'move') {
1941 angular.element(e.target).removeClass(
1942 'eg-grid-column-move-handle-active');
1949 .directive('egGridColumnDragDest', function() {
1952 require : '^egGrid',
1953 link : function(scope, element, attrs, egGridCtrl) {
1955 element.bind('dragover', function(e) { // required for drop
1956 e.stopPropagation();
1958 e.dataTransfer.dropEffect = 'move';
1960 if (egGridCtrl.colResizeDir == 0) return; // move
1962 var cols = egGridCtrl.columnsProvider;
1963 var srcCol = egGridCtrl.dragColumn;
1964 var srcColIdx = cols.indexOf(srcCol);
1966 if (egGridCtrl.colResizeDir == -1) {
1967 if (cols.indexOf(attrs.column) <= srcColIdx) {
1968 egGridCtrl.modifyColumnFlex(
1969 egGridCtrl.columnsProvider.findColumn(
1970 egGridCtrl.dragColumn), -1);
1971 if (cols.columns[srcColIdx+1]) {
1972 // source column shrinks by one, column to the
1973 // right grows by one.
1974 egGridCtrl.modifyColumnFlex(
1975 cols.columns[srcColIdx+1], 1);
1980 if (cols.indexOf(attrs.column) > srcColIdx) {
1981 egGridCtrl.modifyColumnFlex(
1982 egGridCtrl.columnsProvider.findColumn(
1983 egGridCtrl.dragColumn), 1);
1984 if (cols.columns[srcColIdx+1]) {
1985 // source column grows by one, column to the
1986 // right grows by one.
1987 egGridCtrl.modifyColumnFlex(
1988 cols.columns[srcColIdx+1], -1);
1996 element.bind('dragenter', function(e) {
1997 e.stopPropagation();
1999 if (egGridCtrl.dragType == 'move') {
2000 angular.element(e.target).addClass('eg-grid-col-hover');
2002 // resize grips are on the right side of each column.
2003 // dragenter will either occur on the source column
2004 // (dragging left) or the column to the right.
2005 if (egGridCtrl.colResizeDir == 0) {
2006 if (egGridCtrl.dragColumn == attrs.column) {
2007 egGridCtrl.colResizeDir = -1; // west
2009 egGridCtrl.colResizeDir = 1; // east
2015 element.bind('dragleave', function(e) {
2016 e.stopPropagation();
2018 if (egGridCtrl.dragType == 'move') {
2019 angular.element(e.target).removeClass('eg-grid-col-hover');
2023 element.bind('drop', function(e) {
2024 e.stopPropagation();
2026 egGridCtrl.colResizeDir = 0;
2027 if (egGridCtrl.dragType == 'move') {
2028 angular.element(e.target).removeClass('eg-grid-col-hover');
2029 egGridCtrl.onColumnDrop(attrs.column); // move the column
2036 .directive('egGridMenuItem', function() {
2039 require : '^egGrid',
2045 handler : '=', // onclick handler function
2046 divider : '=', // if true, show a divider only
2047 handlerData : '=', // if set, passed as second argument to handler
2048 disabled : '=', // function
2049 hidden : '=' // function
2051 link : function(scope, element, attrs, egGridCtrl) {
2052 egGridCtrl.addMenuItem({
2053 checkbox : scope.checkbox,
2054 checked : scope.checked ? true : false,
2055 label : scope.label,
2056 standalone : scope.standalone ? true : false,
2057 handler : scope.handler,
2058 divider : scope.divider,
2059 disabled : scope.disabled,
2060 hidden : scope.hidden,
2061 handlerData : scope.handlerData
2071 * Translates bare IDL object values into display values.
2072 * 1. Passes dates through the angular date filter
2073 * 2. Translates bools to Booleans so the browser can display translated
2074 * value. (Though we could manually translate instead..)
2075 * Others likely to follow...
2077 .filter('egGridValueFilter', ['$filter','egCore', function($filter,egCore) {
2078 function traversePath(obj,path) {
2079 var list = path.split('.');
2080 for (var part in path) {
2081 if (obj[path]) obj = obj[path]
2087 var GVF = function(value, column, item) {
2088 switch(column.datatype) {
2091 // Browser will translate true/false for us
2093 case '1' : // legacy
2097 case '0' : // legacy
2100 // value may be null, '', etc.
2101 default : return '';
2104 var interval = angular.isFunction(item[column.dateonlyinterval])
2105 ? item[column.dateonlyinterval]()
2106 : item[column.dateonlyinterval];
2108 if (column.dateonlyinterval && !interval) // try it as a dotted path
2109 interval = traversePath(item, column.dateonlyinterval);
2111 var context = angular.isFunction(item[column.datecontext])
2112 ? item[column.datecontext]()
2113 : item[column.datecontext];
2115 if (column.datecontext && !context) // try it as a dotted path
2116 context = traversePath(item, column.datecontext);
2118 var date_filter = column.datefilter || 'egOrgDateInContext';
2120 return $filter(date_filter)(value, column.dateformat, context, interval);
2122 return $filter('currency')(value);
2128 GVF.$stateful = true;