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: object containing function to conditionally apply
61 // optional: object that enables status icon field and contains
62 // function to handle what status icons should exist and why.
65 // optional primary grid label
68 // if true, use the IDL class label as the mainLabel
71 // optional context menu label
74 dateformat : '@', // optional: passed down to egGridValueFilter
75 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
76 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
77 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
79 // Hash of control functions.
81 // These functions are defined by the calling scope and
82 // invoked as-is by the grid w/ the specified parameters.
84 // collectStarted : function() {}
85 // itemRetrieved : function(item) {}
86 // allItemsRetrieved : function() {}
89 // If defined, the grid will watch the return value from
90 // the function defined at watchQuery on each digest and
91 // re-draw the grid when query changes occur.
93 // watchQuery : function() { /* return grid query */ }
96 // These functions are defined by the grid and thus
97 // replace any values defined for these attributes from the
100 // activateItem : function(item) {}
101 // allItems : function(allItems) {}
102 // selectedItems : function(selected) {}
103 // selectItems : function(ids) {}
104 // setQuery : function(queryStruct) {} // causes reload
105 // setSort : function(sortSturct) {} // causes reload
109 // TODO: avoid hard-coded url
110 templateUrl : '/eg/staff/share/t_autogrid',
112 link : function(scope, element, attrs) {
113 // link() is called after page compilation, which means our
114 // eg-grid-field's have been parsed and loaded. Now it's
115 // safe to perform our initial page load.
117 // load auto fields after eg-grid-field's so they are not clobbered
118 scope.handleAutoFields();
121 var statusCell = scope.statusCell;
122 var rowClass = scope.rowClass;
124 scope.grid_element = element;
126 .find('.eg-grid-content-body')
127 .bind('contextmenu', scope.showActionContextMenu);
131 '$scope','$q','egCore','egGridFlatDataProvider','$location',
132 'egGridColumnsProvider','$filter','$window','$sce','$timeout',
134 function($scope, $q , egCore, egGridFlatDataProvider , $location,
135 egGridColumnsProvider , $filter , $window , $sce , $timeout,
140 grid.init = function() {
143 $scope.showGridConf = false;
144 grid.totalCount = -1;
145 $scope.selected = {};
146 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
147 $scope.menuItems = []; // global actions
149 // returns true if any rows are selected.
150 $scope.hasSelected = function() {
151 return grid.getSelectedItems().length > 0 };
153 var features = ($scope.features) ?
154 $scope.features.split(',') : [];
155 delete $scope.features;
157 $scope.showIndex = (features.indexOf('-index') == -1);
159 $scope.allowAll = (features.indexOf('allowAll') > -1);
160 $scope.startSelected = $scope.selectAll = (features.indexOf('startSelected') > -1);
161 $scope.showActions = (features.indexOf('-actions') == -1);
162 $scope.showPagination = (features.indexOf('-pagination') == -1);
163 $scope.showPicker = (features.indexOf('-picker') == -1);
165 $scope.showMenu = (features.indexOf('-menu') == -1);
167 // remove some unneeded values from the scope to reduce bloat
169 grid.idlClass = $scope.idlClass;
170 delete $scope.idlClass;
172 grid.persistKey = $scope.persistKey;
173 delete $scope.persistKey;
175 var stored_limit = 0;
176 if ($scope.showPagination) {
177 if (grid.persistKey) {
178 var stored_limit = Number(
179 egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
183 stored_limit = 10000; // maybe support "Inf"?
186 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
188 grid.indexField = $scope.idField;
189 delete $scope.idField;
191 grid.dataProvider = $scope.itemsProvider;
193 if (!grid.indexField && grid.idlClass)
194 grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
196 grid.columnsProvider = egGridColumnsProvider.instance({
197 idlClass : grid.idlClass,
198 clientSort : (features.indexOf('clientsort') > -1 && features.indexOf('-clientsort') == -1),
199 defaultToHidden : (features.indexOf('-display') > -1),
200 defaultToNoSort : (features.indexOf('-sort') > -1),
201 defaultToNoMultiSort : (features.indexOf('-multisort') > -1),
202 defaultDateFormat : $scope.dateformat,
203 defaultDateContext : $scope.datecontext,
204 defaultDateFilter : $scope.datefilter,
205 defaultDateOnlyInterval : $scope.dateonlyinterval
207 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
209 $scope.handleAutoFields = function() {
210 if ($scope.autoFields) {
211 if (grid.autoLabel) {
213 egCore.idl.classes[grid.idlClass].label;
215 grid.columnsProvider.compileAutoColumns();
216 delete $scope.autoFields;
220 if (!grid.dataProvider) {
221 // no provider, um, provided.
222 // Use a flat data provider
224 grid.selfManagedData = true;
225 grid.dataProvider = egGridFlatDataProvider.instance({
226 indexField : grid.indexField,
227 idlClass : grid.idlClass,
228 columnsProvider : grid.columnsProvider,
233 grid.dataProvider.columnsProvider = grid.columnsProvider;
235 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
236 $scope.indexValue = function(item) {
237 return grid.indexValue(item)
240 grid.applyControlFunctions();
242 grid.loadConfig().then(function() {
243 // link columns to scope after loadConfig(), since it
244 // replaces the columns array.
245 $scope.columns = grid.columnsProvider.columns;
248 // NOTE: grid.collect() is first called from link(), not here.
251 // link our control functions into the gridControls
252 // scope object so the caller can access them.
253 grid.applyControlFunctions = function() {
255 // we use some of these controls internally, so sett
256 // them up even if the caller doesn't request them.
257 var controls = $scope.gridControls || {};
259 controls.columnMap = function() {
261 angular.forEach(grid.columnsProvider.columns, function (c) {
267 controls.columnsProvider = function() {
268 return grid.columnsProvider;
271 // link in the control functions
272 controls.selectedItems = function() {
273 return grid.getSelectedItems()
276 controls.allItems = function() {
280 controls.selectItems = function(ids) {
282 $scope.selected = {};
283 angular.forEach(ids, function(i) {
284 $scope.selected[''+i] = true;
288 // if the caller provided a functional setQuery,
289 // extract the value before replacing it
290 if (controls.setQuery) {
291 grid.dataProvider.query =
295 controls.setQuery = function(query) {
296 grid.dataProvider.query = query;
300 if (controls.watchQuery) {
301 // capture the initial query value
302 grid.dataProvider.query = controls.watchQuery();
305 $scope.gridWatchQuery = controls.watchQuery;
306 $scope.$watch('gridWatchQuery()', function(newv) {
307 controls.setQuery(newv);
311 // if the caller provided a functional setSort
312 // extract the value before replacing it
313 grid.dataProvider.sort =
314 controls.setSort ? controls.setSort() : [];
316 controls.setSort = function(sort) {
320 controls.refresh = function(noReset) {
321 if (!noReset) grid.offset = 0;
325 controls.setLimit = function(limit,forget) {
326 if (!forget && grid.persistKey)
327 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
330 controls.getLimit = function() {
333 controls.setOffset = function(offset) {
334 grid.offset = offset;
336 controls.getOffset = function() {
340 controls.saveConfig = function () {
341 return $scope.saveConfig();
344 grid.dataProvider.refresh = controls.refresh;
345 grid.controls = controls;
348 // If a menu item provides its own HTML template, translate it,
349 // using the menu item for the template scope.
350 // note: $sce is required to avoid security restrictions and
351 // is OK here, since the template comes directly from a
352 // local HTML template (not user input).
353 $scope.translateMenuItemTemplate = function(item) {
354 var html = egCore.strings.$replace(item.template, {item : item});
355 return $sce.trustAsHtml(html);
358 // add a new (global) grid menu item
359 grid.addMenuItem = function(item) {
360 $scope.menuItems.push(item);
361 var handler = item.handler;
362 item.handler = function() {
363 $scope.gridMenuIsOpen = false; // close menu
366 item.handlerData, grid.getSelectedItems());
371 // add a selected-items action
372 grid.addAction = function(act) {
374 $scope.actionGroups.forEach(function(g){
375 if (g.label === act.group) {
381 $scope.actionGroups.push({
388 // remove the stored column configuration preferenc, then recover
389 // the column visibility information from the initial page load.
390 $scope.resetColumns = function() {
391 $scope.gridColumnPickerIsOpen = false;
392 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
394 grid.columnsProvider.reset();
395 if (grid.selfManagedData) grid.collect();
399 $scope.showAllColumns = function() {
400 $scope.gridColumnPickerIsOpen = false;
401 grid.columnsProvider.showAllColumns();
402 if (grid.selfManagedData) grid.collect();
405 $scope.hideAllColumns = function() {
406 $scope.gridColumnPickerIsOpen = false;
407 grid.columnsProvider.hideAllColumns();
408 // note: no need to fetch new data if no columns are visible
411 $scope.toggleColumnVisibility = function(col) {
412 $scope.gridColumnPickerIsOpen = false;
413 col.visible = !col.visible;
415 // egGridFlatDataProvider only retrieves data to be
416 // displayed. When column visibility changes, it's
417 // necessary to fetch the newly visible column data.
418 if (grid.selfManagedData) grid.collect();
421 // save the columns configuration (position, sort, width) to
422 // eg.grid.<persist-key>
423 $scope.saveConfig = function() {
424 $scope.gridColumnPickerIsOpen = false;
426 if (!grid.persistKey) {
428 "Cannot save settings without a grid persist-key");
432 // only store information about visible columns.
433 var conf = grid.columnsProvider.columns.filter(
434 function(col) {return Boolean(col.visible) });
436 // now scrunch the data down to just the needed info
437 conf = conf.map(function(col) {
438 var c = {name : col.name}
439 // Apart from the name, only store non-default values.
440 // No need to store col.visible, since that's implicit
441 if (col.align != 'left') c.align = col.align;
442 if (col.flex != 2) c.flex = col.flex;
443 if (Number(col.sort)) c.sort = Number(c.sort);
447 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
449 // Save operation performed from the grid configuration UI.
450 // Hide the configuration UI and re-draw w/ sort applied
451 if ($scope.showGridConf)
452 $scope.toggleConfDisplay();
457 // load the columns configuration (position, sort, width) from
458 // eg.grid.<persist-key> and apply the loaded settings to the
459 // columns on our columnsProvider
460 grid.loadConfig = function() {
461 if (!grid.persistKey) return $q.when();
463 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
464 .then(function(conf) {
467 var columns = grid.columnsProvider.columns;
470 angular.forEach(conf, function(col) {
471 var grid_col = columns.filter(
472 function(c) {return c.name == col.name})[0];
475 // saved column does not match a column in the
476 // current grid. skip it.
480 grid_col.align = col.align || 'left';
481 grid_col.flex = col.flex || 2;
482 grid_col.sort = col.sort || 0;
483 // all saved columns are assumed to be true
484 grid_col.visible = true;
486 .filter(function (c) {
487 return c.name == grid_col.name;
490 new_cols.push(grid_col);
493 // columns which are not expressed within the saved
494 // configuration are marked as non-visible and
495 // appended to the end of the new list of columns.
496 angular.forEach(columns, function(col) {
497 var found = conf.filter(
498 function(c) {return (c.name == col.name)})[0];
505 grid.columnsProvider.columns = new_cols;
511 $scope.onContextMenu = function($event) {
512 var col = angular.element($event.target).attr('column');
513 console.log('selected column ' + col);
516 $scope.page = function() {
517 return (grid.offset / grid.limit) + 1;
520 $scope.goToPage = function(page) {
522 if (angular.isNumber(page) && page > 0) {
523 grid.offset = (page - 1) * grid.limit;
528 $scope.offset = function(o) {
529 if (angular.isNumber(o))
534 $scope.limit = function(l) {
535 if (angular.isNumber(l)) {
537 egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
543 $scope.onFirstPage = function() {
544 return grid.offset == 0;
547 $scope.hasNextPage = function() {
548 // we have less data than requested, there must
549 // not be any more pages
550 if (grid.count() < grid.limit) return false;
552 // if the total count is not known, assume that a full
553 // page of data implies more pages are available.
554 if (grid.totalCount == -1) return true;
556 // we have a full page of data, but is there more?
557 return grid.totalCount > (grid.offset + grid.count());
560 $scope.incrementPage = function() {
561 grid.offset += grid.limit;
565 $scope.decrementPage = function() {
566 if (grid.offset < grid.limit) {
569 grid.offset -= grid.limit;
574 // number of items loaded for the current page of results
575 grid.count = function() {
576 return $scope.items.length;
579 // returns the unique identifier value for the provided item
580 // for internal consistency, indexValue is always coerced
582 grid.indexValue = function(item) {
583 if (angular.isObject(item)) {
585 if (angular.isFunction(item[grid.indexField]))
586 return ''+item[grid.indexField]();
587 return ''+item[grid.indexField]; // flat data
590 // passed a non-object; assume it's an index
594 // fires the hide handler function for a context action
595 $scope.actionHide = function(action) {
596 if (typeof action.hide == 'undefined') {
599 if (angular.isFunction(action.hide))
600 return action.hide(action);
604 // fires the disable handler function for a context action
605 $scope.actionDisable = function(action) {
606 if (typeof action.disabled == 'undefined') {
609 if (angular.isFunction(action.disabled))
610 return action.disabled(action);
611 return action.disabled;
614 // fires the action handler function for a context action
615 $scope.actionLauncher = function(action) {
616 if (!action.handler) {
618 'No handler specified for "' + action.label + '"');
622 action.handler(grid.getSelectedItems());
624 console.error('Error executing handler for "'
625 + action.label + '" => ' + E + "\n" + E.stack);
628 if ($scope.action_context_showing) $scope.hideActionContextMenu();
633 $scope.hideActionContextMenu = function () {
634 $($scope.menu_dom).css({
636 width: $scope.action_context_width,
637 top: $scope.action_context_y,
638 left: $scope.action_context_x
640 $($scope.action_context_parent).append($scope.menu_dom);
641 $scope.action_context_oldy = $scope.action_context_oldx = 0;
642 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
643 $scope.action_context_showing = false;
646 $scope.action_context_showing = false;
647 $scope.showActionContextMenu = function ($event) {
649 // Have to gather these here, instead of inside link()
650 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
651 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
653 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
654 $event.target.click();
656 if (!$scope.action_context_showing) {
657 $scope.action_context_width = $($scope.menu_dom).css('width');
658 $scope.action_context_y = $($scope.menu_dom).css('top');
659 $scope.action_context_x = $($scope.menu_dom).css('left');
660 $scope.action_context_showing = true;
661 $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
663 $('body').append($($scope.menu_dom));
664 $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
667 $($scope.menu_dom).css({
669 width: $scope.action_context_width,
677 // returns the list of selected item objects
678 grid.getSelectedItems = function() {
679 return $scope.items.filter(
681 return Boolean($scope.selected[grid.indexValue(item)]);
686 grid.getItemByIndex = function(index) {
687 for (var i = 0; i < $scope.items.length; i++) {
688 var item = $scope.items[i];
689 if (grid.indexValue(item) == index)
694 // selects one row after deselecting all of the others
695 grid.selectOneItem = function(index) {
696 $scope.selected = {};
697 $scope.selected[index] = true;
700 // selects or deselects an item, without affecting the others.
701 // returns true if the item is selected; false if de-selected.
702 // we overwrite the object so that we can watch $scope.selected
703 grid.toggleSelectOneItem = function(index) {
704 if ($scope.selected[index]) {
705 delete $scope.selected[index];
706 $scope.selected = angular.copy($scope.selected);
709 $scope.selected[index] = true;
710 $scope.selected = angular.copy($scope.selected);
715 $scope.updateSelected = function () {
716 return $scope.selected = angular.copy($scope.selected);
719 grid.selectAllItems = function() {
720 angular.forEach($scope.items, function(item) {
721 $scope.selected[grid.indexValue(item)] = true
723 $scope.selected = angular.copy($scope.selected);
726 $scope.$watch('selectAll', function(newVal) {
728 grid.selectAllItems();
730 $scope.selected = {};
734 if ($scope.onSelect) {
735 $scope.$watch('selected', function(newVal) {
736 $scope.onSelect(grid.getSelectedItems());
737 if ($scope.afterSelect) $scope.afterSelect();
741 // returns true if item1 appears in the list before item2;
742 // false otherwise. this is slightly more efficient that
743 // finding the position of each then comparing them.
744 // item1 / item2 may be an item or an item index
745 grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
746 var idx1 = grid.indexValue(itemOrIndex1);
747 var idx2 = grid.indexValue(itemOrIndex2);
749 // use for() for early exit
750 for (var i = 0; i < $scope.items.length; i++) {
751 var idx = grid.indexValue($scope.items[i]);
752 if (idx == idx1) return true;
753 if (idx == idx2) return false;
758 // 0-based position of item in the current data set
759 grid.indexOf = function(item) {
760 var idx = grid.indexValue(item);
761 for (var i = 0; i < $scope.items.length; i++) {
762 if (grid.indexValue($scope.items[i]) == idx)
768 grid.modifyColumnFlex = function(column, val) {
770 // prevent flex:0; use hiding instead
774 $scope.modifyColumnFlex = function(col, val) {
775 $scope.lastModColumn = col.name;
776 grid.modifyColumnFlex(col, val);
779 grid.modifyColumnPos = function(col, diff) {
780 var srcIdx, targetIdx;
781 angular.forEach(grid.columnsProvider.columns,
782 function(c, i) { if (c.name == col.name) srcIdx = i });
784 targetIdx = srcIdx + diff;
787 } else if (targetIdx >= grid.columnsProvider.columns.length) {
788 // Target index follows the last visible column.
790 angular.forEach(grid.columnsProvider.columns,
791 function(column, idx) {
792 if (column.visible) lastVisible = idx;
795 targetIdx = lastVisible + 1;
798 // Splice column out of old position, insert at new position.
799 grid.columnsProvider.columns.splice(srcIdx, 1);
800 grid.columnsProvider.columns.splice(targetIdx, 0, col);
803 $scope.modifyColumnPos = function(col, diff) {
804 $scope.lastModColumn = col.name;
805 return grid.modifyColumnPos(col, diff);
809 // handles click, control-click, and shift-click
810 $scope.handleRowClick = function($event, item) {
811 var index = grid.indexValue(item);
813 var origSelected = Object.keys($scope.selected);
815 if (!$scope.canMultiSelect) {
816 grid.selectOneItem(index);
817 grid.lastSelectedItemIndex = index;
821 if ($event.ctrlKey || $event.metaKey /* mac command */) {
823 if (grid.toggleSelectOneItem(index))
824 grid.lastSelectedItemIndex = index;
826 } else if ($event.shiftKey) {
829 if (!grid.lastSelectedItemIndex ||
830 index == grid.lastSelectedItemIndex) {
831 grid.selectOneItem(index);
832 grid.lastSelectedItemIndex = index;
836 var selecting = false;
837 var ascending = grid.itemComesBefore(
838 grid.lastSelectedItemIndex, item);
840 grid.indexOf(grid.lastSelectedItemIndex);
842 // update to new last-selected
843 grid.lastSelectedItemIndex = index;
845 // select each row between the last selected and
846 // currently selected items
848 startPos += ascending ? 1 : -1;
849 var curItem = $scope.items[startPos];
851 var curIdx = grid.indexValue(curItem);
852 $scope.selected[curIdx] = true;
853 if (curIdx == index) break; // all done
855 $scope.selected = angular.copy($scope.selected);
859 grid.selectOneItem(index);
860 grid.lastSelectedItemIndex = index;
864 // Builds a sort expression from column sort priorities.
865 // called on page load and any time the priorities are modified.
866 grid.compileSort = function() {
867 var sortList = grid.columnsProvider.columns.filter(
868 function(col) { return Number(col.sort) != 0 }
871 if (Math.abs(a.sort) < Math.abs(b.sort))
877 if (sortList.length) {
878 grid.dataProvider.sort = sortList.map(function(col) {
880 blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
886 // builds a sort expression using a single column,
887 // toggling between ascending and descending sort.
888 $scope.quickSort = function(col_name) {
889 var sort = grid.dataProvider.sort;
890 if (sort && sort.length &&
891 sort[0] == col_name) {
893 blob[col_name] = 'desc';
894 grid.dataProvider.sort = [blob];
896 grid.dataProvider.sort = [col_name];
903 // show / hide the grid configuration row
904 $scope.toggleConfDisplay = function() {
905 if ($scope.showGridConf) {
906 $scope.showGridConf = false;
907 if (grid.columnsProvider.hasSortableColumn()) {
908 // only refresh the grid if the user has the
909 // ability to modify the sort priorities.
915 $scope.showGridConf = true;
918 delete $scope.lastModColumn;
919 $scope.gridColumnPickerIsOpen = false;
922 // called when a dragged column is dropped onto itself
923 // or any other column
924 grid.onColumnDrop = function(target) {
925 if (angular.isUndefined(target)) return;
926 if (target == grid.dragColumn) return;
927 var srcIdx, targetIdx, srcCol;
928 angular.forEach(grid.columnsProvider.columns,
930 if (col.name == grid.dragColumn) {
933 } else if (col.name == target) {
939 if (srcIdx < targetIdx) targetIdx--;
941 // move src column from old location to new location in
942 // the columns array, then force a page refresh
943 grid.columnsProvider.columns.splice(srcIdx, 1);
944 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
948 // prepares a string for inclusion within a CSV document
949 // by escaping commas and quotes and removing newlines.
950 grid.csvDatum = function(str) {
953 str = str.replace(/\n/g, '');
954 if (str.match(/\,/) || str.match(/"/)) {
955 str = str.replace(/"/g, '""');
956 str = '"' + str + '"';
961 /** Export the full data set as CSV.
963 * 1. User clicks the 'download csv' link
964 * 2. All grid data is retrieved asychronously
965 * 3. Once all data is all present and CSV-ized, the download
966 * attributes are linked to the href.
967 * 4. The href .click() action is prgrammatically fired again,
968 * telling the browser to download the data, now that the
969 * data is available for download.
970 * 5 Once downloaded, the href attributes are reset.
972 grid.csvExportInProgress = false;
973 $scope.generateCSVExportURL = function($event) {
975 if (grid.csvExportInProgress) {
976 // This is secondary href click handler. Give the
977 // browser a moment to start the download, then reset
978 // the CSV download attributes / state.
981 $scope.csvExportURL = '';
982 $scope.csvExportFileName = '';
983 grid.csvExportInProgress = false;
989 grid.csvExportInProgress = true;
990 $scope.gridColumnPickerIsOpen = false;
992 // let the file name describe the grid
993 $scope.csvExportFileName =
994 ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
995 .replace(/\s+/g, '_') + '_' + $scope.page();
997 // toss the CSV into a Blob and update the export URL
998 grid.generateCSV().then(function(csv) {
999 var blob = new Blob([csv], {type : 'text/plain'});
1000 $scope.csvExportURL =
1001 ($window.URL || $window.webkitURL).createObjectURL(blob);
1003 // Fire the 2nd click event now that the browser has
1004 // information on how to download the CSV file.
1005 $timeout(function() {$event.target.click()});
1010 * TODO: does this serve any purpose given we can
1011 * print formatted HTML? If so, generateCSV() now
1012 * returns a promise, needs light refactoring...
1013 $scope.printCSV = function() {
1014 $scope.gridColumnPickerIsOpen = false;
1015 egCore.print.print({
1016 context : 'default',
1017 content : grid.generateCSV(),
1018 content_type : 'text/plain'
1023 // Given a row item and column definition, extract the
1024 // text content for printing. Templated columns must be
1025 // processed and parsed as HTML, then boiled down to their
1027 grid.getItemTextContent = function(item, col) {
1030 val = $scope.translateCellTemplate(col, item);
1032 var node = new DOMParser()
1033 .parseFromString(val, 'text/html');
1034 val = $(node).text();
1037 val = grid.dataProvider.itemFieldValue(item, col);
1038 val = $filter('egGridValueFilter')(val, col, item);
1044 * Fetches all grid data and transates each item into a simple
1045 * key-value pair of column name => text-value.
1046 * Included in the response for convenience is the list of
1047 * currently visible column definitions.
1048 * TODO: currently fetches a maximum of 10k rows. Does this
1049 * need to be configurable?
1051 grid.getAllItemsAsText = function() {
1052 var text_items = [];
1054 // we don't know the total number of rows we're about
1055 // to retrieve, but we can indicate the number retrieved
1056 // so far as each item arrives.
1057 egProgressDialog.open({value : 0});
1059 var visible_cols = grid.columnsProvider.columns.filter(
1060 function(c) { return c.visible });
1062 return grid.dataProvider.get(0, 10000).then(
1064 return {items : text_items, columns : visible_cols};
1068 egProgressDialog.increment();
1070 angular.forEach(visible_cols, function(col) {
1071 text_item[col.name] =
1072 grid.getItemTextContent(item, col);
1074 text_items.push(text_item);
1076 ).finally(egProgressDialog.close);
1079 // Fetch "all" of the grid data, translate it into print-friendly
1080 // text, and send it to the printer service.
1081 $scope.printHTML = function() {
1082 $scope.gridColumnPickerIsOpen = false;
1083 return grid.getAllItemsAsText().then(function(text_items) {
1084 return egCore.print.print({
1085 template : 'grid_html',
1091 // generates CSV for the currently visible grid contents
1092 grid.generateCSV = function() {
1093 return grid.getAllItemsAsText().then(function(text_items) {
1094 var columns = text_items.columns;
1095 var items = text_items.items;
1099 angular.forEach(columns, function(col) {
1100 csvStr += grid.csvDatum(col.label);
1104 csvStr = csvStr.replace(/,$/,'\n');
1107 angular.forEach(items, function(item) {
1108 angular.forEach(columns, function(col) {
1109 csvStr += grid.csvDatum(item[col.name]);
1112 csvStr = csvStr.replace(/,$/,'\n');
1119 // Interpolate the value for column.linkpath within the context
1120 // of the row item to generate the final link URL.
1121 $scope.generateLinkPath = function(col, item) {
1122 return egCore.strings.$replace(col.linkpath, {item : item});
1125 // If a column provides its own HTML template, translate it,
1126 // using the current item for the template scope.
1127 // note: $sce is required to avoid security restrictions and
1128 // is OK here, since the template comes directly from a
1129 // local HTML template (not user input).
1130 $scope.translateCellTemplate = function(col, item) {
1131 var html = egCore.strings.$replace(col.template, {item : item});
1132 return $sce.trustAsHtml(html);
1135 $scope.collect = function() { grid.collect() }
1137 // asks the dataProvider for a page of data
1138 grid.collect = function() {
1140 // avoid firing the collect if there is nothing to collect.
1141 if (grid.selfManagedData && !grid.dataProvider.query) return;
1143 if (grid.collecting) return; // avoid parallel collect()
1144 grid.collecting = true;
1146 console.debug('egGrid.collect() offset='
1147 + grid.offset + '; limit=' + grid.limit);
1149 // ensure all of our dropdowns are closed
1150 // TODO: git rid of these and just use dropdown-toggle,
1151 // which is more reliable.
1152 $scope.gridColumnPickerIsOpen = false;
1153 $scope.gridRowCountIsOpen = false;
1154 $scope.gridPageSelectIsOpen = false;
1157 $scope.selected = {};
1159 // Inform the caller we've asked the data provider
1160 // for data. This is useful for knowing when collection
1161 // has started (e.g. to display a progress dialg) when
1162 // using the stock (flattener) data provider, where the
1163 // user is not directly defining a get() handler.
1164 if (grid.controls.collectStarted)
1165 grid.controls.collectStarted(grid.offset, grid.limit);
1167 grid.dataProvider.get(grid.offset, grid.limit).then(
1169 if (grid.controls.allItemsRetrieved)
1170 grid.controls.allItemsRetrieved();
1175 $scope.items.push(item)
1176 if (grid.controls.itemRetrieved)
1177 grid.controls.itemRetrieved(item);
1178 if ($scope.selectAll)
1179 $scope.selected[grid.indexValue(item)] = true
1181 }).finally(function() {
1182 console.debug('egGrid.collect() complete');
1183 grid.collecting = false
1184 $scope.selected = angular.copy($scope.selected);
1194 * eg-grid-field : used for collecting custom field data from the templates.
1195 * This directive does not direct display, it just passes data up to the
1198 .directive('egGridField', function() {
1200 require : '^egGrid',
1203 flesher: '=', // optional; function that can flesh a linked field, given the value
1204 comparator: '=', // optional; function that can sort the thing at the end of 'path'
1205 name : '@', // required; unique name
1206 path : '@', // optional; flesh path
1207 ignore: '@', // optional; fields to ignore when path is a wildcard
1208 label : '@', // optional; display label
1209 flex : '@', // optional; default flex width
1210 align : '@', // optional; default alignment, left/center/right
1211 dateformat : '@', // optional: passed down to egGridValueFilter
1212 datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
1213 datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
1214 dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
1216 // if a field is part of an IDL object, but we are unable to
1217 // determine the class, because it's nested within a hash
1218 // (i.e. we can't navigate directly to the object via the IDL),
1219 // idlClass lets us specify the class. This is particularly
1220 // useful for nested wildcard fields.
1221 parentIdlClass : '@',
1223 // optional: for non-IDL columns, specifying a datatype
1224 // lets the caller control which display filter is used.
1225 // datatype should match the standard IDL datatypes.
1228 link : function(scope, element, attrs, egGridCtrl) {
1230 // boolean fields are presented as value-less attributes
1239 'required' // if set, always fetch data for this column
1242 if (angular.isDefined(attrs[field]))
1243 scope[field] = true;
1247 // any HTML content within the field is its custom template
1248 var tmpl = element.html();
1249 if (tmpl && !tmpl.match(/^\s*$/))
1250 scope.template = tmpl
1252 egGridCtrl.columnsProvider.add(scope);
1259 * eg-grid-action : used for specifying actions which may be applied
1260 * to items within the grid.
1262 .directive('egGridAction', function() {
1264 require : '^egGrid',
1268 group : '@', // Action group, ungrouped if not set
1269 label : '@', // Action label
1270 handler : '=', // Action function handler
1272 disabled : '=', // function
1275 link : function(scope, element, attrs, egGridCtrl) {
1276 egGridCtrl.addAction({
1278 group : scope.group,
1279 label : scope.label,
1280 divider : scope.divider,
1281 handler : scope.handler,
1282 disabled : scope.disabled,
1289 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1291 function ColumnsProvider(args) {
1294 cols.stockVisible = [];
1295 cols.idlClass = args.idlClass;
1296 cols.clientSort = args.clientSort;
1297 cols.defaultToHidden = args.defaultToHidden;
1298 cols.defaultToNoSort = args.defaultToNoSort;
1299 cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1300 cols.defaultDateFormat = args.defaultDateFormat;
1301 cols.defaultDateContext = args.defaultDateContext;
1303 // resets column width, visibility, and sort behavior
1304 // Visibility resets to the visibility settings defined in the
1305 // template (i.e. the original egGridField values).
1306 cols.reset = function() {
1307 angular.forEach(cols.columns, function(col) {
1311 if (cols.stockVisible.indexOf(col.name) > -1) {
1314 col.visible = false;
1319 // returns true if any columns are sortable
1320 cols.hasSortableColumn = function() {
1321 return cols.columns.filter(
1323 return col.sortable || col.multisortable;
1328 cols.showAllColumns = function() {
1329 angular.forEach(cols.columns, function(column) {
1330 column.visible = true;
1334 cols.hideAllColumns = function() {
1335 angular.forEach(cols.columns, function(col) {
1340 cols.indexOf = function(name) {
1341 for (var i = 0; i < cols.columns.length; i++) {
1342 if (cols.columns[i].name == name)
1348 cols.findColumn = function(name) {
1349 return cols.columns[cols.indexOf(name)];
1352 cols.compileAutoColumns = function() {
1353 var idl_class = egCore.idl.classes[cols.idlClass];
1358 if (field.virtual) return;
1359 if (field.datatype == 'link' || field.datatype == 'org_unit') {
1360 // if the field is a link and the linked class has a
1361 // "selector" field specified, use the selector field
1362 // as the display field for the columns.
1363 // flattener will take care of the fleshing.
1364 if (field['class']) {
1365 var selector_field = egCore.idl.classes[field['class']].fields
1366 .filter(function(f) { return Boolean(f.selector) })[0];
1367 if (selector_field) {
1368 field.path = field.name + '.' + selector_field.selector;
1372 cols.add(field, true);
1377 // if a column definition has a path with a wildcard, create
1378 // columns for all non-virtual fields at the specified
1379 // position in the path.
1380 cols.expandPath = function(colSpec) {
1382 var ignoreList = [];
1384 ignoreList = colSpec.ignore.split(' ');
1386 var dotpath = colSpec.path.replace(/\.?\*$/,'');
1390 if (colSpec.parentIdlClass) {
1391 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1393 class_obj = egCore.idl.classes[cols.idlClass];
1395 var idl_parent = class_obj;
1396 var old_field_label = '';
1398 if (!class_obj) return;
1400 console.debug('egGrid: auto dotpath is: ' + dotpath);
1401 var path_parts = dotpath.split(/\./);
1403 // find the IDL class definition for the last element in the
1404 // path before the .*
1405 // an empty path_parts means expand the root class
1408 for (var path_idx in path_parts) {
1409 old_field = idl_field;
1411 var part = path_parts[path_idx];
1412 idl_field = class_obj.field_map[part];
1414 // unless we're at the end of the list, this field should
1415 // link to another class.
1416 if (idl_field && idl_field['class'] && (
1417 idl_field.datatype == 'link' ||
1418 idl_field.datatype == 'org_unit')) {
1419 if (old_field_label) old_field_label += ' : ';
1420 old_field_label += idl_field.label;
1421 class_obj = egCore.idl.classes[idl_field['class']];
1422 if (old_field) idl_parent = old_field;
1424 if (path_idx < (path_parts.length - 1)) {
1425 // we ran out of classes to hop through before
1426 // we ran out of path components
1427 console.error("egGrid: invalid IDL path: " + dotpath);
1434 angular.forEach(class_obj.fields, function(field) {
1436 // Only show wildcard fields where we have data to show
1437 // Virtual and un-fleshed links will not have any data.
1438 if (field.virtual ||
1439 (field.datatype == 'link' || field.datatype == 'org_unit') ||
1440 ignoreList.indexOf(field.name) > -1
1444 var col = cols.cloneFromScope(colSpec);
1445 col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1447 // log line below is very chatty. disable until needed.
1448 // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1449 cols.add(col, false, true,
1450 {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1453 cols.columns = cols.columns.sort(
1455 if (a.explicit) return -1;
1456 if (b.explicit) return 1;
1458 if (a.idlclass && b.idlclass) {
1459 if (a.idlclass < b.idlclass) return -1;
1460 if (b.idlclass < a.idlclass) return 1;
1463 if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1464 if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1465 if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1468 if (a.label && b.label) {
1469 if (a.label < b.label) return -1;
1470 if (b.label < a.label) return 1;
1473 return a.name < b.name ? -1 : 1;
1480 "egGrid: wildcard path does not resolve to an object: "
1485 // angular.clone(scopeObject) is not permittable. Manually copy
1486 // the fields over that we need (so the scope object can go away).
1487 cols.cloneFromScope = function(colSpec) {
1489 flesher : colSpec.flesher,
1490 comparator : colSpec.comparator,
1491 name : colSpec.name,
1492 label : colSpec.label,
1493 path : colSpec.path,
1494 align : colSpec.align || 'left',
1495 flex : Number(colSpec.flex) || 2,
1496 sort : Number(colSpec.sort) || 0,
1497 required : colSpec.required,
1498 linkpath : colSpec.linkpath,
1499 template : colSpec.template,
1500 visible : colSpec.visible,
1501 hidden : colSpec.hidden,
1502 datatype : colSpec.datatype,
1503 sortable : colSpec.sortable,
1504 nonsortable : colSpec.nonsortable,
1505 multisortable : colSpec.multisortable,
1506 nonmultisortable : colSpec.nonmultisortable,
1507 dateformat : colSpec.dateformat,
1508 datecontext : colSpec.datecontext,
1509 datefilter : colSpec.datefilter,
1510 dateonlyinterval : colSpec.dateonlyinterval,
1511 parentIdlClass : colSpec.parentIdlClass
1516 // Add a column to the columns collection.
1517 // Columns may come from a slim eg-columns-field or
1518 // directly from the IDL.
1519 cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1521 // First added column with the specified path takes precedence.
1522 // This allows for specific definitions followed by wildcard
1523 // definitions. If a match is found, back out.
1524 if (cols.columns.filter(function(c) {
1525 return (c.path == colSpec.path) })[0]) {
1526 console.debug('skipping pre-existing column ' + colSpec.path);
1530 var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1532 if (column.path && column.path.match(/\*$/))
1533 return cols.expandPath(colSpec);
1535 if (!fromExpand) column.explicit = true;
1537 if (!column.name) column.name = column.path;
1538 if (!column.path) column.path = column.name;
1540 if (column.visible || (!cols.defaultToHidden && !column.hidden))
1541 column.visible = true;
1543 if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1544 column.sortable = true;
1546 if (column.multisortable ||
1547 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1548 column.multisortable = true;
1550 if (cols.defaultDateFormat && ! column.dateformat) {
1551 column.dateformat = cols.defaultDateFormat;
1554 if (cols.defaultDateOnlyInterval && ! column.dateonlyinterval) {
1555 column.dateonlyinterval = cols.defaultDateOnlyInterval;
1558 if (cols.defaultDateContext && ! column.datecontext) {
1559 column.datecontext = cols.defaultDateContext;
1562 if (cols.defaultDateFilter && ! column.datefilter) {
1563 column.datefilter = cols.defaultDateFilter;
1566 cols.columns.push(column);
1568 // Track which columns are visible by default in case we
1569 // need to reset column visibility
1571 cols.stockVisible.push(column.name);
1573 if (fromIDL) return; // directly from egIDL. nothing left to do.
1575 // lookup the matching IDL field
1576 if (!idl_info && cols.idlClass)
1577 idl_info = cols.idlFieldFromPath(column.path);
1580 // column is not represented within the IDL
1581 column.adhoc = true;
1585 column.datatype = idl_info.idl_field.datatype;
1587 if (!column.label) {
1588 column.label = idl_info.idl_field.label || column.name;
1591 if (fromExpand && idl_info.idl_class) {
1592 column.idlclass = '';
1593 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1594 column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1596 column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1601 // finds the IDL field from the dotpath, using the columns
1602 // idlClass as the base.
1603 cols.idlFieldFromPath = function(dotpath) {
1604 var class_obj = egCore.idl.classes[cols.idlClass];
1605 var path_parts = dotpath.split(/\./);
1609 for (var path_idx in path_parts) {
1610 var part = path_parts[path_idx];
1611 idl_parent = idl_field;
1612 idl_field = class_obj.field_map[part];
1615 if (idl_field['class'] && (
1616 idl_field.datatype == 'link' ||
1617 idl_field.datatype == 'org_unit')) {
1618 class_obj = egCore.idl.classes[idl_field['class']];
1626 idl_parent: idl_parent,
1627 idl_field : idl_field,
1628 idl_class : class_obj
1634 instance : function(args) { return new ColumnsProvider(args) }
1640 * Generic data provider template class. This is basically an abstract
1641 * class factory service whose instances can be locally modified to
1642 * meet the needs of each individual grid.
1644 .factory('egGridDataProvider',
1645 ['$q','$timeout','$filter','egCore',
1646 function($q , $timeout , $filter , egCore) {
1648 function GridDataProvider(args) {
1649 var gridData = this;
1650 if (!args) args = {};
1653 gridData.get = args.get;
1654 gridData.query = args.query;
1655 gridData.idlClass = args.idlClass;
1656 gridData.columnsProvider = args.columnsProvider;
1658 // Delivers a stream of array data via promise.notify()
1659 // Useful for passing an array of data to egGrid.get()
1660 // If a count is provided, the array will be trimmed to
1661 // the range defined by count and offset
1662 gridData.arrayNotifier = function(arr, offset, count) {
1663 if (!arr || arr.length == 0) return $q.when();
1665 if (gridData.columnsProvider.clientSort
1667 && gridData.sort.length > 0
1669 var sorter_cache = [];
1670 arr.sort(function(a,b) {
1671 for (var si = 0; si < gridData.sort.length; si++) {
1672 if (!sorter_cache[si]) { // Build sort structure on first comparison, reuse thereafter
1673 var field = gridData.sort[si];
1676 if (angular.isObject(field)) {
1677 dir = Object.values(field)[0];
1678 field = Object.keys(field)[0];
1681 var path = gridData.columnsProvider.findColumn(field).path || field;
1682 var comparator = gridData.columnsProvider.findColumn(field).comparator ||
1683 function (x,y) { if (x < y) return -1; if (x > y) return 1; return 0 };
1685 sorter_cache[si] = {
1688 comparator : comparator
1692 var sc = sorter_cache[si];
1696 if (a._isfieldmapper || angular.isFunction(a[sc.field])) {
1697 try {af = a[sc.field](); bf = b[sc.field]() } catch (e) {};
1699 af = a[sc.field]; bf = b[sc.field];
1701 if (af === undefined && sc.field.indexOf('.') > -1) { // assume an object, not flat path
1702 var parts = sc.field.split('.');
1705 angular.forEach(parts, function (p) {
1707 if (af._isfieldmapper || angular.isFunction(af[p])) af = af[p]();
1711 if (bf._isfieldmapper || angular.isFunction(bf[p])) bf = bf[p]();
1717 if (af === undefined) af = null;
1718 if (bf === undefined) bf = null;
1720 if (af === null && bf !== null) return 1;
1721 if (bf === null && af !== null) return -1;
1723 if (!(bf === null && af === null)) {
1724 var partial = sc.comparator(af,bf);
1726 if (sc.dir == 'desc') {
1727 if (partial > 0) return -1;
1739 if (count) arr = arr.slice(offset, offset + count);
1740 var def = $q.defer();
1741 // promise notifications are only witnessed when delivered
1742 // after the caller has his hands on the promise object
1743 $timeout(function() {
1744 angular.forEach(arr, def.notify);
1750 // Calls the grid refresh function. Once instantiated, the
1751 // grid will replace this function with it's own refresh()
1752 gridData.refresh = function(noReset) { }
1754 if (!gridData.get) {
1755 // returns a promise whose notify() delivers items
1756 gridData.get = function(index, count) {
1757 console.error("egGridDataProvider.get() not implemented");
1761 // attempts a flat field lookup first. If the column is not
1762 // found on the top-level object, attempts a nested lookup
1763 // TODO: consider a caching layer to speed up template
1764 // rendering, particularly for nested objects?
1765 gridData.itemFieldValue = function(item, column) {
1767 if (column.name in item) {
1768 if (typeof item[column.name] == 'function') {
1769 val = item[column.name]();
1771 val = item[column.name];
1774 val = gridData.nestedItemFieldValue(item, column);
1780 // TODO: deprecate me
1781 gridData.flatItemFieldValue = function(item, column) {
1782 console.warn('gridData.flatItemFieldValue deprecated; '
1783 + 'leave provider.itemFieldValue unset');
1784 return item[column.name];
1787 // given an object and a dot-separated path to a field,
1788 // extract the value of the field. The path can refer
1789 // to function names or object attributes. If the final
1790 // value is an IDL field, run the value through its
1791 // corresponding output filter.
1792 gridData.nestedItemFieldValue = function(obj, column) {
1793 item = obj; // keep a copy around
1795 if (obj === null || obj === undefined || obj === '') return '';
1796 if (!column.path) return obj;
1799 var parts = column.path.split('.');
1801 angular.forEach(parts, function(step, idx) {
1802 // object is not fleshed to the expected extent
1803 if (typeof obj != 'object') {
1804 if (typeof obj != 'undefined' && column.flesher) {
1805 obj = column.flesher(obj, column, item);
1812 if (!obj) return '';
1814 var cls = obj.classname;
1815 if (cls && (class_obj = egCore.idl.classes[cls])) {
1816 idl_field = class_obj.field_map[step];
1817 obj = obj[step] ? obj[step]() : '';
1819 if (angular.isFunction(obj[step])) {
1827 // We found a nested IDL object which may or may not have
1828 // been configured as a top-level column. Grab the datatype.
1829 if (idl_field && !column.datatype)
1830 column.datatype = idl_field.datatype;
1832 if (obj === null || obj === undefined || obj === '') return '';
1838 instance : function(args) {
1839 return new GridDataProvider(args);
1846 // Factory service for egGridDataManager instances, which are
1847 // responsible for collecting flattened grid data.
1848 .factory('egGridFlatDataProvider',
1849 ['$q','egCore','egGridDataProvider',
1850 function($q , egCore , egGridDataProvider) {
1853 instance : function(args) {
1854 var provider = egGridDataProvider.instance(args);
1856 provider.get = function(offset, count) {
1858 // no query means no call
1859 if (!provider.query ||
1860 angular.equals(provider.query, {}))
1863 // find all of the currently visible columns
1864 var queryFields = {}
1865 angular.forEach(provider.columnsProvider.columns,
1867 // only query IDL-tracked columns
1868 if (!col.adhoc && (col.required || col.visible))
1869 queryFields[col.name] = col.path;
1873 return egCore.net.request(
1875 'open-ils.fielder.flattened_search',
1876 egCore.auth.token(), provider.idlClass,
1877 queryFields, provider.query,
1878 { sort : provider.sort,
1884 //provider.itemFieldValue = provider.flatItemFieldValue;
1891 .directive('egGridColumnDragSource', function() {
1894 require : '^egGrid',
1895 link : function(scope, element, attrs, egGridCtrl) {
1896 angular.element(element).attr('draggable', 'true');
1898 element.bind('dragstart', function(e) {
1899 egGridCtrl.dragColumn = attrs.column;
1900 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1901 egGridCtrl.colResizeDir = 0;
1903 if (egGridCtrl.dragType == 'move') {
1904 // style the column getting moved
1905 angular.element(e.target).addClass(
1906 'eg-grid-column-move-handle-active');
1910 element.bind('dragend', function(e) {
1911 if (egGridCtrl.dragType == 'move') {
1912 angular.element(e.target).removeClass(
1913 'eg-grid-column-move-handle-active');
1920 .directive('egGridColumnDragDest', function() {
1923 require : '^egGrid',
1924 link : function(scope, element, attrs, egGridCtrl) {
1926 element.bind('dragover', function(e) { // required for drop
1927 e.stopPropagation();
1929 e.dataTransfer.dropEffect = 'move';
1931 if (egGridCtrl.colResizeDir == 0) return; // move
1933 var cols = egGridCtrl.columnsProvider;
1934 var srcCol = egGridCtrl.dragColumn;
1935 var srcColIdx = cols.indexOf(srcCol);
1937 if (egGridCtrl.colResizeDir == -1) {
1938 if (cols.indexOf(attrs.column) <= srcColIdx) {
1939 egGridCtrl.modifyColumnFlex(
1940 egGridCtrl.columnsProvider.findColumn(
1941 egGridCtrl.dragColumn), -1);
1942 if (cols.columns[srcColIdx+1]) {
1943 // source column shrinks by one, column to the
1944 // right grows by one.
1945 egGridCtrl.modifyColumnFlex(
1946 cols.columns[srcColIdx+1], 1);
1951 if (cols.indexOf(attrs.column) > srcColIdx) {
1952 egGridCtrl.modifyColumnFlex(
1953 egGridCtrl.columnsProvider.findColumn(
1954 egGridCtrl.dragColumn), 1);
1955 if (cols.columns[srcColIdx+1]) {
1956 // source column grows by one, column to the
1957 // right grows by one.
1958 egGridCtrl.modifyColumnFlex(
1959 cols.columns[srcColIdx+1], -1);
1967 element.bind('dragenter', function(e) {
1968 e.stopPropagation();
1970 if (egGridCtrl.dragType == 'move') {
1971 angular.element(e.target).addClass('eg-grid-col-hover');
1973 // resize grips are on the right side of each column.
1974 // dragenter will either occur on the source column
1975 // (dragging left) or the column to the right.
1976 if (egGridCtrl.colResizeDir == 0) {
1977 if (egGridCtrl.dragColumn == attrs.column) {
1978 egGridCtrl.colResizeDir = -1; // west
1980 egGridCtrl.colResizeDir = 1; // east
1986 element.bind('dragleave', function(e) {
1987 e.stopPropagation();
1989 if (egGridCtrl.dragType == 'move') {
1990 angular.element(e.target).removeClass('eg-grid-col-hover');
1994 element.bind('drop', function(e) {
1995 e.stopPropagation();
1997 egGridCtrl.colResizeDir = 0;
1998 if (egGridCtrl.dragType == 'move') {
1999 angular.element(e.target).removeClass('eg-grid-col-hover');
2000 egGridCtrl.onColumnDrop(attrs.column); // move the column
2007 .directive('egGridMenuItem', function() {
2010 require : '^egGrid',
2016 handler : '=', // onclick handler function
2017 divider : '=', // if true, show a divider only
2018 handlerData : '=', // if set, passed as second argument to handler
2019 disabled : '=', // function
2020 hidden : '=' // function
2022 link : function(scope, element, attrs, egGridCtrl) {
2023 egGridCtrl.addMenuItem({
2024 checkbox : scope.checkbox,
2025 checked : scope.checked ? true : false,
2026 label : scope.label,
2027 standalone : scope.standalone ? true : false,
2028 handler : scope.handler,
2029 divider : scope.divider,
2030 disabled : scope.disabled,
2031 hidden : scope.hidden,
2032 handlerData : scope.handlerData
2042 * Translates bare IDL object values into display values.
2043 * 1. Passes dates through the angular date filter
2044 * 2. Translates bools to Booleans so the browser can display translated
2045 * value. (Though we could manually translate instead..)
2046 * Others likely to follow...
2048 .filter('egGridValueFilter', ['$filter','egCore', function($filter,egCore) {
2049 function traversePath(obj,path) {
2050 var list = path.split('.');
2051 for (var part in path) {
2052 if (obj[path]) obj = obj[path]
2058 var GVF = function(value, column, item) {
2059 switch(column.datatype) {
2062 // Browser will translate true/false for us
2064 case '1' : // legacy
2068 case '0' : // legacy
2071 // value may be null, '', etc.
2072 default : return '';
2075 var interval = angular.isFunction(item[column.dateonlyinterval])
2076 ? item[column.dateonlyinterval]()
2077 : item[column.dateonlyinterval];
2079 if (column.dateonlyinterval && !interval) // try it as a dotted path
2080 interval = traversePath(item, column.dateonlyinterval);
2082 var context = angular.isFunction(item[column.datecontext])
2083 ? item[column.datecontext]()
2084 : item[column.datecontext];
2086 if (column.datecontext && !context) // try it as a dotted path
2087 context = traversePath(item, column.datecontext);
2089 var date_filter = column.datefilter || 'egOrgDateInContext';
2091 return $filter(date_filter)(value, column.dateformat, context, interval);
2093 return $filter('currency')(value);
2099 GVF.$stateful = true;